blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
262d66b82f052137addc17bf9aa2117e8db92c6b | 4a2f11650528159b86ee12ba6e84a1b9071e9222 | /sketches/01_lamp_driver/01_lamp_driver.ino | bc450d9faf252ef388d4c93adbf8034797543b0a | [
"MIT"
] | permissive | xdylanm/arduino-ski-goggle-light | 760c699722c70708f065a5d8ed5b59ad1e077ebe | d5210a77123e9f8a36ecf78fde7c99fb9f921f28 | refs/heads/master | 2020-04-20T18:16:53.769759 | 2019-02-04T14:24:17 | 2019-02-04T14:24:17 | 169,015,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | ino | #include <Adafruit_NeoPixel.h>
#include <CapacitiveSensor.h>
#define PIN_DATA 4 // DIN to Neo Pixels
#define PIN_LED 1 // LED on Model B=PIN0, LED on Model A=PIN1
#define PIN_SENSE_READ 0 // Read for capacitive sensor
#define PIN_SENSE_DRIVE 2 // Drive V for capacitive sensor
#define N_PIXELS 4
// threshold to detect a capacitive touch (0-999)
#define CAP_THRESHOLD 50
// number of samples for capacitive sensor
#define CAP_NUM_SAMPLES 10
// debounce timing (ms)
#define DEBOUNCE_MS 250
// colors
const uint32_t pixel_colors[] = {
0x7F0000, // red
0x6F3F00, // orange
0x5F5F00, // yellow
0x007F00, // green
0x00007F, // blue
0x3F006F, // indigo
0x4F2F4F // violet
};
uint8_t const num_colors = sizeof(pixel_colors)/sizeof(uint32_t);
int8_t current_color = 0;
Adafruit_NeoPixel pixels (N_PIXELS,PIN_DATA,NEO_GRBW+NEO_KHZ800);
CapacitiveSensor cap_sensor (PIN_SENSE_DRIVE, PIN_SENSE_READ);
bool cap_button_clicked() {
long const val = cap_sensor.capacitiveSensor(CAP_NUM_SAMPLES);
return (val > CAP_THRESHOLD);
}
void change_color(int8_t step) {
current_color += step;
if (current_color >= num_colors) {
current_color = 0;
} else if (current_color < 0) {
current_color = num_colors - 1;
}
for (int p = 0; p < N_PIXELS; ++p) {
pixels.setPixelColor(p,pixel_colors[current_color]);
}
pixels.show();
}
void setup() {
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_SENSE_READ, INPUT);
pinMode(PIN_SENSE_DRIVE, OUTPUT);
pixels.begin();
delay(500);
for (int p = 0; p < N_PIXELS; ++p) {
pixels.setPixelColor(p,0);
}
pixels.show();
}
uint8_t toggle = 0;
void loop() {
if (cap_button_clicked()) {
change_color(1);
}
digitalWrite(PIN_LED, toggle);
toggle = (toggle == 0 ? 1 : 0);
delay(DEBOUNCE_MS);
}
| [
"you@example.com"
] | you@example.com |
16f2e19ba94089c1834fb9dbbc5c72933ca456d6 | 5a46c499745cd9ba62566803560e308de862cb64 | /helpers/Config.hpp | 81fa6c6e18eba0e9aeb7cede058c00cbc9cc7890 | [] | no_license | sstokic-tgm/Gladiatorcheatz-v2.1 | 9420e609bb499e22ceb8a5a355c9e8914527a8a2 | c622bcdc45fb52f401eb6feb3178d3ffe1d68411 | refs/heads/master | 2022-02-14T22:23:59.359657 | 2022-01-25T13:07:06 | 2022-01-25T13:07:06 | 133,025,640 | 120 | 77 | null | 2022-01-25T13:07:07 | 2018-05-11T10:25:56 | C++ | UTF-8 | C++ | false | false | 1,022 | hpp | #pragma once
#include "../Singleton.hpp"
class ConfigFile;
class Config : public Singleton<Config>
{
public:
void CreateConfigFolder(std::string path);
bool FileExists(std::string file);
void SaveConfig(const std::string path);
void LoadConfig(const std::string path);
std::vector<std::string> GetAllConfigs();
private:
std::vector<ConfigFile> GetAllConfigsInFolder(const std::string path, const std::string ext);
template<typename T>
void Load(T &value, std::string str);
void LoadArray(float_t value[4], std::string str);
void LoadArray(bool value[14], std::string str);
template<typename T>
void Save(T &value, std::string str);
void SaveArray(float_t value[4], std::string str);
void SaveArray(bool value[14], std::string str);
};
class ConfigFile
{
public:
ConfigFile(const std::string name, const std::string path)
{
this->name = name;
this->path = path;
}
std::string GetName() { return name; };
std::string GetPath() { return path; };
private:
std::string name, path;
}; | [
"stokic95@yahoo.com"
] | stokic95@yahoo.com |
036e8cc0170f8327dcaeb631c0ca0a7d977bab45 | 99d054f93c3dd45a80e99be05f3f64c2c568ea5d | /Online Judges/URI/1160/main.cpp | 332c0ecac3176b6feaedf8fcb2b84df1c1e228fd | [
"MIT"
] | permissive | AnneLivia/Competitive-Programming | 65972d72fc4a0b37589da408e52ada19889f7ba8 | f4057e4bce37a636c85875cc80e5a53eb715f4be | refs/heads/master | 2022-12-23T11:52:04.299919 | 2022-12-12T16:20:05 | 2022-12-12T16:20:05 | 117,617,504 | 74 | 21 | MIT | 2019-11-14T03:11:58 | 2018-01-16T01:58:28 | C++ | UTF-8 | C++ | false | false | 574 | cpp | #include <iostream>
using namespace std;
int main()
{
int t, pA, pB, sumA, sumB;
double g1, g2;
cin >> t;
for ( int i = 1; i <= t; i++)
{
int tAnos = 0;
cin >> pA >> pB >> g1 >> g2;
while(tAnos <= 100 && pA <= pB) {
tAnos++;
sumA = int((pA * g1) / 100);
sumB = int((pB * g2) / 100);
pA += sumA;
pB += sumB;
}
if(tAnos > 100)
cout << "Mais de 1 seculo.\n";
else
cout << tAnos << " anos.\n";
}
return 0;
}
| [
"annelivia16@gmail.com"
] | annelivia16@gmail.com |
1a536cabb0b70b39a02d46e1ce14abfb3a3c63b4 | dde9ff46c792239a908a6388187d8ecfff619e4a | /Minimal/Skybox.h | 526bac37343cf66447121d8e7efb91a8fb0a297b | [] | no_license | zhlcbri/CSE190_Project3_CAVE-Simulator | 9beb63fb48f1b299332710083187d24c51c0e31b | 7eec46ed8d3a71663df326f0e16806508732ab54 | refs/heads/master | 2020-03-17T02:18:39.876865 | 2018-05-18T22:02:15 | 2018-05-18T22:02:15 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,480 | h | #pragma once
//
// Skybox.hpp
// Project3_CSE167
//
// Created by Brittany Zhang on 11/5/17.
// Copyright © 2017 ManianaBonita. All rights reserved.
//
#ifndef Skybox_h
#define Skybox_h
#include <iostream>
#include <stdio.h>
#include <vector>
#define GLFW_INCLUDE_GLEXT
#ifdef __APPLE__
#define GLFW_INCLUDE_GLCOREARB
#else
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/noise.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include "stb_image.h"
//#include "Cube.h"
using namespace std;
class Skybox {
public:
Skybox();
~Skybox();
glm::mat4 toWorld;
//unsigned int cubemapTexture;
GLuint VBO, VAO, EBO;
GLuint uProjection, uModelview;
// unsigned char* loadPPM(const char* filename, int& width, int& height);
unsigned int loadCubemap(vector<string> faces);
void draw(GLuint);
vector<string> faces;
// Define the coordinates and indices needed to draw the cube. Note that it is not necessary
// to use a 2-dimensional array, since the layout in memory is the same as a 1-dimensional array.
// This just looks nicer since it's easy to tell what coordinates/indices belong where.
const GLfloat vertices[8][3] = {
// "Front" vertices
{ -700.0, -700.0, 700.0 },{ 700.0, -700.0, 700.0 },{ 700.0, 700.0, 700.0 },{ -700.0, 700.0, 700.0 },
// {-900.0, -900.0, 900.0}, {900.0, -900.0, 900.0}, {900.0, 900.0, 900.0}, {-900.0, 900.0, 900.0},
// "Back" vertices
{ -700.0, -700.0, -700.0 },{ 700.0, -700.0, -700.0 },{ 700.0, 700.0, -700.0 },{ -700.0, 700.0, -700.0 }
// {-900.0, -900.0, -900.0}, {900.0, -900.0, -900.0}, {900.0, 900.0, -900.0}, {-900.0, 900.0, -900.0}
};
// Note that GL_QUADS is deprecated in modern OpenGL (and removed from OSX systems).
// This is why we need to draw each face as 2 triangles instead of 1 quadrilateral
const GLuint indices[6][6] = {
// Front face
{ 0, 1, 2, 2, 3, 0 },
// {2, 1, 0, 0, 3, 2},
// Top face
{ 1, 5, 6, 6, 2, 1 },
// {6, 5, 1, 1, 2, 6},
// Back face
{ 7, 6, 5, 5, 4, 7 },
// {5, 6, 7, 7, 4, 5},
// Bottom face
{ 4, 0, 3, 3, 7, 4 },
// {3, 0, 4, 4, 7, 3},
// Left face
{ 4, 5, 1, 1, 0, 4 },
// {1, 5, 4, 4, 0, 1},
// Right face
{ 3, 2, 6, 6, 7, 3 }
// {6, 2, 3, 3, 7, 6}
};
};
#endif
| [
"liz100@UCSD.EDU"
] | liz100@UCSD.EDU |
17cae5bb55af685f88bab4fc43e7faab8d3aa818 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/skia/gm/filterbitmap.cpp | 1ec6c8f378b8331195ef6869af61abf2e3c8dfc4 | [
"BSD-3-Clause",
"SGI-B-2.0",
"MIT"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 6,925 | cpp | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"
#include "SkImageDecoder.h"
#include "SkStream.h"
static void setTypeface(SkPaint* paint, const char name[], SkTypeface::Style style) {
SkSafeUnref(paint->setTypeface(SkTypeface::CreateFromName(name, style)));
}
static SkSize computeSize(const SkBitmap& bm, const SkMatrix& mat) {
SkRect bounds = SkRect::MakeWH(SkIntToScalar(bm.width()),
SkIntToScalar(bm.height()));
mat.mapRect(&bounds);
return SkSize::Make(bounds.width(), bounds.height());
}
static void draw_col(SkCanvas* canvas, const SkBitmap& bm, const SkMatrix& mat,
SkScalar dx) {
SkPaint paint;
SkAutoCanvasRestore acr(canvas, true);
canvas->drawBitmapMatrix(bm, mat, &paint);
paint.setFilterLevel(SkPaint::kLow_FilterLevel);
canvas->translate(dx, 0);
canvas->drawBitmapMatrix(bm, mat, &paint);
paint.setFilterLevel(SkPaint::kHigh_FilterLevel);
canvas->translate(dx, 0);
canvas->drawBitmapMatrix(bm, mat, &paint);
}
class FilterBitmapGM : public skiagm::GM {
void onOnceBeforeDraw() {
make_bitmap();
SkScalar cx = SkScalarHalf(fBM.width());
SkScalar cy = SkScalarHalf(fBM.height());
SkScalar scale = get_scale();
fMatrix[0].setScale(scale, scale);
fMatrix[1].setRotate(30, cx, cy); fMatrix[1].postScale(scale, scale);
}
public:
SkBitmap fBM;
SkMatrix fMatrix[2];
SkString fName;
FilterBitmapGM()
{
this->setBGColor(0xFFDDDDDD);
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return fName;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(920, 480);
}
virtual void make_bitmap() = 0;
virtual SkScalar get_scale() = 0;
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
canvas->translate(10, 10);
for (size_t i = 0; i < SK_ARRAY_COUNT(fMatrix); ++i) {
SkSize size = computeSize(fBM, fMatrix[i]);
size.fWidth += 20;
size.fHeight += 20;
draw_col(canvas, fBM, fMatrix[i], size.fWidth);
canvas->translate(0, size.fHeight);
}
}
private:
typedef skiagm::GM INHERITED;
};
class FilterBitmapTextGM: public FilterBitmapGM {
public:
FilterBitmapTextGM(float textSize)
: fTextSize(textSize)
{
fName.printf("filterbitmap_text_%.2fpt", fTextSize);
}
protected:
float fTextSize;
SkScalar get_scale() SK_OVERRIDE {
return 32.f/fTextSize;
}
void make_bitmap() SK_OVERRIDE {
fBM.setConfig(SkBitmap::kARGB_8888_Config, int(fTextSize * 8), int(fTextSize * 6));
fBM.allocPixels();
SkCanvas canvas(fBM);
canvas.drawColor(SK_ColorWHITE);
SkPaint paint;
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTextSize(fTextSize);
setTypeface(&paint, "Times", SkTypeface::kNormal);
canvas.drawText("Hamburgefons", 12, fTextSize/2, 1.2f*fTextSize, paint);
setTypeface(&paint, "Times", SkTypeface::kBold);
canvas.drawText("Hamburgefons", 12, fTextSize/2, 2.4f*fTextSize, paint);
setTypeface(&paint, "Times", SkTypeface::kItalic);
canvas.drawText("Hamburgefons", 12, fTextSize/2, 3.6f*fTextSize, paint);
setTypeface(&paint, "Times", SkTypeface::kBoldItalic);
canvas.drawText("Hamburgefons", 12, fTextSize/2, 4.8f*fTextSize, paint);
}
private:
typedef FilterBitmapGM INHERITED;
};
class FilterBitmapCheckerboardGM: public FilterBitmapGM {
public:
FilterBitmapCheckerboardGM(int size, int num_checks)
: fSize(size), fNumChecks(num_checks)
{
fName.printf("filterbitmap_checkerboard_%d_%d", fSize, fNumChecks);
}
protected:
int fSize;
int fNumChecks;
SkScalar get_scale() SK_OVERRIDE {
return 192.f/fSize;
}
void make_bitmap() SK_OVERRIDE {
fBM.setConfig(SkBitmap::kARGB_8888_Config, fSize, fSize);
fBM.allocPixels();
SkAutoLockPixels lock(fBM);
for (int y = 0; y < fSize; y ++) {
for (int x = 0; x < fSize; x ++) {
SkPMColor* s = fBM.getAddr32(x, y);
int cx = (x * fNumChecks) / fSize;
int cy = (y * fNumChecks) / fSize;
if ((cx+cy)%2) {
*s = 0xFFFFFFFF;
} else {
*s = 0xFF000000;
}
}
}
}
private:
typedef FilterBitmapGM INHERITED;
};
class FilterBitmapImageGM: public FilterBitmapGM {
public:
FilterBitmapImageGM(const char filename[])
: fFilename(filename)
{
fName.printf("filterbitmap_image_%s", filename);
}
protected:
SkString fFilename;
int fSize;
SkScalar get_scale() SK_OVERRIDE {
return 192.f/fSize;
}
void make_bitmap() SK_OVERRIDE {
SkString path(skiagm::GM::gResourcePath);
path.append("/");
path.append(fFilename);
SkImageDecoder *codec = NULL;
SkFILEStream stream(path.c_str());
if (stream.isValid()) {
codec = SkImageDecoder::Factory(&stream);
}
if (codec) {
stream.rewind();
codec->decode(&stream, &fBM, SkBitmap::kARGB_8888_Config,
SkImageDecoder::kDecodePixels_Mode);
SkDELETE(codec);
} else {
fBM.setConfig(SkBitmap::kARGB_8888_Config, 1, 1);
fBM.allocPixels();
*(fBM.getAddr32(0,0)) = 0xFF0000FF; // red == bad
}
fSize = fBM.height();
}
private:
typedef FilterBitmapGM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new FilterBitmapTextGM(3); )
DEF_GM( return new FilterBitmapTextGM(7); )
DEF_GM( return new FilterBitmapTextGM(10); )
DEF_GM( return new FilterBitmapCheckerboardGM(4,4); )
DEF_GM( return new FilterBitmapCheckerboardGM(32,32); )
DEF_GM( return new FilterBitmapCheckerboardGM(32,8); )
DEF_GM( return new FilterBitmapCheckerboardGM(32,2); )
DEF_GM( return new FilterBitmapCheckerboardGM(192,192); )
DEF_GM( return new FilterBitmapImageGM("mandrill_16.png"); )
DEF_GM( return new FilterBitmapImageGM("mandrill_32.png"); )
DEF_GM( return new FilterBitmapImageGM("mandrill_64.png"); )
DEF_GM( return new FilterBitmapImageGM("mandrill_128.png"); )
DEF_GM( return new FilterBitmapImageGM("mandrill_256.png"); )
DEF_GM( return new FilterBitmapImageGM("mandrill_512.png"); )
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
87cc36133f8e853bff38eb9bc9d4a7a5a2094035 | c98a75a0441994ab11195bf4d5cb068fd9e94026 | /physics/kernel/management/inc/Geant/PostStepActionPhysModelHandler.h | e5b3494096bba9c8d17b15b5623d7bcf6366a380 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | amadio/geant | 7d7237c8c48855cdf9225eb864366a4bdad6e125 | a46790aa9eb3663f8324320a71e993d73ca443da | refs/heads/master | 2020-04-06T04:35:44.331502 | 2019-08-27T15:23:58 | 2019-08-27T15:23:58 | 59,431,197 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,294 | h | //===--- PostStepActionPhysModelHandler.h - Geant-V -------------*- C++ -*-===//
//
// Geant-V Prototype
//
//===----------------------------------------------------------------------===//
/**
* @file PostStepActionPhysModelHandler.h
* @brief Implementation of post step action handler for vectorized EM transport
* @author Vitalii Drohan
*/
//===----------------------------------------------------------------------===//
#ifndef POSTSTEPACTIONPHYSPROCESSHANDLER_H
#define POSTSTEPACTIONPHYSPROCESSHANDLER_H
// from geantV
#include "Geant/Handler.h"
// from geantV
namespace geant {
inline namespace GEANT_IMPL_NAMESPACE {
class Propagator;
class Track;
class TaskData;
class Basket;
}
}
namespace geantphysics {
class EMModel;
/**
* @brief Handler for post-step actions specific for physics process (discrete interactions).
* @class PostStepActionPhysProcessHandler
*
* This handler is used only for specific EM physics model in order to use vectorization over basket of particles which
* are undergoing same model sampling.
* (based on PostStepActionHandler by M. Novak)
*/
class PostStepActionPhysModelHandler : public geant::Handler {
public:
/** @brief Default constructor */
PostStepActionPhysModelHandler() : geant::Handler() {}
/**
* @brief Default constructor
* @param propagator Propagator working with this handler
*/
PostStepActionPhysModelHandler(int threshold, geant::Propagator *propagator, int modelIdx);
/** @brief dtr */
virtual ~PostStepActionPhysModelHandler();
/** @brief Scalar DoIt interface */
virtual void DoIt(geant::Track *track, geant::Basket &output, geant::TaskData *td);
/** @brief Vector DoIt interface. Base class implements it as a loop. */
virtual void DoIt(geant::Basket &input, geant::Basket &output, geant::TaskData *td);
private:
PostStepActionPhysModelHandler(const PostStepActionPhysModelHandler &) = delete;
PostStepActionPhysModelHandler &operator=(const PostStepActionPhysModelHandler &) = delete;
void DoItVector(geant::Track **gtracks, int N, geant::Basket &output, geant::TaskData *td);
void DoItScalar(geant::Track **gtracks, int N, geant::Basket &output, geant::TaskData *td);
EMModel *fModel;
};
} // namespace geantphysics
#endif // POSTSTEPACTIONHANDLER_H
| [
"vitalii.drohan@cern.ch"
] | vitalii.drohan@cern.ch |
98eb74d28a8ee8ec7567b7a5c93f81aacd5bde63 | c451db45f27dc9fbc2d8b133d6ff07b87c57de53 | /SkyboxA13/main.cpp | 95bcb13bb5c78284b5994c03bc06a5bc05652503 | [] | no_license | LexaFayte/SkyBoxCPP1 | ca15a34c36c728deb954d8420f24caacdd8c1c26 | 02aab5a8d388cb1ec681d73ef70d66299a255af9 | refs/heads/master | 2021-05-02T15:30:25.002457 | 2018-05-14T03:45:18 | 2018-05-14T03:45:18 | 120,697,372 | 1 | 0 | null | 2018-05-14T03:45:52 | 2018-02-08T02:03:19 | C++ | UTF-8 | C++ | false | false | 1,992 | cpp | #include <iostream>
#include <vector>
#include <ctime>
#include "Shorse.h"
#include "Platyporse.h"
#define ARRAY_MAX 4
#define RAND_MAX 100
#define FLOAT_MOD 1.653257
namespace Utils
{
inline float getRandomFloat()
{
return ((rand() % RAND_MAX) + 1) * FLOAT_MOD;
}
inline int getRandomInt()
{
return (rand() % RAND_MAX) + 1;
}
template<typename T>
const T* GetLargestItem(const T* items, unsigned int itemsSize)
{
const T* largest = items;
for (int i = 0; i < itemsSize; ++i)
{
if (*largest < *(items + i))
{
largest = items + i;
}
}
return largest;
}
template<typename T>
const T* GetSmallestItem(const T* items, unsigned int itemsSize)
{
const T* smallest = items;
for (int i = 0; i < itemsSize; ++i)
{
if (*(items + i) < *smallest)
{
smallest = items + i;
}
}
return smallest;
}
}
int main()
{
using namespace Utils;
srand(time(0));
Shorse shorses[ARRAY_MAX] = {Shorse(getRandomInt()),Shorse(getRandomInt()) ,Shorse(getRandomInt()) ,Shorse(getRandomInt())};
Platyporse platyporses[ARRAY_MAX] = {Platyporse(getRandomFloat()), Platyporse(getRandomFloat()), Platyporse(getRandomFloat()), Platyporse(getRandomFloat())};
const Shorse* s = GetLargestItem(shorses, ARRAY_MAX);
const Platyporse* p = GetLargestItem(platyporses, ARRAY_MAX);
std::cout << "the Shorse with " << s->GetNumberOfTeeth() << " teeth is the largest item in the array of Shorses" << std::endl;
std::cout << "the Platyporse with a bill length of " << p->GetLengthOfBill() << " is the largest item in the array of Platyporses" << std::endl;
s = GetSmallestItem(shorses, ARRAY_MAX);
p = GetSmallestItem(platyporses, ARRAY_MAX);
std::cout << "the Shorse with " << s->GetNumberOfTeeth() << " teeth is the smallest item in the array of Shorses" << std::endl;
std::cout << "the Platyporse with a bill length of " << p->GetLengthOfBill() << " is the smallest item in the array of Platyporses" << std::endl;
system("pause");
return 0;
}
| [
"luciferfayte@hotmail.com"
] | luciferfayte@hotmail.com |
65fd402e3a1068959d948b331791061ed2750512 | b15c487b4865ac52bf51a97ba00e7ce556e0b27b | /UVA Solved/10370.cpp | 1b104de4d63ab50062c027d071ec8bcd288327a7 | [] | no_license | Mehedi32HSTU/UVA-Online-Judge-Code | 52b033c25d913acc5e93db001d5f6d99b583d341 | b34c185c5a1e48cd427b77c5fd9e0c9cfb869650 | refs/heads/master | 2020-08-06T06:01:29.365669 | 2019-10-04T17:02:37 | 2019-10-04T17:02:37 | 212,862,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | cpp | #include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cmath>
#include<math.h>
using namespace std;
int main()
{
int C;
cin>>C;
for(int t=1;t<=C;t++)
{
int N,count;
cin>>N;
float percentag,g[1002],avrg;
for(int j=0;j<N;j++)
{
cin>>g[j];
}
int sum=0;
for(int j=0;j<N;j++)
{
sum+=g[j];
}
avrg=sum/N;
count = 0;
for(int j=0;j<N;j++)
{
if(avrg<g[j]) count++;
}
percentag=(float)(100*count)/N;
printf("%.3f%%\n",percentag);
}
return 0;
}
| [
"mehedi32.cse.hstu@gmail.com"
] | mehedi32.cse.hstu@gmail.com |
53ca96929ecf8063b19d81194ab4fb7370fbb1ae | 23b8cde8ca347c97782c474da0ff6eb3a040e744 | /buttcoin-master/src/qt/paymentserver.h | 80ffcac5707ef9702af197ddae8dd6831afaeb28 | [
"MIT"
] | permissive | derektopper/ButtCoin | 4e602f362b85b11dc9de406729ff9ddcc7b0a22d | 34ccc23ab70960acef75a4d0b4e5e1e2d391cc5a | refs/heads/master | 2021-05-12T17:36:02.340833 | 2018-01-11T04:35:08 | 2018-01-11T04:35:08 | 117,048,280 | 0 | 1 | null | 2018-01-11T04:33:38 | 2018-01-11T04:05:16 | C++ | UTF-8 | C++ | false | false | 5,096 | h | // Copyright (c) 2011-2016 The buttcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef buttcoin_QT_PAYMENTSERVER_H
#define buttcoin_QT_PAYMENTSERVER_H
// This class handles payment requests from clicking on
// buttcoin: URIs
//
// This is somewhat tricky, because we have to deal with
// the situation where the user clicks on a link during
// startup/initialization, when the splash-screen is up
// but the main window (and the Send Coins tab) is not.
//
// So, the strategy is:
//
// Create the server, and register the event handler,
// when the application is created. Save any URIs
// received at or during startup in a list.
//
// When startup is finished and the main window is
// shown, a signal is sent to slot uiReady(), which
// emits a receivedURI() signal for any payment
// requests that happened during startup.
//
// After startup, receivedURI() happens as usual.
//
// This class has one more feature: a static
// method that finds URIs passed in the command line
// and, if a server is running in another process,
// sends them to the server.
//
#include <qt/paymentrequestplus.h>
#include <qt/walletmodel.h>
#include <QObject>
#include <QString>
class OptionsModel;
class CWallet;
QT_BEGIN_NAMESPACE
class QApplication;
class QByteArray;
class QLocalServer;
class QNetworkAccessManager;
class QNetworkReply;
class QSslError;
class QUrl;
QT_END_NAMESPACE
// BIP70 max payment request size in bytes (DoS protection)
static const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000;
class PaymentServer : public QObject
{
Q_OBJECT
public:
// Parse URIs on command line
// Returns false on error
static void ipcParseCommandLine(int argc, char *argv[]);
// Returns true if there were URIs on the command line
// which were successfully sent to an already-running
// process.
// Note: if a payment request is given, SelectParams(MAIN/TESTNET)
// will be called so we startup in the right mode.
static bool ipcSendCommandLine();
// parent should be QApplication object
explicit PaymentServer(QObject* parent, bool startLocalServer = true);
~PaymentServer();
// Load root certificate authorities. Pass nullptr (default)
// to read from the file specified in the -rootcertificates setting,
// or, if that's not set, to use the system default root certificates.
// If you pass in a store, you should not X509_STORE_free it: it will be
// freed either at exit or when another set of CAs are loaded.
static void LoadRootCAs(X509_STORE* store = nullptr);
// Return certificate store
static X509_STORE* getCertStore();
// OptionsModel is used for getting proxy settings and display unit
void setOptionsModel(OptionsModel *optionsModel);
// Verify that the payment request network matches the client network
static bool verifyNetwork(const payments::PaymentDetails& requestDetails);
// Verify if the payment request is expired
static bool verifyExpired(const payments::PaymentDetails& requestDetails);
// Verify the payment request size is valid as per BIP70
static bool verifySize(qint64 requestSize);
// Verify the payment request amount is valid
static bool verifyAmount(const CAmount& requestAmount);
Q_SIGNALS:
// Fired when a valid payment request is received
void receivedPaymentRequest(SendCoinsRecipient);
// Fired when a valid PaymentACK is received
void receivedPaymentACK(const QString &paymentACKMsg);
// Fired when a message should be reported to the user
void message(const QString &title, const QString &message, unsigned int style);
public Q_SLOTS:
// Signal this when the main window's UI is ready
// to display payment requests to the user
void uiReady();
// Submit Payment message to a merchant, get back PaymentACK:
void fetchPaymentACK(CWallet* wallet, const SendCoinsRecipient& recipient, QByteArray transaction);
// Handle an incoming URI, URI with local file scheme or file
void handleURIOrFile(const QString& s);
private Q_SLOTS:
void handleURIConnection();
void netRequestFinished(QNetworkReply*);
void reportSslErrors(QNetworkReply*, const QList<QSslError> &);
void handlePaymentACK(const QString& paymentACKMsg);
protected:
// Constructor registers this on the parent QApplication to
// receive QEvent::FileOpen and QEvent:Drop events
bool eventFilter(QObject *object, QEvent *event);
private:
static bool readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request);
bool processPaymentRequest(const PaymentRequestPlus& request, SendCoinsRecipient& recipient);
void fetchRequest(const QUrl& url);
// Setup networking
void initNetManager();
bool saveURIs; // true during startup
QLocalServer* uriServer;
QNetworkAccessManager* netManager; // Used to fetch payment requests
OptionsModel *optionsModel;
};
#endif // buttcoin_QT_PAYMENTSERVER_H
| [
"derektopper@berkeley.edu"
] | derektopper@berkeley.edu |
ab9f2060f1e7caa5168c71807be742aa58ac8638 | 8a0de1a7c26ef5d62f3d021cb800c764948ed194 | /vector.h | 339fdd36f6d1baaf3a1711eb7dd1254146da2c6f | [] | no_license | NeonRice/rice-vector | 1c27328671cffd8849951d1d9213b1bb1aac63fd | b892c4372161c4146781538ab07329cc5a418b20 | refs/heads/master | 2022-08-03T10:46:36.107649 | 2020-05-27T08:44:59 | 2020-05-27T08:44:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,516 | h | #pragma once
#include <cstddef>
#include <iterator>
#include <stdexcept>
#include <memory>
#include <iostream>
namespace rice
{
template <typename T>
class vector
{
public:
// Type definitions
typedef T value_type;
typedef std::allocator<T> allocator_type;
typedef T &reference;
typedef const T &const_reference;
typedef T *pointer;
typedef const T *const_pointer;
typedef T *iterator;
typedef const T *const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef ptrdiff_t difference_type;
typedef unsigned int size_type;
// Constructors
vector();
vector(size_type n, const T &val = T{});
vector(vector<T>::iterator first, vector<T>::iterator last);
vector(std::initializer_list<T>);
vector(const vector<T> &);
vector(vector<T> &&);
~vector();
// Copy initializers
vector<T> &operator=(const vector<T> &);
vector<T> &operator=(vector<T> &&);
vector<T> &operator=(std::initializer_list<T>);
void assign(size_type, const T &value);
void assign(vector<T>::iterator, vector<T>::iterator);
void assign(std::initializer_list<T>);
// Iterators
iterator begin();
const_iterator cbegin() const;
iterator end();
const_iterator cend() const;
reverse_iterator rbegin();
const_reverse_iterator crbegin() const;
reverse_iterator rend();
const_reverse_iterator crend() const;
bool empty() const;
size_type size() const;
size_type max_size() const;
size_type capacity() const;
size_type getReallocateCnt() const;
void resize(size_type);
void resize(size_type, const T &);
void reserve(size_type);
void shrink_to_fit();
// Operator overloading
reference operator[](size_type);
const_reference operator[](size_type) const;
reference at(size_type);
const_reference at(size_type) const;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
T *data();
const T *data() const;
allocator_type getAllocator() const;
template <class... Args>
void emplace_back(Args &&... args);
void push_back(const T &);
void push_back(T &&);
void pop_back();
template <class... Args>
iterator emplace(const_iterator, Args &&...);
iterator insert(const_iterator, const T &el = T());
iterator insert(const_iterator, T &&el = T());
iterator insert(const_iterator, size_type, const T &);
template <class InputIt>
iterator insert(const_iterator, InputIt, InputIt);
iterator insert(const_iterator, std::initializer_list<T>);
iterator erase(const_iterator);
iterator erase(const_iterator, const_iterator);
void swap(vector<T> &);
void clear();
// Operator overloading
bool operator==(const vector<T> &) const;
bool operator!=(const vector<T> &) const;
private:
size_type vec_sz = 0, cap_sz = 6, reallocateCnt = 0;
T *buffer;
allocator_type allocator;
// Helper functions
inline void reallocate();
inline void grow_allocate(size_type);
inline void grow_reallocate(size_type);
};
template <typename T>
vector<T>::vector()
{
try
{
buffer = allocator.allocate(cap_sz);
}
catch (const std::exception &e)
{
std::cerr << "Allocation Error: " << e.what() << '\n';
}
}
template <typename T>
vector<T>::vector(vector<T>::size_type n, const T &value)
{
grow_allocate(n);
std::uninitialized_fill(buffer, buffer + n, value);
vec_sz = n;
}
template <typename T>
vector<T>::vector(vector<T>::iterator first, vector<T>::iterator last)
{
size_type cnt = last - first;
grow_allocate(cnt);
std::uninitialized_fill(buffer, buffer + cnt, *first);
vec_sz = cnt;
}
template <typename T>
vector<T>::vector(std::initializer_list<T> list)
{
grow_allocate(list.size());
for (auto &item : list)
buffer[vec_sz++] = item;
}
template <typename T>
vector<T>::vector(const vector<T> &other)
{
cap_sz = other.cap_sz, vec_sz = other.vec_sz;
buffer = allocator.allocate(cap_sz);
std::uninitialized_copy(other.buffer, other.buffer + other.vec_sz, buffer);
/* for (size_type i = 0; i < other.vec_sz; ++i)
buffer[i] = other.buffer[i]; */
}
template <typename T>
vector<T>::vector(vector<T> &&other)
{
cap_sz = other.cap_sz, vec_sz = other.vec_sz;
buffer = allocator.allocate(cap_sz);
std::uninitialized_copy(other.buffer, other.buffer + other.vec_sz, buffer);
/* for (size_type i = 0; i < other.vec_sz; ++i)
buffer[i] = std::move(other.buffer[i]); */
}
template <typename T>
vector<T>::~vector()
{
allocator.deallocate(buffer, cap_sz);
}
template <typename T>
vector<T> &vector<T>::operator=(const vector<T> &other)
{
if (cap_sz < other.vec_sz)
{
cap_sz = other.vec_sz << 2;
reallocate();
}
std::uninitialized_copy(other.buffer, other.buffer + other.vec_sz, buffer);
/* for (size_type i = 0; i < other.vec_sz; ++i)
buffer[i] = other.buffer[i]; */
vec_sz = other.vec_sz;
}
template <typename T>
vector<T> &vector<T>::operator=(vector<T> &&other)
{
std::cout << "REALLOCATED" << std::endl;
if (cap_sz < other.cap_sz)
{
cap_sz = other.cap_sz << 2;
reallocate();
}
std::uninitialized_copy(other.buffer, other.buffer + other.vec_sz, buffer);
/* for (size_type i = 0; i < other.vec_sz; ++i)
buffer[i] = std::move(other.buffer[i]); */
vec_sz = other.vec_sz;
}
template <typename T>
vector<T> &vector<T>::operator=(std::initializer_list<T> list)
{
if (cap_sz < list.size())
grow_reallocate(list.size());
vec_sz = 0;
/* for (auto &item : list)
buffer[vec_sz++] = item; */
std::uninitialized_copy(list.begin(), list.end(), buffer);
}
template <typename T>
void vector<T>::assign(vector<T>::size_type count, const T &value)
{
if (count > cap_sz)
grow_reallocate(count);
for (size_type i = 0; i < count; ++i)
buffer[i] = value;
vec_sz = count;
}
template <typename T>
void vector<T>::assign(vector<T>::iterator first, vector<T>::iterator last)
{
size_type count = last - first;
if (count > cap_sz)
grow_reallocate(count);
for (size_type i = 0; i < count; ++i, ++first)
buffer[i] = *first;
vec_sz = count;
}
template <typename T>
void vector<T>::assign(std::initializer_list<T> list)
{
size_type i, count = list.size();
if (count > cap_sz)
grow_reallocate(count);
i = 0;
for (auto &item : list)
buffer[i++] = item;
vec_sz = list.size(); //change here?
}
template <typename T>
typename vector<T>::iterator vector<T>::begin()
{
return buffer;
}
template <typename T>
typename vector<T>::const_iterator vector<T>::cbegin() const
{
return buffer;
}
template <typename T>
typename vector<T>::iterator vector<T>::end()
{
return buffer + vec_sz;
}
template <typename T>
typename vector<T>::const_iterator vector<T>::cend() const
{
return buffer + vec_sz;
}
template <typename T>
typename vector<T>::reverse_iterator vector<T>::rbegin()
{
return reverse_iterator(buffer + vec_sz);
}
template <typename T>
typename vector<T>::const_reverse_iterator vector<T>::crbegin() const
{
return reverse_iterator(buffer + vec_sz);
}
template <typename T>
typename vector<T>::reverse_iterator vector<T>::rend()
{
return reverse_iterator(buffer);
}
template <typename T>
typename vector<T>::const_reverse_iterator vector<T>::crend() const
{
return reverse_iterator(buffer);
}
template <typename T>
inline void vector<T>::reallocate()
{
++reallocateCnt;
try
{
T *temp_buffer = allocator.allocate(cap_sz);
std::uninitialized_copy(buffer, buffer + vec_sz, temp_buffer);
allocator.deallocate(buffer, cap_sz);
buffer = temp_buffer;
}
catch (const std::exception &e)
{
std::cerr << "Allocation Error: " << e.what() << '\n';
}
}
template <typename T>
inline void vector<T>::grow_allocate(vector<T>::size_type n)
{
cap_sz = n << 2;
try
{
buffer = allocator.allocate(cap_sz);
}
catch (const std::exception &e)
{
std::cerr << "Allocation Error: " << e.what() << '\n';
}
}
template <typename T>
inline typename vector<T>::size_type vector<T>::getReallocateCnt() const
{
return reallocateCnt;
}
template <typename T>
inline void vector<T>::grow_reallocate(vector<T>::size_type n)
{
cap_sz = n << 2;
reallocate();
}
template <typename T>
inline bool vector<T>::empty() const
{
return vec_sz == 0;
}
template <typename T>
inline typename vector<T>::size_type vector<T>::size() const
{
return vec_sz;
}
template <typename T>
inline typename vector<T>::size_type vector<T>::max_size() const
{
return allocator.max_size();
}
template <typename T>
inline typename vector<T>::size_type vector<T>::capacity() const
{
return cap_sz;
}
template <typename T>
void vector<T>::resize(typename vector<T>::size_type size)
{
if (size > vec_sz)
{
if (size > vec_sz)
{
cap_sz = size;
reallocate();
}
}
else
{
for (size_type i = vec_sz; i < size; ++i)
allocator.destroy(buffer + i);
}
vec_sz = size;
}
template <typename T>
void vector<T>::resize(typename vector<T>::size_type size, const T &c)
{
if (size > vec_sz)
{
if (size > cap_sz)
{
cap_sz = size;
reallocate();
}
for (size_type i = vec_sz; i < size; ++i)
buffer[i] = c;
}
else
{
for (size_type i = vec_sz; i < size; ++i)
allocator.destroy(buffer + i);
}
vec_sz = size;
}
template <typename T>
void vector<T>::reserve(typename vector<T>::size_type size)
{
if (size > cap_sz)
{
cap_sz = size;
reallocate();
}
}
template <typename T>
void vector<T>::shrink_to_fit()
{
cap_sz = vec_sz;
reallocate();
}
template <typename T>
typename vector<T>::reference vector<T>::operator[](typename vector<T>::size_type index)
{
return buffer[index];
}
template <typename T>
typename vector<T>::const_reference vector<T>::operator[](typename vector<T>::size_type index) const
{
return buffer[index];
}
template <typename T>
typename vector<T>::reference vector<T>::at(size_type pos)
{
if (pos < vec_sz)
return buffer[pos];
else
throw std::out_of_range("Position not in element range");
}
template <typename T>
typename vector<T>::const_reference vector<T>::at(size_type pos) const
{
if (pos < vec_sz)
return buffer[pos];
else
throw std::out_of_range("Position not in element range");
}
template <typename T>
typename vector<T>::reference vector<T>::front()
{
return buffer[0];
}
template <typename T>
typename vector<T>::const_reference vector<T>::front() const
{
return buffer[0];
}
template <typename T>
typename vector<T>::reference vector<T>::back()
{
return buffer[vec_sz - 1];
}
template <typename T>
typename vector<T>::const_reference vector<T>::back() const
{
return buffer[vec_sz - 1];
}
template <typename T>
T *vector<T>::data()
{
return buffer;
}
template <typename T>
const T *vector<T>::data() const
{
return buffer;
}
template <typename T>
typename vector<T>::allocator_type vector<T>::getAllocator() const
{
return allocator;
}
template <typename T>
template <class... Args>
void vector<T>::emplace_back(Args &&... args)
{
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
buffer[vec_sz++] = std::move(T(std::forward<Args>(args)...));
}
template <typename T>
void vector<T>::push_back(const T &val)
{
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
allocator.construct(buffer + vec_sz++, val);
}
template <typename T>
void vector<T>::push_back(T &&val)
{
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
allocator.construct(buffer + vec_sz++, val);
}
template <typename T>
void vector<T>::pop_back()
{
allocator.destroy(buffer + vec_sz--);
}
template <typename T>
template <class... Args>
typename vector<T>::iterator vector<T>::emplace(vector<T>::const_iterator pos, Args &&... args)
{
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
iterator it = &buffer[pos - buffer];
std::uninitialized_move(it, buffer + vec_sz, it + 1);
(*it) = std::move(T(std::forward<Args>(args)...));
++vec_sz;
return it;
}
template <typename T>
typename vector<T>::iterator vector<T>::insert(const_iterator pos, const T &val)
{
size_type index = pos - buffer;
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
iterator it = &buffer[index];
std::uninitialized_move(it, buffer + vec_sz, it + 1);
(*it) = val;
++vec_sz;
return it;
}
template <typename T>
typename vector<T>::iterator vector<T>::insert(const_iterator pos, T &&val)
{
size_type index = pos - buffer;
if (vec_sz == cap_sz)
grow_reallocate(cap_sz);
iterator it = &buffer[index];
std::uninitialized_move(it, buffer + vec_sz, it + 1);
(*it) = val;
++vec_sz;
return it;
}
template <typename T>
typename vector<T>::iterator vector<T>::insert(vector<T>::const_iterator pos, vector<T>::size_type cnt, const T &val)
{
iterator f = &buffer[pos - buffer];
if (!cnt)
return f;
if (vec_sz + cnt > cap_sz)
grow_reallocate(vec_sz + cnt);
std::uninitialized_move(f, buffer + vec_sz, f + cnt);
vec_sz += cnt;
for (iterator pos = f; cnt--; ++pos)
(*pos) = val;
return f;
}
template <typename T>
template <class InputIt>
typename vector<T>::iterator vector<T>::insert(vector<T>::const_iterator pos, InputIt first, InputIt last)
{
iterator f = &buffer[pos - buffer];
size_type cnt = last - first;
if (!cnt)
return f;
if (vec_sz + cnt > cap_sz)
grow_reallocate(vec_sz + cnt);
std::uninitialized_move(f, buffer + vec_sz, f + cnt);
for (iterator pos = f; first != last; ++pos, ++first)
(*pos) = *first;
vec_sz += cnt;
return f;
}
template <typename T>
typename vector<T>::iterator vector<T>::insert(vector<T>::const_iterator pos, std::initializer_list<T> list)
{
size_type cnt = list.size();
if (vec_sz + cnt > cap_sz)
grow_reallocate(vec_sz + cnt);
iterator f = &buffer[pos - buffer];
if (!cnt)
return f;
std::uninitialized_move(f, buffer + vec_sz, f + cnt);
iterator it = f;
for (auto &item : list)
{
(*it) = item;
++it;
}
vec_sz += cnt;
return f;
}
template <typename T>
typename vector<T>::iterator vector<T>::erase(vector<T>::const_iterator pos)
{
iterator it = &buffer[pos - buffer];
allocator.destroy(it);
std::uninitialized_move(it + 1, buffer + vec_sz, it);
--vec_sz;
return it;
}
template <typename T>
typename vector<T>::iterator vector<T>::erase(const_iterator first, const_iterator last)
{
iterator f = &buffer[first - buffer], l = &buffer[last - buffer], d = f;
if (first == last)
return f;
for (; d != l; ++d)
allocator.destroy(d);
std::uninitialized_move(l, buffer + vec_sz, f);
vec_sz -= last - first;
return f;
}
template <typename T>
void vector<T>::swap(vector<T> &rhs)
{
size_t temp_vec_sz = vec_sz,
temp_cap_sz = cap_sz;
T *temp_buffer = buffer;
vec_sz = rhs.vec_sz;
vec_sz = rhs.vec_sz;
buffer = rhs.buffer;
rhs.vec_sz = temp_vec_sz;
rhs.vec_sz = temp_cap_sz;
rhs.buffer = temp_buffer;
}
template <typename T>
void vector<T>::clear()
{
for (size_type i = 0; i < vec_sz; ++i)
allocator.destroy(buffer + i);
vec_sz = 0;
}
template <typename T>
bool vector<T>::operator==(const vector<T> &rhs) const
{
if (vec_sz != rhs.vec_sz)
return false;
for (size_type i = 0; i < vec_sz; ++i)
if (buffer[i] != rhs.buffer[i])
return false;
return true;
}
template <typename T>
bool vector<T>::operator!=(const vector<T> &rhs) const
{
if (vec_sz != rhs.vec_sz)
return true;
for (size_type i = 0; i < vec_sz; ++i)
if (buffer[i] != rhs.buffer[i])
return true;
return false;
}
} // namespace rice
| [
"john@DESKTOP-0MMFBST.localdomain"
] | john@DESKTOP-0MMFBST.localdomain |
d999c09406370279f6c0bb872e94a9225c2f5203 | 0e9de167c9f587d71cbdec78794054ae41fed440 | /src/MsgMgr/ListMsgsDialog.h | 07605d15786294f6faa980fdf24a17ef8f3f75cc | [] | no_license | FirebirdSQL/x-cvs-vulcan | 10d01433df4e670977409817a71675f78e1deed1 | ba93778a72e348c0fbef4de6471a448ac5606f73 | refs/heads/master | 2023-08-03T01:31:05.900834 | 2009-03-04T16:18:54 | 2009-03-04T16:18:54 | 110,444,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h | #pragma once
#include "afxwin.h"
class Database;
enum Order {
none,
number,
symbol,
text
};
// ListMsgsDialog dialog
class ListMsgsDialog : public CDialog
{
DECLARE_DYNAMIC(ListMsgsDialog)
public:
ListMsgsDialog(CWnd* pParent = NULL); // standard constructor
virtual ~ListMsgsDialog();
// Dialog Data
enum { IDD = IDD_LIST_MESSAGES };
Database *database;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog(void);
void populate(Database* database);
CComboBox facilities;
CString facility;
Order order;
afx_msg void OnBnClickedOrderNumber();
afx_msg void OnBnClickedOrderSymbol();
afx_msg void OnBnClickedOrderText();
CString containing;
};
| [
"jimstarkey@users.sourceforge.net"
] | jimstarkey@users.sourceforge.net |
0bf6cd360da7d14a9cc0d2f44b072ff9f572c6f2 | bb864e905a69b6dbe07a97d6d31d9b47cc97dabb | /UFPT/transposematrix.cpp | 1c551979fec5eb47ae152b7b3c25c535d7568fda | [] | no_license | k--chow/CompetitiveProgramming | 74b7eb58dfaca6375e55cfe1aa097d43bc154d81 | d5b00609141ae33aaaf736fd265b3db4a47dbe62 | refs/heads/master | 2021-01-17T01:57:54.378698 | 2016-12-30T01:01:21 | 2016-12-30T01:01:21 | 40,216,189 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,266 | cpp | #include <algorithm>
#include <vector>
#include <tuple>
#include <string>
#include <iostream>
#include <math.h>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
using namespace std;
typedef pair<int, int> P;
int main()
{
std::ios::sync_with_stdio(false);
cin.tie();
int n, m;
while (scanf("%d %d", &n, &m) != EOF)
{
vector< vector<P> > ans(m+1);
// Go through all of the rows
for(int i=1; i<=n; i++)
{
int r; scanf("%d", &r);
// If there are values on this row
if (r != 0) {
//get indices
vector<int> indices;
for(int j=0; j<r; j++)
{
int input; scanf("%d", &input);
indices.push_back(input);
}
//get values
vector<int> values;
for(int j=0; j<r; j++)
{
int input; scanf("%d", &input);
values.push_back(input);
ans[indices[j]].push_back(make_pair(i, values[j]));
}
}
}
cout << m << " " << n << endl;
// Go through all of the rows in the answer
for(int i=1; i<=m; i++)
{
// If there aren't any values in this row
if (ans[i].size() == 0) {
// Print zero, then an empty line
cout << ans[i].size() << endl << endl;
}
// Otherwise
else {
// Print the number of elements
cout << ans[i].size() << " ";
// Print the indices
for(int j=0; j<ans[i].size(); j++)
{
P temp = ans[i][j];
// Output the element index
cout << temp.first;
// And a spacer if it's not the last
if (j != ans[i].size()-1) cout << " ";
}
cout << endl;
// Print the values
for(int j=0; j<ans[i].size(); j++)
{
P temp = ans[i][j];
// If it's not the first element, output a spacer
if (j > 0) cout << " ";
// And output the value
cout << temp.second;
}
cout << endl;
}
}
}
}
| [
"kchow23@ufl.edu"
] | kchow23@ufl.edu |
75e9c3690cafc0d02448e831a1180888ee513ad7 | 01345e25f8a9987d13c8776611a62a9b60380481 | /potd-q46/Heap.cpp | 95827b689816fafdb8a53ae7a1efbf6e2fc8a46a | [] | no_license | wenhaoz2/cs225-potd | 4c655e3196c389e0484ac4feb2d9c168e9488feb | d3075969b3724308892ec32a3701824c600ec8d9 | refs/heads/master | 2020-07-29T06:55:53.536377 | 2019-01-02T17:01:27 | 2019-01-02T17:01:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | cpp | #include "Heap.h"
#include <iostream>
#include <vector>
using namespace std;
void Heap::_percolateDown(int hole) {
int left = hole*2;
int right = hole*2+1;
int smallest = hole;
if (left<size() && _data[left]>_data[smallest]) smallest=left;
if (right<size() && _data[right]>_data[smallest]) smallest=right;
if (smallest!=hole) {
swap(_data[hole], _data[smallest]);
_percolateDown(smallest);
}
}
int Heap::size() const {
return _data.size();
}
void Heap::enQueue(const int &x){
_data.push_back(x);
int hole = _data.size() - 1;
for(; hole > 1 && x > _data[hole/2]; hole /= 2){
_data[hole] = _data[hole/2];
}
_data[hole] = x;
}
int Heap::deQueue(){
int minItem = _data[1];
_data[1] = _data[_data.size() - 1];
_data.pop_back();
_percolateDown(1);
return minItem;
}
void Heap::printQueue(){
std::cout << "Current Priority Queue is: ";
for(auto i = _data.begin() + 1; i != _data.end(); ++i){
std::cout << *i << " ";
}
std::cout << std::endl;
}
std::vector<int> & Heap::getData() {
return _data;
}
| [
"marcharvey1470@gmail.com"
] | marcharvey1470@gmail.com |
77497ed894d96d0f11aec37031c4baeca22a004a | f9ea01aa0a109fe9bf50b3e9412b16265943e1c6 | /tcl/tcl_call_cpp/4_swig_manual/example.cpp | 930513deed49d6e3368ea2ef6de967c182f78761 | [] | no_license | sjtusonic/exe | 24ab4ed02a9ab1a3e2f8897004a5e8eec070350c | b02e7f6d63da4eab08358ed8bcec8f7c7670b31d | refs/heads/master | 2021-07-13T10:27:43.401389 | 2021-06-28T03:04:17 | 2021-06-28T03:04:17 | 43,668,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | cpp | /* PowObjCmd
*
* Tcl 8.x wrapper for the pow(x,y) function.
*/
#include <tcl.h>
#include <math.h>
int
PowObjCmd(ClientData clientData, Tcl_Interp *interp,
int objc, Tcl_Obj *CONST objv[])
{
Tcl_Obj *resultptr;
double x,y,result;
int error;
if (objc != 3) {
Tcl_WrongNumArgs(interp,2,objv,
"Usage : pow x y");
return TCL_ERROR;
}
error = Tcl_GetDoubleFromObj(interp, objv[1], &x);
if (error != TCL_OK) return error;
error = Tcl_GetDoubleFromObj(interp, objv[2], &y);
if (error != TCL_OK) return error;
result = pow(x,y);
resultptr = Tcl_GetObjResult(interp);
Tcl_SetDoubleObj(resultptr,result);
return TCL_OK;
}
//To make this new command available to Tcl, you also need to write an initialization function such as follows:
int
Example_Init(Tcl_Interp *interp) {
Tcl_CreateObjCommand(interp, "pow", PowObjCmd,
(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
return TCL_OK;
}
| [
"121939849@qq.com"
] | 121939849@qq.com |
12f05ec2a23f58e389a263bd2ba2ad29706bb8e1 | bb2d3a5c150976e3fb741e5c44acd27c1b9a5ffd | /main.cpp | a70de23215928b210295e8d9515fbf3b790cbe47 | [] | no_license | nicolasaiwen/Three-Pulse-Detection | 8cf36c56e403c1fbc054adf06866fc16821542d9 | bc2762088fdc3675e43510555ca67040c9465c40 | refs/heads/master | 2022-11-21T08:11:15.389877 | 2020-07-28T09:42:39 | 2020-07-28T09:42:39 | 283,165,018 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#include <QApplication>
#include "logindialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LoginDialog w;
w.show();
return a.exec();
}
| [
"xuwen1013@tju.edu.cn"
] | xuwen1013@tju.edu.cn |
6f22d98fb77a4a6400e35d3279c86f4059832c6b | 084c373d2cd1c005d5cef7625fac39e594a93af5 | /day_05/ex03/Form.hpp | ccdf69214c20a0d3f26e77ab3ce5c62044b98b97 | [] | no_license | mshbbrv/cpp_module | deb3ea1627f8fff4098f7119bd3a643a42908b5c | 5db99905ca5030f625d5050d0b39e3732e1b5828 | refs/heads/master | 2023-08-23T19:37:00.459002 | 2021-10-26T20:01:32 | 2021-10-26T20:01:32 | 409,241,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | hpp | #pragma once
#ifndef FORM_HPP
#define FORM_HPP
#include <iostream>
#include <string>
#include "Bureaucrat.hpp"
class Bureaucrat;
class Form {
public:
Form( void );
Form( std::string name, int gradeToSign, int gradeToExec );
virtual ~Form( void );
Form( const Form &form );
std::string getName( void ) const;
int getGradeToSign( void ) const;
int getGradeToExec( void ) const;
bool isSigned( void ) const;
void beSigned( Bureaucrat const &bureaucrat );
virtual void execute( Bureaucrat const &executor ) const = 0;
class GradeTooHighException : public std::exception {
public:
virtual const char *what( void ) const throw();
};
class GradeTooLowException : public std::exception {
public:
virtual const char *what( void ) const throw();
};
private:
const std::string _name;
bool _isSigned;
const int _gradeToSign;
const int _gradeToExec;
Form& operator= ( const Form &form );
};
std::ostream &operator<<(std::ostream &out, const Form &form);
#endif //FORM_HPP
| [
"mshbbrv@gmail.com"
] | mshbbrv@gmail.com |
f657aec6190bc498c8ce7e328991157860d13cf1 | 4c8c13eb891b514037d3adb1be7f28af53144e85 | /test/core/test_lennard_jones_wall_potential.cpp | e71ba35a11a2ec634a19f2a20ddb5cc88b606f6d | [
"MIT"
] | permissive | Mjolnir-MD/Mjolnir | f07b501cf60d6d1ca7cdeafc400749423dcde142 | 20dbdea5529c24a49b71e8876ac1651efc512445 | refs/heads/master | 2023-02-03T22:59:33.972243 | 2022-04-12T10:23:04 | 2022-04-12T10:23:04 | 74,558,351 | 14 | 9 | MIT | 2023-01-27T04:46:54 | 2016-11-23T08:53:31 | C++ | UTF-8 | C++ | false | false | 1,519 | cpp | #define BOOST_TEST_MODULE "test_lennard_jones_wall_potential"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/forcefield/external/LennardJonesWallPotential.hpp>
BOOST_AUTO_TEST_CASE(LennardJonesWallPotential_double)
{
using real_type = double;
constexpr static std::size_t N = 10000;
constexpr static real_type h = 1e-6;
constexpr static real_type tol = 1e-5;
const real_type sigma = 1.0;
const real_type epsilon = 1.0;
const std::vector<std::pair<std::size_t, std::pair<real_type, real_type>>>
sigma_epsilon{{0u, {sigma, epsilon}}};
mjolnir::LennardJonesWallPotential<real_type> ljw(2.5, sigma_epsilon);
const real_type cutoff_length = ljw.max_cutoff_length();
const real_type z_min = sigma * 0.5;
const real_type z_max = cutoff_length;
const real_type dz = (z_max - z_min) / N;
real_type z = z_min;
for(std::size_t i = 0; i < N; ++i)
{
const real_type pot1 = ljw.potential(0, z + h);
const real_type pot2 = ljw.potential(0, z - h);
const real_type dpot = (pot1 - pot2) / (2 * h);
const real_type deri = ljw.derivative(0, z);
if(std::abs(deri) > tol)
{
BOOST_TEST(dpot == deri, boost::test_tools::tolerance(tol));
}
else
{
BOOST_TEST(deri == 0.0, boost::test_tools::tolerance(tol));
}
z += dz;
}
}
| [
"niina.toru.68u@gmail.com"
] | niina.toru.68u@gmail.com |
36ccdb8fadc88b81a074d7caf1bfc57faed2342d | 123cdb1d6a6956586dd91c86d02e0d1bacdcebae | /planner/src/kcl_pandora/planning_system/src/SensorFeedback.cpp | bb18618a179e8cd0d2c704b90081ed08b8b41cc9 | [
"BSD-2-Clause"
] | permissive | KCL-Planning/strategic-tactical-pandora | 1862f3240028d6eb5dbecf02350b9f295ec8f788 | aa609af26a59e756b25212fa57fa72be937766e7 | refs/heads/master | 2021-01-23T05:50:00.669556 | 2017-11-30T11:16:48 | 2017-11-30T11:16:48 | 102,473,151 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | cpp | #include "ros/ros.h"
#include "nav_msgs/Odometry.h"
//#include "auv_msgs/NavSts.h"
//#include "ntua_controlNessie/EnergyEstimation.h"
/**
* listener to update the current AUV position and stats.
* This is used as the initial position of the vehicle during PRM construction;
* it may be later replaced by a call to the ontology.
*/
namespace PandoraKCL
{
bool positionInitialised = false;
/* get position from /pose_ekf_slam/odometry topic (UdG) */
void odometryCallbackUDG(const nav_msgs::Odometry::ConstPtr& msg)
{
PandoraKCL::currentEstimatedLocation.N = msg->pose.pose.position.x;
PandoraKCL::currentEstimatedLocation.E = msg->pose.pose.position.y;
PandoraKCL::currentEstimatedLocation.D = msg->pose.pose.position.z;
positionInitialised = true;
}
/* get position from /nav/nav_sts topic (HWU)
void odometryCallbackHWU(const auv_msgs::NavSts::ConstPtr& msg)
{
PandoraKCL::currentEstimatedLocation.N = msg->position.north;
PandoraKCL::currentEstimatedLocation.E = msg->position.east;
PandoraKCL::currentEstimatedLocation.D = msg->position.depth;
positionInitialised = true;
}*/
/* get energy estimation from /path_planning/energyEstimation topic (NTUA/HWU)
void totalEnergyCallbackHWU(const ntua_controlNessie::EnergyEstimation::ConstPtr& msg)
{
// nothing yet
}*/
} //close namespace
| [
"bram.ridder@gmail.com"
] | bram.ridder@gmail.com |
75e2536a948ae50f03464bbdeed59d2f85355007 | 62f325b29d4de158367f0e69a3198b8e1d154c24 | /Project7/Project7/game.h | ad24157573f42d44e8956273afd2b6ebb8d1fb74 | [] | no_license | collegeteamAS/comp-projects | 73bf427b80d8ea290b6257df9de32c1b6e24364c | e21b7db2a488875a47b8964b48e62eeb50b9b071 | refs/heads/master | 2021-01-23T09:50:45.770036 | 2014-12-05T08:37:30 | 2014-12-05T08:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,511 | h | /*
Andre Allan Ponce
a_ponce1@u.pacific.edu
Steve Suh
h_suh@u.pacific.edu
*/
#ifndef _GAME_H_INCLUDED_
#define _GAME_H_INCLUDED_
#include "locationdata.h"
#include "coordlist.h"
class Location;
class Floor;
class Player;
class Item;
class LinkedList;
class Game {
protected:
Floor** world; // the world
LocationData locations;
// holds roomlayout data for the tiles
Player* player; // the player
//Player* monster; // the monster
/* STATE machine:
-1- nothing
0 - start up state, reading in data, preparing game
1 - game start, explore
2 - the final door has been found
5 - game finish
6 - game quit
*/
int state;
int endGameCounter;
// starts at 0, increases by 1 per new room
// this room is where you supposed to drop the keys.
bool isFinalDoorIn; // here is the end
int finalRoomX; // the endgame x coord
int finalRoomY; // the endgame room y coord
std::string activeText; // debug
std::string modeText; // what you should be doing right now.
// where is the player right now?
//int currX;
//int currY;
// what floor is the player on right now?
//int curr_floor;
Location* createRandomRoom(int x, int y, int flor);
/*// creates a random room (which really isnt random since we only have one type of tile
@param x - the x coordinate of the room to create
@param y - the y coordinate of the room to create
@param flor - the floor of the room to create
@return a pointer to the new location
//*/
void createWorld();
void deletePlayer();
void deleteWorld();
void dropOffItem();
void Game::gameStates(int& old_state, bool& mapPrint, clock_t& startTime);
/*// handles other game states other than finish and pregame
@param old_state - the old_state, used for debugging
@param mapPrint - true if we want a new map, false if not
@param startTime - clocking the time we started, used for debugging
//*/
bool getKeyInput(unsigned short key);
/*// decides what we do based on input key
@param key - the key we pressed
refer to http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx for key codes
@return true for updating the map, false if not
//*/
Floor* makeFloor(int id);
Location* makeRoom(int id, int x, int y, int flor);
bool movePlayer(int xMove, int yMove);
void pickUpItem();
void preGameInit();
void setupDoors(Location* loc, int id);
/*// sets the door bools based on the id
@param loc - pointer to location to adjust doors
@param id - id of the room
//*/
// int selectItem();
// allow user to select which item to drop
// cannot be used with the current display inventory
public:
enum Constants{
PLAYER_SYMBOL = 'O',
// STATE MACHINE
STATE_WAIT = -1,
STATE_PRE_GAME = 0,
STATE_EXPLORE = 1,
STATE_FINAL_DOOR = 2,
STATE_GAME_FINISH = 5,
STATE_GAME_FINSH_BAD = 6,
// STARTING FlOOR and ROOM
START_FLOOR = 1, // this should be the ground floor
START_ROOM_X = 15,
START_ROOM_Y = 15,
// The player is always in the middle of the map
CENTER_PLAYER_X = 22,
CETNER_PLAYER_Y = 22,
// how many floors do we have
WORLD_SIZE = 1
};
Game();
~Game();
int getRandomNumber(int start, int end);
/*// gets a random number from start to end
@param start - the starting number of the range (inclusive)
@param end - the ending number of the range (exclusive)
@return an int between start (inclusive) and end (exclusive)
//*/
void printGame();
void printGamePartial();
void printHelp();
void readInFile(std::string fileName);
void runGame();
};
#endif
| [
"andreponce@null.net"
] | andreponce@null.net |
b478f7229d9394ca6239632232a9fa3c5cef6e5a | 2834f98b53d78bafc9f765344ded24cf41ffebb0 | /chrome/browser/apps/app_service/arc_apps.cc | 9775902cb781368f20d3e24b4ab3150bc746f4b2 | [
"BSD-3-Clause"
] | permissive | cea56/chromium | 81bffdf706df8b356c2e821c1a299f9d4bd4c620 | 013d244f2a747275da76758d2e6240f88c0165dd | refs/heads/master | 2023-01-11T05:44:41.185820 | 2019-12-09T04:14:16 | 2019-12-09T04:14:16 | 226,785,888 | 1 | 0 | BSD-3-Clause | 2019-12-09T04:40:07 | 2019-12-09T04:40:07 | null | UTF-8 | C++ | false | false | 35,279 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/apps/app_service/arc_apps.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/flat_map.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "base/optional.h"
#include "base/stl_util.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/arc_apps_factory.h"
#include "chrome/browser/apps/app_service/dip_px_util.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_dialog.h"
#include "chrome/browser/ui/app_list/arc/arc_app_icon.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/common/chrome_features.h"
#include "chrome/grit/component_extension_resources.h"
#include "chrome/services/app_service/public/cpp/intent_filter_util.h"
#include "components/arc/app_permissions/arc_app_permissions_bridge.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/mojom/app_permissions.mojom.h"
#include "components/arc/session/arc_bridge_service.h"
#include "content/public/browser/system_connector.h"
#include "extensions/grit/extensions_browser_resources.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/size.h"
// TODO(crbug.com/826982): consider that, per khmel@, "App icon can be
// overwritten (setTaskDescription) or by assigning the icon for the app
// window. In this case some consumers (Shelf for example) switch to
// overwritten icon... IIRC this applies to shelf items and ArcAppWindow icon".
namespace {
void OnArcAppIconCompletelyLoaded(
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
apps::IconEffects icon_effects,
apps::mojom::Publisher::LoadIconCallback callback,
ArcAppIcon* icon) {
if (!icon) {
std::move(callback).Run(apps::mojom::IconValue::New());
return;
}
apps::mojom::IconValuePtr iv = apps::mojom::IconValue::New();
iv->icon_compression = icon_compression;
iv->is_placeholder_icon = false;
if (icon_compression == apps::mojom::IconCompression::kUncompressed) {
iv->uncompressed = icon->image_skia();
if (icon_effects != apps::IconEffects::kNone) {
apps::ApplyIconEffects(icon_effects, size_hint_in_dip, &iv->uncompressed);
}
} else {
auto& compressed_images = icon->compressed_images();
auto iter =
compressed_images.find(apps_util::GetPrimaryDisplayUIScaleFactor());
if (iter == compressed_images.end()) {
std::move(callback).Run(apps::mojom::IconValue::New());
return;
}
const std::string& data = iter->second;
iv->compressed = std::vector<uint8_t>(data.begin(), data.end());
if (icon_effects != apps::IconEffects::kNone) {
// TODO(crbug.com/988321): decompress the image, apply icon effects then
// re-compress.
}
}
std::move(callback).Run(std::move(iv));
}
void UpdateAppPermissions(
const base::flat_map<arc::mojom::AppPermission,
arc::mojom::PermissionStatePtr>& new_permissions,
std::vector<apps::mojom::PermissionPtr>* permissions) {
for (const auto& new_permission : new_permissions) {
auto permission = apps::mojom::Permission::New();
permission->permission_id = static_cast<uint32_t>(new_permission.first);
permission->value_type = apps::mojom::PermissionValueType::kBool;
permission->value = static_cast<uint32_t>(new_permission.second->granted);
permission->is_managed = new_permission.second->managed;
permissions->push_back(std::move(permission));
}
}
base::Optional<arc::UserInteractionType> GetUserInterationType(
apps::mojom::LaunchSource launch_source) {
auto user_interaction_type = arc::UserInteractionType::NOT_USER_INITIATED;
switch (launch_source) {
// kUnknown is not set anywhere, this case is not valid.
case apps::mojom::LaunchSource::kUnknown:
return base::nullopt;
case apps::mojom::LaunchSource::kFromAppListGrid:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_LAUNCHER;
break;
case apps::mojom::LaunchSource::kFromAppListGridContextMenu:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_LAUNCHER_CONTEXT_MENU;
break;
case apps::mojom::LaunchSource::kFromAppListQuery:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_LAUNCHER_SEARCH;
break;
case apps::mojom::LaunchSource::kFromAppListQueryContextMenu:
user_interaction_type = arc::UserInteractionType::
APP_STARTED_FROM_LAUNCHER_SEARCH_CONTEXT_MENU;
break;
case apps::mojom::LaunchSource::kFromAppListRecommendation:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_LAUNCHER_SUGGESTED_APP;
break;
case apps::mojom::LaunchSource::kFromParentalControls:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_SETTINGS;
break;
case apps::mojom::LaunchSource::kFromShelf:
user_interaction_type = arc::UserInteractionType::APP_STARTED_FROM_SHELF;
break;
case apps::mojom::LaunchSource::kFromFileManager:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_FILE_MANAGER;
break;
case apps::mojom::LaunchSource::kFromLink:
user_interaction_type = arc::UserInteractionType::APP_STARTED_FROM_LINK;
break;
case apps::mojom::LaunchSource::kFromOmnibox:
user_interaction_type =
arc::UserInteractionType::APP_STARTED_FROM_OMNIBOX;
break;
default:
NOTREACHED();
return base::nullopt;
}
return user_interaction_type;
}
arc::mojom::IntentInfoPtr CreateArcViewIntent(apps::mojom::IntentPtr intent) {
arc::mojom::IntentInfoPtr arc_intent;
if (!intent->scheme.has_value() || !intent->host.has_value() ||
!intent->path.has_value()) {
return arc_intent;
}
arc_intent = arc::mojom::IntentInfo::New();
auto uri_components = arc::mojom::UriComponents::New();
constexpr char kAndroidIntentActionView[] = "android.intent.action.VIEW";
uri_components->scheme = intent->scheme.value();
uri_components->authority = intent->host.value();
uri_components->path = intent->path.value();
arc_intent->action = kAndroidIntentActionView;
arc_intent->uri_components = std::move(uri_components);
return arc_intent;
}
apps::mojom::IntentFilterPtr ConvertArcIntentFilter(
const arc::IntentFilter& arc_intent_filter) {
auto intent_filter = apps::mojom::IntentFilter::New();
std::vector<apps::mojom::ConditionValuePtr> scheme_condition_values;
for (auto& scheme : arc_intent_filter.schemes()) {
scheme_condition_values.push_back(apps_util::MakeConditionValue(
scheme, apps::mojom::PatternMatchType::kNone));
}
if (!scheme_condition_values.empty()) {
auto scheme_condition =
apps_util::MakeCondition(apps::mojom::ConditionType::kScheme,
std::move(scheme_condition_values));
intent_filter->conditions.push_back(std::move(scheme_condition));
}
std::vector<apps::mojom::ConditionValuePtr> host_condition_values;
for (auto& authority : arc_intent_filter.authorities()) {
host_condition_values.push_back(apps_util::MakeConditionValue(
authority.host(), apps::mojom::PatternMatchType::kNone));
}
if (!host_condition_values.empty()) {
auto host_condition = apps_util::MakeCondition(
apps::mojom::ConditionType::kHost, std::move(host_condition_values));
intent_filter->conditions.push_back(std::move(host_condition));
}
std::vector<apps::mojom::ConditionValuePtr> path_condition_values;
for (auto& path : arc_intent_filter.paths()) {
apps::mojom::PatternMatchType match_type;
switch (path.match_type()) {
case arc::mojom::PatternType::PATTERN_LITERAL:
match_type = apps::mojom::PatternMatchType::kLiteral;
break;
case arc::mojom::PatternType::PATTERN_PREFIX:
match_type = apps::mojom::PatternMatchType::kPrefix;
break;
case arc::mojom::PatternType::PATTERN_SIMPLE_GLOB:
match_type = apps::mojom::PatternMatchType::kGlob;
break;
}
path_condition_values.push_back(
apps_util::MakeConditionValue(path.pattern(), match_type));
}
if (!path_condition_values.empty()) {
auto path_condition = apps_util::MakeCondition(
apps::mojom::ConditionType::kPattern, std::move(path_condition_values));
intent_filter->conditions.push_back(std::move(path_condition));
}
return intent_filter;
}
} // namespace
namespace apps {
// static
ArcApps* ArcApps::Get(Profile* profile) {
return ArcAppsFactory::GetForProfile(profile);
}
// static
ArcApps* ArcApps::CreateForTesting(Profile* profile,
apps::AppServiceProxy* proxy) {
return new ArcApps(profile, proxy);
}
ArcApps::ArcApps(Profile* profile) : ArcApps(profile, nullptr) {}
ArcApps::ArcApps(Profile* profile, apps::AppServiceProxy* proxy)
: profile_(profile), arc_icon_once_loader_(profile) {
if (!arc::IsArcAllowedForProfile(profile_) ||
(arc::ArcServiceManager::Get() == nullptr)) {
return;
}
if (!proxy) {
proxy = apps::AppServiceProxyFactory::GetForProfile(profile);
}
mojo::Remote<apps::mojom::AppService>& app_service = proxy->AppService();
if (!app_service.is_bound()) {
return;
}
// Make some observee-observer connections.
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
prefs->AddObserver(this);
proxy->SetArcIsRegistered();
auto* intent_helper_bridge =
arc::ArcIntentHelperBridge::GetForBrowserContext(profile_);
if (intent_helper_bridge) {
arc_intent_helper_observer_.Add(intent_helper_bridge);
}
app_service->RegisterPublisher(receiver_.BindNewPipeAndPassRemote(),
apps::mojom::AppType::kArc);
}
ArcApps::~ArcApps() = default;
void ArcApps::Shutdown() {
// Disconnect the observee-observer connections that we made during the
// constructor.
//
// This isn't entirely correct. The object returned by
// ArcAppListPrefs::Get(some_profile) can vary over the lifetime of that
// profile. If it changed, we'll try to disconnect from different
// ArcAppListPrefs-related objects than the ones we connected to, at the time
// of this object's construction.
//
// Even so, this is probably harmless, assuming that calling
// foo->RemoveObserver(bar) is a no-op (and e.g. does not crash) if bar
// wasn't observing foo in the first place, and assuming that the dangling
// observee-observer connection on the old foo's are never followed again.
//
// To fix this properly, we would probably need to add something like an
// OnArcAppListPrefsWillBeDestroyed method to ArcAppListPrefs::Observer, and
// in this class's implementation of that method, disconnect. Furthermore,
// when the new ArcAppListPrefs object is created, we'll have to somehow be
// notified so we can re-connect this object as an observer.
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (prefs) {
prefs->RemoveObserver(this);
}
arc_icon_once_loader_.StopObserving(prefs);
arc_intent_helper_observer_.RemoveAll();
}
void ArcApps::Connect(
mojo::PendingRemote<apps::mojom::Subscriber> subscriber_remote,
apps::mojom::ConnectOptionsPtr opts) {
std::vector<apps::mojom::AppPtr> apps;
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (prefs) {
for (const auto& app_id : prefs->GetAppIds()) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (app_info) {
apps.push_back(Convert(prefs, app_id, *app_info));
}
}
}
mojo::Remote<apps::mojom::Subscriber> subscriber(
std::move(subscriber_remote));
subscriber->OnApps(std::move(apps));
subscribers_.Add(std::move(subscriber));
}
void ArcApps::LoadIcon(const std::string& app_id,
apps::mojom::IconKeyPtr icon_key,
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
LoadIconCallback callback) {
if (!icon_key) {
std::move(callback).Run(apps::mojom::IconValue::New());
return;
}
IconEffects icon_effects = static_cast<IconEffects>(icon_key->icon_effects);
// Treat the Play Store as a special case, loading an icon defined by a
// resource instead of asking the Android VM (or the cache of previous
// responses from the Android VM). Presumably this is for bootstrapping:
// the Play Store icon (the UI for enabling and installing Android apps)
// should be showable even before the user has installed their first
// Android app and before bringing up an Android VM for the first time.
if (app_id == arc::kPlayStoreAppId) {
LoadPlayStoreIcon(icon_compression, size_hint_in_dip, icon_effects,
std::move(callback));
} else if (allow_placeholder_icon) {
constexpr bool is_placeholder_icon = true;
LoadIconFromResource(icon_compression, size_hint_in_dip,
IDR_APP_DEFAULT_ICON, is_placeholder_icon,
icon_effects, std::move(callback));
} else {
arc_icon_once_loader_.LoadIcon(
app_id, size_hint_in_dip, icon_compression,
base::BindOnce(&OnArcAppIconCompletelyLoaded, icon_compression,
size_hint_in_dip, icon_effects, std::move(callback)));
}
}
void ArcApps::Launch(const std::string& app_id,
int32_t event_flags,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
auto user_interaction_type = GetUserInterationType(launch_source);
if (!user_interaction_type.has_value()) {
return;
}
arc::LaunchApp(profile_, app_id, event_flags, user_interaction_type.value(),
display_id);
}
void ArcApps::LaunchAppWithIntent(const std::string& app_id,
apps::mojom::IntentPtr intent,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
auto user_interaction_type = GetUserInterationType(launch_source);
if (!user_interaction_type.has_value()) {
return;
}
UMA_HISTOGRAM_ENUMERATION("Arc.UserInteraction",
user_interaction_type.value());
auto* arc_service_manager = arc::ArcServiceManager::Get();
arc::mojom::IntentHelperInstance* instance = nullptr;
if (arc_service_manager) {
instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_service_manager->arc_bridge_service()->intent_helper(),
HandleIntent);
}
if (!instance) {
return;
}
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (!app_info) {
LOG(ERROR) << "Launch App failed, could not find app with id " << app_id;
return;
}
arc::mojom::ActivityNamePtr activity = arc::mojom::ActivityName::New();
activity->package_name = app_info->package_name;
activity->activity_name = app_info->activity;
auto arc_intent = CreateArcViewIntent(std::move(intent));
if (!arc_intent) {
LOG(ERROR) << "Launch App failed, launch intent is not valid";
return;
}
instance->HandleIntent(std::move(arc_intent), std::move(activity));
prefs->SetLastLaunchTime(app_id);
}
void ArcApps::SetPermission(const std::string& app_id,
apps::mojom::PermissionPtr permission) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (!app_info) {
LOG(ERROR) << "SetPermission failed, could not find app with id " << app_id;
return;
}
auto* arc_service_manager = arc::ArcServiceManager::Get();
if (!arc_service_manager) {
LOG(WARNING) << "SetPermission failed, ArcServiceManager not available.";
return;
}
auto permission_type =
static_cast<arc::mojom::AppPermission>(permission->permission_id);
if (permission->value) {
auto* permissions_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_service_manager->arc_bridge_service()->app_permissions(),
GrantPermission);
if (permissions_instance) {
permissions_instance->GrantPermission(app_info->package_name,
permission_type);
}
} else {
auto* permissions_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_service_manager->arc_bridge_service()->app_permissions(),
RevokePermission);
if (permissions_instance) {
permissions_instance->RevokePermission(app_info->package_name,
permission_type);
}
}
}
void ArcApps::PromptUninstall(const std::string& app_id) {
if (!profile_) {
return;
}
arc::ShowArcAppUninstallDialog(profile_, nullptr /* controller */, app_id);
}
void ArcApps::Uninstall(const std::string& app_id,
bool clear_site_data,
bool report_abuse) {
arc::UninstallArcApp(app_id, profile_);
}
void ArcApps::PauseApp(const std::string& app_id) {
if (paused_apps_.find(app_id) != paused_apps_.end()) {
return;
}
paused_apps_.insert(app_id);
SetIconEffect(app_id);
CloseTasks(app_id);
}
void ArcApps::UnpauseApps(const std::string& app_id) {
if (paused_apps_.find(app_id) == paused_apps_.end()) {
return;
}
paused_apps_.erase(app_id);
SetIconEffect(app_id);
}
void ArcApps::OpenNativeSettings(const std::string& app_id) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (!app_info) {
LOG(ERROR) << "Cannot open native settings for " << app_id
<< ". App is not found.";
return;
}
arc::ShowPackageInfo(app_info->package_name,
arc::mojom::ShowPackageInfoPage::MAIN,
display::Screen::GetScreen()->GetPrimaryDisplay().id());
}
void ArcApps::OnPreferredAppSet(const std::string& app_id,
apps::mojom::IntentFilterPtr intent_filter,
apps::mojom::IntentPtr intent) {
auto* arc_service_manager = arc::ArcServiceManager::Get();
arc::mojom::IntentHelperInstance* instance = nullptr;
if (arc_service_manager) {
instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_service_manager->arc_bridge_service()->intent_helper(),
AddPreferredApp);
}
if (!instance) {
return;
}
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (!app_info) {
LOG(ERROR) << "Launch App failed, could not find app with id " << app_id;
return;
}
auto arc_intent = CreateArcViewIntent(std::move(intent));
std::vector<std::string> schemes;
std::vector<arc::IntentFilter::AuthorityEntry> authorities;
std::vector<arc::IntentFilter::PatternMatcher> paths;
for (auto& condition : intent_filter->conditions) {
switch (condition->condition_type) {
case apps::mojom::ConditionType::kScheme:
for (auto& condition_value : condition->condition_values) {
schemes.push_back(condition_value->value);
}
break;
case apps::mojom::ConditionType::kHost:
for (auto& condition_value : condition->condition_values) {
authorities.push_back(
arc::IntentFilter::AuthorityEntry(condition_value->value, 0));
}
break;
case apps::mojom::ConditionType::kPattern:
for (auto& condition_value : condition->condition_values) {
arc::mojom::PatternType match_type;
switch (condition_value->match_type) {
case apps::mojom::PatternMatchType::kLiteral:
match_type = arc::mojom::PatternType::PATTERN_LITERAL;
break;
case apps::mojom::PatternMatchType::kPrefix:
match_type = arc::mojom::PatternType::PATTERN_PREFIX;
break;
case apps::mojom::PatternMatchType::kGlob:
match_type = arc::mojom::PatternType::PATTERN_SIMPLE_GLOB;
break;
case apps::mojom::PatternMatchType::kNone:
NOTREACHED();
return;
}
paths.push_back(arc::IntentFilter::PatternMatcher(
condition_value->value, match_type));
}
break;
}
}
// TODO(crbug.com/853604): Add support for other action and category types.
arc::IntentFilter arc_intent_filter(app_info->package_name,
std::move(authorities), std::move(paths),
std::move(schemes));
instance->AddPreferredApp(app_info->package_name,
std::move(arc_intent_filter),
std::move(arc_intent));
}
void ArcApps::OnAppRegistered(const std::string& app_id,
const ArcAppListPrefs::AppInfo& app_info) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (prefs) {
Publish(Convert(prefs, app_id, app_info));
}
}
void ArcApps::OnAppStatesChanged(const std::string& app_id,
const ArcAppListPrefs::AppInfo& app_info) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (prefs) {
Publish(Convert(prefs, app_id, app_info));
}
}
void ArcApps::OnAppRemoved(const std::string& app_id) {
paused_apps_.erase(app_id);
if (base::Contains(app_id_to_task_ids_, app_id)) {
for (int task_id : app_id_to_task_ids_[app_id]) {
task_id_to_app_id_.erase(task_id);
}
app_id_to_task_ids_.erase(app_id);
}
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->readiness = apps::mojom::Readiness::kUninstalledByUser;
Publish(std::move(app));
mojo::Remote<apps::mojom::AppService>& app_service =
apps::AppServiceProxyFactory::GetForProfile(profile_)->AppService();
if (!app_service.is_bound()) {
return;
}
app_service->RemovePreferredApp(apps::mojom::AppType::kArc, app_id);
}
void ArcApps::OnAppIconUpdated(const std::string& app_id,
const ArcAppIconDescriptor& descriptor) {
static constexpr uint32_t icon_effects = 0;
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->icon_key = icon_key_factory_.MakeIconKey(icon_effects);
Publish(std::move(app));
}
void ArcApps::OnAppNameUpdated(const std::string& app_id,
const std::string& name) {
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->name = name;
Publish(std::move(app));
}
void ArcApps::OnAppLastLaunchTimeUpdated(const std::string& app_id) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
if (!app_info) {
return;
}
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->last_launch_time = app_info->last_launch_time;
Publish(std::move(app));
}
void ArcApps::OnPackageInstalled(
const arc::mojom::ArcPackageInfo& package_info) {
ConvertAndPublishPackageApps(package_info);
}
void ArcApps::OnPackageModified(
const arc::mojom::ArcPackageInfo& package_info) {
static constexpr bool update_icon = false;
ConvertAndPublishPackageApps(package_info, update_icon);
}
void ArcApps::OnPackageListInitialRefreshed() {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
// This method is called when ARC++ finishes booting. Do not update the icon;
// it should be impossible for the icon to have changed since ARC++ has not
// been running.
static constexpr bool update_icon = false;
for (const auto& app_id : prefs->GetAppIds()) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
if (app_info) {
Publish(Convert(prefs, app_id, *app_info, update_icon));
}
}
}
void ArcApps::OnTaskCreated(int task_id,
const std::string& package_name,
const std::string& activity,
const std::string& intent) {
const std::string app_id = ArcAppListPrefs::GetAppId(package_name, activity);
app_id_to_task_ids_[app_id].insert(task_id);
task_id_to_app_id_[task_id] = app_id;
}
void ArcApps::OnTaskDestroyed(int task_id) {
auto it = task_id_to_app_id_.find(task_id);
if (it == task_id_to_app_id_.end()) {
return;
}
const std::string app_id = it->second;
task_id_to_app_id_.erase(it);
DCHECK(base::Contains(app_id_to_task_ids_, app_id));
app_id_to_task_ids_[app_id].erase(task_id);
if (app_id_to_task_ids_[app_id].empty()) {
app_id_to_task_ids_.erase(app_id);
}
}
void ArcApps::OnIntentFiltersUpdated(
const base::Optional<std::string>& package_name) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
auto GetAppInfoAndPublish = [prefs, this](std::string app_id) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
if (app_info) {
Publish(Convert(prefs, app_id, *app_info));
}
};
// If there is no specific package_name, update all apps, otherwise update
// apps for the package.
// Note: Cannot combine the two for-loops because the return type of
// GetAppIds() is std::vector<std::string> and the return type of
// GetAppsForPackage() is std::unordered_set<std::string>.
if (package_name == base::nullopt) {
for (const auto& app_id : prefs->GetAppIds()) {
GetAppInfoAndPublish(app_id);
}
} else {
for (const auto& app_id : prefs->GetAppsForPackage(package_name.value())) {
GetAppInfoAndPublish(app_id);
}
}
}
void ArcApps::OnPreferredAppsChanged() {
mojo::Remote<apps::mojom::AppService>& app_service =
apps::AppServiceProxyFactory::GetForProfile(profile_)->AppService();
if (!app_service.is_bound()) {
return;
}
auto* intent_helper_bridge =
arc::ArcIntentHelperBridge::GetForBrowserContext(profile_);
if (!intent_helper_bridge) {
return;
}
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
const std::vector<arc::IntentFilter>& added_preferred_apps =
intent_helper_bridge->GetAddedPreferredApps();
for (auto& added_preferred_app : added_preferred_apps) {
constexpr bool kFromPublisher = true;
// TODO(crbug.com/853604): Currently only handles one App ID per package.
// If need to handle multiple activities per package, will need to
// update ARC to send through the corresponding activity and ensure this
// activity matches with the main_activity that stored in app_service.
// Will add an activity field in the arc::mojom::intent_filter.
// Also need to make sure this still work with the Chrome set preference
// because the intent filter uplifted for each package doesn't contain
// activity info.
std::string app_id =
prefs->GetAppIdByPackageName(added_preferred_app.package_name());
app_service->AddPreferredApp(apps::mojom::AppType::kArc, app_id,
ConvertArcIntentFilter(added_preferred_app),
/*intent=*/nullptr, kFromPublisher);
}
const std::vector<arc::IntentFilter>& deleted_preferred_apps =
intent_helper_bridge->GetDeletedPreferredApps();
for (auto& deleted_preferred_app : deleted_preferred_apps) {
// TODO(crbug.com/853604): Currently only handles one App ID per package.
// If need to handle multiple activities per package, will need to
// update ARC to send through the corresponding activity and ensure this
// activity matches with the main_activity that stored in app_service.
// Will add an activity field in the arc::mojom::intent_filter.
// Also need to make sure this still work with the Chrome set preference
// because the intent filter uplifted for each package doesn't contain
// activity info.
std::string app_id =
prefs->GetAppIdByPackageName(deleted_preferred_app.package_name());
app_service->RemovePreferredAppForFilter(
apps::mojom::AppType::kArc, app_id,
ConvertArcIntentFilter(deleted_preferred_app));
}
}
void ArcApps::LoadPlayStoreIcon(apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
IconEffects icon_effects,
LoadIconCallback callback) {
// Use overloaded Chrome icon for Play Store that is adapted to Chrome style.
constexpr bool quantize_to_supported_scale_factor = true;
int size_hint_in_px = apps_util::ConvertDipToPx(
size_hint_in_dip, quantize_to_supported_scale_factor);
int resource_id = (size_hint_in_px <= 32) ? IDR_ARC_SUPPORT_ICON_32
: IDR_ARC_SUPPORT_ICON_192;
constexpr bool is_placeholder_icon = false;
LoadIconFromResource(icon_compression, size_hint_in_dip, resource_id,
is_placeholder_icon, icon_effects, std::move(callback));
}
apps::mojom::InstallSource GetInstallSource(const ArcAppListPrefs* prefs,
const std::string& package_name) {
// TODO(crbug.com/1010821): Create a generic check for kSystem apps.
if (prefs->GetAppIdByPackageName(package_name) == arc::kPlayStoreAppId) {
return apps::mojom::InstallSource::kSystem;
}
if (prefs->IsDefault(package_name)) {
return apps::mojom::InstallSource::kDefault;
}
if (prefs->IsOem(package_name)) {
return apps::mojom::InstallSource::kOem;
}
if (prefs->IsControlledByPolicy(package_name)) {
return apps::mojom::InstallSource::kPolicy;
}
return apps::mojom::InstallSource::kUser;
}
apps::mojom::AppPtr ArcApps::Convert(ArcAppListPrefs* prefs,
const std::string& app_id,
const ArcAppListPrefs::AppInfo& app_info,
bool update_icon) {
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->readiness = app_info.suspended
? apps::mojom::Readiness::kDisabledByPolicy
: apps::mojom::Readiness::kReady;
app->name = app_info.name;
app->short_name = app->name;
app->publisher_id = app_info.package_name;
if (update_icon) {
IconEffects icon_effects = IconEffects::kNone;
if (app_info.suspended) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kGray);
}
app->icon_key = icon_key_factory_.MakeIconKey(icon_effects);
}
app->last_launch_time = app_info.last_launch_time;
app->install_time = app_info.install_time;
app->install_source = GetInstallSource(prefs, app_info.package_name);
app->is_platform_app = apps::mojom::OptionalBool::kFalse;
app->recommendable = apps::mojom::OptionalBool::kTrue;
app->searchable = apps::mojom::OptionalBool::kTrue;
auto show = app_info.show_in_launcher ? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->show_in_launcher = show;
app->show_in_search = show;
app->show_in_management = show;
app->paused = apps::mojom::OptionalBool::kFalse;
std::unique_ptr<ArcAppListPrefs::PackageInfo> package =
prefs->GetPackage(app_info.package_name);
if (package) {
UpdateAppPermissions(package->permissions, &app->permissions);
}
auto* intent_helper_bridge =
arc::ArcIntentHelperBridge::GetForBrowserContext(profile_);
if (intent_helper_bridge) {
UpdateAppIntentFilters(app_info.package_name, intent_helper_bridge,
&app->intent_filters);
}
return app;
}
void ArcApps::Publish(apps::mojom::AppPtr app) {
for (auto& subscriber : subscribers_) {
std::vector<apps::mojom::AppPtr> apps;
apps.push_back(app.Clone());
subscriber->OnApps(std::move(apps));
}
}
void ArcApps::ConvertAndPublishPackageApps(
const arc::mojom::ArcPackageInfo& package_info,
bool update_icon) {
if (!package_info.permissions.has_value()) {
return;
}
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (prefs) {
for (const auto& app_id :
prefs->GetAppsForPackage(package_info.package_name)) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
prefs->GetApp(app_id);
if (app_info) {
Publish(Convert(prefs, app_id, *app_info, update_icon));
}
}
}
}
void ArcApps::SetIconEffect(const std::string& app_id) {
ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile_);
if (!prefs) {
return;
}
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
if (!app_info) {
return;
}
IconEffects icon_effects = IconEffects::kNone;
if (app_info->suspended) {
icon_effects = static_cast<IconEffects>(icon_effects | IconEffects::kGray);
}
if (paused_apps_.find(app_id) != paused_apps_.end()) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kPaused);
}
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kArc;
app->app_id = app_id;
app->icon_key = icon_key_factory_.MakeIconKey(icon_effects);
Publish(std::move(app));
}
void ArcApps::CloseTasks(const std::string& app_id) {
if (!base::FeatureList::IsEnabled(features::kAppServiceInstanceRegistry)) {
return;
}
if (!base::Contains(app_id_to_task_ids_, app_id)) {
return;
}
for (int task_id : app_id_to_task_ids_[app_id]) {
arc::CloseTask(task_id);
task_id_to_app_id_.erase(task_id);
}
app_id_to_task_ids_.erase(app_id);
}
void ArcApps::UpdateAppIntentFilters(
std::string package_name,
arc::ArcIntentHelperBridge* intent_helper_bridge,
std::vector<apps::mojom::IntentFilterPtr>* intent_filters) {
const std::vector<arc::IntentFilter>& arc_intent_filters =
intent_helper_bridge->GetIntentFilterForPackage(package_name);
for (auto& arc_intent_filter : arc_intent_filters) {
intent_filters->push_back(ConvertArcIntentFilter(arc_intent_filter));
}
}
} // namespace apps
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
04dc14f63c84b870a7fb378cd633814e1d090e78 | 4da997729f4bb8b5a67ae318faba2a1990f8f8e7 | /dravede.cpp | 601e86f389349929b391bbf3095397c6c9dfa0dc | [] | no_license | atyamsriharsha/codeforces_practice | bd9b37cfbec38f6e0e7a8c4f27b18a5e6671df57 | 8ed0071b3f344d7db77796c87a09a58ffd89e96c | refs/heads/master | 2020-05-17T10:51:48.713100 | 2015-08-03T04:00:55 | 2015-08-03T04:00:55 | 40,104,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std ;
typedef struct point
{
int x ;
int y ;
}point;
typedef struct speed
{
int x;
int y ;
int z ;
}speed;
int main()
{
int n,i=0,f ;
cin >> n ;
point points[n] ;
while(n--)
{
cin >> points[i].x ;
cin >> points[i].y ;
i++ ;
}
point a ;
cin >> a.x >> a.y ;
speed v,u ;
cin >> v.x >> v.y >> v.z ;
cin >> f ;
cin >> u.x >> u.y >> u.z ;
return 0 ;
} | [
"atyamsriharsha@gmail.com"
] | atyamsriharsha@gmail.com |
9fedb375599cfbb9f8b918e2b38f0f3ef8e4494d | be3989c18030bb6d6fd51c20419d68d04358d5be | /OOInteraction/src/string_components/VariableAccessStringComponents.cpp | fbdf7747dcee5918d92b7985f861878e7fc3a87a | [
"BSD-3-Clause"
] | permissive | Andresbu/Envision | e6226ab826a15827ad7187823625646e3f1c5c12 | 864396334ed521c2ff6dee8a24f624b2c70e2a86 | refs/heads/master | 2021-01-18T08:43:15.416892 | 2012-03-29T15:36:27 | 2012-03-29T15:36:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,499 | cpp | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2012 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
/*
* VariableAccessStringComponents.cpp
*
* Created on: Feb 17, 2012
* Author: Dimitar Asenov
*/
#include "string_components/VariableAccessStringComponents.h"
#include "OOModel/src/expressions/VariableAccess.h"
namespace OOInteraction {
VariableAccessStringComponents::VariableAccessStringComponents(OOModel::VariableAccess* e)
: exp_(e)
{
}
QStringList VariableAccessStringComponents::components()
{
QStringList result;
if (!exp_) return result;
QString prefix = stringForNode(exp_->prefix());
if (!prefix.isEmpty()) result << prefix << ".";
result << exp_->ref()->path().split(':').last();
return result;
}
} /* namespace OOInteraction */
| [
"dimitar.asenov@inf.ethz.ch"
] | dimitar.asenov@inf.ethz.ch |
2f8bc6894d8ae69feb84575e8ccc3c613edaf5ce | 6436d1e6c23f9f43a8025889dc4414a3ad66acf2 | /CvGameCoreDLL/Boost-1.32.0/include/boost/mpl/vector/vector30.hpp | e32097ac6b52955477aee122787402b15014ce3c | [
"MIT"
] | permissive | dguenms/Dawn-of-Civilization | b710195c4f46fe11d9229182c3b1e07b77f42637 | a305e7846d085d6edf1e9c472e8dfceee1c07dd4 | refs/heads/develop | 2023-09-04T04:57:00.086384 | 2023-09-01T15:24:28 | 2023-09-01T15:24:28 | 45,362,597 | 116 | 121 | MIT | 2023-02-08T00:18:53 | 2015-11-01T23:52:28 | C++ | UTF-8 | C++ | false | false | 1,299 | hpp |
#ifndef BOOST_MPL_VECTOR_VECTOR30_HPP_INCLUDED
#define BOOST_MPL_VECTOR_VECTOR30_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/boost/boost/boost/mpl/vector/vector30.hpp,v $
// $Date: 2004/09/02 15:41:19 $
// $Revision: 1.6 $
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/vector/vector20.hpp>
#endif
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# define BOOST_MPL_PREPROCESSED_HEADER vector30.hpp
# include <boost/mpl/vector/aux_/include_preprocessed.hpp>
#else
# include <boost/mpl/aux_/config/typeof.hpp>
# include <boost/mpl/aux_/config/ctps.hpp>
# include <boost/preprocessor/iterate.hpp>
namespace boost { namespace mpl {
# define BOOST_PP_ITERATION_PARAMS_1 \
(3,(21, 30, <boost/mpl/vector/aux_/numbered.hpp>))
# include BOOST_PP_ITERATE()
}}
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_VECTOR_VECTOR30_HPP_INCLUDED
| [
"Leoreth@94cdc8ef-5f1a-49b8-8b82-819f55b6d80d"
] | Leoreth@94cdc8ef-5f1a-49b8-8b82-819f55b6d80d |
c096a49bf961fc18bfc8798510521dd338c82794 | a0ebb11a23e14e9cddb0555d8914357a5e464af5 | /include/ecst/context/system.hpp | 59d53a6cee5b3021f0af833a659994b0acc78d66 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | porpoisepor/ecst | b1b591814b72224d8200961ee5d2b7c3dd5f7aff | 6b54ab09d13f976efc32d554d78a05b539425dba | refs/heads/master | 2021-01-18T00:35:25.845121 | 2016-05-04T13:07:31 | 2016-05-04T13:07:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | hpp | // Copyright (c) 2015-2016 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include "./system/state.hpp"
#include "./system/instance.hpp"
#include "./system/runner.hpp"
| [
"vittorio.romeo@outlook.com"
] | vittorio.romeo@outlook.com |
6f88afd00aeb94cd5a80a0048cec7ae91ffa1b46 | ceed8ee18ab314b40b3e5b170dceb9adedc39b1e | /android/external/pdfium/fpdfsdk/src/javascript/JS_Runtime.h | decc5539741c6faf085c7a2a627837ab29fcbbc7 | [
"BSD-3-Clause"
] | permissive | BPI-SINOVOIP/BPI-H3-New-Android7 | c9906db06010ed6b86df53afb6e25f506ad3917c | 111cb59a0770d080de7b30eb8b6398a545497080 | refs/heads/master | 2023-02-28T20:15:21.191551 | 2018-10-08T06:51:44 | 2018-10-08T06:51:44 | 132,708,249 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,619 | h | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef FPDFSDK_SRC_JAVASCRIPT_JS_RUNTIME_H_
#define FPDFSDK_SRC_JAVASCRIPT_JS_RUNTIME_H_
#include <set>
#include <utility>
#include <vector>
#include "JS_EventHandler.h"
#include "core/include/fxcrt/fx_basic.h"
#include "fpdfsdk/include/javascript/IJavaScript.h"
#include "fpdfsdk/include/jsapi/fxjs_v8.h"
class CJS_Context;
class CJS_Runtime : public IJS_Runtime {
public:
class Observer {
public:
virtual void OnDestroyed() = 0;
protected:
virtual ~Observer() {}
};
using FieldEvent = std::pair<CFX_WideString, JS_EVENT_T>;
static CJS_Runtime* FromContext(const IJS_Context* cc);
explicit CJS_Runtime(CPDFDoc_Environment* pApp);
~CJS_Runtime() override;
// IJS_Runtime
IJS_Context* NewContext() override;
void ReleaseContext(IJS_Context* pContext) override;
IJS_Context* GetCurrentContext() override;
void SetReaderDocument(CPDFSDK_Document* pReaderDoc) override;
CPDFSDK_Document* GetReaderDocument() override { return m_pDocument; }
int Execute(IJS_Context* cc,
const wchar_t* script,
CFX_WideString* info) override;
CPDFDoc_Environment* GetReaderApp() const { return m_pApp; }
// Returns true if the event isn't already found in the set.
bool AddEventToSet(const FieldEvent& event);
void RemoveEventFromSet(const FieldEvent& event);
void BeginBlock() { m_bBlocking = TRUE; }
void EndBlock() { m_bBlocking = FALSE; }
FX_BOOL IsBlocking() const { return m_bBlocking; }
v8::Isolate* GetIsolate() const { return m_isolate; }
v8::Local<v8::Context> NewJSContext();
#ifdef PDF_ENABLE_XFA
FX_BOOL GetHValueByName(const CFX_ByteStringC& utf8Name,
FXJSE_HVALUE hValue) override;
FX_BOOL SetHValueByName(const CFX_ByteStringC& utf8Name,
FXJSE_HVALUE hValue) override;
#endif // PDF_ENABLE_XFA
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
private:
void DefineJSObjects();
CFX_ArrayTemplate<CJS_Context*> m_ContextArray;
CPDFDoc_Environment* m_pApp;
CPDFSDK_Document* m_pDocument;
FX_BOOL m_bBlocking;
std::set<FieldEvent> m_FieldEventSet;
v8::Isolate* m_isolate;
bool m_isolateManaged;
v8::Global<v8::Context> m_context;
std::vector<v8::Global<v8::Object>*> m_StaticObjects;
std::set<Observer*> m_observers;
};
#endif // FPDFSDK_SRC_JAVASCRIPT_JS_RUNTIME_H_
| [
"Justin"
] | Justin |
9de75f5c987afad4bd54bf325399197dae6d395e | ec7002ba79e9f38ab71ba19b5a3e1503a61d91d6 | /include/godot_cpp/PacketPeerStream.hpp | ebc0d7520bcaad78ea736dbed50d6d1f1e029221 | [] | no_license | triptych/Godot-Webrtc-test-project | a7e2615e098d6c1f329ed16c3b0c6414b0cb6070 | 0a7aa5e8b386a1a397ecde23689ad8ce7d87ae5c | refs/heads/master | 2020-05-02T09:17:45.170566 | 2018-08-07T06:49:23 | 2018-08-07T06:49:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | hpp | #ifndef PACKETPEERSTREAM_H
#define PACKETPEERSTREAM_H
#if defined(_WIN32) && defined(_GD_CPP_BINDING_IMPL)
# define GD_CPP_BINDING_API __declspec(dllexport)
#elif defined(_WIN32)
# define GD_CPP_BINDING_API __declspec(dllimport)
#else
# define GD_CPP_BINDING_API
#endif
#include "core/CoreTypes.hpp"
#include <godot.h>
#include "PacketPeer.hpp"
namespace godot {
class StreamPeer;
class GD_CPP_BINDING_API PacketPeerStream : public PacketPeer {
public:
void _init();
void set_stream_peer(const StreamPeer *peer);
};
}
#endif
| [
"bmicmak@gmail.com"
] | bmicmak@gmail.com |
4afdb4d3f0fa4386bb5ff028542b3ef5ab1ebc61 | e60ca08722245d732f86701cf28b581ac5eeb737 | /xbmc/cores/dvdplayer/DVDCodecs/Overlay/DVDOverlay.h | d58ff2e1025e9a5428d279d1d6e6beb8b1d65f0e | [] | no_license | paulopina21/plxJukebox-11 | 6d915e60b3890ce01bc8a9e560342c982f32fbc7 | 193996ac99b99badab3a1d422806942afca2ad01 | refs/heads/master | 2020-04-09T13:31:35.220058 | 2013-02-06T17:31:23 | 2013-02-06T17:31:23 | 8,056,228 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,833 | h | #pragma once
#include "cores/VideoRenderers/OverlayRenderer.h"
#include "threads/Atomics.h"
#include <assert.h>
#include <vector>
enum DVDOverlayType
{
DVDOVERLAY_TYPE_NONE = -1,
DVDOVERLAY_TYPE_SPU = 1,
DVDOVERLAY_TYPE_TEXT = 2,
DVDOVERLAY_TYPE_IMAGE = 3,
DVDOVERLAY_TYPE_SSA = 4
};
class CDVDOverlay
{
public:
CDVDOverlay(DVDOverlayType type)
{
m_type = type;
iPTSStartTime = 0LL;
iPTSStopTime = 0LL;
bForced = false;
replace = false;
m_references = 1;
iGroupId = 0;
m_overlay = NULL;
}
CDVDOverlay(const CDVDOverlay& src)
{
m_type = src.m_type;
iPTSStartTime = src.iPTSStartTime;
iPTSStopTime = src.iPTSStopTime;
bForced = src.bForced;
replace = src.replace;
iGroupId = src.iGroupId;
if(src.m_overlay)
m_overlay = src.m_overlay->Acquire();
else
m_overlay = NULL;
m_references = 1;
}
virtual ~CDVDOverlay()
{
assert(m_references == 0);
if(m_overlay)
m_overlay->Release();
}
/**
* decrease the reference counter by one.
*/
CDVDOverlay* Acquire()
{
AtomicIncrement(&m_references);
return this;
}
/**
* increase the reference counter by one.
*/
long Release()
{
long count = AtomicDecrement(&m_references);
if (count == 0) delete this;
return count;
}
bool IsOverlayType(DVDOverlayType type) { return (m_type == type); }
double iPTSStartTime;
double iPTSStopTime;
bool bForced; // display, no matter what
bool replace; // replace by next nomatter what stoptime it has
int iGroupId;
OVERLAY::COverlay* m_overlay;
protected:
DVDOverlayType m_type;
private:
long m_references;
};
typedef std::vector<CDVDOverlay*> VecOverlays;
typedef std::vector<CDVDOverlay*>::iterator VecOverlaysIter;
| [
"pontesmail@gmail.com"
] | pontesmail@gmail.com |
d8eb00efa439d5b25c8f295f55218ef004f60a54 | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /components/sync/base/user_selectable_type.cc | a8679835cab178b8ac918d0a203912d872180fdc | [
"BSD-3-Clause"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 7,767 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/base/user_selectable_type.h"
#include <type_traits>
#include "base/logging.h"
#include "base/optional.h"
#include "components/sync/base/model_type.h"
#include "components/sync/base/pref_names.h"
#if defined(OS_CHROMEOS)
#include "chromeos/constants/chromeos_features.h"
#endif
namespace syncer {
namespace {
struct UserSelectableTypeInfo {
const char* const type_name;
const ModelType canonical_model_type;
const ModelTypeSet model_type_group;
};
constexpr char kBookmarksTypeName[] = "bookmarks";
constexpr char kPreferencesTypeName[] = "preferences";
constexpr char kPasswordsTypeName[] = "passwords";
constexpr char kAutofillTypeName[] = "autofill";
constexpr char kThemesTypeName[] = "themes";
constexpr char kTypedUrlsTypeName[] = "typedUrls";
constexpr char kExtensionsTypeName[] = "extensions";
constexpr char kAppsTypeName[] = "apps";
constexpr char kReadingListTypeName[] = "readingList";
constexpr char kTabsTypeName[] = "tabs";
UserSelectableTypeInfo GetUserSelectableTypeInfo(UserSelectableType type) {
// UserSelectableTypeInfo::type_name is used in js code and shouldn't be
// changed without updating js part.
switch (type) {
case UserSelectableType::kBookmarks:
return {kBookmarksTypeName, BOOKMARKS, {BOOKMARKS}};
case UserSelectableType::kPreferences: {
ModelTypeSet model_types = {PREFERENCES, DICTIONARY, PRIORITY_PREFERENCES,
SEARCH_ENGINES};
#if defined(OS_CHROMEOS)
// SplitSettingsSync makes Printers a separate OS setting.
if (!chromeos::features::IsSplitSettingsSyncEnabled())
model_types.Put(PRINTERS);
#endif
return {kPreferencesTypeName, PREFERENCES, model_types};
}
case UserSelectableType::kPasswords:
return {kPasswordsTypeName, PASSWORDS, {PASSWORDS}};
case UserSelectableType::kAutofill:
return {kAutofillTypeName,
AUTOFILL,
{AUTOFILL, AUTOFILL_PROFILE, AUTOFILL_WALLET_DATA,
AUTOFILL_WALLET_METADATA}};
case UserSelectableType::kThemes:
return {kThemesTypeName, THEMES, {THEMES}};
case UserSelectableType::kHistory:
return {kTypedUrlsTypeName,
TYPED_URLS,
{TYPED_URLS, HISTORY_DELETE_DIRECTIVES, SESSIONS, FAVICON_IMAGES,
FAVICON_TRACKING, USER_EVENTS}};
case UserSelectableType::kExtensions:
return {
kExtensionsTypeName, EXTENSIONS, {EXTENSIONS, EXTENSION_SETTINGS}};
case UserSelectableType::kApps: {
#if defined(OS_CHROMEOS)
// SplitSettingsSync moves apps to Chrome OS settings.
if (chromeos::features::IsSplitSettingsSyncEnabled()) {
return {kAppsTypeName, UNSPECIFIED};
} else {
return {kAppsTypeName,
APPS,
{APP_LIST, APPS, APP_SETTINGS, ARC_PACKAGE, WEB_APPS}};
}
#else
return {kAppsTypeName, APPS, {APPS, APP_SETTINGS, WEB_APPS}};
#endif
}
case UserSelectableType::kReadingList:
return {kReadingListTypeName, READING_LIST, {READING_LIST}};
case UserSelectableType::kTabs:
return {kTabsTypeName,
PROXY_TABS,
{PROXY_TABS, SESSIONS, FAVICON_IMAGES, FAVICON_TRACKING,
SEND_TAB_TO_SELF}};
}
NOTREACHED();
return {nullptr, UNSPECIFIED};
}
#if defined(OS_CHROMEOS)
constexpr char kOsAppsTypeName[] = "osApps";
constexpr char kOsPreferencesTypeName[] = "osPreferences";
constexpr char kWifiConfigurationsTypeName[] = "wifiConfigurations";
UserSelectableTypeInfo GetUserSelectableOsTypeInfo(UserSelectableOsType type) {
// UserSelectableTypeInfo::type_name is used in js code and shouldn't be
// changed without updating js part.
switch (type) {
case UserSelectableOsType::kOsApps:
return {kOsAppsTypeName,
APPS,
{APP_LIST, APPS, APP_SETTINGS, ARC_PACKAGE, WEB_APPS}};
case UserSelectableOsType::kOsPreferences:
return {kOsPreferencesTypeName,
OS_PREFERENCES,
{OS_PREFERENCES, OS_PRIORITY_PREFERENCES, PRINTERS}};
case UserSelectableOsType::kWifiConfigurations:
return {kWifiConfigurationsTypeName,
WIFI_CONFIGURATIONS,
{WIFI_CONFIGURATIONS}};
}
}
#endif // defined(OS_CHROMEOS)
} // namespace
const char* GetUserSelectableTypeName(UserSelectableType type) {
return GetUserSelectableTypeInfo(type).type_name;
}
base::Optional<UserSelectableType> GetUserSelectableTypeFromString(
const std::string& type) {
if (type == kBookmarksTypeName) {
return UserSelectableType::kBookmarks;
}
if (type == kPreferencesTypeName) {
return UserSelectableType::kPreferences;
}
if (type == kPasswordsTypeName) {
return UserSelectableType::kPasswords;
}
if (type == kAutofillTypeName) {
return UserSelectableType::kAutofill;
}
if (type == kThemesTypeName) {
return UserSelectableType::kThemes;
}
if (type == kTypedUrlsTypeName) {
return UserSelectableType::kHistory;
}
if (type == kExtensionsTypeName) {
return UserSelectableType::kExtensions;
}
if (type == kAppsTypeName) {
return UserSelectableType::kApps;
}
if (type == kReadingListTypeName) {
return UserSelectableType::kReadingList;
}
if (type == kTabsTypeName) {
return UserSelectableType::kTabs;
}
return base::nullopt;
}
std::string UserSelectableTypeSetToString(UserSelectableTypeSet types) {
std::string result;
for (UserSelectableType type : types) {
if (!result.empty()) {
result += ", ";
}
result += GetUserSelectableTypeName(type);
}
return result;
}
ModelTypeSet UserSelectableTypeToAllModelTypes(UserSelectableType type) {
return GetUserSelectableTypeInfo(type).model_type_group;
}
ModelType UserSelectableTypeToCanonicalModelType(UserSelectableType type) {
return GetUserSelectableTypeInfo(type).canonical_model_type;
}
int UserSelectableTypeToHistogramInt(UserSelectableType type) {
// TODO(crbug.com/1007293): Use ModelTypeHistogramValue instead of casting to
// int.
return static_cast<int>(
ModelTypeHistogramValue(UserSelectableTypeToCanonicalModelType(type)));
}
#if defined(OS_CHROMEOS)
const char* GetUserSelectableOsTypeName(UserSelectableOsType type) {
return GetUserSelectableOsTypeInfo(type).type_name;
}
base::Optional<UserSelectableOsType> GetUserSelectableOsTypeFromString(
const std::string& type) {
if (type == kOsAppsTypeName) {
return UserSelectableOsType::kOsApps;
}
if (type == kOsPreferencesTypeName) {
return UserSelectableOsType::kOsPreferences;
}
if (type == kWifiConfigurationsTypeName) {
return UserSelectableOsType::kWifiConfigurations;
}
// Some pref types migrated from browser prefs to OS prefs. Map the browser
// type name to the OS type so that enterprise policy SyncTypesListDisabled
// still applies to the migrated names during SplitSettingsSync roll-out.
// TODO(https://crbug.com/1059309): Rename "osApps" to "apps" after
// SplitSettingsSync is the default, and remove the mapping for "preferences".
if (type == kAppsTypeName) {
return UserSelectableOsType::kOsApps;
}
if (type == kPreferencesTypeName) {
return UserSelectableOsType::kOsPreferences;
}
return base::nullopt;
}
ModelTypeSet UserSelectableOsTypeToAllModelTypes(UserSelectableOsType type) {
return GetUserSelectableOsTypeInfo(type).model_type_group;
}
ModelType UserSelectableOsTypeToCanonicalModelType(UserSelectableOsType type) {
return GetUserSelectableOsTypeInfo(type).canonical_model_type;
}
#endif // defined(OS_CHROMEOS)
} // namespace syncer
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a2e825a6611e5c74a18cca3ab9de294bb706738a | 871f67f1b50178ad6937cc6855314e7c0973ff6c | /maximum_path_sum_between_two_leaf_nodes.cpp | 65e95ca0e627367bf491fcbab842dc17365a4490 | [] | no_license | anubhav-jangra/geeksforgeeks | c40b154de0347b27bfae8d7d18fc69cc58ceb0ca | f2b27e13a464913d10fa654b50170509458de6f8 | refs/heads/master | 2023-02-19T04:02:29.063815 | 2021-01-19T19:11:54 | 2021-01-19T19:11:54 | 325,098,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,110 | cpp | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// Tree Node
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
// Function to Build Tree
Node *buildTree(string str) {
// Corner Case
if (str.length() == 0 || str[0] == 'N') return NULL;
// Creating vector of strings from input
// string after spliting by space
vector<string> ip;
istringstream iss(str);
for (string str; iss >> str;) ip.push_back(str);
// Create the root of the tree
Node *root = new Node(stoi(ip[0]));
// Push the root to the queue
queue<Node *> queue;
queue.push(root);
// Starting from the second element
int i = 1;
while (!queue.empty() && i < ip.size()) {
// Get and remove the front of the queue
Node *currNode = queue.front();
queue.pop();
// Get the current Node's value from the string
string currVal = ip[i];
// If the left child is not null
if (currVal != "N") {
// Create the left child for the current Node
currNode->left = new Node(stoi(currVal));
// Push it to the queue
queue.push(currNode->left);
}
// For the right child
i++;
if (i >= ip.size()) break;
currVal = ip[i];
// If the right child is not null
if (currVal != "N") {
// Create the right child for the current Node
currNode->right = new Node(stoi(currVal));
// Push it to the queue
queue.push(currNode->right);
}
i++;
}
return root;
}
int maxPathSum(Node *);
int main() {
int tc;
scanf("%d ", &tc);
while (tc--) {
string treeString;
getline(cin, treeString);
Node *root = buildTree(treeString);
cout << maxPathSum(root) << "\n";
}
return 0;
}// } Driver Code Ends
/*
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int x){
data = x;
left = right = NULL;
}
};
*/
// Sol1 O(n) time, O(H) space
// Assumption (after running the expected output code): there will be at least two leaf nodes
int recurseUtil(Node *root, int *path_sum) {
int left_score = INT_MIN, right_score = INT_MIN;
if (root -> left) left_score = recurseUtil(root -> left, path_sum);
if (root -> right) right_score = recurseUtil(root -> right, path_sum);
if (left_score != INT_MIN && right_score != INT_MIN)
*path_sum = max(*path_sum, left_score + right_score + root -> data);
if (left_score == INT_MIN && right_score == INT_MIN) return root -> data;
if (left_score == INT_MIN && right_score != INT_MIN) return root -> data + right_score;
if (left_score != INT_MIN && right_score == INT_MIN) return root -> data + left_score;
else return max(root -> data + left_score, root -> data + right_score);
}
int maxPathSum(Node* root) {
int ans = INT_MIN;
recurseUtil(root, &ans);
return ans;
}
| [
"anubhav0603@gmail.com"
] | anubhav0603@gmail.com |
f8b2487e51dd59a9fa22f92df89a599ca51699d8 | efc3bf4f88a2bfc885de5495c87433d345b54429 | /ZOJ/1514.cpp | 18c89142ebe6634a528db09e57f127e90754a828 | [] | no_license | calvinxiao/Algorithm-Solution | 26ff42cc26aaca87a4706b82a325a92829878552 | afe254a4efa779598be8a82c5c5bcfcc94f80272 | refs/heads/master | 2016-09-05T21:08:35.852486 | 2015-08-23T15:13:23 | 2015-08-23T15:13:23 | 20,149,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | /*
#Problem ID: 1514
#Submit Time: 2012-08-21 13:46:46
#Run Time: 0
#Run Memory: 208
#ZOJ User: calvinxiao
*/
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<cstdio>
#include<memory.h>
using namespace std;
bool v[10001], c[10001];
int t, n, m, ans;
int main()
{
while(1) {
memset(v, 0, sizeof v);
memset(c, 0, sizeof c);
ans = 0;
cin >> n >> m;
if(!n) break;
for(int i = 0; i < m; ++i) {
cin >> t;
if(v[t]) {
if(!c[t])
ans++;
c[t] = 1;
}
else v[t] = 1;
}
cout << ans << endl;
}
return 0;
}
| [
"calvin.xiao@scaurugby.com"
] | calvin.xiao@scaurugby.com |
e01b190421e02787418cbd8ac6c6cdc0e66aea98 | 90495bf0779a2b7930f30a5c3a35551185322ec5 | /Kode/QuadDrone/ControlFaker.cpp | 851411a829b33a746ca14d55a9592df2a90e9d42 | [] | no_license | IHA-Quadro/Drone | e0d353d8fd2971c41ecf9fef2268aa8dd116bc32 | 6600a5204252f3ddc4c084e21024f88f2a4c6b6f | refs/heads/master | 2021-03-12T23:11:57.621012 | 2013-12-17T15:58:55 | 2013-12-17T15:58:55 | 10,316,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,785 | cpp | #include "ControlFaker.h"
int _controllerInput[channelsInUse];
boolean _initialized;
boolean _calibrationPerformed;
boolean _motorsArmed;
boolean _safetyChecked;
void DronePrint(String s)
{
printNewLine(s, DEBUGMODE);
}
void SetupControlFaker()
{
printNewLine("Init ControlFaker", STATUSMODE);
_initialized = false;
_calibrationPerformed = false;
_motorsArmed = false;
_safetyChecked = false;
for(byte i = 0; i < channelsInUse ; i++)
{
_controllerInput[0] = 0;
}
}
void KillMotor()
{
if(getMotorStatus())
{
//Reset axis
byte axis;
for(axis = XAXIS; axis < THROTTLE; axis++)
{
_controllerInput[axis] = 1500;
}
//Thottle killed
_controllerInput[THROTTLE] = 1000;
}
}
void FMSignal()
{
//Code from Rasmus1
}
void SelectProgram()
{
//Run test program or a specific pattern program
}
void SonarCheck()
{
//Needs implementation
}
void CalculateAltitude()
{
//A function may already exist for this
}
void ApplyHeading()
{
KillMotor();
}
void ArmMotors()
{
_controllerInput[ZAXIS] = 2000;
_motorsArmed = true;
}
void SafetyCheck()
{
_controllerInput[ZAXIS] = 1150;
_safetyChecked = true;
}
void PerformCalibration()
{
_controllerInput[ZAXIS] = 1000;
_controllerInput[XAXIS] = 2000;
_controllerInput[YAXIS] = 1000;
_controllerInput[THROTTLE] = 1000;
_calibrationPerformed = true;
}
void ApplySpeed()
{
//Specific for the program.
//Input is missing but not known what format it will be
KillMotor();
}
void ResetInputData()
{
_controllerInput[XAXIS] = 1500;
_controllerInput[YAXIS] = 1500;
_controllerInput[ZAXIS] = 1500;
_controllerInput[THROTTLE] = 1200;
_controllerInput[MODE] = 1000;
_controllerInput[AUX1] = 1000;
//ResetAccelData();
//ResetKinematicData();
//ResetGyroData();
//ResetHeadingData();
}
| [
"git@bakgaard.net"
] | git@bakgaard.net |
5e62378c7726efd3c961ac1ec8fbc49b61b85855 | e84e19c5d52f511ae280bb02d2febb8e0650a116 | /code227.cpp | 5e1273817badf2e05e6cefdabf0d1ae9baaf6d77 | [] | no_license | AlJamilSuvo/LeetCode | 2e3afe0c588d003aa15ea3eb08a8d2ca381c35dd | 9ad26f2974ad4a41a9654a5564fe1ad27ae2463c | refs/heads/master | 2022-03-15T15:43:21.826485 | 2022-03-04T20:40:50 | 2022-03-04T20:40:50 | 174,458,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | #include <bits/stdc++.h>
using namespace std;
class Item
{
public:
bool isOperator = false;
int number = 0;
char op = ' ';
};
class Solution
{
public:
int calculate(string s)
{
queue<Item> outputQue;
stack<char> optStk;
string cur;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
continue;
if (s[i] == '/' || s[i] == '*' || s[i] == '-' || s[i] == '+')
{
if (cur != "")
{
int num = stoi(cur);
Item item;
item.isOperator = false;
item.number = num;
outputQue.push(item);
}
cur = "";
char op1 = s[i];
while (!optStk.empty() && !isGreateOpt(op1, optStk.top()))
{
char op2 = optStk.top();
Item item;
item.isOperator = true;
item.op = op2;
optStk.pop();
}
}
}
}
bool isGreateOpt(char op1, char op2)
{
map<char, int> rank;
rank['/'] = 4;
rank['*'] = 3;
rank['-'] = 2;
rank['+'] = 1;
return rank[op1] >= rank[op2];
}
}; | [
"aljamilsuvo@gmail.com"
] | aljamilsuvo@gmail.com |
b8b65965d0ebb4102c3e9821adb04b75774adac2 | 5762283bd1a94866b54109377c276c31195c7606 | /project-1/src/texture.cpp | a0d451f26cc0b295148f37ca057e804cb51e707a | [
"MIT"
] | permissive | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | de12fe3700e1b05ee7239404bf4265639298e9e5 | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | refs/heads/main | 2023-04-14T01:44:15.960294 | 2021-04-19T08:55:41 | 2021-04-19T08:55:41 | 332,593,421 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,667 | cpp | #include "texture.h"
#include "color.h"
#include <assert.h>
#include <iostream>
#include <algorithm>
using namespace std;
namespace CS248 {
inline void uint8_to_float( float dst[4], unsigned char* src ) {
uint8_t* src_uint8 = (uint8_t *)src;
dst[0] = src_uint8[0] / 255.f;
dst[1] = src_uint8[1] / 255.f;
dst[2] = src_uint8[2] / 255.f;
dst[3] = src_uint8[3] / 255.f;
}
inline void float_to_uint8( unsigned char* dst, float src[4] ) {
uint8_t* dst_uint8 = (uint8_t *)dst;
dst_uint8[0] = (uint8_t) ( 255.f * max( 0.0f, min( 1.0f, src[0])));
dst_uint8[1] = (uint8_t) ( 255.f * max( 0.0f, min( 1.0f, src[1])));
dst_uint8[2] = (uint8_t) ( 255.f * max( 0.0f, min( 1.0f, src[2])));
dst_uint8[3] = (uint8_t) ( 255.f * max( 0.0f, min( 1.0f, src[3])));
}
void Sampler2DImp::generate_mips(Texture& tex, int startLevel) {
// NOTE:
// This starter code allocates the mip levels and generates a level
// map by filling each level with placeholder data in the form of a
// color that differs from its neighbours'. You should instead fill
// with the correct data!
// Extra credit: Implement this
// check start level
if ( startLevel >= tex.mipmap.size() ) {
std::cerr << "Invalid start level";
}
// allocate sublevels
int baseWidth = tex.mipmap[startLevel].width;
int baseHeight = tex.mipmap[startLevel].height;
int numSubLevels = (int)(log2f( (float)max(baseWidth, baseHeight)));
numSubLevels = min(numSubLevels, kMaxMipLevels - startLevel - 1);
tex.mipmap.resize(startLevel + numSubLevels + 1);
int width = baseWidth;
int height = baseHeight;
for (int i = 1; i <= numSubLevels; i++) {
MipLevel& level = tex.mipmap[startLevel + i];
// handle odd size texture by rounding down
width = max( 1, width / 2); assert(width > 0);
height = max( 1, height / 2); assert(height > 0);
level.width = width;
level.height = height;
level.texels = vector<unsigned char>(4 * width * height);
}
// fill all 0 sub levels with interchanging colors
Color colors[3] = { Color(1,0,0,1), Color(0,1,0,1), Color(0,0,1,1) };
for(size_t i = 1; i < tex.mipmap.size(); ++i) {
Color c = colors[i % 3];
MipLevel& mip = tex.mipmap[i];
for(size_t i = 0; i < 4 * mip.width * mip.height; i += 4) {
float_to_uint8( &mip.texels[i], &c.r );
}
}
}
Color Sampler2DImp::sample_nearest(Texture& tex,
float u, float v,
int level) {
// return magenta for invalid level
if (level >= tex.mipmap.size())
return Color(1,0,1,1);
// Task 4: Implement nearest neighbour interpolation
MipLevel mLevel = tex.mipmap[level];
int width = mLevel.width;
int height = mLevel.height;
float x = floor(u * width);
float y = floor(v * height);
Color color;
color.r = mLevel.texels[4 * (x + y * width)] / 255.f;
color.g = mLevel.texels[4 * (x + y * width) + 1] / 255.f;
color.b = mLevel.texels[4 * (x + y * width) + 2] / 255.f;
color.a = mLevel.texels[4 * (x + y * width) + 3] / 255.f;
return color;
}
Color Sampler2DImp::sample_bilinear(Texture& tex,
float u, float v,
int level) {
// Task 4: Implement bilinear filtering
// return magenta for invalid level
return Color(1,0,1,1);
}
Color Sampler2DImp::sample_trilinear(Texture& tex,
float u, float v,
float u_scale, float v_scale) {
// Extra credit: Implement trilinear filtering
// return magenta for invalid level
return Color(1,0,1,1);
}
} // namespace CS248
| [
"carlosrivero96@gmail.com"
] | carlosrivero96@gmail.com |
e423281a83579d1c9156d1d56553aaaaeb4706d5 | 425963de819e446a75441ff901adbfe5f1c5dea6 | /chrome/browser/offline_pages/offline_page_request_handler_unittest.cc | 034b020fdc58bf76a866d9cf70576beeed53a38c | [
"BSD-3-Clause"
] | permissive | Igalia/chromium | 06590680bcc074cf191979c496d84888dbb54df6 | 261db3a6f6a490742786cf841afa92e02a53b33f | refs/heads/ozone-wayland-dev | 2022-12-06T16:31:09.335901 | 2019-12-06T21:11:21 | 2019-12-06T21:11:21 | 85,595,633 | 123 | 25 | NOASSERTION | 2019-02-05T08:04:47 | 2017-03-20T15:45:36 | null | UTF-8 | C++ | false | false | 91,080 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/offline_pages/offline_page_request_job.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/post_task.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/default_clock.h"
#include "chrome/browser/offline_pages/offline_page_model_factory.h"
#include "chrome/browser/offline_pages/offline_page_request_interceptor.h"
#include "chrome/browser/offline_pages/offline_page_tab_helper.h"
#include "chrome/browser/offline_pages/offline_page_url_loader.h"
#include "chrome/browser/renderer_host/chrome_navigation_ui_data.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/offline_pages/core/archive_validator.h"
#include "components/offline_pages/core/client_namespace_constants.h"
#include "components/offline_pages/core/model/offline_page_model_taskified.h"
#include "components/offline_pages/core/offline_page_metadata_store.h"
#include "components/offline_pages/core/request_header/offline_page_navigation_ui_data.h"
#include "components/offline_pages/core/stub_system_download_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/previews_state.h"
#include "content/public/common/resource_type.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "mojo/public/cpp/system/wait.h"
#include "net/base/filename_util.h"
#include "net/http/http_request_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace offline_pages {
namespace {
const char kPrivateOfflineFileDir[] = "offline_pages";
const char kPublicOfflineFileDir[] = "public_offline_pages";
const GURL kUrl("http://test.org/page");
const GURL kUrl2("http://test.org/another");
const base::FilePath kFilename1(FILE_PATH_LITERAL("hello.mhtml"));
const base::FilePath kFilename2(FILE_PATH_LITERAL("test.mhtml"));
const base::FilePath kNonexistentFilename(
FILE_PATH_LITERAL("nonexistent.mhtml"));
const int kFileSize1 = 471; // Real size of hello.mhtml.
const int kFileSize2 = 444; // Real size of test.mhtml.
const int kMismatchedFileSize = 99999;
const std::string kDigest1(
"\x43\x60\x62\x02\x06\x15\x0f\x3e\x77\x99\x3d\xed\xdc\xd4\xe2\x0d\xbe\xbd"
"\x77\x1a\xfb\x32\x00\x51\x7e\x63\x7d\x3b\x2e\x46\x63\xf6",
32); // SHA256 Hash of hello.mhtml.
const std::string kDigest2(
"\xBD\xD3\x37\x79\xDA\x7F\x4E\x6A\x16\x66\xED\x49\x67\x18\x54\x48\xC6\x8E"
"\xA1\x47\x16\xA5\x44\x45\x43\xD0\x0E\x04\x9F\x4C\x45\xDC",
32); // SHA256 Hash of test.mhtml.
const std::string kMismatchedDigest(
"\xff\x64\xF9\x7C\x94\xE5\x9E\x91\x83\x3D\x41\xB0\x36\x90\x0A\xDF\xB3\xB1"
"\x5C\x13\xBE\xB8\x35\x8C\xF6\x5B\xC4\xB5\x5A\xFC\x3A\xCC",
32); // Wrong SHA256 Hash.
const int kTabId = 1;
const int kBufSize = 1024;
const char kAggregatedRequestResultHistogram[] =
"OfflinePages.AggregatedRequestResult2";
const char kOpenFileErrorCodeHistogram[] =
"OfflinePages.RequestJob.OpenFileErrorCode";
const char kSeekFileErrorCodeHistogram[] =
"OfflinePages.RequestJob.SeekFileErrorCode";
const char kAccessEntryPointHistogram[] = "OfflinePages.AccessEntryPoint.";
const char kPageSizeAccessOfflineHistogramBase[] =
"OfflinePages.PageSizeOnAccess.Offline.";
const char kPageSizeAccessOnlineHistogramBase[] =
"OfflinePages.PageSizeOnAccess.Online.";
const int64_t kDownloadId = 42LL;
struct ResponseInfo {
explicit ResponseInfo(int request_status) : request_status(request_status) {
DCHECK_NE(net::OK, request_status);
}
ResponseInfo(int request_status,
const std::string& mime_type,
const std::string& data_received)
: request_status(request_status),
mime_type(mime_type),
data_received(data_received) {}
int request_status;
std::string mime_type;
std::string data_received;
};
class TestURLRequestDelegate : public net::URLRequest::Delegate {
public:
typedef base::Callback<void(const ResponseInfo&)> ReadCompletedCallback;
explicit TestURLRequestDelegate(const ReadCompletedCallback& callback)
: read_completed_callback_(callback),
buffer_(base::MakeRefCounted<net::IOBuffer>(kBufSize)),
request_status_(net::ERR_IO_PENDING) {}
void OnResponseStarted(net::URLRequest* request, int net_error) override {
DCHECK_NE(net::ERR_IO_PENDING, net_error);
if (net_error != net::OK) {
OnReadCompleted(request, net_error);
return;
}
// Initiate the first read.
int bytes_read = request->Read(buffer_.get(), kBufSize);
if (bytes_read >= 0) {
OnReadCompleted(request, bytes_read);
} else if (bytes_read != net::ERR_IO_PENDING) {
request_status_ = bytes_read;
OnResponseCompleted(request);
}
}
void OnReadCompleted(net::URLRequest* request, int bytes_read) override {
if (bytes_read > 0)
data_received_.append(buffer_->data(), bytes_read);
// If it was not end of stream, request to read more.
while (bytes_read > 0) {
bytes_read = request->Read(buffer_.get(), kBufSize);
if (bytes_read > 0)
data_received_.append(buffer_->data(), bytes_read);
}
request_status_ = (bytes_read >= 0) ? net::OK : bytes_read;
if (bytes_read != net::ERR_IO_PENDING)
OnResponseCompleted(request);
}
private:
void OnResponseCompleted(net::URLRequest* request) {
if (request_status_ != net::OK)
data_received_.clear();
if (read_completed_callback_.is_null())
return;
std::string mime_type;
request->GetMimeType(&mime_type);
read_completed_callback_.Run(
ResponseInfo(request_status_, mime_type, data_received_));
}
ReadCompletedCallback read_completed_callback_;
scoped_refptr<net::IOBuffer> buffer_;
std::string data_received_;
int request_status_;
DISALLOW_COPY_AND_ASSIGN(TestURLRequestDelegate);
};
content::WebContents* GetWebContents(content::WebContents* web_contents) {
return web_contents;
}
bool GetTabId(int tab_id_value,
content::WebContents* web_content,
int* tab_id) {
*tab_id = tab_id_value;
return true;
}
class TestURLRequestInterceptingJobFactory
: public net::URLRequestInterceptingJobFactory {
public:
TestURLRequestInterceptingJobFactory(
std::unique_ptr<net::URLRequestJobFactory> job_factory,
std::unique_ptr<net::URLRequestInterceptor> interceptor,
content::WebContents* web_contents)
: net::URLRequestInterceptingJobFactory(std::move(job_factory),
std::move(interceptor)),
web_contents_(web_contents) {}
~TestURLRequestInterceptingJobFactory() override { web_contents_ = nullptr; }
net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
const std::string& scheme,
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override {
net::URLRequestJob* job = net::URLRequestInterceptingJobFactory::
MaybeCreateJobWithProtocolHandler(scheme, request, network_delegate);
if (job) {
OfflinePageRequestJob* offline_page_request_job =
static_cast<OfflinePageRequestJob*>(job);
offline_page_request_job->SetWebContentsGetterForTesting(
base::BindRepeating(&GetWebContents, web_contents_));
offline_page_request_job->SetTabIdGetterForTesting(
base::BindRepeating(&GetTabId, kTabId));
}
return job;
}
private:
content::WebContents* web_contents_;
DISALLOW_COPY_AND_ASSIGN(TestURLRequestInterceptingJobFactory);
};
class TestNetworkChangeNotifier : public net::NetworkChangeNotifier {
public:
TestNetworkChangeNotifier() : online_(true) {}
~TestNetworkChangeNotifier() override {}
net::NetworkChangeNotifier::ConnectionType GetCurrentConnectionType()
const override {
return online_ ? net::NetworkChangeNotifier::CONNECTION_UNKNOWN
: net::NetworkChangeNotifier::CONNECTION_NONE;
}
bool online() const { return online_; }
void set_online(bool online) { online_ = online; }
private:
bool online_;
DISALLOW_COPY_AND_ASSIGN(TestNetworkChangeNotifier);
};
// TODO(jianli, carlosk): This should be removed in favor of using with
// OfflinePageTestArchiver.
class TestOfflinePageArchiver : public OfflinePageArchiver {
public:
TestOfflinePageArchiver(const GURL& url,
const base::FilePath& archive_file_path,
int archive_file_size,
const std::string& digest)
: url_(url),
archive_file_path_(archive_file_path),
archive_file_size_(archive_file_size),
digest_(digest) {}
~TestOfflinePageArchiver() override {}
void CreateArchive(const base::FilePath& archives_dir,
const CreateArchiveParams& create_archive_params,
content::WebContents* web_contents,
CreateArchiveCallback callback) override {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback),
ArchiverResult::SUCCESSFULLY_CREATED, url_,
archive_file_path_, base::string16(),
archive_file_size_, digest_));
}
void PublishArchive(
const OfflinePageItem& offline_page,
const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
const base::FilePath& new_file_path,
SystemDownloadManager* download_manager,
PublishArchiveDoneCallback publish_done_callback) override {
publish_archive_result_.move_result = SavePageResult::SUCCESS;
publish_archive_result_.new_file_path = offline_page.file_path;
publish_archive_result_.download_id = 0;
std::move(publish_done_callback).Run(offline_page, publish_archive_result_);
}
private:
const GURL url_;
const base::FilePath archive_file_path_;
const int archive_file_size_;
const std::string digest_;
PublishArchiveResult publish_archive_result_;
DISALLOW_COPY_AND_ASSIGN(TestOfflinePageArchiver);
};
class TestURLLoaderClient : public network::mojom::URLLoaderClient {
public:
class Observer {
public:
virtual void OnReceiveRedirect(const GURL& redirected_url) = 0;
virtual void OnReceiveResponse(
const network::ResourceResponseHead& response_head) = 0;
virtual void OnStartLoadingResponseBody() = 0;
virtual void OnComplete() = 0;
protected:
virtual ~Observer() {}
};
explicit TestURLLoaderClient(Observer* observer)
: observer_(observer), binding_(this) {}
~TestURLLoaderClient() override {}
void OnReceiveResponse(
const network::ResourceResponseHead& response_head) override {
observer_->OnReceiveResponse(response_head);
}
void OnReceiveRedirect(
const net::RedirectInfo& redirect_info,
const network::ResourceResponseHead& response_head) override {
observer_->OnReceiveRedirect(redirect_info.new_url);
}
void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {}
void OnTransferSizeUpdated(int32_t transfer_size_diff) override {}
void OnUploadProgress(int64_t current_position,
int64_t total_size,
OnUploadProgressCallback ack_callback) override {}
void OnStartLoadingResponseBody(
mojo::ScopedDataPipeConsumerHandle body) override {
response_body_ = std::move(body);
observer_->OnStartLoadingResponseBody();
}
void OnComplete(const network::URLLoaderCompletionStatus& status) override {
completion_status_ = status;
observer_->OnComplete();
}
network::mojom::URLLoaderClientPtr CreateInterfacePtr() {
network::mojom::URLLoaderClientPtr client_ptr;
binding_.Bind(mojo::MakeRequest(&client_ptr));
binding_.set_connection_error_handler(base::BindOnce(
&TestURLLoaderClient::OnConnectionError, base::Unretained(this)));
return client_ptr;
}
mojo::DataPipeConsumerHandle response_body() { return response_body_.get(); }
const network::URLLoaderCompletionStatus& completion_status() const {
return completion_status_;
}
private:
void OnConnectionError() {}
Observer* observer_ = nullptr;
mojo::Binding<network::mojom::URLLoaderClient> binding_;
mojo::ScopedDataPipeConsumerHandle response_body_;
network::URLLoaderCompletionStatus completion_status_;
DISALLOW_COPY_AND_ASSIGN(TestURLLoaderClient);
};
// Helper function to make a character array filled with |size| bytes of
// test content.
std::string MakeContentOfSize(int size) {
EXPECT_GE(size, 0);
std::string result;
result.reserve(size);
for (int i = 0; i < size; i++)
result.append(1, static_cast<char>(i % 256));
return result;
}
static network::ResourceRequest CreateResourceRequest(
const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) {
network::ResourceRequest request;
request.method = method;
request.headers = extra_headers;
request.url = url;
request.is_main_frame = is_main_frame;
return request;
}
} // namespace
class OfflinePageRequestHandlerTestBase : public testing::Test {
public:
OfflinePageRequestHandlerTestBase();
~OfflinePageRequestHandlerTestBase() override {}
virtual void InterceptRequest(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) = 0;
void SetUp() override;
void TearDown() override;
void SimulateHasNetworkConnectivity(bool has_connectivity);
void RunUntilIdle();
void WaitForAsyncOperation();
base::FilePath CreateFileWithContent(const std::string& content);
// Returns an offline id of the saved page.
// |file_path| in SavePublicPage and SaveInternalPage can be either absolute
// or relative. If relative, |file_path| will be appended to public/internal
// archive directory used for the testing.
// |file_path| in SavePage should be absolute.
int64_t SavePublicPage(const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest);
int64_t SaveInternalPage(const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest);
int64_t SavePage(const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest);
OfflinePageItem GetPage(int64_t offline_id);
void LoadPage(const GURL& url);
void LoadPageWithHeaders(const GURL& url,
const net::HttpRequestHeaders& extra_headers);
void ReadCompleted(const ResponseInfo& reponse,
bool is_offline_page_set_in_navigation_data);
// Expect exactly one count of |result| UMA reported. No other bucket should
// have sample.
void ExpectOneUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result);
// Expect exactly |count| of |result| UMA reported. No other bucket should
// have sample.
void ExpectMultiUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result,
int count);
// Expect one count of |result| UMA reported. Other buckets may have samples
// as well.
void ExpectOneNonuniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result);
// Expect no samples to have been reported to the aggregated results
// histogram.
void ExpectNoSamplesInAggregatedRequestResult();
void ExpectOpenFileErrorCode(int result);
void ExpectSeekFileErrorCode(int result);
void ExpectAccessEntryPoint(
OfflinePageRequestHandler::AccessEntryPoint entry_point);
void ExpectNoAccessEntryPoint();
void ExpectOfflinePageSizeUniqueSample(int bucket, int count);
void ExpectOfflinePageSizeTotalSuffixCount(int count);
void ExpectOnlinePageSizeUniqueSample(int bucket, int count);
void ExpectOnlinePageSizeTotalSuffixCount(int count);
void ExpectOfflinePageAccessCount(int64_t offline_id, int count);
void ExpectNoOfflinePageServed(
int64_t offline_id,
OfflinePageRequestHandler::AggregatedRequestResult
expected_request_result);
void ExpectOfflinePageServed(
int64_t expected_offline_id,
int expected_file_size,
OfflinePageRequestHandler::AggregatedRequestResult
expected_request_result);
// Use the offline header with specific reason and offline_id. Return the
// full header string.
std::string UseOfflinePageHeader(OfflinePageHeader::Reason reason,
int64_t offline_id);
std::string UseOfflinePageHeaderForIntent(OfflinePageHeader::Reason reason,
int64_t offline_id,
const GURL& intent_url);
Profile* profile() { return profile_; }
content::WebContents* web_contents() const { return web_contents_.get(); }
OfflinePageTabHelper* offline_page_tab_helper() const {
return offline_page_tab_helper_;
}
int request_status() const { return response_.request_status; }
int bytes_read() const { return response_.data_received.length(); }
const std::string& data_received() const { return response_.data_received; }
const std::string& mime_type() const { return response_.mime_type; }
bool is_offline_page_set_in_navigation_data() const {
return is_offline_page_set_in_navigation_data_;
}
bool is_connected_with_good_network() {
return network_change_notifier_->online() &&
// Exclude prohibitively slow network.
!allow_preview() &&
// Exclude flaky network.
offline_page_header_.reason != OfflinePageHeader::Reason::NET_ERROR;
}
void set_allow_preview(bool allow_preview) { allow_preview_ = allow_preview; }
bool allow_preview() const { return allow_preview_; }
private:
static std::unique_ptr<KeyedService> BuildTestOfflinePageModel(
SimpleFactoryKey* key);
// TODO(https://crbug.com/809610): The static members below will be removed
// once the reference to BuildTestOfflinePageModel in SetUp is converted to a
// base::OnceCallback.
static base::FilePath private_archives_dir_;
static base::FilePath public_archives_dir_;
OfflinePageRequestHandler::AccessEntryPoint GetExpectedAccessEntryPoint()
const;
void OnSavePageDone(SavePageResult result, int64_t offline_id);
void OnGetPageByOfflineIdDone(const OfflinePageItem* pages);
// Runs on IO thread.
void CreateFileWithContentOnIO(const std::string& content,
const base::Closure& callback);
content::TestBrowserThreadBundle thread_bundle_;
TestingProfileManager profile_manager_;
TestingProfile* profile_;
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<base::HistogramTester> histogram_tester_;
OfflinePageTabHelper* offline_page_tab_helper_; // Not owned.
int64_t last_offline_id_;
ResponseInfo response_;
bool is_offline_page_set_in_navigation_data_;
OfflinePageItem page_;
OfflinePageHeader offline_page_header_;
// These are not thread-safe. But they can be used in the pattern that
// setting the state is done first from one thread and reading this state
// can be from any other thread later.
std::unique_ptr<TestNetworkChangeNotifier> network_change_notifier_;
bool allow_preview_ = false;
// These should only be accessed purely from IO thread.
base::ScopedTempDir private_archives_temp_base_dir_;
base::ScopedTempDir public_archives_temp_base_dir_;
base::ScopedTempDir temp_dir_;
base::FilePath temp_file_path_;
int file_name_sequence_num_ = 0;
bool async_operation_completed_ = false;
base::Closure async_operation_completed_callback_;
DISALLOW_COPY_AND_ASSIGN(OfflinePageRequestHandlerTestBase);
};
OfflinePageRequestHandlerTestBase::OfflinePageRequestHandlerTestBase()
: thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD),
profile_manager_(TestingBrowserProcess::GetGlobal()),
last_offline_id_(0),
response_(net::ERR_IO_PENDING),
is_offline_page_set_in_navigation_data_(false),
network_change_notifier_(new TestNetworkChangeNotifier) {}
void OfflinePageRequestHandlerTestBase::SetUp() {
// Create a test profile.
ASSERT_TRUE(profile_manager_.SetUp());
profile_ = profile_manager_.CreateTestingProfile("Profile 1");
// Create a test web contents.
web_contents_ = content::WebContents::Create(
content::WebContents::CreateParams(profile_));
OfflinePageTabHelper::CreateForWebContents(web_contents_.get());
offline_page_tab_helper_ =
OfflinePageTabHelper::FromWebContents(web_contents_.get());
// Set up the factory for testing.
// Note: The extra dir into the temp folder is needed so that the helper
// dir-copy operation works properly. That operation copies the source dir
// final path segment into the destination, and not only its immediate
// contents so this same-named path here makes the archive dir variable point
// to the correct location.
// TODO(romax): add the more recent "temporary" dir here instead of reusing
// the private one.
ASSERT_TRUE(private_archives_temp_base_dir_.CreateUniqueTempDir());
private_archives_dir_ = private_archives_temp_base_dir_.GetPath().AppendASCII(
kPrivateOfflineFileDir);
ASSERT_TRUE(public_archives_temp_base_dir_.CreateUniqueTempDir());
public_archives_dir_ = public_archives_temp_base_dir_.GetPath().AppendASCII(
kPublicOfflineFileDir);
OfflinePageModelFactory::GetInstance()->SetTestingFactoryAndUse(
profile()->GetSimpleFactoryKey(), profile()->GetPrefs(),
base::BindRepeating(
&OfflinePageRequestHandlerTestBase::BuildTestOfflinePageModel));
// Initialize OfflinePageModel.
OfflinePageModelTaskified* model = static_cast<OfflinePageModelTaskified*>(
OfflinePageModelFactory::GetForBrowserContext(profile()));
// Skip the logic to clear the original URL if it is same as final URL.
// This is needed in order to test that offline page request handler can
// omit the redirect under this circumstance, for compatibility with the
// metadata already written to the store.
model->SetSkipClearingOriginalUrlForTesting();
// Avoid running the model's maintenance tasks.
model->DoNotRunMaintenanceTasksForTesting();
// Move test data files into their respective temporary test directories. The
// model's maintenance tasks must not be executed in the meantime otherwise
// these files will be wiped by consistency checks.
base::FilePath test_data_dir_path;
base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_path);
base::FilePath test_data_private_archives_dir =
test_data_dir_path.AppendASCII(kPrivateOfflineFileDir);
ASSERT_TRUE(base::CopyDirectory(test_data_private_archives_dir,
private_archives_dir_.DirName(), true));
base::FilePath test_data_public_archives_dir =
test_data_dir_path.AppendASCII(kPublicOfflineFileDir);
ASSERT_TRUE(base::CopyDirectory(test_data_public_archives_dir,
public_archives_dir_.DirName(), true));
histogram_tester_ = std::make_unique<base::HistogramTester>();
}
void OfflinePageRequestHandlerTestBase::TearDown() {
EXPECT_TRUE(private_archives_temp_base_dir_.Delete());
EXPECT_TRUE(public_archives_temp_base_dir_.Delete());
// This check confirms that the model's maintenance tasks were not executed
// during the test run.
histogram_tester_->ExpectTotalCount("OfflinePages.ClearTemporaryPages.Result",
0);
}
void OfflinePageRequestHandlerTestBase::SimulateHasNetworkConnectivity(
bool online) {
network_change_notifier_->set_online(online);
}
void OfflinePageRequestHandlerTestBase::RunUntilIdle() {
base::RunLoop().RunUntilIdle();
}
void OfflinePageRequestHandlerTestBase::WaitForAsyncOperation() {
// No need to wait if async operation is not needed.
if (async_operation_completed_)
return;
base::RunLoop run_loop;
async_operation_completed_callback_ = run_loop.QuitClosure();
run_loop.Run();
}
void OfflinePageRequestHandlerTestBase::CreateFileWithContentOnIO(
const std::string& content,
const base::Closure& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!temp_dir_.IsValid()) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
std::string file_name("test");
file_name += base::NumberToString(file_name_sequence_num_++);
file_name += ".mht";
temp_file_path_ = temp_dir_.GetPath().AppendASCII(file_name);
ASSERT_NE(base::WriteFile(temp_file_path_, content.c_str(), content.length()),
-1);
callback.Run();
}
base::FilePath OfflinePageRequestHandlerTestBase::CreateFileWithContent(
const std::string& content) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::RunLoop run_loop;
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(
&OfflinePageRequestHandlerTestBase::CreateFileWithContentOnIO,
base::Unretained(this), content, run_loop.QuitClosure()));
run_loop.Run();
return temp_file_path_;
}
void OfflinePageRequestHandlerTestBase::
ExpectOneUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result) {
histogram_tester_->ExpectUniqueSample(kAggregatedRequestResultHistogram,
static_cast<int>(result), 1);
}
void OfflinePageRequestHandlerTestBase::
ExpectMultiUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result,
int count) {
histogram_tester_->ExpectUniqueSample(kAggregatedRequestResultHistogram,
static_cast<int>(result), count);
}
void OfflinePageRequestHandlerTestBase::
ExpectOneNonuniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult result) {
histogram_tester_->ExpectBucketCount(kAggregatedRequestResultHistogram,
static_cast<int>(result), 1);
}
void OfflinePageRequestHandlerTestBase::
ExpectNoSamplesInAggregatedRequestResult() {
histogram_tester_->ExpectTotalCount(kAggregatedRequestResultHistogram, 0);
}
void OfflinePageRequestHandlerTestBase::ExpectOpenFileErrorCode(int result) {
histogram_tester_->ExpectUniqueSample(kOpenFileErrorCodeHistogram, -result,
1);
}
void OfflinePageRequestHandlerTestBase::ExpectSeekFileErrorCode(int result) {
histogram_tester_->ExpectUniqueSample(kSeekFileErrorCodeHistogram, -result,
1);
}
void OfflinePageRequestHandlerTestBase::ExpectAccessEntryPoint(
OfflinePageRequestHandler::AccessEntryPoint entry_point) {
histogram_tester_->ExpectUniqueSample(
std::string(kAccessEntryPointHistogram) + kDownloadNamespace,
static_cast<int>(entry_point), 1);
}
void OfflinePageRequestHandlerTestBase::ExpectNoAccessEntryPoint() {
EXPECT_TRUE(
histogram_tester_->GetTotalCountsForPrefix(kAccessEntryPointHistogram)
.empty());
}
void OfflinePageRequestHandlerTestBase::ExpectOfflinePageSizeUniqueSample(
int bucket,
int count) {
histogram_tester_->ExpectUniqueSample(
std::string(kPageSizeAccessOfflineHistogramBase) + kDownloadNamespace,
bucket, count);
}
void OfflinePageRequestHandlerTestBase::ExpectOfflinePageSizeTotalSuffixCount(
int count) {
int total_offline_count = 0;
base::HistogramTester::CountsMap all_offline_counts =
histogram_tester_->GetTotalCountsForPrefix(
kPageSizeAccessOfflineHistogramBase);
for (const std::pair<std::string, base::HistogramBase::Count>&
namespace_and_count : all_offline_counts) {
total_offline_count += namespace_and_count.second;
}
EXPECT_EQ(count, total_offline_count)
<< "Wrong histogram samples count under prefix "
<< kPageSizeAccessOfflineHistogramBase << "*";
}
void OfflinePageRequestHandlerTestBase::ExpectOnlinePageSizeUniqueSample(
int bucket,
int count) {
histogram_tester_->ExpectUniqueSample(
std::string(kPageSizeAccessOnlineHistogramBase) + kDownloadNamespace,
bucket, count);
}
void OfflinePageRequestHandlerTestBase::ExpectOnlinePageSizeTotalSuffixCount(
int count) {
int online_count = 0;
base::HistogramTester::CountsMap all_online_counts =
histogram_tester_->GetTotalCountsForPrefix(
kPageSizeAccessOnlineHistogramBase);
for (const std::pair<std::string, base::HistogramBase::Count>&
namespace_and_count : all_online_counts) {
online_count += namespace_and_count.second;
}
EXPECT_EQ(count, online_count)
<< "Wrong histogram samples count under prefix "
<< kPageSizeAccessOnlineHistogramBase << "*";
}
void OfflinePageRequestHandlerTestBase::ExpectOfflinePageAccessCount(
int64_t offline_id,
int count) {
OfflinePageItem offline_page = GetPage(offline_id);
EXPECT_EQ(count, offline_page.access_count);
}
void OfflinePageRequestHandlerTestBase::ExpectNoOfflinePageServed(
int64_t offline_id,
OfflinePageRequestHandler::AggregatedRequestResult
expected_request_result) {
EXPECT_NE("multipart/related", mime_type());
EXPECT_EQ(0, bytes_read());
EXPECT_FALSE(is_offline_page_set_in_navigation_data());
EXPECT_FALSE(offline_page_tab_helper()->GetOfflinePageForTest());
if (expected_request_result !=
OfflinePageRequestHandler::AggregatedRequestResult::
AGGREGATED_REQUEST_RESULT_MAX) {
ExpectOneUniqueSampleForAggregatedRequestResult(expected_request_result);
}
ExpectNoAccessEntryPoint();
ExpectOfflinePageSizeTotalSuffixCount(0);
ExpectOnlinePageSizeTotalSuffixCount(0);
ExpectOfflinePageAccessCount(offline_id, 0);
}
void OfflinePageRequestHandlerTestBase::ExpectOfflinePageServed(
int64_t expected_offline_id,
int expected_file_size,
OfflinePageRequestHandler::AggregatedRequestResult
expected_request_result) {
EXPECT_EQ(net::OK, request_status());
EXPECT_EQ("multipart/related", mime_type());
EXPECT_EQ(expected_file_size, bytes_read());
EXPECT_TRUE(is_offline_page_set_in_navigation_data());
ASSERT_TRUE(offline_page_tab_helper()->GetOfflinePageForTest());
EXPECT_EQ(expected_offline_id,
offline_page_tab_helper()->GetOfflinePageForTest()->offline_id);
OfflinePageTrustedState expected_trusted_state =
private_archives_dir_.IsParent(
offline_page_tab_helper()->GetOfflinePageForTest()->file_path)
? OfflinePageTrustedState::TRUSTED_AS_IN_INTERNAL_DIR
: OfflinePageTrustedState::TRUSTED_AS_UNMODIFIED_AND_IN_PUBLIC_DIR;
EXPECT_EQ(expected_trusted_state,
offline_page_tab_helper()->GetTrustedStateForTest());
if (expected_request_result !=
OfflinePageRequestHandler::AggregatedRequestResult::
AGGREGATED_REQUEST_RESULT_MAX) {
ExpectOneUniqueSampleForAggregatedRequestResult(expected_request_result);
}
OfflinePageRequestHandler::AccessEntryPoint expected_entry_point =
GetExpectedAccessEntryPoint();
ExpectAccessEntryPoint(expected_entry_point);
if (is_connected_with_good_network()) {
ExpectOnlinePageSizeUniqueSample(expected_file_size / 1024, 1);
ExpectOfflinePageSizeTotalSuffixCount(0);
} else {
ExpectOfflinePageSizeUniqueSample(expected_file_size / 1024, 1);
ExpectOnlinePageSizeTotalSuffixCount(0);
}
ExpectOfflinePageAccessCount(expected_offline_id, 1);
}
OfflinePageRequestHandler::AccessEntryPoint
OfflinePageRequestHandlerTestBase::GetExpectedAccessEntryPoint() const {
switch (offline_page_header_.reason) {
case OfflinePageHeader::Reason::DOWNLOAD:
return OfflinePageRequestHandler::AccessEntryPoint::DOWNLOADS;
case OfflinePageHeader::Reason::NOTIFICATION:
return OfflinePageRequestHandler::AccessEntryPoint::NOTIFICATION;
case OfflinePageHeader::Reason::FILE_URL_INTENT:
return OfflinePageRequestHandler::AccessEntryPoint::FILE_URL_INTENT;
case OfflinePageHeader::Reason::CONTENT_URL_INTENT:
return OfflinePageRequestHandler::AccessEntryPoint::CONTENT_URL_INTENT;
case OfflinePageHeader::Reason::NET_ERROR_SUGGESTION:
return OfflinePageRequestHandler::AccessEntryPoint::NET_ERROR_PAGE;
default:
return OfflinePageRequestHandler::AccessEntryPoint::LINK;
}
}
std::string OfflinePageRequestHandlerTestBase::UseOfflinePageHeader(
OfflinePageHeader::Reason reason,
int64_t offline_id) {
DCHECK_NE(OfflinePageHeader::Reason::NONE, reason);
offline_page_header_.reason = reason;
if (offline_id)
offline_page_header_.id = base::NumberToString(offline_id);
return offline_page_header_.GetCompleteHeaderString();
}
std::string OfflinePageRequestHandlerTestBase::UseOfflinePageHeaderForIntent(
OfflinePageHeader::Reason reason,
int64_t offline_id,
const GURL& intent_url) {
DCHECK_NE(OfflinePageHeader::Reason::NONE, reason);
DCHECK(offline_id);
offline_page_header_.reason = reason;
offline_page_header_.id = base::NumberToString(offline_id);
offline_page_header_.intent_url = intent_url;
return offline_page_header_.GetCompleteHeaderString();
}
int64_t OfflinePageRequestHandlerTestBase::SavePublicPage(
const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest) {
base::FilePath final_path;
if (file_path.IsAbsolute()) {
final_path = file_path;
} else {
final_path = public_archives_dir_.Append(file_path);
}
return SavePage(url, original_url, final_path, file_size, digest);
}
int64_t OfflinePageRequestHandlerTestBase::SaveInternalPage(
const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest) {
base::FilePath final_path;
if (file_path.IsAbsolute()) {
final_path = file_path;
} else {
final_path = private_archives_dir_.Append(file_path);
}
return SavePage(url, original_url, final_path, file_size, digest);
}
int64_t OfflinePageRequestHandlerTestBase::SavePage(
const GURL& url,
const GURL& original_url,
const base::FilePath& file_path,
int64_t file_size,
const std::string& digest) {
DCHECK(file_path.IsAbsolute());
static int item_counter = 0;
++item_counter;
std::unique_ptr<TestOfflinePageArchiver> archiver(
new TestOfflinePageArchiver(url, file_path, file_size, digest));
async_operation_completed_ = false;
OfflinePageModel::SavePageParams save_page_params;
save_page_params.url = url;
save_page_params.client_id =
ClientId(kDownloadNamespace, base::NumberToString(item_counter));
save_page_params.original_url = original_url;
OfflinePageModelFactory::GetForBrowserContext(profile())->SavePage(
save_page_params, std::move(archiver), nullptr,
base::Bind(&OfflinePageRequestHandlerTestBase::OnSavePageDone,
base::Unretained(this)));
WaitForAsyncOperation();
return last_offline_id_;
}
// static
std::unique_ptr<KeyedService>
OfflinePageRequestHandlerTestBase::BuildTestOfflinePageModel(
SimpleFactoryKey* key) {
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
base::ThreadTaskRunnerHandle::Get();
base::FilePath store_path =
key->path().Append(chrome::kOfflinePageMetadataDirname);
std::unique_ptr<OfflinePageMetadataStore> metadata_store(
new OfflinePageMetadataStore(task_runner, store_path));
std::unique_ptr<SystemDownloadManager> download_manager(
new StubSystemDownloadManager(kDownloadId, true));
// Since we're not saving page into temporary dir, it's set the same as the
// private dir.
std::unique_ptr<ArchiveManager> archive_manager(
new ArchiveManager(private_archives_dir_, private_archives_dir_,
public_archives_dir_, task_runner));
return std::unique_ptr<KeyedService>(new OfflinePageModelTaskified(
std::move(metadata_store), std::move(archive_manager),
std::move(download_manager), task_runner));
}
// static
base::FilePath OfflinePageRequestHandlerTestBase::private_archives_dir_;
base::FilePath OfflinePageRequestHandlerTestBase::public_archives_dir_;
void OfflinePageRequestHandlerTestBase::OnSavePageDone(SavePageResult result,
int64_t offline_id) {
ASSERT_EQ(SavePageResult::SUCCESS, result);
last_offline_id_ = offline_id;
async_operation_completed_ = true;
if (!async_operation_completed_callback_.is_null())
async_operation_completed_callback_.Run();
}
OfflinePageItem OfflinePageRequestHandlerTestBase::GetPage(int64_t offline_id) {
OfflinePageModelFactory::GetForBrowserContext(profile())->GetPageByOfflineId(
offline_id,
base::Bind(&OfflinePageRequestHandlerTestBase::OnGetPageByOfflineIdDone,
base::Unretained(this)));
RunUntilIdle();
return page_;
}
void OfflinePageRequestHandlerTestBase::OnGetPageByOfflineIdDone(
const OfflinePageItem* page) {
ASSERT_TRUE(page);
page_ = *page;
}
void OfflinePageRequestHandlerTestBase::LoadPage(const GURL& url) {
InterceptRequest(url, "GET", net::HttpRequestHeaders(),
true /* is_main_frame */);
}
void OfflinePageRequestHandlerTestBase::LoadPageWithHeaders(
const GURL& url,
const net::HttpRequestHeaders& extra_headers) {
InterceptRequest(url, "GET", extra_headers, true /* is_main_frame */);
}
void OfflinePageRequestHandlerTestBase::ReadCompleted(
const ResponseInfo& response,
bool is_offline_page_set_in_navigation_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
response_ = response;
is_offline_page_set_in_navigation_data_ =
is_offline_page_set_in_navigation_data;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
template <typename T>
class OfflinePageRequestHandlerTest : public OfflinePageRequestHandlerTestBase {
public:
OfflinePageRequestHandlerTest() : interceptor_factory_(this) {}
void InterceptRequest(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
interceptor_factory_.InterceptRequest(url, method, extra_headers,
is_main_frame);
}
private:
T interceptor_factory_;
};
// Builds an OfflinePageRequestJob to test the request interception without
// network service enabled.
class OfflinePageRequestJobBuilder {
public:
explicit OfflinePageRequestJobBuilder(
OfflinePageRequestHandlerTestBase* test_base)
: test_base_(test_base) {}
void InterceptRequest(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame);
OfflinePageRequestHandlerTestBase* test_base() { return test_base_; }
private:
std::unique_ptr<net::URLRequest> CreateRequest(const GURL& url,
const std::string& method,
bool is_main_frame);
// Runs on IO thread.
void SetUpNetworkObjectsOnIO();
void TearDownNetworkObjectsOnIO();
void InterceptRequestOnIO(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame);
void ReadCompletedOnIO(const ResponseInfo& response);
void TearDownOnReadCompletedOnIO(const ResponseInfo& response,
bool is_offline_page_set_in_navigation_data);
OfflinePageRequestHandlerTestBase* test_base_;
// These should only be accessed purely from IO thread.
std::unique_ptr<net::TestURLRequestContext> test_url_request_context_;
std::unique_ptr<net::URLRequestJobFactoryImpl> url_request_job_factory_;
std::unique_ptr<net::URLRequestInterceptingJobFactory>
intercepting_job_factory_;
std::unique_ptr<TestURLRequestDelegate> url_request_delegate_;
std::unique_ptr<net::URLRequest> request_;
};
void OfflinePageRequestJobBuilder::SetUpNetworkObjectsOnIO() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (test_url_request_context_.get())
return;
url_request_job_factory_.reset(new net::URLRequestJobFactoryImpl);
// Create a context with delayed initialization.
test_url_request_context_.reset(new net::TestURLRequestContext(true));
// Install the interceptor.
std::unique_ptr<net::URLRequestInterceptor> interceptor(
new OfflinePageRequestInterceptor());
std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory_impl(
new net::URLRequestJobFactoryImpl());
intercepting_job_factory_.reset(new TestURLRequestInterceptingJobFactory(
std::move(job_factory_impl), std::move(interceptor),
test_base_->web_contents()));
test_url_request_context_->set_job_factory(intercepting_job_factory_.get());
test_url_request_context_->Init();
}
void OfflinePageRequestJobBuilder::TearDownNetworkObjectsOnIO() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
request_.reset();
url_request_delegate_.reset();
intercepting_job_factory_.reset();
url_request_job_factory_.reset();
test_url_request_context_.reset();
}
std::unique_ptr<net::URLRequest> OfflinePageRequestJobBuilder::CreateRequest(
const GURL& url,
const std::string& method,
bool is_main_frame) {
url_request_delegate_ = std::make_unique<TestURLRequestDelegate>(
base::Bind(&OfflinePageRequestJobBuilder::ReadCompletedOnIO,
base::Unretained(this)));
std::unique_ptr<net::URLRequest> request =
test_url_request_context_->CreateRequest(url, net::DEFAULT_PRIORITY,
url_request_delegate_.get());
request->set_method(method);
content::ResourceRequestInfo::AllocateForTesting(
request.get(),
is_main_frame ? content::RESOURCE_TYPE_MAIN_FRAME
: content::RESOURCE_TYPE_SUB_FRAME,
nullptr,
/*render_process_id=*/1,
/*render_view_id=*/-1,
/*render_frame_id=*/1,
/*is_main_frame=*/true, content::ResourceInterceptPolicy::kAllowAll,
/*is_async=*/true,
test_base_->allow_preview() ? content::OFFLINE_PAGE_ON
: content::PREVIEWS_OFF,
std::make_unique<ChromeNavigationUIData>());
return request;
}
void OfflinePageRequestJobBuilder::InterceptRequestOnIO(
const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
SetUpNetworkObjectsOnIO();
request_ = CreateRequest(url, method, is_main_frame);
if (!extra_headers.IsEmpty())
request_->SetExtraRequestHeaders(extra_headers);
request_->Start();
}
void OfflinePageRequestJobBuilder::InterceptRequest(
const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&OfflinePageRequestJobBuilder::InterceptRequestOnIO,
base::Unretained(this), url, method, extra_headers,
is_main_frame));
base::RunLoop().Run();
}
void OfflinePageRequestJobBuilder::ReadCompletedOnIO(
const ResponseInfo& response) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
bool is_offline_page_set_in_navigation_data = false;
content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request_.get());
ChromeNavigationUIData* navigation_data =
static_cast<ChromeNavigationUIData*>(info->GetNavigationUIData());
if (navigation_data) {
offline_pages::OfflinePageNavigationUIData* offline_page_data =
navigation_data->GetOfflinePageNavigationUIData();
if (offline_page_data && offline_page_data->is_offline_page())
is_offline_page_set_in_navigation_data = true;
}
// Since the caller is still holding a request object which we want to dispose
// as part of tearing down on IO thread, we need to do it in a separate task.
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&OfflinePageRequestJobBuilder::TearDownOnReadCompletedOnIO,
base::Unretained(this), response,
is_offline_page_set_in_navigation_data));
}
void OfflinePageRequestJobBuilder::TearDownOnReadCompletedOnIO(
const ResponseInfo& response,
bool is_offline_page_set_in_navigation_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
TearDownNetworkObjectsOnIO();
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&OfflinePageRequestHandlerTestBase::ReadCompleted,
base::Unretained(test_base()), response,
is_offline_page_set_in_navigation_data));
}
// Builds an OfflinePageURLLoader to test the request interception with network
// service enabled.
class OfflinePageURLLoaderBuilder : public TestURLLoaderClient::Observer {
public:
explicit OfflinePageURLLoaderBuilder(
OfflinePageRequestHandlerTestBase* test_base);
void OnReceiveRedirect(const GURL& redirected_url) override;
void OnReceiveResponse(
const network::ResourceResponseHead& response_head) override;
void OnStartLoadingResponseBody() override;
void OnComplete() override;
void InterceptRequest(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame);
OfflinePageRequestHandlerTestBase* test_base() { return test_base_; }
private:
void OnHandleReady(MojoResult result, const mojo::HandleSignalsState& state);
void InterceptRequestOnIO(const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame);
void MaybeStartLoader(
const network::ResourceRequest& request,
content::URLLoaderRequestInterceptor::RequestHandler request_handler);
void ReadBody();
void ReadCompletedOnIO(const ResponseInfo& response);
OfflinePageRequestHandlerTestBase* test_base_;
std::unique_ptr<ChromeNavigationUIData> navigation_ui_data_;
std::unique_ptr<OfflinePageURLLoader> url_loader_;
std::unique_ptr<TestURLLoaderClient> client_;
std::unique_ptr<mojo::SimpleWatcher> handle_watcher_;
network::mojom::URLLoaderPtr loader_;
std::string mime_type_;
std::string body_;
};
OfflinePageURLLoaderBuilder::OfflinePageURLLoaderBuilder(
OfflinePageRequestHandlerTestBase* test_base)
: test_base_(test_base) {
navigation_ui_data_ = std::make_unique<ChromeNavigationUIData>();
}
void OfflinePageURLLoaderBuilder::OnReceiveRedirect(
const GURL& redirected_url) {
InterceptRequestOnIO(redirected_url, "GET", net::HttpRequestHeaders(), true);
}
void OfflinePageURLLoaderBuilder::OnReceiveResponse(
const network::ResourceResponseHead& response_head) {
mime_type_ = response_head.mime_type;
}
void OfflinePageURLLoaderBuilder::OnStartLoadingResponseBody() {
ReadBody();
}
void OfflinePageURLLoaderBuilder::OnComplete() {
if (client_->completion_status().error_code != net::OK) {
mime_type_.clear();
body_.clear();
}
ReadCompletedOnIO(
ResponseInfo(client_->completion_status().error_code, mime_type_, body_));
}
void OfflinePageURLLoaderBuilder::InterceptRequestOnIO(
const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
client_ = std::make_unique<TestURLLoaderClient>(this);
network::ResourceRequest request =
CreateResourceRequest(url, method, extra_headers, is_main_frame);
request.previews_state = test_base_->allow_preview()
? content::OFFLINE_PAGE_ON
: content::PREVIEWS_OFF;
url_loader_ = OfflinePageURLLoader::Create(
navigation_ui_data_.get(),
test_base_->web_contents()->GetMainFrame()->GetFrameTreeNodeId(), request,
base::BindOnce(&OfflinePageURLLoaderBuilder::MaybeStartLoader,
base::Unretained(this), request));
// |url_loader_| may not be created.
if (!url_loader_)
return;
url_loader_->SetTabIdGetterForTesting(base::BindRepeating(&GetTabId, kTabId));
}
void OfflinePageURLLoaderBuilder::InterceptRequest(
const GURL& url,
const std::string& method,
const net::HttpRequestHeaders& extra_headers,
bool is_main_frame) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&OfflinePageURLLoaderBuilder::InterceptRequestOnIO,
base::Unretained(this), url, method, extra_headers,
is_main_frame));
base::RunLoop().Run();
}
void OfflinePageURLLoaderBuilder::MaybeStartLoader(
const network::ResourceRequest& request,
content::URLLoaderRequestInterceptor::RequestHandler request_handler) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_handler) {
ReadCompletedOnIO(ResponseInfo(net::ERR_FAILED));
return;
}
// OfflinePageURLLoader decides to handle the request as offline page. Since
// now, OfflinePageURLLoader will own itself and live as long as its URLLoader
// and URLLoaderClientPtr are alive.
url_loader_.release();
std::move(request_handler)
.Run(request, mojo::MakeRequest(&loader_), client_->CreateInterfacePtr());
}
void OfflinePageURLLoaderBuilder::ReadBody() {
while (true) {
MojoHandle consumer = client_->response_body().value();
const void* buffer;
uint32_t num_bytes;
MojoResult rv = MojoBeginReadData(consumer, nullptr, &buffer, &num_bytes);
if (rv == MOJO_RESULT_SHOULD_WAIT) {
handle_watcher_ = std::make_unique<mojo::SimpleWatcher>(
FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
base::SequencedTaskRunnerHandle::Get());
handle_watcher_->Watch(
client_->response_body(),
MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(&OfflinePageURLLoaderBuilder::OnHandleReady,
base::Unretained(this)));
return;
}
// The pipe was closed.
if (rv == MOJO_RESULT_FAILED_PRECONDITION) {
ReadCompletedOnIO(ResponseInfo(net::ERR_FAILED));
return;
}
CHECK_EQ(rv, MOJO_RESULT_OK);
body_.append(static_cast<const char*>(buffer), num_bytes);
MojoEndReadData(consumer, num_bytes, nullptr);
}
}
void OfflinePageURLLoaderBuilder::OnHandleReady(
MojoResult result,
const mojo::HandleSignalsState& state) {
if (result != MOJO_RESULT_OK) {
ReadCompletedOnIO(ResponseInfo(net::ERR_FAILED));
return;
}
ReadBody();
}
void OfflinePageURLLoaderBuilder::ReadCompletedOnIO(
const ResponseInfo& response) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
handle_watcher_.reset();
client_.reset();
url_loader_.reset();
loader_.reset();
bool is_offline_page_set_in_navigation_data = false;
offline_pages::OfflinePageNavigationUIData* offline_page_data =
navigation_ui_data_->GetOfflinePageNavigationUIData();
if (offline_page_data && offline_page_data->is_offline_page())
is_offline_page_set_in_navigation_data = true;
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&OfflinePageRequestHandlerTestBase::ReadCompleted,
base::Unretained(test_base()), response,
is_offline_page_set_in_navigation_data));
}
// Lists all scenarios we want to test.
typedef testing::Types<OfflinePageRequestJobBuilder,
OfflinePageURLLoaderBuilder>
MyTypes;
TYPED_TEST_SUITE(OfflinePageRequestHandlerTest, MyTypes);
TYPED_TEST(OfflinePageRequestHandlerTest, FailedToCreateRequestJob) {
this->SimulateHasNetworkConnectivity(false);
// Must be http/https URL.
this->InterceptRequest(GURL("ftp://host/doc"), "GET",
net::HttpRequestHeaders(), true /* is_main_frame */);
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
this->InterceptRequest(GURL("file:///path/doc"), "GET",
net::HttpRequestHeaders(), true /* is_main_frame */);
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
// Must be GET method.
this->InterceptRequest(kUrl, "POST", net::HttpRequestHeaders(),
true /* is_main_frame */);
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
this->InterceptRequest(kUrl, "HEAD", net::HttpRequestHeaders(),
true /* is_main_frame */);
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
// Must be main resource.
this->InterceptRequest(kUrl, "POST", net::HttpRequestHeaders(),
false /* is_main_frame */);
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
this->ExpectNoSamplesInAggregatedRequestResult();
this->ExpectOfflinePageSizeTotalSuffixCount(0);
this->ExpectOnlinePageSizeTotalSuffixCount(0);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
LoadOfflinePageOnDisconnectedNetwork) {
this->SimulateHasNetworkConnectivity(false);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, PageNotFoundOnDisconnectedNetwork) {
this->SimulateHasNetworkConnectivity(false);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
this->LoadPage(kUrl2);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
PAGE_NOT_FOUND_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
NetErrorPageSuggestionOnDisconnectedNetwork) {
this->SimulateHasNetworkConnectivity(false);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeader(
OfflinePageHeader::Reason::NET_ERROR_SUGGESTION, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
LoadOfflinePageOnProhibitivelySlowNetwork) {
this->SimulateHasNetworkConnectivity(true);
this->set_allow_preview(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_PROHIBITIVELY_SLOW_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
DontLoadReloadOfflinePageOnProhibitivelySlowNetwork) {
this->SimulateHasNetworkConnectivity(true);
this->set_allow_preview(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// Treat this as a reloaded page.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::RELOAD, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
// The existentce of RELOAD header will force to treat the network as
// connected regardless current network condition. So we will fall back to
// the default handling immediately and no request result should be reported.
// Passing AGGREGATED_REQUEST_RESULT_MAX to skip checking request result in
// the helper function.
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
AGGREGATED_REQUEST_RESULT_MAX);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
PageNotFoundOnProhibitivelySlowNetwork) {
this->SimulateHasNetworkConnectivity(true);
this->set_allow_preview(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
this->LoadPage(kUrl2);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
PAGE_NOT_FOUND_ON_PROHIBITIVELY_SLOW_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, LoadOfflinePageOnFlakyNetwork) {
this->SimulateHasNetworkConnectivity(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// When custom offline header exists and contains "reason=error", it means
// that net error is hit in last request due to flaky network.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::NET_ERROR, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_FLAKY_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, PageNotFoundOnFlakyNetwork) {
this->SimulateHasNetworkConnectivity(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// When custom offline header exists and contains "reason=error", it means
// that net error is hit in last request due to flaky network.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::NET_ERROR, 0));
this->LoadPageWithHeaders(kUrl2, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
PAGE_NOT_FOUND_ON_FLAKY_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
ForceLoadOfflinePageOnConnectedNetwork) {
this->SimulateHasNetworkConnectivity(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// When custom offline header exists and contains value other than
// "reason=error", it means that offline page is forced to load.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::DOWNLOAD, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_CONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, PageNotFoundOnConnectedNetwork) {
this->SimulateHasNetworkConnectivity(true);
// Save an offline page.
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// When custom offline header exists and contains value other than
// "reason=error", it means that offline page is forced to load.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::DOWNLOAD, 0));
this->LoadPageWithHeaders(kUrl2, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
PAGE_NOT_FOUND_ON_CONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
DoNotLoadOfflinePageOnConnectedNetwork) {
this->SimulateHasNetworkConnectivity(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
this->LoadPage(kUrl);
// When the network is good, we will fall back to the default handling
// immediately. So no request result should be reported. Passing
// AGGREGATED_REQUEST_RESULT_MAX to skip checking request result in
// the helper function.
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
AGGREGATED_REQUEST_RESULT_MAX);
}
// TODO(https://crbug.com/830282): Flaky on "Marshmallow Phone Tester (rel)".
TYPED_TEST(OfflinePageRequestHandlerTest,
DISABLED_LoadMostRecentlyCreatedOfflinePage) {
this->SimulateHasNetworkConnectivity(false);
// Save 2 offline pages associated with same online URL, but pointing to
// different archive file.
int64_t offline_id1 = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
int64_t offline_id2 = this->SaveInternalPage(kUrl, GURL(), kFilename2,
kFileSize2, std::string());
// Load an URL that matches multiple offline pages. Expect that the most
// recently created offline page is fetched.
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id2, kFileSize2,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
this->ExpectOfflinePageAccessCount(offline_id1, 0);
}
TYPED_TEST(OfflinePageRequestHandlerTest, LoadOfflinePageByOfflineID) {
this->SimulateHasNetworkConnectivity(true);
// Save 2 offline pages associated with same online URL, but pointing to
// different archive file.
int64_t offline_id1 = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
int64_t offline_id2 = this->SaveInternalPage(kUrl, GURL(), kFilename2,
kFileSize2, std::string());
// Load an URL with a specific offline ID designated in the custom header.
// Expect the offline page matching the offline id is fetched.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeader(
OfflinePageHeader::Reason::DOWNLOAD, offline_id1));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOfflinePageServed(
offline_id1, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_CONNECTED_NETWORK);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
}
TYPED_TEST(OfflinePageRequestHandlerTest, FailToLoadByOfflineIDOnUrlMismatch) {
this->SimulateHasNetworkConnectivity(true);
int64_t offline_id = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// The offline page found with specific offline ID does not match the passed
// online URL. Should fall back to find the offline page based on the online
// URL.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeader(
OfflinePageHeader::Reason::DOWNLOAD, offline_id));
this->LoadPageWithHeaders(kUrl2, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
PAGE_NOT_FOUND_ON_CONNECTED_NETWORK);
}
// TODO(https://crbug.com/830282): Flaky on "Marshmallow Phone Tester (rel)".
TYPED_TEST(OfflinePageRequestHandlerTest,
DISABLED_LoadOfflinePageForUrlWithFragment) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page associated with online URL without fragment.
int64_t offline_id1 = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
// Save another offline page associated with online URL that has a fragment.
GURL url2_with_fragment(kUrl2.spec() + "#ref");
int64_t offline_id2 = this->SaveInternalPage(
url2_with_fragment, GURL(), kFilename2, kFileSize2, std::string());
this->ExpectOfflinePageAccessCount(offline_id1, 0);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
// Loads an url with fragment, that will match the offline URL without the
// fragment.
GURL url_with_fragment(kUrl.spec() + "#ref");
this->LoadPage(url_with_fragment);
this->ExpectOfflinePageServed(
offline_id1, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
// Loads an url without fragment, that will match the offline URL with the
// fragment.
this->LoadPage(kUrl2);
EXPECT_EQ(kFileSize2, this->bytes_read());
ASSERT_TRUE(this->offline_page_tab_helper()->GetOfflinePageForTest());
EXPECT_EQ(
offline_id2,
this->offline_page_tab_helper()->GetOfflinePageForTest()->offline_id);
this->ExpectMultiUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK,
2);
this->ExpectOfflinePageSizeTotalSuffixCount(2);
this->ExpectOnlinePageSizeTotalSuffixCount(0);
this->ExpectOfflinePageAccessCount(offline_id1, 1);
this->ExpectOfflinePageAccessCount(offline_id2, 1);
// Loads an url with fragment, that will match the offline URL with different
// fragment.
GURL url2_with_different_fragment(kUrl2.spec() + "#different_ref");
this->LoadPage(url2_with_different_fragment);
EXPECT_EQ(kFileSize2, this->bytes_read());
ASSERT_TRUE(this->offline_page_tab_helper()->GetOfflinePageForTest());
EXPECT_EQ(
offline_id2,
this->offline_page_tab_helper()->GetOfflinePageForTest()->offline_id);
this->ExpectMultiUniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK,
3);
this->ExpectOfflinePageSizeTotalSuffixCount(3);
this->ExpectOnlinePageSizeTotalSuffixCount(0);
this->ExpectOfflinePageAccessCount(offline_id1, 1);
this->ExpectOfflinePageAccessCount(offline_id2, 2);
}
TYPED_TEST(OfflinePageRequestHandlerTest, LoadOfflinePageAfterRedirect) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page with same original URL and final URL.
int64_t offline_id = this->SaveInternalPage(kUrl, kUrl2, kFilename1,
kFileSize1, std::string());
// This should trigger redirect first.
this->LoadPage(kUrl2);
// Passing AGGREGATED_REQUEST_RESULT_MAX to skip checking request result in
// the helper function. Different checks will be done after that.
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
AGGREGATED_REQUEST_RESULT_MAX);
this->ExpectOneNonuniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult::
REDIRECTED_ON_DISCONNECTED_NETWORK);
this->ExpectOneNonuniqueSampleForAggregatedRequestResult(
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
NoRedirectForOfflinePageWithSameOriginalURL) {
this->SimulateHasNetworkConnectivity(false);
// Skip the logic to clear the original URL if it is same as final URL.
// This is needed in order to test that offline page request handler can
// omit the redirect under this circumstance, for compatibility with the
// metadata already written to the store.
OfflinePageModelTaskified* model = static_cast<OfflinePageModelTaskified*>(
OfflinePageModelFactory::GetForBrowserContext(this->profile()));
model->SetSkipClearingOriginalUrlForTesting();
// Save an offline page with same original URL and final URL.
int64_t offline_id =
this->SaveInternalPage(kUrl, kUrl, kFilename1, kFileSize1, std::string());
// Check if the original URL is still present.
OfflinePageItem page = this->GetPage(offline_id);
EXPECT_EQ(kUrl, page.original_url_if_different);
// No redirect should be triggered when original URL is same as final URL.
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
LoadOfflinePageFromNonExistentInternalFile) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page pointing to non-existent internal archive file.
int64_t offline_id = this->SaveInternalPage(
kUrl, GURL(), kNonexistentFilename, kFileSize1, std::string());
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id,
OfflinePageRequestHandler::AggregatedRequestResult::FILE_NOT_FOUND);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
LoadOfflinePageFromNonExistentPublicFile) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page pointing to non-existent public archive file.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kNonexistentFilename,
kFileSize1, kDigest1);
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id,
OfflinePageRequestHandler::AggregatedRequestResult::FILE_NOT_FOUND);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
FileSizeMismatchOnDisconnectedNetwork) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page in public location with mismatched file size.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kMismatchedFileSize, kDigest1);
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
FileSizeMismatchOnProhibitivelySlowNetwork) {
this->SimulateHasNetworkConnectivity(true);
this->set_allow_preview(true);
// Save an offline page in public location with mismatched file size.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kMismatchedFileSize, kDigest1);
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_PROHIBITIVELY_SLOW_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, FileSizeMismatchOnConnectedNetwork) {
this->SimulateHasNetworkConnectivity(true);
// Save an offline page in public location with mismatched file size.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kMismatchedFileSize, kDigest1);
// When custom offline header exists and contains value other than
// "reason=error", it means that offline page is forced to load.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::DOWNLOAD, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_CONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, FileSizeMismatchOnFlakyNetwork) {
this->SimulateHasNetworkConnectivity(true);
// Save an offline page in public location with mismatched file size.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kMismatchedFileSize, kDigest1);
// When custom offline header exists and contains "reason=error", it means
// that net error is hit in last request due to flaky network.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::NET_ERROR, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_FLAKY_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, DigestMismatchOnDisconnectedNetwork) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page in public location with mismatched digest.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kFileSize1, kMismatchedDigest);
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
DigestMismatchOnProhibitivelySlowNetwork) {
this->SimulateHasNetworkConnectivity(true);
this->set_allow_preview(true);
// Save an offline page in public location with mismatched digest.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kFileSize1, kMismatchedDigest);
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_PROHIBITIVELY_SLOW_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, DigestMismatchOnConnectedNetwork) {
this->SimulateHasNetworkConnectivity(true);
// Save an offline page in public location with mismatched digest.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kFileSize1, kMismatchedDigest);
// When custom offline header exists and contains value other than
// "reason=error", it means that offline page is forced to load.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::DOWNLOAD, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_CONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, DigestMismatchOnFlakyNetwork) {
this->SimulateHasNetworkConnectivity(true);
// Save an offline page in public location with mismatched digest.
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), kFilename1,
kFileSize1, kMismatchedDigest);
// When custom offline header exists and contains "reason=error", it means
// that net error is hit in last request due to flaky network.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(
this->UseOfflinePageHeader(OfflinePageHeader::Reason::NET_ERROR, 0));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_FLAKY_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest, FailOnNoDigestForPublicArchiveFile) {
this->SimulateHasNetworkConnectivity(false);
// Save an offline page in public location with no digest.
int64_t offline_id =
this->SavePublicPage(kUrl, GURL(), kFilename1, kFileSize1, std::string());
this->LoadPage(kUrl);
this->ExpectNoOfflinePageServed(
offline_id, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_DISCONNECTED_NETWORK);
}
TYPED_TEST(OfflinePageRequestHandlerTest,
FailToLoadByOfflineIDOnDigestMismatch) {
this->SimulateHasNetworkConnectivity(true);
// Save 2 offline pages associated with same online URL, one in internal
// location, while another in public location with mismatched digest.
int64_t offline_id1 = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
int64_t offline_id2 = this->SavePublicPage(kUrl, GURL(), kFilename1,
kFileSize1, kMismatchedDigest);
// The offline page found with specific offline ID does not pass the
// validation. Though there is another page with the same URL, it will not be
// fetched. Instead, fall back to load the online URL.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeader(
OfflinePageHeader::Reason::DOWNLOAD, offline_id2));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectNoOfflinePageServed(
offline_id1, OfflinePageRequestHandler::AggregatedRequestResult::
DIGEST_MISMATCH_ON_CONNECTED_NETWORK);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
}
TYPED_TEST(OfflinePageRequestHandlerTest, LoadOtherPageOnDigestMismatch) {
this->SimulateHasNetworkConnectivity(false);
// Save 2 offline pages associated with same online URL, one in internal
// location, while another in public location with mismatched digest.
int64_t offline_id1 = this->SaveInternalPage(kUrl, GURL(), kFilename1,
kFileSize1, std::string());
int64_t offline_id2 = this->SavePublicPage(kUrl, GURL(), kFilename2,
kFileSize2, kMismatchedDigest);
this->ExpectOfflinePageAccessCount(offline_id1, 0);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
// There're 2 offline pages matching kUrl. The most recently created one
// should fail on mistmatched digest. The second most recently created offline
// page should work.
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id1, kFileSize1,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
this->ExpectOfflinePageAccessCount(offline_id2, 0);
}
// Disabled due to https://crbug.com/917113.
TYPED_TEST(OfflinePageRequestHandlerTest, DISABLED_EmptyFile) {
this->SimulateHasNetworkConnectivity(false);
const std::string expected_data("");
base::FilePath temp_file_path = this->CreateFileWithContent(expected_data);
ArchiveValidator archive_validator;
const std::string expected_digest = archive_validator.Finish();
int64_t offline_id =
this->SavePublicPage(kUrl, GURL(), temp_file_path, 0, expected_digest);
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, 0,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
EXPECT_EQ(expected_data, this->data_received());
}
TYPED_TEST(OfflinePageRequestHandlerTest, TinyFile) {
this->SimulateHasNetworkConnectivity(false);
std::string expected_data("hello world");
base::FilePath temp_file_path = this->CreateFileWithContent(expected_data);
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), temp_file_path,
expected_size, expected_digest);
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, expected_size,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
EXPECT_EQ(expected_data, this->data_received());
}
TYPED_TEST(OfflinePageRequestHandlerTest, SmallFile) {
this->SimulateHasNetworkConnectivity(false);
std::string expected_data(MakeContentOfSize(2 * 1024));
base::FilePath temp_file_path = this->CreateFileWithContent(expected_data);
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), temp_file_path,
expected_size, expected_digest);
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, expected_size,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
EXPECT_EQ(expected_data, this->data_received());
}
TYPED_TEST(OfflinePageRequestHandlerTest, BigFile) {
this->SimulateHasNetworkConnectivity(false);
std::string expected_data(MakeContentOfSize(3 * 1024 * 1024));
base::FilePath temp_file_path = this->CreateFileWithContent(expected_data);
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), temp_file_path,
expected_size, expected_digest);
this->LoadPage(kUrl);
this->ExpectOfflinePageServed(
offline_id, expected_size,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_DISCONNECTED_NETWORK);
EXPECT_EQ(expected_data, this->data_received());
}
TYPED_TEST(OfflinePageRequestHandlerTest, LoadFromFileUrlIntent) {
this->SimulateHasNetworkConnectivity(true);
std::string expected_data(MakeContentOfSize(2 * 1024));
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
// Create a file with unmodified data. The path to this file will be feed
// into "intent_url" of extra headers.
base::FilePath unmodified_file_path =
this->CreateFileWithContent(expected_data);
// Create a file with modified data. An offline page is created to associate
// with this file, but with size and digest matching the unmodified version.
std::string modified_data(expected_data);
modified_data[10] = '@';
base::FilePath modified_file_path =
this->CreateFileWithContent(modified_data);
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), modified_file_path,
expected_size, expected_digest);
// Load an URL with custom header that contains "intent_url" pointing to
// unmodified file. Expect the file from the intent URL is fetched.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeaderForIntent(
OfflinePageHeader::Reason::FILE_URL_INTENT, offline_id,
net::FilePathToFileURL(unmodified_file_path)));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOfflinePageServed(
offline_id, expected_size,
OfflinePageRequestHandler::AggregatedRequestResult::
SHOW_OFFLINE_ON_CONNECTED_NETWORK);
EXPECT_EQ(expected_data, this->data_received());
}
TYPED_TEST(OfflinePageRequestHandlerTest, IntentFileNotFound) {
this->SimulateHasNetworkConnectivity(true);
std::string expected_data(MakeContentOfSize(2 * 1024));
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
// Create a file with unmodified data. An offline page is created to associate
// with this file.
base::FilePath unmodified_file_path =
this->CreateFileWithContent(expected_data);
// Get a path pointing to non-existing file. This path will be feed into
// "intent_url" of extra headers.
base::FilePath nonexistent_file_path =
unmodified_file_path.DirName().AppendASCII("nonexistent");
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), unmodified_file_path,
expected_size, expected_digest);
// Load an URL with custom header that contains "intent_url" pointing to
// non-existent file. Expect the request fails.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeaderForIntent(
OfflinePageHeader::Reason::FILE_URL_INTENT, offline_id,
net::FilePathToFileURL(nonexistent_file_path)));
this->LoadPageWithHeaders(kUrl, extra_headers);
this->ExpectOpenFileErrorCode(net::ERR_FILE_NOT_FOUND);
EXPECT_EQ(net::ERR_FAILED, this->request_status());
EXPECT_NE("multipart/related", this->mime_type());
EXPECT_EQ(0, this->bytes_read());
EXPECT_FALSE(this->is_offline_page_set_in_navigation_data());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
}
TYPED_TEST(OfflinePageRequestHandlerTest, IntentFileModifiedInTheMiddle) {
this->SimulateHasNetworkConnectivity(true);
std::string expected_data(MakeContentOfSize(2 * 1024));
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
// Create a file with modified data in the middle. An offline page is created
// to associate with this modified file, but with size and digest matching the
// unmodified version.
std::string modified_data(expected_data);
modified_data[10] = '@';
base::FilePath modified_file_path =
this->CreateFileWithContent(modified_data);
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), modified_file_path,
expected_size, expected_digest);
// Load an URL with custom header that contains "intent_url" pointing to
// modified file. Expect the request fails.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeaderForIntent(
OfflinePageHeader::Reason::FILE_URL_INTENT, offline_id,
net::FilePathToFileURL(modified_file_path)));
this->LoadPageWithHeaders(kUrl, extra_headers);
EXPECT_EQ(net::ERR_FAILED, this->request_status());
EXPECT_NE("multipart/related", this->mime_type());
EXPECT_EQ(0, this->bytes_read());
// Note that the offline bit is not cleared on purpose due to the fact that
// other flag, like request status, should already indicate that the offline
// page fails to load.
EXPECT_TRUE(this->is_offline_page_set_in_navigation_data());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
}
TYPED_TEST(OfflinePageRequestHandlerTest,
IntentFileModifiedWithMoreDataAppended) {
this->SimulateHasNetworkConnectivity(true);
std::string expected_data(MakeContentOfSize(2 * 1024));
ArchiveValidator archive_validator;
archive_validator.Update(expected_data.c_str(), expected_data.length());
std::string expected_digest = archive_validator.Finish();
int expected_size = expected_data.length();
// Create a file with more data appended. An offline page is created to
// associate with this modified file, but with size and digest matching the
// unmodified version.
std::string modified_data(expected_data);
modified_data += "foo";
base::FilePath modified_file_path =
this->CreateFileWithContent(modified_data);
int64_t offline_id = this->SavePublicPage(kUrl, GURL(), modified_file_path,
expected_size, expected_digest);
// Load an URL with custom header that contains "intent_url" pointing to
// modified file. Expect the request fails.
net::HttpRequestHeaders extra_headers;
extra_headers.AddHeaderFromString(this->UseOfflinePageHeaderForIntent(
OfflinePageHeader::Reason::FILE_URL_INTENT, offline_id,
net::FilePathToFileURL(modified_file_path)));
this->LoadPageWithHeaders(kUrl, extra_headers);
EXPECT_EQ(net::ERR_FAILED, this->request_status());
EXPECT_NE("multipart/related", this->mime_type());
EXPECT_EQ(0, this->bytes_read());
// Note that the offline bit is not cleared on purpose due to the fact that
// other flag, like request status, should already indicate that the offline
// page fails to load.
EXPECT_TRUE(this->is_offline_page_set_in_navigation_data());
EXPECT_FALSE(this->offline_page_tab_helper()->GetOfflinePageForTest());
}
} // namespace offline_pages
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
80d5518ee6344af2d024a15f458003cc1e00e309 | e1d75af0a14eb9c17e25965b008d5e03ee30dadb | /C++/hud.h | cbbfe01004917e9879244fc5a1ed63f975c30c7a | [
"Unlicense"
] | permissive | Galaco/BTLRN_XTRM | 854e2011205e96cec829df3e7e44c1b081eef10c | c55405d5a36a44a8b1e3def555de9ec10027625b | refs/heads/master | 2020-03-23T07:53:00.702862 | 2018-12-28T21:48:13 | 2018-12-28T21:48:13 | 141,295,026 | 0 | 0 | Unlicense | 2018-12-28T21:48:14 | 2018-07-17T13:40:38 | C++ | UTF-8 | C++ | false | false | 1,966 | h | #ifndef HUD_H
#define HUD_H
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include "menuButton.h"
#include "animator.h"
#include "highscores.h"
#include "inputName.h"
class Hud
{
public:
Hud( ); // Default constructor
void addScore( int , bool ); // Add score
void addLives( int , bool ); // Add lives/reset lives if bool = true
void addHealth( int , bool ); // Add health/set to int if bool = true
void addKeys( int i );
void startup( sf::RenderWindow* );
void draw( sf::RenderWindow* win );
void update();
std::string getState();
int getMarkerPos();
int getLives();
int getHealth();
bool hasKey();
bool hasPound();
void grantPound();
void setPressed( bool );
void setSelPos( bool );
void setState( std::string );
void saveTimer();
void addChar( char );
void removeChar();
~Hud();
protected:
sf::Clock Clock;
std::ostringstream oss;
sf::Font f;
private:
//Required
int lives , selPos, selFrame, oldSelFrame , health, keys;
bool keyPressed, p_pound;
float pauseTime, totalTime;
std::string state;
sf::SoundBuffer BufferCollect , BufferSel , BufferMusic;
sf::Sound SoundCollect , SoundSel , SoundMusic;
sf::Sound::Status MusicStatus;
Highscore scores;
MenuButton play;
MenuButton lvlSel;
MenuButton options;
MenuButton exit;
Animator animator;
InputName playerName;
std::string name;
sf::Image i_bg , i_sel , i_logo, i_UI, i_pound , i_p_pickup;
sf::Texture t_bg , t_sel , t_logo , t_UI , t_pound , t_p_pickup;
sf::Sprite s_bg , s_sel , s_logo , s_UI , s_pound , s_p_pickup;
//Below are varables required for showing the time
float time;
sf::Text s_health , s_time , s_pause, s_lives, s_keys;
std::string str_time , str_m , str_s , str_ms , str_health, str_lives, str_keys;
int i_s , i_m;
double i_ms , i_msOld;
};
#endif | [
"mail@galaco.me"
] | mail@galaco.me |
fe1436b35cfde29e3d3ced0fe290ddc39184bace | 272274a37c6f4ea031dea803cf8fc8ee689ac471 | /chrome/browser/android/image_fetcher/image_fetcher_bridge.h | fb60718db0a444b77cf4ad4bea21c636c2f8d6a6 | [
"BSD-3-Clause"
] | permissive | zjh19861014/chromium | 6db9890f3b2981df3e8a0a56883adc93f6761fd5 | 8d48b756239d336d8724f8f593a7b22959c506b4 | refs/heads/master | 2023-01-09T06:34:30.549622 | 2019-04-13T06:55:11 | 2019-04-13T06:55:11 | 181,134,794 | 1 | 0 | NOASSERTION | 2019-04-13T07:12:06 | 2019-04-13T07:12:06 | null | UTF-8 | C++ | false | false | 3,203 | h | // Copyright 2018 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.
#ifndef CHROME_BROWSER_ANDROID_IMAGE_FETCHER_IMAGE_FETCHER_BRIDGE_H_
#define CHROME_BROWSER_ANDROID_IMAGE_FETCHER_IMAGE_FETCHER_BRIDGE_H_
#include <memory>
#include <string>
#include "base/android/scoped_java_ref.h"
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "components/image_fetcher/core/request_metadata.h"
#include "ui/gfx/image/image.h"
namespace image_fetcher {
class ImageFetcherService;
// Native counterpart of ImageFetcherBridge.java.
class ImageFetcherBridge {
public:
ImageFetcherBridge(ImageFetcherService* image_fetcher_service,
base::FilePath base_file_path);
~ImageFetcherBridge();
void Destroy(JNIEnv* j_env, const base::android::JavaRef<jobject>& j_this);
base::android::ScopedJavaLocalRef<jstring> GetFilePath(
JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const base::android::JavaRef<jstring>& j_url);
void FetchImageData(JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const base::android::JavaRef<jstring>& j_url,
const base::android::JavaRef<jstring>& j_client_name,
const base::android::JavaRef<jobject>& j_callback);
void FetchImage(JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const jint j_image_fetcher_config,
const base::android::JavaRef<jstring>& j_url,
const base::android::JavaRef<jstring>& j_client_name,
const base::android::JavaRef<jobject>& j_callback);
void ReportEvent(JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const base::android::JavaRef<jstring>& j_client_name,
const jint j_event_id);
void ReportCacheHitTime(JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const base::android::JavaRef<jstring>& j_client_name,
const jlong start_time_millis);
void ReportTotalFetchTimeFromNative(
JNIEnv* j_env,
const base::android::JavaRef<jobject>& j_this,
const base::android::JavaRef<jstring>& j_client_name,
const jlong start_time_millis);
private:
void OnImageDataFetched(base::android::ScopedJavaGlobalRef<jobject> callback,
const std::string& image_data,
const RequestMetadata& request_metadata);
void OnImageFetched(base::android::ScopedJavaGlobalRef<jobject> callback,
const gfx::Image& image,
const RequestMetadata& request_metadata);
// This service outlives the bridge.
ImageFetcherService* image_fetcher_service_;
base::FilePath base_file_path_;
base::WeakPtrFactory<ImageFetcherBridge> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ImageFetcherBridge);
};
} // namespace image_fetcher
#endif // CHROME_BROWSER_ANDROID_IMAGE_FETCHER_IMAGE_FETCHER_BRIDGE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
54420fab50bbcf05049200871474f7b88c997745 | a6f6a3bb02306a6d77ceca8b8d432e653041cbe0 | /src/qt/sendcoinsentry.cpp | 1bb75e48206d11d81bf582265988f56503e0e25a | [
"MIT"
] | permissive | ProfProfcompile/Vunt | 1be52327144fe5be2739136f2551e4f80e4b037c | 30942f425bd0828c37f2162cf7f41bad9f642bc5 | refs/heads/master | 2020-09-12T15:26:46.733080 | 2018-07-26T23:05:30 | 2018-07-26T23:05:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,293 | cpp | #include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a Vunt address (e.g. eH13UjuHSQ2wovNJucwSFg7nw7FNvE15Zt)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| [
"root@vultr.guest"
] | root@vultr.guest |
16bca3b7520ea0db66eacb55921c2157b36d9ab5 | 97e4b961fa101bc637934dbe01ac93152f0850fa | /c++/string2/string2/main.cpp | 51cf4e72dc244a873ad23dc09484187f51651e66 | [] | no_license | emmanuelfils435/C-C-_memory | b7150cfe7c2f32a481e40873a0c5b35a8426e13d | 0a6b26e2fc3b19132183161380b72c5f50ba9ca8 | refs/heads/master | 2023-03-19T20:35:32.166421 | 2020-04-30T08:00:39 | 2020-04-30T08:00:39 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,518 | cpp | #include <iostream>
#include <string>
using namespace std;
//class Solution {
//public:
// string addStrings(string num1, string num2) {
// /* int i = 0;
// if (num1.length() >= num2.length())
// {
// i = num1.length();
// }
// else
// {
// i = num2.length();
// }
// int j = 0, tmp = 0, wei = 0, flag = 0;
// string s;
// for (j = 0; j<i; j++)
// {
// tmp = num1[j] - '0' + num2[j] - '0' + wei;
// if (tmp>9)
// {
// wei = tmp - 10;
// }
// else
// {
// wei = 0;
// }
// tmp = tmp / 10;
// }*/
// int len1 = num1.size() - 1;
// int len2 = num2.size() - 1;
// int step = 0,sum=0;
// string ret = "";
// while (len1 >= 0 || len2 >= 0)
// {
// sum = 0;
// //当前位的和 : num1[len1]+num2[lne2]+step
// sum += step; //现加上一位的进位
// if (len1 >= 0)
// {
// sum += num1[len1]-'0';
// }
// if (len2 >= 0)
// {
// sum += num2[len2]-'0';
// }
// //获取当前为的值
// if (sum > 9)
// {
// sum -= 10;//减比模效率高
// //更新进位
// step = 1;
// }
// else
// {
// step = 0;
// }
// //当前位置的值保存到字符串中 头插
// ret.insert(0, 1, sum + '0'); //在0的位置插入一个字符!!!
// //计算下一位
// len1--;
// len2--;
// }
// if (step == 1)
// {
// ret.insert(0, 1, '1');
// }
// return ret;
// }
//};
//int main()
//{
// Solution s;
// string s1;
// string s2;
// while (cin>>s1>>s2)
// {
// cout << s.addStrings(s1, s2) << endl;
// }
// return 0;
//}
| [
"1023826776@qq.com"
] | 1023826776@qq.com |
5d44164921f355ece5f755a7293230d554a099b1 | f019ca1e4029b4077472087d1b677052583c0392 | /src/netbase.cpp | 77b69cb66943b37bcb63bd1972b6ab40744dc8a5 | [
"MIT"
] | permissive | mirzaei-ce/core-civilbit | 9204dd9c4c3ce04f867105da4e7fa9a56af1f8ba | cab3e53bdc6b04a84f4bc48114efc07865be814a | refs/heads/master | 2021-04-26T05:03:32.282526 | 2017-10-16T15:39:44 | 2017-10-16T15:39:44 | 107,148,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,587 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifdef HAVE_CONFIG_H
#include "config/civilbit-config.h"
#endif
#include "netbase.h"
#include "hash.h"
#include "sync.h"
#include "uint256.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#ifdef HAVE_GETADDRINFO_A
#include <netdb.h>
#endif
#ifndef WIN32
#if HAVE_INET_PTON
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/thread.hpp>
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Settings
static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = DEFAULT_NAME_LOOKUP;
static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
enum Network ParseNetwork(std::string net) {
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor" || net == "onion") return NET_TOR;
return NET_UNROUTABLE;
}
std::string GetNetworkName(enum Network net) {
switch(net)
{
case NET_IPV4: return "ipv4";
case NET_IPV6: return "ipv6";
case NET_TOR: return "onion";
default: return "";
}
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
#ifdef HAVE_GETADDRINFO_A
struct in_addr ipv4_addr;
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
struct in6_addr ipv6_addr;
if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
vIP.push_back(CNetAddr(ipv6_addr));
return true;
}
#else
ipv4_addr.s_addr = inet_addr(pszName);
if (ipv4_addr.s_addr != INADDR_NONE) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
#endif
#endif
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
aiHint.ai_family = AF_UNSPEC;
#ifdef WIN32
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo *aiRes = NULL;
#ifdef HAVE_GETADDRINFO_A
struct gaicb gcb, *query = &gcb;
memset(query, 0, sizeof(struct gaicb));
gcb.ar_name = pszName;
gcb.ar_request = &aiHint;
int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
if (nErr)
return false;
do {
// Should set the timeout limit to a resonable value to avoid
// generating unnecessary checking call during the polling loop,
// while it can still response to stop request quick enough.
// 2 seconds looks fine in our situation.
struct timespec ts = { 2, 0 };
gai_suspend(&query, 1, &ts);
boost::this_thread::interruption_point();
nErr = gai_error(query);
if (0 == nErr)
aiRes = query->ar_result;
} while (nErr == EAI_INPROGRESS);
#else
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
#endif
if (nErr)
return false;
struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{
if (aiTrav->ai_family == AF_INET)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
if (aiTrav->ai_family == AF_INET6)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
{
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
struct timeval MillisToTimeval(int64_t nTimeout)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
/**
* Read bytes from socket. This will either read the full number of bytes requested
* or return False on error or timeout.
* This function can be interrupted by boost thread interrupt.
*
* @param data Buffer to receive into
* @param len Length of data to receive
* @param timeout Timeout in milliseconds for receive operation
*
* @note This function requires that hSocket is in non-blocking mode.
*/
bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
{
int64_t curTime = GetTimeMillis();
int64_t endTime = curTime + timeout;
// Maximum time to wait in one select call. It will take up until this time (in millis)
// to break off in case of an interruption.
const int64_t maxWait = 1000;
while (len > 0 && curTime < endTime) {
ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
if (ret > 0) {
len -= ret;
data += ret;
} else if (ret == 0) { // Unexpected disconnection
return false;
} else { // Other error or blocking
int nErr = WSAGetLastError();
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
if (!IsSelectableSocket(hSocket)) {
return false;
}
struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
if (nRet == SOCKET_ERROR) {
return false;
}
} else {
return false;
}
}
boost::this_thread::interruption_point();
curTime = GetTimeMillis();
}
return len == 0;
}
struct ProxyCredentials
{
std::string username;
std::string password;
};
/** Connect using SOCKS5 (as described in RFC1928) */
static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
{
LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255) {
CloseSocket(hSocket);
return error("Hostname too long");
}
// Accepted authentication methods
std::vector<uint8_t> vSocks5Init;
vSocks5Init.push_back(0x05);
if (auth) {
vSocks5Init.push_back(0x02); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
} else {
vSocks5Init.push_back(0x01); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
}
ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5Init.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to initialize");
}
if (pchRet1[1] == 0x02 && auth) {
// Perform username/password authentication (as described in RFC1929)
std::vector<uint8_t> vAuth;
vAuth.push_back(0x01);
if (auth->username.size() > 255 || auth->password.size() > 255)
return error("Proxy username or password too long");
vAuth.push_back(auth->username.size());
vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
vAuth.push_back(auth->password.size());
vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vAuth.size()) {
CloseSocket(hSocket);
return error("Error sending authentication to proxy");
}
LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
char pchRetA[2];
if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy authentication response");
}
if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
CloseSocket(hSocket);
return error("Proxy authentication unsuccessful");
}
} else if (pchRet1[1] == 0x00) {
// Perform no authentication
} else {
CloseSocket(hSocket);
return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
}
std::vector<uint8_t> vSocks5;
vSocks5.push_back(0x05); // VER protocol version
vSocks5.push_back(0x01); // CMD CONNECT
vSocks5.push_back(0x00); // RSV Reserved
vSocks5.push_back(0x03); // ATYP DOMAINNAME
vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
vSocks5.push_back((port >> 8) & 0xFF);
vSocks5.push_back((port >> 0) & 0xFF);
ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00) {
CloseSocket(hSocket);
switch (pchRet2[1])
{
case 0x01: return error("Proxy error: general failure");
case 0x02: return error("Proxy error: connection not allowed");
case 0x03: return error("Proxy error: network unreachable");
case 0x04: return error("Proxy error: host unreachable");
case 0x05: return error("Proxy error: connection refused");
case 0x06: return error("Proxy error: TTL expired");
case 0x07: return error("Proxy error: protocol error");
case 0x08: return error("Proxy error: address type not supported");
default: return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00) {
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3])
{
case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
case 0x03:
{
ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
int nRecv = pchRet3[0];
ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
break;
}
default: CloseSocket(hSocket); return error("Error: malformed proxy response");
}
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
int set = 1;
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
//Disable Nagle's algorithm
#ifdef WIN32
setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
#else
setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
#endif
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true))
return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
{
struct timeval timeout = MillisToTimeval(nTimeout);
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
CloseSocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
if (nRet != 0)
{
LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
CloseSocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, const proxyType &addrProxy) {
assert(net >= 0 && net < NET_MAX);
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = addrProxy;
return true;
}
bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].IsValid())
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
bool SetNameProxy(const proxyType &addrProxy) {
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
nameProxy = addrProxy;
return true;
}
bool GetNameProxy(proxyType &nameProxyOut) {
LOCK(cs_proxyInfos);
if(!nameProxy.IsValid())
return false;
nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy() {
LOCK(cs_proxyInfos);
return nameProxy.IsValid();
}
bool IsProxy(const CNetAddr &addr) {
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
return true;
}
return false;
}
static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
if (outProxyConnectionFailed)
*outProxyConnectionFailed = true;
return false;
}
// do socks negotiation
if (proxy.randomize_credentials) {
ProxyCredentials random_auth;
random_auth.username = strprintf("%i", insecure_rand());
random_auth.password = strprintf("%i", insecure_rand());
if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
return false;
} else {
if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
proxyType proxy;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
if (GetProxy(addrDest.GetNetwork(), proxy))
return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
else // no proxy needed (none set for target network)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
}
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
{
std::string strDest;
int port = portDefault;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
SplitHostPort(std::string(pszDest), port, strDest);
proxyType nameProxy;
GetNameProxy(nameProxy);
CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!HaveNameProxy())
return false;
return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
}
void CNetAddr::Init()
{
memset(ip, 0, sizeof(ip));
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
{
switch(network)
{
case NET_IPV4:
memcpy(ip, pchIPv4, 12);
memcpy(ip+12, ip_in, 4);
break;
case NET_IPV6:
memcpy(ip, ip_in, 16);
break;
default:
assert(!"invalid network");
}
}
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
bool CNetAddr::SetSpecial(const std::string &strName)
{
if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
}
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
}
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
unsigned int CNetAddr::GetByte(int n) const
{
return ip[15-n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (
GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC2544() const
{
return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC6598() const
{
return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
}
bool CNetAddr::IsRFC5737() const
{
return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
(GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
(GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
|| (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Cleanup 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4())
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
CService serv(*this, 0);
struct sockaddr_storage sockaddr;
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
return true;
}
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal())
{
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable())
{
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052())
{
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunnelled addresses, use the encapsulated IPv4 address
else if (IsRFC3964())
{
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380())
{
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
}
else if (IsTor())
{
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8)
{
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
return vchRet;
}
uint64_t CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64_t nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch(theirNet) {
case NET_IPV4:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4;
}
case NET_IPV6:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV4: return REACH_IPV4;
case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
}
case NET_TOR:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR: return REACH_PRIVATE;
}
case NET_TEREDO:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
default:
return false;
}
}
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%u", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
CSubNet::CSubNet():
valid(false)
{
memset(netmask, 0, sizeof(netmask));
}
CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
{
size_t slash = strSubnet.find_last_of('/');
std::vector<CNetAddr> vIP;
valid = true;
// Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
memset(netmask, 255, sizeof(netmask));
std::string strAddress = strSubnet.substr(0, slash);
if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
{
network = vIP[0];
if (slash != strSubnet.npos)
{
std::string strNetmask = strSubnet.substr(slash + 1);
int32_t n;
// IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
const int astartofs = network.IsIPv4() ? 12 : 0;
if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
{
if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
{
n += astartofs*8;
// Clear bits [n..127]
for (; n < 128; ++n)
netmask[n>>3] &= ~(1<<(7-(n&7)));
}
else
{
valid = false;
}
}
else // If not a valid number, try full netmask syntax
{
if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
{
// Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
// we don't want pchIPv4 to be part of the mask.
for(int x=astartofs; x<16; ++x)
netmask[x] = vIP[0].ip[x];
}
else
{
valid = false;
}
}
}
}
else
{
valid = false;
}
// Normalize network according to netmask
for(int x=0; x<16; ++x)
network.ip[x] &= netmask[x];
}
CSubNet::CSubNet(const CNetAddr &addr):
valid(addr.IsValid())
{
memset(netmask, 255, sizeof(netmask));
network = addr;
}
bool CSubNet::Match(const CNetAddr &addr) const
{
if (!valid || !addr.IsValid())
return false;
for(int x=0; x<16; ++x)
if ((addr.ip[x] & netmask[x]) != network.ip[x])
return false;
return true;
}
static inline int NetmaskBits(uint8_t x)
{
switch(x) {
case 0x00: return 0; break;
case 0x80: return 1; break;
case 0xc0: return 2; break;
case 0xe0: return 3; break;
case 0xf0: return 4; break;
case 0xf8: return 5; break;
case 0xfc: return 6; break;
case 0xfe: return 7; break;
case 0xff: return 8; break;
default: return -1; break;
}
}
std::string CSubNet::ToString() const
{
/* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
int cidr = 0;
bool valid_cidr = true;
int n = network.IsIPv4() ? 12 : 0;
for (; n < 16 && netmask[n] == 0xff; ++n)
cidr += 8;
if (n < 16) {
int bits = NetmaskBits(netmask[n]);
if (bits < 0)
valid_cidr = false;
else
cidr += bits;
++n;
}
for (; n < 16 && valid_cidr; ++n)
if (netmask[n] != 0x00)
valid_cidr = false;
/* Format output */
std::string strNetmask;
if (valid_cidr) {
strNetmask = strprintf("%u", cidr);
} else {
if (network.IsIPv4())
strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
else
strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
}
return network.ToString() + "/" + strNetmask;
}
bool CSubNet::IsValid() const
{
return valid;
}
bool operator==(const CSubNet& a, const CSubNet& b)
{
return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
}
bool operator!=(const CSubNet& a, const CSubNet& b)
{
return !(a==b);
}
bool operator<(const CSubNet& a, const CSubNet& b)
{
return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
}
#ifdef WIN32
std::string NetworkErrorString(int err)
{
char buf[256];
buf[0] = 0;
if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL))
{
return strprintf("%s (%d)", buf, err);
}
else
{
return strprintf("Unknown error (%d)", err);
}
}
#else
std::string NetworkErrorString(int err)
{
char buf[256];
const char *s = buf;
buf[0] = 0;
/* Too bad there are two incompatible implementations of the
* thread-safe strerror. */
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
#endif
bool CloseSocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
return false;
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret != SOCKET_ERROR;
}
bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
{
if (fNonBlocking) {
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
} else {
#ifdef WIN32
u_long nZero = 0;
if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
}
return true;
}
| [
"mirzaei@ce.sharif.edu"
] | mirzaei@ce.sharif.edu |
f7d1aaf2fa61b3e065276d486edcaf1966371961 | 9ee2dddd7ac519f5e71c202495ed661141cbb8ec | /Lab-8/strassen.cpp | 85a6e485d4e7bd0743effabbb04efe9abf28dcd9 | [] | no_license | ahana2511/DAA-Lab | 9ddcb36c137e16fbfcbd6dab6b1e094718fe7106 | 164e47b4613b210fd39147dd8c1c437786e63571 | refs/heads/main | 2023-08-11T07:33:52.328902 | 2021-09-20T17:45:46 | 2021-09-20T17:45:46 | 408,542,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,446 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
int** create(int,int);
int** createZeroMatrix(int);
int** strassensMultiplication(int **, int **,int);
int** standardMultiplication(int **,int **,int);
int** strassensMultRec(int **, int**,int n);
int** divide(int ** matrixA,int n, int row,int col);
void printMatrix(int **, int);
int ** add(int**,int**,int);
int** sub(int**,int**,int);
void compose(int**,int**,int,int,int);
/*
* Main function where the execution starts.
*/
int main() {
int i=0,j=0,n=0;
std::cout << "Enter n: ";
std::cin >> n;
if(n<1){
printf("\nError: Invalid matrix dimension!\n\n");
return 0;
}
//To handle when n is not power of k we do the padding with zero
int pow = 1;
while(pow<n){
pow=pow*2;
}
cout << "\nMatrix A: \n";
int ** matrixA = new int*[n];
for(int i = 0 ; i < n ; i++)
{
matrixA[i] = new int[n];
for(int j = 0 ; j < n ; j++)
cin >> matrixA[i][j];
}
cout << "\nMatrix B: \n";
int ** matrixB = new int*[n];
for(int i = 0 ; i < n ; i++)
{
matrixB[i] = new int[n];
for(int j = 0 ; j < n ; j++)
cin >> matrixB[i][j];
}
n = pow;
int ** standardRes,**strassenRes;
int ** stdRes = standardMultiplication(matrixA,matrixB,n);
printf("\nStandard Multiplication Output:\n");
printMatrix(stdRes,n);
printf("\nStrassen's Multiplication Output:\n");
int ** strassensRes = strassensMultiplication(matrixA,matrixB,n);
printMatrix(strassensRes,n);
return 0;
}
/*
* Create the matrix with random inting point numbers betweeen -5 to 5
*/
int ** create(int n,int pow){
int ** array = createZeroMatrix(pow);
int i,j;
for(i = 0;i < n; i++) {
for(j = 0; j < n; j++) {
array[i][j] = ((((int)rand())/((int)RAND_MAX) *10.0) - 5.0);
}
}
return array;
}
/*
* This function creates the matrix and initialize all elements to zero
*/
int ** createZeroMatrix(int n){
int ** array = (int**)malloc(n*sizeof(int *));
int i,j;
for(i = 0;i < n; i++) {
array[i] = (int*)malloc(n*sizeof(int));
for(j = 0; j < n; j++) {
array[i][j] = 0.0;
}
}
return array;
}
/*
* Function to Print Matrix
*/
void printMatrix(int ** matrix,int n) {
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout << matrix[i][j] << " ";
}
printf("\n");
}
}
/*
* Standard Matrix multiplication with O(n) time complexity.
*/
int ** standardMultiplication(int ** matrixA,int ** matrixB,int n) {
int ** result;
int i,j,k;
result = (int**)malloc(n*sizeof(int *));
for(i=0;i<n;i++){
result[i]=(int*)malloc(n*sizeof(int));
for(j=0;j<n;j++){
result[i][j]=0;
for(k=0;k<n;k++) {
result[i][j]=result[i][j]+(matrixA[i][k]*matrixB[k][j]);
}
}
}
return result;
}
/*
* Wrapper function over strassensMultRec.
*/
int ** strassensMultiplication(int ** matrixA, int** matrixB,int n){
int ** result = strassensMultRec(matrixA,matrixB,n);
return result;
}
/*
* Strassen's Multiplication algorithm using Divide and Conquer technique.
*/
int** strassensMultRec(int ** matrixA, int** matrixB,int n){
int ** result = createZeroMatrix(n);
if(n>1) {
//Divide the matrix
int ** a11 = divide(matrixA, n, 0, 0);
int ** a12 = divide(matrixA, n, 0, (n/2));
int ** a21 = divide(matrixA, n, (n/2), 0);
int ** a22 = divide(matrixA, n, (n/2), (n/2));
int ** b11 = divide(matrixB, n, 0, 0);
int ** b12 = divide(matrixB, n, 0, n/2);
int ** b21 = divide(matrixB, n, n/2, 0);
int ** b22 = divide(matrixB, n, n/2, n/2);
//Recursive call for Divide and Conquer
int** m1= strassensMultRec(add(a11,a22,n/2),add(b11,b22,n/2),n/2);
int** m2= strassensMultRec(add(a21,a22,n/2),b11,n/2);
int** m3= strassensMultRec(a11,sub(b12,b22,n/2),n/2);
int** m4= strassensMultRec(a22,sub(b21,b11,n/2),n/2);
int** m5= strassensMultRec(add(a11,a12,n/2),b22,n/2);
int** m6= strassensMultRec(sub(a21,a11,n/2),add(b11,b12,n/2),n/2);
int** m7= strassensMultRec(sub(a12,a22,n/2),add(b21,b22,n/2),n/2);
int** c11 = add(sub(add(m1,m4,n/2),m5,n/2),m7,n/2);
int** c12 = add(m3,m5,n/2);
int** c21 = add(m2,m4,n/2);
int** c22 = add(sub(add(m1,m3,n/2),m2,n/2),m6,n/2);
//Compose the matrix
compose(c11,result,0,0,n/2);
compose(c12,result,0,n/2,n/2);
compose(c21,result,n/2,0,n/2);
compose(c22,result,n/2,n/2,n/2);
}
else {
//This is the terminating condition for recurssion.
result[0][0]=matrixA[0][0]*matrixB[0][0];
}
return result;
}
/*
* This method combines the matrix in the result matrix
*/
void compose(int** matrix,int** result,int row,int col,int n){
int i,j,r=row,c=col;
for(i=0;i<n;i++){
c=col;
for(j=0;j<n;j++){
result[r][c]=matrix[i][j];
c++;
}
r++;
}
}
/*
* Sub-divide the matrix according to row and col specified
*/
int** divide(int ** matrix,int n, int row,int col) {
int n_new=n/2;
int ** array = createZeroMatrix(n_new);
int i,j,r=row,c=col;
for(i = 0;i < n_new; i++) {
c=col;
for(j = 0; j < n_new; j++) {
array[i][j] = matrix[r][c];
c++;
}
r++;
}
return array;
}
/*
* Add the two input matrix
*/
int** add(int** matrixA,int** matrixB,int n){
int ** res = createZeroMatrix(n);
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
res[i][j]=matrixA[i][j]+matrixB[i][j];
return res;
}
/*
* Subtract the two matrix
*/
int** sub(int** matrixA,int** matrixB,int n){
int ** res = createZeroMatrix(n);
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
res[i][j]=matrixA[i][j]-matrixB[i][j];
return res;
} | [
"ahanaagg.2250@gmail.com"
] | ahanaagg.2250@gmail.com |
b9edd4edc1437602d2d7e0726325a58bcc93bab2 | 2385652507f121c8d2c64e90bd828a70b0eb44d0 | /Algorithms/cpp/Sqrt(x)/Newton_iterative.cpp | ddb310c4f9c20e61aa4db5a2468fc9a819049446 | [] | no_license | LuoWDK/leetcode | 8e3dbda2ae91db4f6b93f86589efea37505d41af | 3b5d9db45aacb390e657097ac8f51fda37505520 | refs/heads/master | 2021-01-24T20:47:36.546582 | 2018-04-19T08:57:00 | 2018-04-19T08:57:00 | 123,259,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | class Solution {
public:
int mySqrt(int x) {
double ans = x;
double inf = 0.0001;
while (fabs(pow(ans, 2) - x) > inf) {
ans = (ans + x / ans) / 2;
}
return ans;
}
};
| [
"Maggieluo0120@gmail.com"
] | Maggieluo0120@gmail.com |
ee987bc702917b8ce2e604ecad4d09d67fd46d1b | d27a1ec1a64a6c275b16c929e0245a6ff48efb7a | /KPoint(Ingeritance)/KPoint(Ingeritance)/KShape.cpp | 43f6b4a8d37175cc901933ad4f16cc696d8699e8 | [] | no_license | MarshalBrain/C-projects | b48a78bd0537faeb913dfd735946c3ac3ea51886 | d54718c2d6c1ef32a74d9e77ac0d9229a72481ae | refs/heads/master | 2021-09-14T10:36:02.932017 | 2018-05-11T19:25:00 | 2018-05-11T19:25:00 | 131,203,931 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,669 | cpp | #include "stdafx.h"
#include "KShape.h"
const double rad = 3.14159265358979323846 / 180;
void KShape::Explode(double a)
{
if (a > 0)
{
high *= a;
width *= a;
Count();
}
else
if (a < 0)
{
high /= -a;
width /= -a;
Count();
}
}
//void KShape::Shift(double dx, double dy)
//{
// Shift(dx, dy, centre);
// Count();
//}
void KShape::Shift(double dx, double dy, KPoint& A_) // сдвиг точки на dx, dy
{
A_.x += dx;
A_.y += dy;
}
void KShape::MoveTo(KPoint& B_)
{
MoveTo(centre, B_); // Move centre to _B
Count(); // пересчёт координат точек фигуры
}
void KShape::MoveTo(KPoint& A_, KPoint& B_) // переместить точку А на место B
{
A_.x = B_.x;
A_.y = B_.y;
}
void KShape::Rotate(KPoint& A_, KPoint const& centre_, double angle_) //rotate A_ about B_ by an angle = angle_
{
double x = A_.x, y = A_.y, x0 = centre.x, y0 = centre.y;
double sn, cs;
if ((int)angle_ % 270 == 0) { sn = -1; cs = 0; }
else
if ((int)angle_ % 90 == 0 && (int)angle_ % 180 != 0) { sn = 1; cs = 0; }
else
if ((int)angle_ % 180 == 0 && (int)angle_ % 360 != 0) { sn = 0; cs = -1; }
else
if ((int)angle_ % 360 == 0) { sn = 0; cs = 1; }
else
if ((int)angle_ % 360 == 60) { sn = sqrt(3) / 2; cs = 0.5; }
else
if ((int)angle_ % 360 == 30) { cs = sqrt(3) / 2; sn = 0.5; }
else
{
angle_ *= rad;
sn = sin(angle_);
cs = cos(angle_);
}
double out_x = x0 + ((x - x0) * cs - (y - y0) * sn);
double out_y = y0 + ((x - x0) * sn + (y - y0) * cs);
A_.x = out_x;
A_.y = out_y;
} | [
"marshalzhukov3000@gmail.com"
] | marshalzhukov3000@gmail.com |
810c07fcbd48cd2f43174840d2bb6cf3fc20594b | d73e37810beb21fcd592b88131011a1c727e75c6 | /StackInArray/demo.cpp | 424e477689eec55ce825df00cf0c01ee9f579e82 | [] | no_license | mike711028/StackInArray_demo | 0b20f814cce729b6c9de0b081c62c8b7ad5b7157 | 0c628d827a79c76f72de32ae998195c34a5c9231 | refs/heads/master | 2020-05-19T06:06:07.620098 | 2019-05-04T07:58:23 | 2019-05-04T07:58:23 | 184,865,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | #include <iostream>
#include "stack.h"
int main()
{
// default without value
Stack A;
// default with the first value
Stack S(1);
S.PrintArray();
for (int i = 0; i < 11; i++)
{
S.Push(i);
}
} | [
"mikeli0117@outlook.com"
] | mikeli0117@outlook.com |
4de8c1fd1d04761ca8b710cc5ed150bb404ae286 | e7659eff4dd40810c552fa914cfe0b3d1a773687 | /Assignment 10 - GUI + QtCharts/Assignment10GUIQtCharts.h | a45f7dec1184eeccfc19793221f1a37428a3ea01 | [] | no_license | adabirtocian/Evidence_Storage | aab5397425c053276f089f8a75c5f3ee5ea6efbf | e43bfe9d85c1752485523a27c8df30e16c1cf82d | refs/heads/master | 2023-01-12T16:31:23.450036 | 2020-11-22T21:00:34 | 2020-11-22T21:00:34 | 315,131,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | h | #pragma once
#include <QtWidgets/QMainWindow>
#include "ui_Assignment10GUIQtCharts.h"
class Assignment10GUIQtCharts : public QMainWindow
{
Q_OBJECT
public:
Assignment10GUIQtCharts(QWidget *parent = Q_NULLPTR);
private:
Ui::Assignment10GUIQtChartsClass ui;
};
| [
"adabirtocian@yahoo.com"
] | adabirtocian@yahoo.com |
938f6c2b85390cfb0053b4f2d72c0b6921257c96 | 1e49d897c11ca25eb635c413f99d57a0fdb144e0 | /proqram-2015/class/telebe bali(friend funksiyalar).cpp | 6a324a7c4fb3eb2a3b20dd3b6ab39e19574fc260 | [] | no_license | FeridAdashov/C-and-CPP | 4295074021b6314e7893819756af5f854331ef6f | 1ecd2a81587c1851bf9d5004f5c8b3f109be3f9a | refs/heads/master | 2020-04-06T19:33:00.825018 | 2018-11-15T16:43:30 | 2018-11-15T16:43:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | #include<iostream>
using namespace std;
class sinif{
int qiymet;
public:
friend void al(sinif *a){
cout<<"\nOyrencinin qiymetini gir: "; cin>>a->qiymet;
}
friend void goster(sinif a){
cout<<"\nQiymet="<<a.qiymet;
}
};
//ONA GORE UNVANA GORE OTURULURKI QIYMET YAZANDA BIRBASA UNVANA YAZILSIN YENI KOPYA
//UZERINDE EMELIYYAT APARILANDA SONRADAN QIYMET CAP ETSEK DAXIL ETDIYIMIZ QIYMETLER OLMAYACAQ
int main(){
sinif telebe1,telebe2,telebe3;
al(&telebe1);
al(&telebe2);
al(&telebe3);
goster(telebe1);
goster(telebe2);
goster(telebe3);
return 0;
}
| [
"fadasov@mail.ru"
] | fadasov@mail.ru |
217b9d51924952b03984b6a7158a2408c077ad35 | c652e54406d56ea1850c963bd1c232c4ce1db69e | /VideoParsing/Utils/VisualizationHelper.cpp | 6961f7f6283e15c7f6d10e39ea32f1f455715eef | [] | no_license | Lecanyu/CRFOptimize | d0598ec8cbe01a20721d74a80b8174c2cdccd196 | b5acf0f7bb5d0e0ceb89cb9b09fb1da0f0cfc118 | refs/heads/master | 2020-03-22T07:58:25.847052 | 2018-09-03T03:13:12 | 2018-09-03T03:13:12 | 139,736,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,605 | cpp | /**
* @file VisualizationHelper.cpp
* @brief VisualizationHelper
*
* @author Abhijit Kundu
*/
#include "VideoParsing/Utils/VisualizationHelper.h"
#include <opencv2/highgui/highgui.hpp>
#include <boost/format.hpp>
#include <iostream>
namespace vp {
WaitKeyNavigation::WaitKeyNavigation(int lower_bound, int upper_bound, int start_value, bool start_paused, bool start_step_fwd)
: value_(start_value),
lower_bound_(lower_bound),
upper_bound_(upper_bound),
paused_(start_paused),
step_fwd_(start_step_fwd) {
value_ = std::max(lower_bound_, value_);
value_ = std::min(value_, upper_bound_);
std::cout << "Use W/A/S/D to move fwd/bwd. Use P to toggle pause/unpause.\n";
}
WaitKeyNavigation::WaitKeyNavigation(int lower_bound, int upper_bound, bool start_paused, bool start_step_fwd)
: value_(lower_bound),
lower_bound_(lower_bound),
upper_bound_(upper_bound),
paused_(start_paused),
step_fwd_(start_step_fwd){
value_ = std::max(lower_bound_, value_);
value_ = std::min(value_, upper_bound_);
std::cout << "Use W/A/S/D to move fwd/bwd. Use P to toggle pause/unpause.\n";
}
bool WaitKeyNavigation::operator ()() {
const int key = cv::waitKey(!paused_);
if (key == 27 || key == 81 || key == 113) // Esc or Q or q
return false;
else if (key == 123 || key == 125 || key == 50 || key == 52 || key == 'a' || key == 'A'
|| key == 's' || key == 'S') // Down or Left Arrow key (including numpad) or 'a' and 's'
step_fwd_ = false;
else if (key == 124 || key == 126 || key == 54 || key == 56 || key == 'w' || key == 'W'
|| key == 'd' || key == 'D') // Up or Right Arrow or 'w' or 'd'
step_fwd_ = true;
else if (key == 'p' || key == 'P')
paused_ = !paused_;
if(step_fwd_)
++value_;
else
--value_;
value_ = std::max(lower_bound_, value_);
value_ = std::min(value_, upper_bound_);
return true;
}
void visualizeImages(const std::vector<cv::Mat>& images,
const int start_frame,
const std::string& window_name,
const int diplay_location,
const float scale) {
const int last_image_id = images.size() - 1;
cv::namedWindow(window_name, CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED);
cv::moveWindow(window_name, diplay_location * images.front().cols, 0);
cv::resizeWindow(window_name, images.front().cols * scale, images.front().rows * scale);
const boost::format window_msg(" Frame = %d/%d Paused = %s");
// Now display the results until q or Esc is pressed
WaitKeyNavigation nav(0, last_image_id, true, true);
do {
const int i = nav.value();
const std::string overlay_msg = (boost::format(window_msg) % (i + start_frame) % (last_image_id + start_frame)
% (nav.paused() ? "ON" : "OFF")).str();
cv::displayOverlay(window_name,overlay_msg);
cv::imshow(window_name, images.at(i));
} while(nav());
}
void visualizeImages(const std::vector<cv::Mat>& imagesA,
const std::vector<cv::Mat>& imagesB,
const int start_frame,
const std::string& window_name,
const int diplay_location,
const float scale) {
if(imagesA.size() != imagesB.size())
throw std::runtime_error("imagesA.size() != imagesB.size()");
std::vector<cv::Mat> canvas_images(imagesA.size());
const int mid_border = 5;
#pragma omp parallel for
for(int i = 0; i < canvas_images.size(); ++i) {
const cv::Mat& imgA = imagesA[i];
const cv::Mat& imgB = imagesB[i];
if(imgA.type() != CV_8UC3)
throw std::runtime_error("Only supports CV_8UC3");
if(imgB.type() != CV_8UC3)
throw std::runtime_error("Only supports CV_8UC3");
canvas_images[i] = cv::Mat::zeros(imgA.rows + mid_border + imgB.rows, std::max(imgA.cols, imgB.cols), CV_8UC3 );
imgA.copyTo(canvas_images[i](cv::Range(0,imgA.rows),cv::Range(0,imgA.cols)));
imgB.copyTo(canvas_images[i](cv::Range(imgA.rows + mid_border, imgA.rows + mid_border + imgB.rows),cv::Range(0,imgB.cols)));
}
visualizeImages(canvas_images, start_frame,window_name, diplay_location, scale);
}
void saveImages(const std::vector<cv::Mat>& images,
const int start_frame,
const std::string& out_image_pattern) {
const boost::format out_image_names(out_image_pattern);
#pragma omp parallel for
for (int i = 0; i < images.size(); ++i) {
const int frame_id = i + start_frame;
cv::imwrite((boost::format(out_image_names) % frame_id).str(), images[i]);
}
}
} // namespace vp
| [
"lecanyu@gmail.com"
] | lecanyu@gmail.com |
03a7456f2f3e90fe216930c016390c9c08a87cb2 | a2e16fbd38c14139d792f87636b99dbc02828918 | /src/RT_PFAST2D.cpp | 3bc3f3174c394677784cf388658b165382465c02 | [
"MIT"
] | permissive | Yuan-ShuangQi/PFAST | c1a8d9db378e967eb9d1d7292e255277690060bc | a8904afe4609a78dcfb8366886c47440440100d8 | refs/heads/master | 2022-01-02T23:06:21.531262 | 2018-03-12T00:10:14 | 2018-03-12T00:10:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,863 | cpp | /* This is program is to implement Transmission and/or Relection Travel time Tomography using Adjoint state method and FSM algorithm,
* based on the papers:
* [1] Zhao Hongkai, 2004, A Fast Sweeping Method for Eikonal Equaitons, Mathemtatics of Computiation,
* Vol. 74, No. 250, pp. 603-627
* [2] Leung, Shingyu and Qian, Jianliang, 2006, An Adjoint State Method for Three-dimensional Transmission Traveltime
* Tomograhy using Frist-arrivals, Comm. Math. Sci., Vol. 4, No. 1, pp. 249-266.
*
* First created by Junwei Huang @ NRCan, Mar 08 2010,
* PLEASE DO NOT DISTRIBUTE. PLEASE REFER OTHER PEOPLE TO THE AUTHOR.
* Author
* Dr. Jun-Wei Huang,
* Geological Survey of Canada,
* 615 Booth Street, Ottawa, Ontario,
* Canada
* ph: +1 613 992 4968
* mailto:juhuang@nrcan.gc.ca
* Homepage: http://www.junweihuang.info
* If you want to publish results calculated with this program please
* give a reference to the following paper:
Huang, J.W., and Bellefleur, G., 2011, Joint Transmission and Reflection Traveltime Tomography in Imaging Permafrost and Thermokarst lakes in Northwest Territories, Canada, The Leading Edge.
Huang, J.W., and Bellefleur, G., 2012, Joint Transmission and Reflection Traveltime Tomography using the Fast Sweeping Method and the Adjoint-state Technique, Geophysical Journal International.
*
* ----------------------------------------------------------------
* History of important modifications:
* 21.02.2010 Version 1.00 original implementation of fast sweeping
Jun-Wei Huang
* 08.03.2010 Original Iimplementation of inversion
Jun-Wei Huang
* 22.03.2010 Version 1.01 Parallelization
Jun-Wei Huang
* 07.04.2010 Version 1.02 Implement Nonlinear Conjugate Gradient Method, Hestenes-Stiefel scheme
Jun-Wei Huang
* 11.04.2010 Version 1.03 Implement Strong Wolfe Condition for line searching
Jun-Wei Huang
* 12.04.2010 Version 1.04 Implement Nonlinear Conjugate Gradient Method, CGDECENT scheme according to
"Harger, W.W. and Zhang, H.C., 2005,
A new Conjugate Gradient Method with Guaranteed Descent and an Efficient Line Search,
SIAM, J. OPTIM., Vo. 16, No. 1, pp. 170-192"
Jun-Wei Huang
* 13.04.2010 Version 1.05 Implement L-BFGS Quasi-Newton Method
Jun-Wei Huang
* 23.04.2010 Version 1.06 Implement handling of different number of source and active receivers
Jun-Wei Huang
* 27.04.2010 Version 1.07 Implement primary reflections from predefined reflectors, see RTpfsm2d.h
Jun-Wei Huang
* 07.05.2010 Version 1.08 Implement Joint inversion of transmision and reflection travel time
Jun-Wei Huang
* 07.11.2010 Version 1.09 Implement Spatial Varying Weighting factor for joint inversion
Jun-Wei Huang
*/
#include "RT_pfsm2d.h"
#include "RT_padjoint2d.h"
#include <mpi.h>
/*--------FFT Accuracy Control Switch----------*/
#define FFT_NOFLOAT
#undef REAL
#ifdef TEST_FLOAT
# define REAL float
# define fftn fftnf
#else
# define REAL double
#endif
using namespace std;
int main(int argc, char *argv[])
{
FILE *fp;
int NX,NY,M=0,LM,schemetag=1,RTtag=3,lsrc,NumofSrc,NumofRec,NumofR,count=0,Iterk=0,MAXIter=500,MAXLineSch=5,MAXSwp=500,ConvFlag=0;
int *src,*srnum,*rec,sNX,sNY,rNX,rNY,gmNX,gmNY,ch0,ch1,chr;
char *inpf,line[100],inp[20][100],tempar[8][80],vp0file[100],srcfile[100],recfile[100],refgeom[100],obsfile[100],vpfile[100],twfile[100],lmdfile[100],p_obsfile[100],p_vpfile[100],cmd[100];
double dx,dz,*nxy,*TT_obs,*TR_obs, c1=1.0e-4,c2=0.9;//*WR;
double nux=80.,nuy=50.;
float temp;
//===========start multi-processes========
int my_rank,np;
double Telapse,tic,lstime;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&np);
MPI_Status status;
if (my_rank==0) Telapse=MPI_Wtime();
if (my_rank==0) info();
#ifndef NoInverse
if (argc==2){
inpf=argv[1];LM=5;RTtag=3;
if (my_rank==0) printf("Optimization Method: L-BFGS\nDefault Memory Number m=%d (Ignore if L-BFGS is not used)\n",LM);
}
else if (argc==3){
inpf=argv[1];LM=atoi(argv[2]);RTtag=3;
if (my_rank==0) printf("Optimization Method: L-BFGS\nSpecified Memory Number m=%d (Ignore if L-BFGS is not used)\n",LM);
}
else if (argc==4){
inpf=argv[1];LM=atoi(argv[2]);RTtag=atoi(argv[3]);
if (my_rank==0) printf("Optimization Method: L-BFGS\nSpecified Memory Number m=%d (Ignore if L-BFGS is not used)\n",LM);
}
else{
if (my_rank==0) usage();
return 1;
}
if (my_rank==0) {
printf(" *****************************************************************\n");
switch(RTtag){
case 3:
printf("Joint Inversion of Reflection and Transmission\n");
break;
case 1:
printf("Inversion of Transmission ONLY\n");
break;
case 2:
printf("Inversion of Reflection ONLY\n");
break;
}
printf(" *****************************************************************\n");
}
#else
inpf=argv[1];
#endif
// printf("input arguments %d\ninfile: %s\noutfile: %s",argc,inpf,outf);
if( (fp = fopen( inpf, "r" )) == NULL )
{if (my_rank==0) printf( "The file %s was not opened\n",inpf );}
else
{if (my_rank==0) printf( "Read input parameters from file %s\nUser Parameters are as follows:\n",inpf );}
while(fgets(line,100,fp)){
//printf("%s",line);
if(line[0]!='#'){
strcpy(inp[M],line);
M=M+1;
}
}
fclose(fp);
///////////////////////////
//Read Input parameters
sscanf(inp[0],"%s",vp0file);
sscanf(inp[1],"%s",srcfile);
sscanf(inp[2],"%s%s",tempar,tempar+1);sNX=atoi(tempar[0]);sNY=atoi(tempar[1]);
sscanf(inp[3],"%s",recfile);
sscanf(inp[4],"%s%s",tempar,tempar+1);rNX=atoi(tempar[0]);rNY=atoi(tempar[1]);
sscanf(inp[5],"%s",refgeom);
sscanf(inp[6],"%s%s",tempar,tempar+1);gmNX=atoi(tempar[0]);gmNY=atoi(tempar[1]);
sscanf(inp[7],"%s%s%s%s",tempar,tempar+1,tempar+2,tempar+3);
NX=atoi(tempar[0]);NY=atoi(tempar[1]);dx=atof(tempar[2]);dz=atof(tempar[3]);
sscanf(inp[8],"%s",vpfile);
sscanf(inp[9],"%s%s",tempar,tempar+1);
nux=atof(tempar[0]);nuy=atof(tempar[1]);
sscanf(inp[10],"%s",twfile);
sscanf(inp[11],"%s%s",tempar,tempar+1);schemetag=atoi(tempar[0]);lsrc=atoi(tempar[1]);
//////////////////////////
///////////////////////
//Report Input
if (my_rank==0)
{
printf("\nThe initial velocity file... %s\n",vp0file);
printf("The source location file... %s\n",srcfile);
printf("The receiver location file... %s\n",recfile);
printf("The source binary file dimension... %d x %d\n",sNX,sNY);
printf("The receiver binary file dimension... %d x %d\n",rNX,rNY);
printf("The reflector geometry file... %s\n",refgeom);
printf("The reflector geometry binary file dimension... %d x %d\n",gmNX,gmNY);
printf("The size of the model... %d X %d\nSample Interval... %.2lfm x %.2lfm\n",NX,NY,dx,dz);
printf("Final Velocity Model Output to %s\n",vpfile);
printf("The weighting factor matrix file... %s\n\n",twfile);
}
//////////////////////
if (my_rank==0) {
switch(schemetag){
case 1:
printf("HS Nonlinear Conjugate Method In Use\n");
break;
case 2:
printf("CGDESCENT Nonlinear Conjugate Method In Use\n");
break;
case 3:
printf("L-BFGS quasi-newton method In Use\n");
break;
case 0:
printf("Steepest Decent Method In Use\n");
break;
}
switch(lsrc){
case 1:
printf("Secant method with exact Conditions\n");
break;
case 2:
printf("Line Search with Strong Wolfe Conditions\n");
break;
case 3:
printf("Cubic Interpolation method with Strong Wolfe Conditions\n");
break;
case 0:
printf("No Line Search for steepest decent only\n");
break;
}
}
NumofR=(int)ceil((double)gmNX/NY); //number of reflectors
double *vp=new (nothrow)double [NX*NY]; //NX=number of rows, NY=number of colums
double *TT=new (nothrow)double [NX*NY]; //store Transmission Travel time in the whole model
double *TTd=new (nothrow)double [NX*NY*NumofR]; //store downgoing travel time
double *TTu=new (nothrow)double [NX*NY*NumofR]; //store upgoing travel time
double *Tr; //store travel time at receiver locations, not identical among processors
double *Z=new (nothrow)double [gmNX*gmNY]; //store reflector geometry
double *lambdaT_i,*lambdaR_i; //store single shot adjoint state of transmission and reflection wave
double *lambdaT,*lambdaR,*lambdaRT; //store local shots adjoint state within one processing unit of transmission and reflection wave
double *srcArray=new (nothrow) double [sNX*sNY]; //store source z, x, number of channel
double *recArray=new (nothrow) double [rNX*rNY]; //store receiver z, x, -nz, -nx, FB, R1, R2,...Rn
strcpy(p_vpfile,"");
strncat(p_vpfile,vp0file,strlen(vp0file)-3);
if (!TT && !TTd && !TTu && !vp && !Z && !srcArray && !recArray ) {
printf("PE_%d: Not enough memory...sadly abort...\n",my_rank);
return 1;
}
////////////////////////////
//To Load the velocity model
if (my_rank==0) {
readmod(vp, vp0file, NX, NY);
readmod(srcArray,srcfile,sNX,sNY);
readmod(recArray,recfile,rNX,rNY);
readmod(Z,refgeom,gmNX,gmNY);
}
MPI_Barrier( MPI_COMM_WORLD );
MPI_Bcast( &vp[0], NX*NY, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast( &srcArray[0], sNX*sNY, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast( &recArray[0], rNX*rNY, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast( &Z[0], gmNX*gmNY, MPI_DOUBLE, 0, MPI_COMM_WORLD);
///////////////////////////
///////////////////////////
//Read NumofSrc
NumofSrc=sNX;
src=new (nothrow)int [NumofSrc*DIM];
srnum=new (nothrow)int [NumofSrc];
int rmd=NumofSrc % np; //remainder
int loc_nofs=(NumofSrc-(rmd))/np; //shots number per PE
int *loc_srcid= new int [np];
if (rmd!=0) {
if (my_rank==0) printf("!!!WARNING...Number of Shots %d is not divisible to %d PEs\n\n",NumofSrc,np);
for (int i=0;i<np;i++){
if (i<rmd)
loc_srcid[i]=(i+1)*(loc_nofs+1);
else
loc_srcid[i]=loc_srcid[i-1]+loc_nofs;
}
}
else {
for (int i=0;i<np;i++)
loc_srcid[i]=(i+1)*(loc_nofs);
}
printf("PE_%d (out of %d) handles %d shots: %d ~ %d\n",my_rank,np,loc_srcid[my_rank]-(my_rank-1>=0?loc_srcid[my_rank-1]:0),(my_rank-1>=0?loc_srcid[my_rank-1]:0)+1,loc_srcid[my_rank]);
MPI_Barrier( MPI_COMM_WORLD );
///////////////////////////
//Read Source Locations
if (my_rank==0) {
printf("...reading source file:\n\t%s\n",srcfile);
printf(" ----------------------------------\n");
printf("| Total Number of Sources: %d\n",NumofSrc);
printf("| index\trow\tcolumn\tNumofChn\n");
for (int ii=0;ii<NumofSrc;ii++){
src[ii*DIM+0]=(int)ceil(srcArray[ii*sNY+0]/dz)-1;//C++ start index from 0
src[ii*DIM+1]=(int)ceil(srcArray[ii*sNY+1]/dx)-1;
srnum[ii]=(int)(srcArray[ii*sNY+2]);
if (ii<=20 )
printf("| %d\t%d\t%d\t%d\n",ii,src[ii*DIM]+1,src[ii*DIM+1]+1,srnum[ii]);
else if (ii==21)
printf("| ......\n");
else if (ii==(NumofSrc-1) )
printf("| %d\t%d\t%d\t%d\n",ii,src[ii*DIM]+1,src[ii*DIM+1]+1,srnum[ii]);
}
printf("| The End of Source Locations\n");
printf(" ---------------------------------\n");
}
MPI_Barrier( MPI_COMM_WORLD );
MPI_Bcast( &src[0], NumofSrc*DIM, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast( &srnum[0], NumofSrc, MPI_INT, 0, MPI_COMM_WORLD);
ch1=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<loc_srcid[my_rank];j++) ch1+=srnum[j];
//printf("PE_%d: ch1=%d\n",my_rank,ch1);
Tr=new (nothrow) double [ch1*(NumofR+1)];
if (!Tr) {printf("PE_%d: Not enough memory for Tr...sadly abort...\n",my_rank);return 1;}
///////////////////////////////////
///////////////////////////
//Read Receivers
NumofRec=rNX;
rec=new (nothrow)int [NumofRec*DIM]; nxy=new (nothrow)double [NumofRec*DIM];
TT_obs=new (nothrow)double [NumofRec];TR_obs=new (nothrow)double [NumofRec*NumofR];
if (my_rank==0) {
printf("...reading receiver file:\n\t%s\n",recfile);
printf(" ----------------------------------\n");
printf("| Total Number of Channels: %d\n",NumofRec);
printf("| index\trow\tcolumn\t\tnormal_ny\tnormal_nx\tTT\tTR1......TRn\n");
for (int ii=0;ii<NumofRec;ii++){
rec[ii*DIM]=(int)ceil(recArray[ii*rNY+0]/dz)-1;//C++ start index from 0
rec[ii*DIM+1]=(int)ceil(recArray[ii*rNY+1]/dx)-1;
nxy[ii*DIM]=recArray[ii*rNY+2];//C++ start index from 0
nxy[ii*DIM+1]=recArray[ii*rNY+3];
TT_obs[ii]=recArray[ii*rNY+4];
for (int it=0;it<NumofR;it++) TR_obs[ii*NumofR+it]=recArray[ii*rNY+5+it];
if (ii<=20)
printf("| %d\t%d\t%d\t\t%6.3f\t%6.3f\t%6.3f\t%6.3f......%6.3f\n",ii,rec[ii*DIM]+1,rec[ii*DIM+1]+1,nxy[ii*DIM],nxy[ii*DIM+1],TT_obs[ii],TR_obs[ii*NumofR+0],TR_obs[ii*NumofR+NumofR-1]);
else if (ii==21)
printf("| ......\n");
else if (ii==(NumofRec-1))
printf("| %d\t%d\t%d\t\t%6.3f\t%6.3f\t%6.3f\t%6.3f......%6.3f\n",ii,rec[ii*DIM]+1,rec[ii*DIM+1]+1,nxy[ii*DIM],nxy[ii*DIM+1],TT_obs[ii],TR_obs[ii*NumofR+0],TR_obs[ii*NumofR+NumofR-1]);
}
printf("| The End of Receiver Locations\n");
printf(" ---------------------------------\n");
}
MPI_Barrier( MPI_COMM_WORLD );
MPI_Bcast( &rec[0], NumofRec*DIM, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast( &nxy[0], NumofRec*DIM, MPI_DOUBLE, 0, MPI_COMM_WORLD);
//MPI_Bcast( &rectag[0], NX*NY, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast( &TT_obs[0], NumofRec, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast( &TR_obs[0], NumofRec*NumofR, MPI_DOUBLE, 0, MPI_COMM_WORLD);
delete [] recArray;recArray=NULL;
delete [] srcArray;srcArray=NULL;
///////////////////////////
//Read Reflector Geometry
if (my_rank==0) {
printf("...reading reflector geometry file:\n\t%s\n",refgeom);
printf(" ----------------------------------\n");
printf("| Total Number of reflector geometry points: %d\n",gmNX);
printf("| Total Number of reflector layers: %d\n",NumofR);
printf("| index\tdz\t\tref_ny\tref_nx\n");
for (int ii=0;ii<gmNX;ii++){
if (ii<=20)
printf("| %d\t%6.3f\t%6.3f\t%6.3f\n",ii,Z[ii*3+0],Z[ii*3+1],Z[ii*3+2]);
else if (ii==21)
printf("| ......\n");
else if (ii==(gmNX-1))
printf("| %d\t%6.3f\t%6.3f\t%6.3f\n",ii,Z[ii*3+0],Z[ii*3+1],Z[ii*3+2]);
}
printf("| The End of Reflector Geometries\n");
printf(" ---------------------------------\n");
}
MPI_Barrier( MPI_COMM_WORLD );
#ifndef NoInverse //if undefined, this is an inverse run
//////////////////////////
//Start Iterating
bool convflag=false;
double alpha0=0.0,alpha1=5.0e3,alphak,f0,f1,beta;
double *Djk1=new (nothrow)double [NX*NY],*Djk0=new (nothrow)double [NX*NY], *dk=new (nothrow) double [NX*NY],*Dj1=new (nothrow)double [NX*NY],*loc_vp=new (nothrow)double [NX*NY];
double *sk=new (nothrow) double [NX*NY*LM], *yk=new (nothrow) double [NX*NY*LM],*rhoi=new (nothrow) double [LM],*q=new (nothrow) double [NX*NY],*ai=new (nothrow) double [LM],tmp,gamma;
double *WR=new (nothrow)double [NX*NY]; //store spatial varying weighting factors, NX=number of rows, NY=number of colums
////////////////////////////
//To Load the weighting factor model
if (my_rank==0) {
readmod(WR, twfile, NX, NY);
}
MPI_Barrier( MPI_COMM_WORLD );
MPI_Bcast( &WR[0], NX*NY, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if (sk && yk){for (int i=0;i<NX*NY*LM;i++) {sk[i]=0.0;yk[i]=0.0;}}
else {printf("PE%d: Memory Shortage for sk and yk...sadly abort...\n",my_rank);return 1;}
//For regularization
double global_E[MAXIter],global_Et[MAXIter],global_Er[MAXIter],loc_E=0.0,loc_Er=0.0,loc_Et=0.0;
FILE *fe;
while (!convflag && Iterk++<MAXIter){
//nux=2.*nux/double(Iterk+1);nuy=2.*nuy/double(Iterk+1);
if (my_rank==0) printf("Iterating No. %d: (nux,nuy)=(%f,%f)\n",Iterk,nux,nuy);
tic=MPI_Wtime();
lambdaR=new (nothrow)double [NX*NY];lambdaT=new (nothrow)double [NX*NY];lambdaRT=new (nothrow)double [NX*NY];
for (int kk=0;kk<NY*NX;kk++) {lambdaR[kk]=0.0;lambdaT[kk]=0.0;lambdaRT[kk]=0.0;Djk0[kk]=Djk1[kk];}
loc_E=0.0;loc_Er=0.0;loc_Et=0.0;
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
//ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
RT_fsm2d(vp, TT, TTd, TTu, Z, src,rec, srnum, srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
lambdaT_i=new (nothrow)double [NX*NY];
loc_Et+=Tadjoint_fsm2d(lambdaT_i,TT,TT_obs,rec,nxy,src,srnum,srcid,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaT[kk]=lambdaT[kk]-lambdaT_i[kk]/(vp[kk]*vp[kk]*vp[kk]);
delete [] lambdaT_i;lambdaT_i=NULL;
lambdaR_i=new (nothrow)double [NX*NY];
loc_Er+=Radjoint_fsm2d(lambdaR_i,TTd,TTu, TR_obs,rec,nxy,src,srnum,srcid,NumofR,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaR[kk]=lambdaR[kk]-lambdaR_i[kk]/(vp[kk]*vp[kk]*vp[kk]);
delete [] lambdaR_i;lambdaR_i=NULL;
//RTweight(WR,lambdaRT,lambdaR,lambdaT,&loc_E,&loc_Er,&loc_Et,NX,NY);
for (int kk=0;kk<NX*NY;kk++) lambdaRT[kk]=lambdaT[kk]*(1.-WR[kk])+lambdaR[kk]*WR[kk];
loc_E=loc_Er+loc_Et;
}
MPI_Barrier( MPI_COMM_WORLD );
if (RTtag==3) {//Joint
MPI_Allreduce( &lambdaRT[0], &Djk1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==1) {//Transmission
MPI_Allreduce( &lambdaT[0], &Djk1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==2) {//Reflection
MPI_Allreduce( &lambdaR[0], &Djk1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (my_rank==0)
{printf("RTtag is unrecognized!...abort...\n");exit(1);}
MPI_Allreduce( &loc_E, &global_E[Iterk-1], 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Et, &global_Et[Iterk-1], 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Er, &global_Er[Iterk-1], 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
double *gRtmp=new double [NX*NY];
double *gTtmp=new double [NX*NY];
MPI_Allreduce( &lambdaR[0], &gRtmp[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &lambdaT[0], &gTtmp[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
if (my_rank==0) {
printf("Average Time Residual (TR): %g ms\t",1000*sqrt(2*global_E[Iterk-1]/NumofRec));
printf("(T): %g ms\t",1000*sqrt(2*global_Et[Iterk-1]/NumofRec));
printf("(R): %g ms\n",1000*sqrt(2*global_Er[Iterk-1]/NumofRec));
//fprintf(fe,"%f\n",global_E[Iterk-1]);
}
if (my_rank==0 ) {sprintf(lmdfile,"%s_bf_regu_RT%d",p_vpfile,Iterk);writemod(Djk1,lmdfile,NX,NY);}
regu2d(Djk1,vp,nux, nuy, dx,dz, NX,NY);
if (schemetag==3) {
if (Iterk==1) alpha1=5e2*magnitudeOf(Djk1,NX,NY);
}
else alpha1=5e2*magnitudeOf(Djk1,NX,NY);
if (my_rank==0 ) {sprintf(lmdfile,"%s_af_regu_RT%d",p_vpfile,Iterk); writemod(Djk1,lmdfile,NX,NY);}
if (my_rank==0 ) {sprintf(lmdfile,"%s_bf_regu_R%d",p_vpfile,Iterk);writemod(gRtmp,lmdfile,NX,NY);}
regu2d(gRtmp,vp,nux, nuy, dx,dz, NX,NY);
if (my_rank==0 ) {sprintf(lmdfile,"%s_af_regu_R%d",p_vpfile,Iterk); writemod(gRtmp,lmdfile,NX,NY);}
if (my_rank==0 ) {sprintf(lmdfile,"%s_bf_regu_T%d",p_vpfile,Iterk);writemod(gTtmp,lmdfile,NX,NY);}
regu2d(gTtmp,vp,nux, nuy, dx,dz, NX,NY);
if (my_rank==0 ) {sprintf(lmdfile,"%s_af_regu_T%d",p_vpfile,Iterk); writemod(gTtmp,lmdfile,NX,NY);}
delete [] gRtmp;gRtmp=NULL;
delete [] gTtmp;gTtmp=NULL;
if (my_rank==0) {
sprintf(lmdfile,"%s_GlobalErr_TR_T_R.txt",p_vpfile);
if ((fe=fopen(lmdfile,"w"))==NULL) printf(" The file %s cannot be opened\n",lmdfile);
for (int i=0;i<Iterk;i++)
fprintf(fe,"%g\t%g\t%g\n",global_E[i],global_Et[i],global_Er[i]);
fclose(fe);
}
//delete [] lambdaR;lambdaR=NULL;
//delete [] lambdaT;lambdaT=NULL;
/*
1-HS Nonlinear Conjugate Method
2-CGDESCENT Nonlinear Conjugate Method
3-L-BFGS quasi-newton method
*/
//schemetag=1;
if (Iterk==1) {
for (int ii=0;ii<NX*NY;ii++)
dk[ii]=Djk1[ii];
}
else {
switch(schemetag)
{
case 1:
beta=beta_HS(Djk1,Djk0,dk,NX,NY);
for (int ii=0;ii<NX*NY;ii++)
dk[ii]=Djk1[ii]+dk[ii]*beta;
c1=1.0e-4;c2=0.1;
break;
case 2:
beta=beta_CGDESCENT(Djk1,Djk0,dk,NX,NY);
for (int ii=0;ii<NX*NY;ii++)
dk[ii]=Djk1[ii]+dk[ii]*beta;
c1=1.0e-4;c2=0.1;
break;
case 3:
for (int j=0;j<NX*NY;j++) q[j]=Djk1[j];
//printf("PE_%d: size of ai=%d\n",my_rank,Iterk-1-((Iterk-LM-1)<=0?0:Iterk-LM-1));
gamma=gd2sk(Djk1,Djk0,dk,alpha1,rhoi,sk,yk,Iterk,LM,NX,NY);
//if (Iterk-2>=LM-1) printf("PE_%d: gamma=%f, after gd2sk\n",my_rank,gamma);
//L_BFGS two-loop recursion to update searching direction dk
for (int i=Iterk-2;i>=((Iterk-LM-1>=0)?Iterk-LM-1:0);i--)
{
ai[i%LM]=0.0;for (int j=0;j<NX*NY;j++) ai[i%LM]+=rhoi[i%LM]*sk[(i%LM)*NX*NY+j]*q[j];
for (int j=0;j<NX*NY;j++) q[j]-=ai[i]*yk[(i%LM)*NX*NY+j];
}
for (int j=0;j<NX*NY;j++) dk[j]=gamma*q[j];
//if (Iterk-2>=LM-1) printf("PE_%d: break 1\n",my_rank);
//delete [] q;q=NULL;
for (int i=((Iterk-LM-1>=0)?Iterk-LM-1:0);i<=Iterk-2;i++)
{
tmp=0.0;for (int j=0;j<NX*NY;j++) tmp+=rhoi[i%LM]*yk[(i%LM)*NX*NY+j]*dk[j];
for (int j=0;j<NX*NY;j++) dk[j]+=sk[(i%LM)*NX*NY+j]*(ai[i%LM]-tmp);
}
//for (int j=0;j<NX*NY;j++) dk[j]=-dk[j];
//if (Iterk-2>=LM-1) printf("PE_%d: break 2\n",my_rank);
//delete [] ai;ai=NULL;
alpha0=0.0;alpha1=1.0;
c1=1.0e-4;c2=0.9;
break;
default:
if (my_rank==0) printf("Numerical Optimization Method Unknown..abort...\n");
return 1;
break;
}
}
//int lsrc=3;
/*Line search method:
1-Secant method with exact Conditions
2-Line Search with Strong Wolfe Conditions
3-Cubic Interpolation method with Strong Wolfe Conditions
0-No Line Search
*/
switch (lsrc)
{
case 1:
{lstime=MPI_Wtime();
if (my_rank==0) printf("Secant Method Line Search for 'exact' condition (alpha1=%g)...\n",alpha1);
//if (my_rank==0) printf("(alpha_0 alpha_1)=(%f %f)\n",alpha0,alpha1);
count=0;alpha0=0.e3;loc_vp=new (nothrow) double [NX*NY];
for (int i=0;i<NX*NY;i++) f0=f0+Djk1[i]*dk[i];
while (fabs(alpha1-alpha0)/fabs(alpha0)>1e-2 && count++<MAXLineSch){
for (int i=0;i<NX*NY;i++){loc_vp[i]=vp[i]+alpha1*dk[i];lambdaRT[i]=0.0;lambdaR[i]=0.0;lambdaT[i]=0.0;}
loc_E=0.0;loc_Er=0.0;loc_Et=0.0;
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
//ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
RT_fsm2d(loc_vp, TT, TTd, TTu, Z,src,rec, srnum,srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
lambdaT_i=new (nothrow)double [NX*NY];
loc_Et+=Tadjoint_fsm2d(lambdaT_i,TT,TT_obs,rec,nxy,src,srnum,srcid,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaT[kk]=lambdaT[kk]-lambdaT_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaT_i;lambdaT_i=NULL;
lambdaR_i=new (nothrow)double [NX*NY];
loc_Er+=Radjoint_fsm2d(lambdaR_i,TTd,TTu,TR_obs,rec,nxy,src,srnum,srcid,NumofR,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaR[kk]=lambdaR[kk]-lambdaR_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaR_i;lambdaR_i=NULL;
//RTweight(WR,lambdaRT,lambdaR,lambdaT,&loc_E,&loc_Er,&loc_Et,NX,NY);
for (int kk=0;kk<NX*NY;kk++) lambdaRT[kk]=lambdaT[kk]*(1.-WR[kk])+lambdaR[kk]*WR[kk];
loc_E=loc_Er+loc_Et;
}
MPI_Barrier( MPI_COMM_WORLD );
if (RTtag==3) //Joint
MPI_Allreduce( &lambdaRT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
else if (RTtag==1) //Transmission
MPI_Allreduce( &lambdaT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
else if (RTtag==2) //Reflection
MPI_Allreduce( &lambdaR[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
else if (my_rank==0)
{printf("RTtag is unrecognized!...abort...\n");exit(1);}
regu2d(Dj1,vp,nux, nuy, dx,dz, NX,NY);
//if (my_rank==0) {sprintf(lmdfile,"Dj1_after_regu%d.tmp",Iterk); writemod(Dj1,lmdfile,NX,NY);}
f0=0.0;f1=0.0;
for (int i=0;i<NX*NY;i++) f1=f1+Dj1[i]*dk[i];
alphak=alpha1-(alpha1-alpha0)*f1/(f1-f0);alpha0=alpha1;alpha1=alphak;f0=f1;
//if (my_rank==0) printf("f1=%20f, f0=%20f\n",f1,f0);
//if (my_rank==0) printf("Updated (alpha_0 alpha_1)=(%f %f), changed by %f\n",alpha0,alpha1,fabs((alpha1-alpha0)/alpha0));
}
if (count>MAXLineSch) {
if(my_rank==0) printf("Line Search Stopped, takes %g seconds, Stepsize=%f\n ...Updating velocity now...\n",MPI_Wtime()-lstime,alpha1);}
else {
if(my_rank==0) printf("Line Search Completed After %d Iterations, takes %g seconds, Stepsize=%f\n...Updating velocity now...\n",count,MPI_Wtime()-lstime,alpha1);}
delete [] loc_vp;loc_vp=NULL;
break;}
case 2: //with strong wolfe conditions
{lstime=MPI_Wtime();
if (my_rank==0) printf("Secant Method Line Search with Strong Wolfe Condition (alpha1=%g)...\n",alpha1);
bool isWolfe=false;
double phi0=global_E[Iterk-1],phi1;
double dphi0=0.0,dphi1=0.0;
count=0;alpha0=0.0;
//if (my_rank==0) printf("(alpha_0 alpha_1)=(%f %f)\n",alpha0,alpha1);
dphi0=0.0; for (int i=0;i<NX*NY;i++) dphi0+=-dk[i]*Djk1[i];
while (!isWolfe && count++<MAXLineSch ){
for (int i=0;i<NX*NY;i++) {loc_vp[i]=vp[i]+alpha1*dk[i];lambdaRT[i]=0.0;lambdaR[i]=0.0;lambdaT[i]=0.0;}
loc_E=0.0;loc_Er=0.0;loc_Et=0.0;
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
//ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
RT_fsm2d(loc_vp, TT, TTd, TTu, Z,src,rec, srnum,srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
lambdaT_i=new (nothrow)double [NX*NY];
loc_Et+=Tadjoint_fsm2d(lambdaT_i,TT,TT_obs,rec,nxy,src,srnum,srcid,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaT[kk]=lambdaT[kk]-lambdaT_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaT_i;lambdaT_i=NULL;
lambdaR_i=new (nothrow)double [NX*NY];
loc_Er+=Radjoint_fsm2d(lambdaR_i,TTd,TTu,TR_obs,rec,nxy,src,srnum,srcid,NumofR,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaR[kk]=lambdaR[kk]-lambdaR_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaR_i;lambdaR_i=NULL;
//RTweight(WR,lambdaRT,lambdaR,lambdaT,&loc_E,&loc_Er,&loc_Et,NX,NY);
for (int kk=0;kk<NX*NY;kk++) lambdaRT[kk]=lambdaT[kk]*(1.-WR[kk])+lambdaR[kk]*WR[kk];
loc_E=loc_Er+loc_Et;
}
MPI_Barrier( MPI_COMM_WORLD );
if (RTtag==3) {//Joint
MPI_Allreduce( &lambdaRT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_E, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==1) {//Transmission
MPI_Allreduce( &lambdaT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Et, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==2) {//Reflection
MPI_Allreduce( &lambdaR[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Er, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (my_rank==0)
{printf("RTtag is unrecognized!...abort...\n");exit(1);}
//MPI_Allreduce( &lambdaRT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
//MPI_Allreduce( &loc_E, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
regu2d(Dj1,vp,nux, nuy, dx,dz, NX,NY);
dphi1=0.0;for (int i=0;i<NX*NY;i++) dphi1+=-dk[i]*Dj1[i];
//if (count==1) {alpha1=alpha1-(alpha1-alpha0)*dphi1/(dphi1-dphi0);}
if(my_rank==0) printf("(alpha0,alpha1,phi0,phi1,dphi0,dphi1)=(%g %g %g %g %g %g\n",alpha0,alpha1,phi0,phi1,dphi0,dphi1);
if (phi1<=phi0+c1*alpha1*dphi0 && fabs(dphi1)<=-c2*dphi0)
isWolfe=true;
else
alpha1=alpha1-(alpha1-alpha0)*dphi1/(dphi1-dphi0);
//if (my_rank==0) printf("(alpha_0 alpha_1)=(%g %g)\n",alpha0,alpha1);
}
if (count>MAXLineSch) {
if(my_rank==0) printf("Line Search Stopped, takes %g seconds, Stepsize=%f\n ...Updating velocity now...\n",MPI_Wtime()-lstime,alpha1);
}
else {
if(my_rank==0) printf("Wolfe condition satisfied After %d Iterations, takes %g seconds, Stepsize=%f\n...Updating velocity now...\n",count,MPI_Wtime()-lstime,alpha1);
//if(my_rank==0) printf("(alpha0,alpha1,phi0,phi1,dphi0,dphi1)=(%g %g %g %g %g %g\n",alpha0,alpha1,phi0,phi1,dphi0,dphi1);
}
//delete [] loc_vp;loc_vp=NULL;
break;}
case 3: //cubic interpolation
{
lstime=MPI_Wtime();
if (my_rank==0) {
if (schemetag==3) printf("Cubic Interpolation Line Search with Strong Wolfe Condition (alpha1=%g)...\n",alpha1);
else printf("Cubic Interpolation Line Search (alpha1=%g)...\n",alpha1);
}
bool isWolfe=false;
double phi0=global_E[Iterk-1],phi1;
double dphi0=0.0,dphi1=0.0;
count=0;alpha0=0.0;
dphi0=0.0; for (int i=0;i<NX*NY;i++) dphi0+=-dk[i]*Djk1[i];
if (schemetag==3){ //LBFGS, Strong Wolfe Condition Applied
while (!isWolfe && count++<MAXLineSch ){
for (int i=0;i<NX*NY;i++) {loc_vp[i]=vp[i]+alpha1*dk[i];lambdaRT[i]=0.0;lambdaR[i]=0.0;lambdaT[i]=0.0;}
loc_E=0.0;loc_Er=0.0;loc_Et=0.0;
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
//ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
RT_fsm2d(loc_vp, TT, TTd, TTu, Z,src,rec, srnum,srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
lambdaT_i=new (nothrow)double [NX*NY];
loc_Et+=Tadjoint_fsm2d(lambdaT_i,TT,TT_obs,rec,nxy,src,srnum,srcid,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaT[kk]=lambdaT[kk]-lambdaT_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaT_i;lambdaT_i=NULL;
lambdaR_i=new (nothrow)double [NX*NY];
loc_Er+=Radjoint_fsm2d(lambdaR_i,TTd,TTu,TR_obs,rec,nxy,src,srnum,srcid,NumofR,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaR[kk]=lambdaR[kk]-lambdaR_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaR_i;lambdaR_i=NULL;
//RTweight(WR,lambdaRT,lambdaR,lambdaT,&loc_E,&loc_Er,&loc_Et,NX,NY);
for (int kk=0;kk<NX*NY;kk++) lambdaRT[kk]=lambdaT[kk]*(1.-WR[kk])+lambdaR[kk]*WR[kk];
loc_E=loc_Er+loc_Et;
}
MPI_Barrier( MPI_COMM_WORLD );
if (RTtag==3) {//Joint
MPI_Allreduce( &lambdaRT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_E, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==1) {//Transmission
MPI_Allreduce( &lambdaT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Et, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==2) {//Reflection
MPI_Allreduce( &lambdaR[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Er, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (my_rank==0)
{printf("RTtag is unrecognized!...abort...\n");exit(1);}
regu2d(Dj1,vp,nux, nuy, dx,dz, NX,NY);
dphi1=0.0;for (int i=0;i<NX*NY;i++) dphi1+=-dk[i]*Dj1[i];
if (phi1<=phi0+c1*alpha1*dphi0 && fabs(dphi1)<=-c2*dphi0)
isWolfe=true;
else
alpha1=cubicInterp(alpha0,alpha1,phi0,phi1,dphi0,dphi1);
if(my_rank==0) printf("(alpha0,alpha1,phi0,phi1,dphi0,dphi1)=(%g %g %g %g %g %g\n",alpha0,alpha1,phi0,phi1,dphi0,dphi1);
}
if (count>MAXLineSch) {
if(my_rank==0) printf("Line Search Stopped, takes %g seconds, Stepsize=%f\n ...Updating velocity now...\n",MPI_Wtime()-lstime,alpha1);
}
else {
if(my_rank==0) printf("Wolfe condition satisfied After %d Iterations, takes %g seconds, Stepsize=%f\n...Updating velocity now...\n",count,MPI_Wtime()-lstime,alpha1);
}
}
else {
for (int i=0;i<NX*NY;i++) {loc_vp[i]=vp[i]+alpha1*dk[i];lambdaRT[i]=0.0;lambdaR[i]=0.0;lambdaT[i]=0.0;}
loc_E=0.0;loc_Er=0.0;loc_Et=0.0;
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
//ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
RT_fsm2d(loc_vp, TT, TTd, TTu, Z,src,rec, srnum,srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
lambdaT_i=new (nothrow)double [NX*NY];
loc_Et+=Tadjoint_fsm2d(lambdaT_i,TT,TT_obs,rec,nxy,src,srnum,srcid,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaT[kk]=lambdaT[kk]-lambdaT_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaT_i;lambdaT_i=NULL;
lambdaR_i=new (nothrow)double [NX*NY];
loc_Er+=Radjoint_fsm2d(lambdaR_i,TTd,TTu,TR_obs,rec,nxy,src,srnum,srcid,NumofR,MAXSwp,dx,dz,NX,NY,my_rank);
for (int kk=0;kk<NX*NY;kk++) lambdaR[kk]=lambdaR[kk]-lambdaR_i[kk]/(loc_vp[kk]*loc_vp[kk]*loc_vp[kk]);
delete [] lambdaR_i;lambdaR_i=NULL;
//RTweight(WR,lambdaRT,lambdaR,lambdaT,&loc_E,&loc_Er,&loc_Et,NX,NY);
for (int kk=0;kk<NX*NY;kk++) lambdaRT[kk]=lambdaT[kk]*(1.-WR[kk])+lambdaR[kk]*WR[kk];
loc_E=loc_Er+loc_Et;
}
MPI_Barrier( MPI_COMM_WORLD );
if (RTtag==3) {//Joint
MPI_Allreduce( &lambdaRT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_E, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==1) {//Transmission
MPI_Allreduce( &lambdaT[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Et, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (RTtag==2) {//Reflection
MPI_Allreduce( &lambdaR[0], &Dj1[0], NX*NY, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
MPI_Allreduce( &loc_Er, &phi1, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD );
}
else if (my_rank==0)
{printf("RTtag is unrecognized!...abort...\n");exit(1);}
regu2d(Dj1,vp,nux, nuy, dx,dz, NX,NY);
dphi1=0.0;for (int i=0;i<NX*NY;i++) dphi1+=-dk[i]*Dj1[i];
alpha1=cubicInterp(alpha0,alpha1,phi0,phi1,dphi0,dphi1);
if(my_rank==0) printf("(alpha0,alpha1,phi0,phi1,dphi0,dphi1)=(%g %g %g %g %g %g\n",alpha0,alpha1,phi0,phi1,dphi0,dphi1);
}
break;}
case 0:
if (my_rank==0) printf("No Line Searching, Stepsize=%f\n",alpha1);
break;
default:
if (my_rank==0) printf("Line search tag unknown..abort...\n");
return 1;
break;
}
updatevp(vp,dk,alpha1,NX,NY);
if (my_rank==0) {
sprintf(lmdfile,"%s_%d",p_vpfile,Iterk);
writemod(vp,lmdfile,NX,NY);
//sprintf(lmdfile,"%s_%d.gTimeRes",p_vpfile,Iterk);
//writemod(g_TimeRes, lmdfile, NumofRec, NumofR+1+DIM);
}
convflag=check_conv(dk,alpha1,vp,global_E,Iterk,10.0,NX,NY);
MPI_Barrier( MPI_COMM_WORLD );
if (my_rank==0) printf("--------Interating No. %d takes %10.4f seconds---------------\n\n",Iterk,MPI_Wtime()-tic);
}
MPI_Barrier( MPI_COMM_WORLD );
if(my_rank==0) {
writemod(vp, vpfile, NX, NY);
sprintf(lmdfile,"%s_AveRes_TR_T_R.txt",p_vpfile);
if ((fe=fopen(lmdfile,"w"))==NULL)
printf(" The file Err.txt cannot be opened\n");
for (int i=0;i<Iterk;i++)
fprintf(fe,"%g\t%g\t%g\n",1000*sqrt(2*global_E[i]/NumofRec),1000*sqrt(2*global_Et[i]/NumofRec),1000*sqrt(2*global_Er[i]/NumofRec));
fclose(fe);
printf("Total Elapse Time: %10.4f seconds (%8.4f hours) \n",MPI_Wtime()-Telapse, (MPI_Wtime()-Telapse)/3600.0);
RTinfo(RTtag);
}
#else
for (int srcid=(my_rank-1>=0?loc_srcid[my_rank-1]:0);srcid<loc_srcid[my_rank];srcid++){
ch0=0;for (int j=(my_rank-1>=0?loc_srcid[my_rank-1]:0);j<srcid;j++) ch0+=srnum[j];
chr=0;for (int j=0;j<srcid;j++) chr+=srnum[j];
//printf("PE_%d:ch0=%d,chr=%d\n",my_rank,ch0,chr);
RT_fsm2d(vp, TT, TTd, TTu, Z,src,rec, srnum,srcid, NumofR, MAXSwp, dx,dz, NX,NY,my_rank);
for (int idx=0;idx<srnum[srcid];idx++) {
int i=rec[(idx+chr)*DIM+0],j=rec[(idx+chr)*DIM+1];
//if (TT_obs[(ch0+idx)*(NumofR+1)+0]<100)
Tr[(ch0+idx)*(NumofR+1)+0]=TT[i*NY+j];
//else
//Tr[(ch0+idx)*(NumofR+1)+0]=INF;
}
for (int ir=0;ir<NumofR;ir++){
for (int idx=0;idx<srnum[srcid];idx++) {
int i=rec[(idx+chr)*DIM+0],j=rec[(idx+chr)*DIM+1];
//if (TR_obs[(ch0+idx)*(NumofR+1)+ir+1]>0)
Tr[(ch0+idx)*(NumofR+1)+ir+1]=TTu[ir*NX*NY+i*NY+j];
//else
// Tr[(ch0+idx)*(NumofR+1)+ir+1]=0;
}
}
#ifndef NoShotGather
sprintf(lmdfile,"%s_Src%d_TTd.2d",p_vpfile,srcid);writemod(TTd,lmdfile,NumofR,NX*NY);
sprintf(lmdfile,"%s_Src%d_TTu.2d",p_vpfile,srcid);writemod(TTu,lmdfile,NumofR,NX*NY);
#endif
}
sprintf(lmdfile,"Tr2D.%d",my_rank);writemod(Tr, lmdfile, ch1, NumofR+1);
MPI_Barrier( MPI_COMM_WORLD );
if(my_rank==0) {
for (int i=0;i<np;i++){
if (i==0) {sprintf(cmd,"cat Tr2D.%d > %s_Tr2D.bin ",i,p_vpfile);system(cmd);}
else {sprintf(cmd,"cat Tr2D.%d >> %s_Tr2D.bin ",i,p_vpfile);system(cmd);}
sprintf(cmd,"rm Tr2D.%d",i);system(cmd);
}
printf("Total Elapse Time: %10.4f seconds (%8.4f hours) \n",MPI_Wtime()-Telapse, (MPI_Wtime()-Telapse)/3600.0);}
#endif
MPI_Finalize();
return 0;
}
| [
"jwhuang1982@gmail.com"
] | jwhuang1982@gmail.com |
db43a53c46655fc680943e7d2f6bcf072d353b2b | 08f0c67aa6813e59fb4c2672297d3c33c0b4f9cf | /importfbx/parsematerial.cpp | fbce6a99337203a31fd30b0df8b68e58c101ead6 | [
"MIT",
"Zlib"
] | permissive | ssshammi/contentexporter | 7d4164213e0ff89282aacb5719989633be2324e1 | 1e92da3cdee59da9e96d8f123d45d1a09d941007 | refs/heads/master | 2023-01-19T00:59:14.560813 | 2020-12-05T03:20:05 | 2020-12-05T03:20:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,753 | cpp | //-------------------------------------------------------------------------------------
// ParseMaterial.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=226208
//-------------------------------------------------------------------------------------
#include "StdAfx.h"
#include <algorithm>
#include "ParseMaterial.h"
using namespace ATG;
extern ATG::ExportScene* g_pScene;
bool MaterialParameterSort(ExportMaterialParameter A, ExportMaterialParameter B)
{
if (A.ParamType == MPT_TEXTURE2D && B.ParamType != MPT_TEXTURE2D)
return true;
return false;
}
void FixupGenericMaterial(ExportMaterial* pMaterial)
{
ExportMaterialParameter OutputParam;
OutputParam.ParamType = MPT_TEXTURE2D;
OutputParam.bInstanceParam = true;
ExportMaterialParameter* pParam = pMaterial->FindParameter("DiffuseTexture");
if (!pParam)
{
OutputParam.ValueString = ExportMaterial::GetDefaultDiffuseMapTextureName();
if (*OutputParam.ValueString)
{
ExportLog::LogMsg(2, "Material \"%s\" has no diffuse texture. Assigning a default diffuse texture.", pMaterial->GetName().SafeString());
OutputParam.Name = "DiffuseTexture";
pMaterial->AddParameter(OutputParam);
}
}
else if (g_ExportCoreSettings.bMaterialColors)
{
auto pColor = pMaterial->FindParameter("DiffuseColor");
if (pColor && pColor->ValueFloat[0] == 0 && pColor->ValueFloat[1] == 0 && pColor->ValueFloat[2] == 0)
{
ExportLog::LogWarning("Material \"%s\" has a black DiffuseColor which will modulate a DiffuseTexture to black. Set a DiffuseColor or use -materialcolors-.", pMaterial->GetName().SafeString());
}
}
pParam = pMaterial->FindParameter("NormalMapTexture");
if (!pParam)
{
OutputParam.ValueString = ExportMaterial::GetDefaultNormalMapTextureName();
if (*OutputParam.ValueString)
{
ExportLog::LogMsg(2, "Material \"%s\" has no normal map texture. Assigning a default normal map texture.", pMaterial->GetName().SafeString());
OutputParam.Name = "NormalMapTexture";
pMaterial->AddParameter(OutputParam);
}
}
pParam = pMaterial->FindParameter("SpecularMapTexture");
if (!pParam)
{
if (g_ExportCoreSettings.bUseEmissiveTexture)
{
pParam = pMaterial->FindParameter("EmissiveMapTexture");
if (pParam)
{
// Copy emissive to specular (SDKMESH's material doesn't have an emissive texture slot)
ExportLog::LogMsg(4, "EmissiveMapTexture encoded as SpecularMapTexture in material \"%s\".", pMaterial->GetName().SafeString());
OutputParam.Name = "SpecularMapTexture";
OutputParam.ValueString = pParam->ValueString;
pMaterial->AddParameter(OutputParam);
}
}
if (!pParam)
{
OutputParam.ValueString = ExportMaterial::GetDefaultSpecularMapTextureName();
if (*OutputParam.ValueString)
{
ExportLog::LogMsg(2, "Material \"%s\" has no specular map texture. Assigning a default specular map texture.", pMaterial->GetName().SafeString());
OutputParam.Name = "SpecularMapTexture";
pMaterial->AddParameter(OutputParam);
}
}
}
auto pParamList = pMaterial->GetParameterList();
//std::reverse( pParamList->begin(), pParamList->end() );
std::stable_sort(pParamList->begin(), pParamList->end(), MaterialParameterSort);
}
void AddTextureParameter(ExportMaterial* pMaterial, const CHAR* strParamName, DWORD dwIndex, const CHAR* strFileName, DWORD dwFlags)
{
ExportMaterialParameter OutputParam;
if (dwIndex == 0)
{
OutputParam.Name = strParamName;
}
else
{
CHAR strDecoratedName[512];
sprintf_s(strDecoratedName, "%s%u", strParamName, dwIndex);
OutputParam.Name = strDecoratedName;
}
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%s\"", OutputParam.Name.SafeString(), strFileName);
OutputParam.ValueString = strFileName;
OutputParam.ParamType = MPT_TEXTURE2D;
OutputParam.bInstanceParam = true;
OutputParam.Flags = dwFlags;
pMaterial->AddParameter(OutputParam);
}
static void CheckUVSettings(FbxFileTexture* texture, const ExportMaterial* pMaterial)
{
if (texture->GetSwapUV())
{
ExportLog::LogWarning("Material \"%s\" has swapped UVs which are not exported as such", pMaterial->GetName().SafeString());
}
if (texture->GetWrapModeU() != FbxTexture::eRepeat
|| texture->GetWrapModeV() != FbxTexture::eRepeat)
{
ExportLog::LogWarning("Material \"%s\" has set to clamp wrap U/V mode which is not exported", pMaterial->GetName().SafeString());
}
auto& uvScaling = texture->GetUVScaling();
auto& uvTrans = texture->GetUVTranslation();
if (uvScaling[0] != 1.0
|| uvScaling[1] != 1.0
|| uvTrans[0] != 0
|| uvTrans[1] != 0)
{
ExportLog::LogWarning("Material \"%s\" has UV transforms which are not exported", pMaterial->GetName().SafeString());
}
}
bool ExtractTextures(FbxProperty Property, const CHAR* strParameterName, ExportMaterial* pMaterial, DWORD dwFlags)
{
bool bResult = false;
const DWORD dwLayeredTextureCount = Property.GetSrcObjectCount<FbxLayeredTexture>();
if (dwLayeredTextureCount > 0)
{
DWORD dwTextureIndex = 0;
for (DWORD i = 0; i < dwLayeredTextureCount; ++i)
{
auto pFbxLayeredTexture = FbxCast<FbxLayeredTexture>(Property.GetSrcObject<FbxLayeredTexture>(i));
const DWORD dwTextureCount = pFbxLayeredTexture->GetSrcObjectCount<FbxFileTexture>();
for (DWORD j = 0; j < dwTextureCount; ++j)
{
auto pFbxTexture = FbxCast<FbxFileTexture>(pFbxLayeredTexture->GetSrcObject<FbxFileTexture>(j));
if (!pFbxTexture)
continue;
CheckUVSettings(pFbxTexture, pMaterial);
AddTextureParameter(pMaterial, strParameterName, dwTextureIndex, pFbxTexture->GetFileName(), dwFlags);
++dwTextureIndex;
bResult = true;
}
}
}
else
{
const DWORD dwTextureCount = Property.GetSrcObjectCount<FbxFileTexture>();
for (DWORD i = 0; i < dwTextureCount; ++i)
{
auto pFbxTexture = FbxCast<FbxFileTexture>(Property.GetSrcObject<FbxFileTexture>(i));
if (!pFbxTexture)
continue;
CheckUVSettings(pFbxTexture, pMaterial);
AddTextureParameter(pMaterial, strParameterName, i, pFbxTexture->GetFileName(), dwFlags);
bResult = true;
}
}
return bResult;
}
ExportMaterial* ParseMaterial(FbxSurfaceMaterial* pFbxMaterial)
{
if (!pFbxMaterial)
return nullptr;
auto pExistingMaterial = g_pScene->FindMaterial(pFbxMaterial);
if (pExistingMaterial)
{
ExportLog::LogMsg(4, "Found existing material \"%s\".", pFbxMaterial->GetName());
return pExistingMaterial;
}
ExportLog::LogMsg(2, "Parsing material \"%s\".", pFbxMaterial->GetName());
bool bRenameMaterial = false;
ExportString MaterialName(pFbxMaterial->GetName());
ExportMaterial* pSameNameMaterial = nullptr;
DWORD dwRenameIndex = 0;
do
{
pSameNameMaterial = g_pScene->FindMaterial(MaterialName);
if (pSameNameMaterial)
{
bRenameMaterial = true;
CHAR strName[200];
sprintf_s(strName, "%s_%u", pFbxMaterial->GetName(), dwRenameIndex++);
MaterialName = strName;
}
} while (pSameNameMaterial);
if (bRenameMaterial)
{
ExportLog::LogMsg(2, "Found duplicate material name; renaming material \"%s\" to \"%s\".", pFbxMaterial->GetName(), MaterialName.SafeString());
}
ExportMaterial* pMaterial = new ExportMaterial(MaterialName);
pMaterial->SetDCCObject(pFbxMaterial);
pMaterial->SetDefaultMaterialName(g_pScene->Settings().strDefaultMaterialName);
if (g_ExportCoreSettings.bMaterialColors)
{
auto pFbxLambert = FbxCast<FbxSurfaceLambert>(pFbxMaterial);
if (pFbxLambert)
{
// Diffuse Color
{
FbxDouble3 color = pFbxLambert->Diffuse.Get();
const double factor = pFbxLambert->DiffuseFactor.Get();
ExportMaterialParameter OutputParam;
OutputParam.Name = "DiffuseColor";
OutputParam.ValueFloat[0] = static_cast<float>(color[0] * factor);
OutputParam.ValueFloat[1] = static_cast<float>(color[1] * factor);
OutputParam.ValueFloat[2] = static_cast<float>(color[2] * factor);
OutputParam.ValueFloat[3] = static_cast<float>(1.0 - pFbxLambert->TransparencyFactor.Get());
OutputParam.ParamType = MPT_FLOAT4;
OutputParam.bInstanceParam = true;
OutputParam.Flags = 0;
pMaterial->AddParameter(OutputParam);
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%f %f %f %f\"", OutputParam.Name.SafeString(),
OutputParam.ValueFloat[0], OutputParam.ValueFloat[1], OutputParam.ValueFloat[2], OutputParam.ValueFloat[3]);
}
// Ambient Color
{
FbxDouble3 color = pFbxLambert->Ambient.Get();
const double factor = pFbxLambert->AmbientFactor.Get();
ExportMaterialParameter OutputParam;
OutputParam.Name = "AmbientColor";
OutputParam.ValueFloat[0] = static_cast<float>(color[0] * factor);
OutputParam.ValueFloat[1] = static_cast<float>(color[1] * factor);
OutputParam.ValueFloat[2] = static_cast<float>(color[2] * factor);
OutputParam.ParamType = MPT_FLOAT3;
OutputParam.bInstanceParam = true;
OutputParam.Flags = 0;
pMaterial->AddParameter(OutputParam);
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%f %f %f\"", OutputParam.Name.SafeString(),
OutputParam.ValueFloat[0], OutputParam.ValueFloat[1], OutputParam.ValueFloat[2]);
}
// Emissive Color
{
FbxDouble3 color = pFbxLambert->Emissive.Get();
const double factor = pFbxLambert->EmissiveFactor.Get();
ExportMaterialParameter OutputParam;
OutputParam.Name = "EmissiveColor";
OutputParam.ValueFloat[0] = static_cast<float>(color[0] * factor);
OutputParam.ValueFloat[1] = static_cast<float>(color[1] * factor);
OutputParam.ValueFloat[2] = static_cast<float>(color[2] * factor);
OutputParam.ParamType = MPT_FLOAT3;
OutputParam.bInstanceParam = true;
OutputParam.Flags = 0;
pMaterial->AddParameter(OutputParam);
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%f %f %f\"", OutputParam.Name.SafeString(),
OutputParam.ValueFloat[0], OutputParam.ValueFloat[1], OutputParam.ValueFloat[2]);
}
auto pFbxPhong = FbxCast<FbxSurfacePhong>(pFbxLambert);
if (pFbxPhong)
{
// Specular Color
{
FbxDouble3 color = pFbxPhong->Specular.Get();
const double factor = pFbxPhong->SpecularFactor.Get();
ExportMaterialParameter OutputParam;
OutputParam.Name = "SpecularColor";
OutputParam.ValueFloat[0] = static_cast<float>(color[0] * factor);
OutputParam.ValueFloat[1] = static_cast<float>(color[1] * factor);
OutputParam.ValueFloat[2] = static_cast<float>(color[2] * factor);
OutputParam.ParamType = MPT_FLOAT3;
OutputParam.bInstanceParam = true;
OutputParam.Flags = 0;
pMaterial->AddParameter(OutputParam);
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%f %f %f\"", OutputParam.Name.SafeString(),
OutputParam.ValueFloat[0], OutputParam.ValueFloat[1], OutputParam.ValueFloat[2]);
}
// Specular Power
{
ExportMaterialParameter OutputParam;
OutputParam.Name = "SpecularPower";
OutputParam.ValueFloat[0] = static_cast<float>(pFbxPhong->Shininess.Get());
OutputParam.ParamType = MPT_FLOAT;
OutputParam.bInstanceParam = true;
OutputParam.Flags = 0;
pMaterial->AddParameter(OutputParam);
ExportLog::LogMsg(4, "Material parameter \"%s\" = \"%f\"", OutputParam.Name.SafeString(), OutputParam.ValueFloat[0]);
}
}
}
}
enum ParameterPostOperations
{
PPO_Nothing = 0,
PPO_TransparentMaterial = 1,
};
struct TextureParameterExtraction
{
const CHAR* strFbxPropertyName;
const CHAR* strParameterName;
DWORD dwPostOperations;
DWORD dwParameterFlags;
};
const TextureParameterExtraction ExtractionList[] =
{
{ FbxSurfaceMaterial::sTransparentColor, "AlphaTexture", PPO_TransparentMaterial, ExportMaterialParameter::EMPF_ALPHACHANNEL },
{ FbxSurfaceMaterial::sDiffuse, "DiffuseTexture", PPO_Nothing, ExportMaterialParameter::EMPF_DIFFUSEMAP },
{ FbxSurfaceMaterial::sAmbient, "AOTexture", PPO_Nothing, ExportMaterialParameter::EMPF_AOMAP },
{ FbxSurfaceMaterial::sBump, "NormalMapTexture", PPO_Nothing, 0 /*ExportMaterialParameter::EMPF_BUMPMAP*/ },
{ FbxSurfaceMaterial::sNormalMap, "NormalMapTexture", PPO_Nothing, ExportMaterialParameter::EMPF_NORMALMAP },
{ FbxSurfaceMaterial::sSpecular, "SpecularMapTexture", PPO_Nothing, ExportMaterialParameter::EMPF_SPECULARMAP },
{ FbxSurfaceMaterial::sEmissive, "EmissiveMapTexture", PPO_Nothing, 0 },
};
for (DWORD dwExtractionIndex = 0; dwExtractionIndex < ARRAYSIZE(ExtractionList); ++dwExtractionIndex)
{
const TextureParameterExtraction& tpe = ExtractionList[dwExtractionIndex];
auto Property = pFbxMaterial->FindProperty(tpe.strFbxPropertyName);
if (!Property.IsValid())
continue;
const bool bFound = ExtractTextures(Property, tpe.strParameterName, pMaterial, tpe.dwParameterFlags);
if (bFound)
{
if (tpe.dwPostOperations & PPO_TransparentMaterial)
{
ExportLog::LogMsg(4, "Material \"%s\" is transparent.", pMaterial->GetName().SafeString());
pMaterial->SetTransparent(true);
}
}
}
FixupGenericMaterial(pMaterial);
const bool bResult = g_pScene->AddMaterial(pMaterial);
assert(bResult);
if (!bResult)
{
ExportLog::LogError("Could not add material \"%s\" to scene.", pMaterial->GetName().SafeString());
}
g_pScene->Statistics().MaterialsExported++;
return pMaterial;
}
| [
"chuckw@windows.microsoft.com"
] | chuckw@windows.microsoft.com |
1c257638d0fadbf14e957530b78c0d8f534d93de | 895594e52af5f2ef624802d6fc408573640ded58 | /剑指offer/9_CQueue.cpp | b759167b9d6d8edbc3663cc3726c6d10c40162b0 | [] | no_license | NICKEY-CHEN/my_leetcode | d9c592a6a9662b7272ad0bca1befba47244ee4c8 | cbc1aea960eadc1a56fb5b5710534f74c836b4c7 | refs/heads/master | 2023-01-02T15:56:18.932954 | 2020-10-24T06:14:53 | 2020-10-24T06:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,048 | cpp | // @File : 9_CQueue.cpp
// @Source : https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
// @Title : 面试题09. 用两个栈实现队列
// @Auther : sun_ds
// @Date : 2020/2/19
/** 题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
*
* s1负责入,s2负责出。
* s2的值由s1出栈后又入栈组成。则s2的栈顶即为最先进入的数,满足先入先出。
* s2中没有元素可以输出时,从s1出栈后入栈来补充。
*
*/
class CQueue {
public:
stack<int> s1,s2;
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
int ans = -1;
if(!s2.empty()){
ans = s2.top();
s2.pop();
}else{
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
if(!s2.empty()){
ans = s2.top();
s2.pop();
}
}
return ans;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/ | [
"1406161541@qq.com"
] | 1406161541@qq.com |
c404b794399bfc5905bb64816fd78e3d38dbde17 | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/Action/actionIgnitedThrown.cpp | 791ee57f4decb921d47541f5ea353c4e06db9188 | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 1,090 | cpp | #include "Game/AI/Action/actionIgnitedThrown.h"
namespace uking::action {
IgnitedThrown::IgnitedThrown(const InitArg& arg) : ksys::act::ai::Action(arg) {}
IgnitedThrown::~IgnitedThrown() = default;
bool IgnitedThrown::init_(sead::Heap* heap) {
return ksys::act::ai::Action::init_(heap);
}
void IgnitedThrown::enter_(ksys::act::ai::InlineParamPack* params) {
ksys::act::ai::Action::enter_(params);
}
void IgnitedThrown::leave_() {
ksys::act::ai::Action::leave_();
}
void IgnitedThrown::loadParams_() {
getStaticParam(&mReactionLevel_s, "ReactionLevel");
getStaticParam(&mDamageScale_s, "DamageScale");
getStaticParam(&mFinishWaterDepth_s, "FinishWaterDepth");
getStaticParam(&mIsScaling_s, "IsScaling");
getStaticParam(&mIsFinishedByOneHit_s, "IsFinishedByOneHit");
getStaticParam(&mIsFadeIn_s, "IsFadeIn");
getStaticParam(&mIsAbleGuard_s, "IsAbleGuard");
getStaticParam(&mIsForceOnly_s, "IsForceOnly");
getStaticParam(&mAS_s, "AS");
}
void IgnitedThrown::calc_() {
ksys::act::ai::Action::calc_();
}
} // namespace uking::action
| [
"leo@leolam.fr"
] | leo@leolam.fr |
35cc1a7695a814fb0d5576a6cc20013f3ecff083 | c4fe6870c29dfd244e45d88f134d2bfcf226a522 | /engine/PerformanceTimer.cpp | ff1298e7db05e3c1b51427f31df6d331493f258e | [] | no_license | Neevan09/NNSample | c4a907c4b01cbe96fb374570dfb3832ce3b865df | 2390372f7d7f968b84960d4aa1d93a57dc8f7d37 | refs/heads/master | 2020-03-14T06:57:50.362708 | 2018-04-29T13:54:06 | 2018-04-29T13:54:06 | 131,493,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | #include "PerformanceTimer.h"
#if TOFU_PERFORMANCE_TIMER_ENABLED == 1
namespace CodeEngine
{
int64_t PerformanceTimer::counterFreq = 0;
int64_t PerformanceTimer::startTick = 0;
int64_t PerformanceTimer::timerSlots[kMaxPerformanceTimerSlot];
int64_t PerformanceTimer::deltaTimerSlots[kMaxPerformanceTimerSlot];
}
#endif | [
"Naveen@DESKTOP-794QGAI"
] | Naveen@DESKTOP-794QGAI |
cc3bacc470650354cb13a51647bcc4da81f1c3bc | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/ds/security/passport/atlmfc/atlsimpstr.h | cf5b7eba3fa7da4ae03421f5b5a194e2e7657b11 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,444 | h | // This is a part of the Active Template Library.
// Copyright (C) 1996-2001 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
#ifndef __ATLSIMPSTR_H__
#define __ATLSIMPSTR_H__
#pragma once
#include <atldef.h>
#include <atlbase.h>
#include <atlexcept.h>
#include <atlmem.h>
namespace ATL
{
struct CStringData;
__interface IAtlStringMgr
{
public:
// Allocate a new CStringData
CStringData* Allocate( int nAllocLength, int nCharSize ) throw();
// Free an existing CStringData
void Free( CStringData* pData ) throw();
// Change the size of an existing CStringData
CStringData* Reallocate( CStringData* pData, int nAllocLength, int nCharSize ) throw();
// Get the CStringData for a Nil string
CStringData* GetNilString() throw();
IAtlStringMgr* Clone() throw();
};
#ifdef _M_IX86
#ifndef _M_CEE
extern "C"
{
LONG _InterlockedIncrement( LONG* pn );
LONG _InterlockedDecrement( LONG* pn );
};
#pragma intrinsic( _InterlockedIncrement )
#pragma intrinsic( _InterlockedDecrement )
#else
#define _InterlockedIncrement InterlockedIncrement
#define _InterlockedDecrement InterlockedDecrement
#endif // !_M_CEE
#endif // _M_IX86_
struct CStringData
{
IAtlStringMgr* pStringMgr; // String manager for this CStringData
int nDataLength; // Length of currently used data in XCHARs (not including terminating null)
int nAllocLength; // Length of allocated data in XCHARs (not including terminating null)
long nRefs; // Reference count: negative == locked
// XCHAR data[nAllocLength+1] // A CStringData is always followed in memory by the actual array of character data
void* data() throw()
{
return (this+1);
}
void AddRef() throw()
{
ATLASSERT(nRefs > 0);
_InterlockedIncrement(&nRefs);
}
bool IsLocked() const throw()
{
return nRefs < 0;
}
bool IsShared() const throw()
{
return( nRefs > 1 );
}
void Lock() throw()
{
ATLASSERT( nRefs <= 1 );
nRefs--; // Locked buffers can't be shared, so no interlocked operation necessary
if( nRefs == 0 )
{
nRefs = -1;
}
}
void Release() throw()
{
ATLASSERT( nRefs != 0 );
if( _InterlockedDecrement( &nRefs ) <= 0 )
{
pStringMgr->Free( this );
}
}
void Unlock() throw()
{
ATLASSERT( IsLocked() );
nRefs++; // Locked buffers can't be shared, so no interlocked operation necessary
if( nRefs == 0 )
{
nRefs = 1;
}
}
};
class CNilStringData :
public CStringData
{
public:
CNilStringData() throw()
{
pStringMgr = NULL;
nRefs = 2; // Never gets freed by IAtlStringMgr
nDataLength = 0;
nAllocLength = 0;
achNil[0] = 0;
achNil[1] = 0;
}
void SetManager( IAtlStringMgr* pMgr ) throw()
{
ATLASSERT( pStringMgr == NULL );
pStringMgr = pMgr;
}
public:
wchar_t achNil[2];
};
class CAtlStringMgr :
public IAtlStringMgr
{
public:
CAtlStringMgr( IAtlMemMgr* pMemMgr = NULL ) throw() :
m_pMemMgr( pMemMgr )
{
m_nil.SetManager( this );
}
~CAtlStringMgr() throw()
{
}
void SetMemoryManager( IAtlMemMgr* pMemMgr ) throw()
{
ATLASSERT( m_pMemMgr == NULL );
m_pMemMgr = pMemMgr;
}
// IAtlStringMgr
public:
virtual CStringData* Allocate( int nChars, int nCharSize ) throw()
{
size_t nTotalSize;
CStringData* pData;
size_t nDataBytes;
nChars = AtlAlignUp( nChars + 1, 8 ); // Prevent excessive reallocation. The heap will usually round up anyway.
nDataBytes = nChars*nCharSize;
nTotalSize = sizeof( CStringData )+nDataBytes;
pData = static_cast< CStringData* >( m_pMemMgr->Allocate( nTotalSize ) );
if( pData == NULL )
{
return( NULL );
}
pData->pStringMgr = this;
pData->nRefs = 1;
pData->nAllocLength = nChars - 1;
pData->nDataLength = 0;
return( pData );
}
virtual void Free( CStringData* pData ) throw()
{
ATLASSERT( pData->pStringMgr == this );
m_pMemMgr->Free( pData );
}
virtual CStringData* Reallocate( CStringData* pData, int nChars, int nCharSize ) throw()
{
CStringData* pNewData;
ULONG nTotalSize;
ULONG nDataBytes;
ATLASSERT( pData->pStringMgr == this );
nChars = AtlAlignUp( nChars+1, 8 ); // Prevent excessive reallocation. The heap will usually round up anyway.
nDataBytes = nChars*nCharSize;
nTotalSize = sizeof( CStringData )+nDataBytes;
pNewData = static_cast< CStringData* >( m_pMemMgr->Reallocate( pData, nTotalSize ) );
if( pNewData == NULL )
{
return NULL;
}
pNewData->nAllocLength = nChars - 1;
return pNewData;
}
virtual CStringData* GetNilString() throw()
{
m_nil.AddRef();
return &m_nil;
}
virtual IAtlStringMgr* Clone() throw()
{
return this;
}
protected:
IAtlMemMgr* m_pMemMgr;
CNilStringData m_nil;
};
template< typename BaseType, const int t_nSize >
class CStaticString
{
public:
CStaticString( const BaseType* psz ) :
m_psz( psz )
{
}
operator const BaseType*() const
{
return m_psz;
}
static int GetLength()
{
return (t_nSize/sizeof( BaseType ))-1;
}
private:
const BaseType* m_psz;
private:
CStaticString( const CStaticString& str ) throw();
CStaticString& operator=( const CStaticString& str ) throw();
};
#define _ST( psz ) ATL::CStaticString< TCHAR, sizeof( _T( psz ) ) >( _T( psz ) )
#define _SA( psz ) ATL::CStaticString< char, sizeof( psz ) >( psz )
#define _SW( psz ) ATL::CStaticString< wchar_t, sizeof( L##psz ) >( L##psz )
#define _SO( psz ) _SW( psz )
template< typename BaseType = char >
class ChTraitsBase
{
public:
typedef char XCHAR;
typedef LPSTR PXSTR;
typedef LPCSTR PCXSTR;
typedef wchar_t YCHAR;
typedef LPWSTR PYSTR;
typedef LPCWSTR PCYSTR;
};
template<>
class ChTraitsBase< wchar_t >
{
public:
typedef wchar_t XCHAR;
typedef LPWSTR PXSTR;
typedef LPCWSTR PCXSTR;
typedef char YCHAR;
typedef LPSTR PYSTR;
typedef LPCSTR PCYSTR;
};
template< typename BaseType >
class CSimpleStringT
{
public:
typedef ChTraitsBase< BaseType >::XCHAR XCHAR;
typedef ChTraitsBase< BaseType >::PXSTR PXSTR;
typedef ChTraitsBase< BaseType >::PCXSTR PCXSTR;
typedef ChTraitsBase< BaseType >::YCHAR YCHAR;
typedef ChTraitsBase< BaseType >::PYSTR PYSTR;
typedef ChTraitsBase< BaseType >::PCYSTR PCYSTR;
public:
explicit CSimpleStringT( IAtlStringMgr* pStringMgr ) throw()
{
ATLASSERT( pStringMgr != NULL );
CStringData* pData = pStringMgr->GetNilString();
Attach( pData );
}
CSimpleStringT( const CSimpleStringT& strSrc )
{
CStringData* pSrcData = strSrc.GetData();
CStringData* pNewData = CloneData( pSrcData );
Attach( pNewData );
}
CSimpleStringT( PCXSTR pszSrc, IAtlStringMgr* pStringMgr )
{
ATLASSERT( pStringMgr != NULL );
int nLength = StringLength( pszSrc );
CStringData* pData = pStringMgr->Allocate( nLength, sizeof( XCHAR ) );
if( pData == NULL )
{
ThrowMemoryException();
}
Attach( pData );
SetLength( nLength );
CopyChars( m_pszData, pszSrc, nLength );
}
CSimpleStringT( const XCHAR* pchSrc, int nLength, IAtlStringMgr* pStringMgr )
{
ATLASSERT( pStringMgr != NULL );
CStringData* pData = pStringMgr->Allocate( nLength, sizeof( XCHAR ) );
if( pData == NULL )
{
ThrowMemoryException();
}
Attach( pData );
SetLength( nLength );
CopyChars( m_pszData, pchSrc, nLength );
}
~CSimpleStringT() throw()
{
CStringData* pData = GetData();
pData->Release();
}
CSimpleStringT& operator=( const CSimpleStringT& strSrc )
{
CStringData* pSrcData = strSrc.GetData();
CStringData* pOldData = GetData();
if( pSrcData != pOldData )
{
if( pOldData->IsLocked() )
{
SetString( strSrc.GetString(), strSrc.GetLength() );
}
else
{
CStringData* pNewData = CloneData( pSrcData );
pOldData->Release();
Attach( pNewData );
}
}
return( *this );
}
CSimpleStringT& operator=( PCXSTR pszSrc )
{
SetString( pszSrc );
return( *this );
}
CSimpleStringT& operator+=( const CSimpleStringT& strSrc )
{
Append( strSrc );
return( *this );
}
CSimpleStringT& operator+=( PCXSTR pszSrc )
{
Append( pszSrc );
return( *this );
}
template< int t_nSize >
CSimpleStringT& operator+=( const CStaticString< XCHAR, t_nSize >& strSrc )
{
Append( strSrc.m_psz, strSrc.GetLength() );
return( *this );
}
CSimpleStringT& operator+=( char ch )
{
XCHAR chTemp = XCHAR( ch );
Append( &chTemp, 1 );
return( *this );
}
CSimpleStringT& operator+=( unsigned char ch )
{
XCHAR chTemp = XCHAR( ch );
Append( &chTemp, 1 );
return( *this );
}
CSimpleStringT& operator+=( wchar_t ch )
{
XCHAR chTemp = XCHAR( ch );
Append( &chTemp, 1 );
return( *this );
}
XCHAR operator[]( int iChar ) const throw()
{
ATLASSERT( (iChar >= 0) && (iChar <= GetLength()) ); // Indexing the '\0' is OK
return( m_pszData[iChar] );
}
operator PCXSTR() const throw()
{
return( m_pszData );
}
void Append( PCXSTR pszSrc )
{
Append( pszSrc, StringLength( pszSrc ) );
}
void Append( PCXSTR pszSrc, int nLength )
{
// See comment in SetString() about why we do this
UINT_PTR nOffset = pszSrc-GetString();
UINT nOldLength = GetLength();
int nNewLength = nOldLength+nLength;
PXSTR pszBuffer = GetBuffer( nNewLength );
if( nOffset <= nOldLength )
{
pszSrc = pszBuffer+nOffset;
// No need to call CopyCharsOverlapped, since the destination is
// beyond the end of the original buffer
}
CopyChars( pszBuffer+nOldLength, pszSrc, nLength );
ReleaseBuffer( nNewLength );
}
void Append( const CSimpleStringT& strSrc )
{
Append( strSrc.GetString(), strSrc.GetLength() );
}
void Empty() throw()
{
CStringData* pOldData = GetData();
IAtlStringMgr* pStringMgr = pOldData->pStringMgr;
if( pOldData->nDataLength == 0 )
{
return;
}
if( pOldData->IsLocked() )
{
// Don't reallocate a locked buffer that's shrinking
SetLength( 0 );
}
else
{
pOldData->Release();
CStringData* pNewData = pStringMgr->GetNilString();
Attach( pNewData );
}
}
void FreeExtra() throw()
{
CStringData* pOldData = GetData();
int nLength = pOldData->nDataLength;
IAtlStringMgr* pStringMgr = pOldData->pStringMgr;
if( pOldData->nAllocLength == nLength )
{
return;
}
if( !pOldData->IsLocked() ) // Don't reallocate a locked buffer that's shrinking
{
CStringData* pNewData = pStringMgr->Allocate( nLength, sizeof( XCHAR ) );
if( pNewData == NULL )
{
SetLength( nLength );
return;
}
CopyChars( PXSTR( pNewData->data() ), PCXSTR( pOldData->data() ), nLength );
pOldData->Release();
Attach( pNewData );
SetLength( nLength );
}
}
int GetAllocLength() const throw()
{
return( GetData()->nAllocLength );
}
XCHAR GetAt( int iChar ) const throw()
{
ATLASSERT( (iChar >= 0) && (iChar <= GetLength()) ); // Indexing the '\0' is OK
return( m_pszData[iChar] );
}
PXSTR GetBuffer()
{
CStringData* pData = GetData();
if( pData->IsShared() )
{
Fork( pData->nDataLength );
}
return( m_pszData );
}
PXSTR GetBuffer( int nMinBufferLength )
{
return( PrepareWrite( nMinBufferLength ) );
}
PXSTR GetBufferSetLength( int nLength )
{
PXSTR pszBuffer = GetBuffer( nLength );
SetLength( nLength );
return( pszBuffer );
}
int GetLength() const throw()
{
return( GetData()->nDataLength );
}
IAtlStringMgr* GetManager() const throw()
{
return( GetData()->pStringMgr->Clone() );
}
PCXSTR GetString() const throw()
{
return( m_pszData );
}
bool IsEmpty() const throw()
{
return( GetLength() == 0 );
}
PXSTR LockBuffer()
{
CStringData* pData = GetData();
if( pData->IsShared() )
{
Fork( pData->nDataLength );
pData = GetData(); // Do it again, because the fork might have changed it
}
pData->Lock();
return( m_pszData );
}
void UnlockBuffer() throw()
{
CStringData* pData = GetData();
pData->Unlock();
}
void Preallocate( int nLength )
{
PrepareWrite( nLength );
}
void ReleaseBuffer( int nNewLength = -1 ) throw()
{
if( nNewLength == -1 )
{
nNewLength = StringLength( m_pszData );
}
SetLength( nNewLength );
}
void Truncate( int nNewLength )
{
ATLASSERT( nNewLength <= GetLength() );
GetBuffer( nNewLength );
ReleaseBuffer( nNewLength );
}
void SetAt( int iChar, XCHAR ch )
{
ATLASSERT( (iChar >= 0) && (iChar < GetLength()) );
int nLength = GetLength();
PXSTR pszBuffer = GetBuffer();
pszBuffer[iChar] = ch;
ReleaseBuffer( nLength );
}
void SetManager( IAtlStringMgr* pStringMgr )
{
ATLASSERT( IsEmpty() );
CStringData* pData = GetData();
pData->Release();
pData = pStringMgr->GetNilString();
Attach( pData );
}
void SetString( PCXSTR pszSrc )
{
SetString( pszSrc, StringLength( pszSrc ) );
}
void SetString( PCXSTR pszSrc, int nLength )
{
if( nLength == 0 )
{
Empty();
}
else
{
// It is possible that pszSrc points to a location inside of our
// buffer. GetBuffer() might change m_pszData if (1) the buffer
// is shared or (2) the buffer is too small to hold the new
// string. We detect this aliasing, and modify pszSrc to point
// into the newly allocated buffer instead.
UINT nOldLength = GetLength();
UINT_PTR nOffset = pszSrc-GetString();
// If 0 <= nOffset <= nOldLength, then pszSrc points into our
// buffer
PXSTR pszBuffer = GetBuffer( nLength );
if( nOffset <= nOldLength )
{
CopyCharsOverlapped( pszBuffer, pszBuffer+nOffset, nLength );
}
else
{
CopyChars( pszBuffer, pszSrc, nLength );
}
ReleaseBuffer( nLength );
}
}
public:
friend CSimpleStringT operator+(
const CSimpleStringT& str1,
const CSimpleStringT& str2 )
{
CSimpleStringT s( str1.GetManager() );
Concatenate( s, str1, str1.GetLength(), str2, str2.GetLength() );
return( s );
}
friend CSimpleStringT operator+(
const CSimpleStringT& str1,
PCXSTR psz2 )
{
CSimpleStringT s( str1.GetManager() );
Concatenate( s, str1, str1.GetLength(), psz2, StringLength( psz2 ) );
return( s );
}
friend CSimpleStringT operator+(
PCXSTR psz1,
const CSimpleStringT& str2 )
{
CSimpleStringT s( str2.GetManager() );
Concatenate( s, psz1, StringLength( psz1 ), str2, str2.GetLength() );
return( s );
}
static void CopyChars( XCHAR* pchDest, const XCHAR* pchSrc, int nChars ) throw()
{
memcpy( pchDest, pchSrc, nChars*sizeof( XCHAR ) );
}
static void CopyCharsOverlapped( XCHAR* pchDest, const XCHAR* pchSrc, int nChars ) throw()
{
memmove( pchDest, pchSrc, nChars*sizeof( XCHAR ) );
}
#ifdef _ATL_MIN_CRT
ATL_NOINLINE static int StringLength( PCXSTR psz ) throw()
{
int nLength = 0;
if( psz != NULL )
{
const XCHAR* pch = psz;
while( *pch != 0 )
{
nLength++;
pch++;
}
}
return( nLength );
}
#else
static int StringLength( const char* psz ) throw()
{
if( psz == NULL )
{
return( 0 );
}
return( int( strlen( psz ) ) );
}
template<>
static int StringLength( const wchar_t* psz ) throw()
{
if( psz == NULL )
{
return( 0 );
}
return( int( wcslen( psz ) ) );
}
#endif
protected:
static void Concatenate( CSimpleStringT& strResult, PCXSTR psz1, int nLength1, PCXSTR psz2, int nLength2 )
{
int nNewLength = nLength1+nLength2;
PXSTR pszBuffer = strResult.GetBuffer( nNewLength );
CopyChars( pszBuffer, psz1, nLength1 );
CopyChars( pszBuffer+nLength1, psz2, nLength2 );
strResult.ReleaseBuffer( nNewLength );
}
ATL_NOINLINE static void ThrowMemoryException()
{
AtlThrow( E_OUTOFMEMORY );
}
// Implementation
private:
void Attach( CStringData* pData ) throw()
{
m_pszData = static_cast< PXSTR >( pData->data() );
}
ATL_NOINLINE void Fork( int nLength )
{
CStringData* pOldData = GetData();
int nOldLength = pOldData->nDataLength;
CStringData* pNewData = pOldData->pStringMgr->Clone()->Allocate( nLength, sizeof( XCHAR ) );
if( pNewData == NULL )
{
ThrowMemoryException();
}
int nCharsToCopy = ((nOldLength < nLength) ? nOldLength : nLength)+1; // Copy '\0'
CopyChars( PXSTR( pNewData->data() ), PCXSTR( pOldData->data() ), nCharsToCopy );
pNewData->nDataLength = nOldLength;
pOldData->Release();
Attach( pNewData );
}
CStringData* GetData() const throw()
{
return( reinterpret_cast< CStringData* >( m_pszData )-1 );
}
PXSTR PrepareWrite( int nLength )
{
CStringData* pOldData = GetData();
int nShared = 1-pOldData->nRefs; // nShared < 0 means true, >= 0 means false
int nTooShort = pOldData->nAllocLength-nLength; // nTooShort < 0 means true, >= 0 means false
if( (nShared|nTooShort) < 0 ) // If either sign bit is set (i.e. either is less than zero), we need to copy data
{
PrepareWrite2( nLength );
}
return( m_pszData );
}
ATL_NOINLINE void PrepareWrite2( int nLength )
{
CStringData* pOldData = GetData();
if( pOldData->nDataLength > nLength )
{
nLength = pOldData->nDataLength;
}
if( pOldData->IsShared() )
{
Fork( nLength );
}
else if( pOldData->nAllocLength < nLength )
{
// Grow exponentially, until we hit 1K.
int nNewLength = pOldData->nAllocLength;
if( nNewLength > 1024 )
{
nNewLength += 1024;
}
else
{
nNewLength *= 2;
}
if( nNewLength < nLength )
{
nNewLength = nLength;
}
Reallocate( nNewLength );
}
}
ATL_NOINLINE void Reallocate( int nLength )
{
CStringData* pOldData = GetData();
ATLASSERT( pOldData->nAllocLength < nLength );
IAtlStringMgr* pStringMgr = pOldData->pStringMgr;
CStringData* pNewData = pStringMgr->Reallocate( pOldData, nLength, sizeof( XCHAR ) );
if( pNewData == NULL )
{
ThrowMemoryException();
}
Attach( pNewData );
}
void SetLength( int nLength ) throw()
{
ATLASSERT( nLength >= 0 );
ATLASSERT( nLength <= GetData()->nAllocLength );
GetData()->nDataLength = nLength;
m_pszData[nLength] = 0;
}
static CStringData* CloneData( CStringData* pData )
{
CStringData* pNewData = NULL;
IAtlStringMgr* pNewStringMgr = pData->pStringMgr->Clone();
if( !pData->IsLocked() && (pNewStringMgr == pData->pStringMgr) )
{
pNewData = pData;
pNewData->AddRef();
}
else
{
pNewData = pNewStringMgr->Allocate( pData->nDataLength, sizeof( XCHAR ) );
if( pNewData == NULL )
{
ThrowMemoryException();
}
pNewData->nDataLength = pData->nDataLength;
CopyChars( PXSTR( pNewData->data() ), PCXSTR( pData->data() ), pData->nDataLength+1 ); // Copy '\0'
}
return( pNewData );
}
private:
PXSTR m_pszData;
};
template< typename TCharType >
class CStrBufT
{
public:
typedef CSimpleStringT< TCharType > StringType;
typedef StringType::XCHAR XCHAR;
typedef StringType::PXSTR PXSTR;
typedef StringType::PCXSTR PCXSTR;
static const DWORD AUTO_LENGTH = 0x01; // Automatically determine the new length of the string at release. The string must be null-terminated.
static const DWORD SET_LENGTH = 0x02; // Set the length of the string object at GetBuffer time
public:
explicit CStrBufT( StringType& str ) throw( ... ) :
m_str( str ),
m_pszBuffer( NULL ),
#ifdef _DEBUG
m_nBufferLength( str.GetLength() ),
#endif
m_nLength( str.GetLength() )
{
m_pszBuffer = m_str.GetBuffer();
}
CStrBufT( StringType& str, int nMinLength, DWORD dwFlags = AUTO_LENGTH ) throw( ... ) :
m_str( str ),
m_pszBuffer( NULL ),
#ifdef _DEBUG
m_nBufferLength( nMinLength ),
#endif
m_nLength( (dwFlags&AUTO_LENGTH) ? -1 : nMinLength )
{
if( dwFlags&SET_LENGTH )
{
m_pszBuffer = m_str.GetBufferSetLength( nMinLength );
}
else
{
m_pszBuffer = m_str.GetBuffer( nMinLength );
}
}
~CStrBufT() throw()
{
m_str.ReleaseBuffer( m_nLength );
}
operator PXSTR() throw()
{
return( m_pszBuffer );
}
operator PCXSTR() const throw()
{
return( m_pszBuffer );
}
void SetLength( int nLength ) throw()
{
ATLASSERT( nLength <= m_nBufferLength );
m_nLength = nLength;
}
// Implementation
private:
StringType& m_str;
PXSTR m_pszBuffer;
int m_nLength;
#ifdef _DEBUG
int m_nBufferLength;
#endif
// Private copy constructor and copy assignment operator to prevent accidental use
private:
CStrBufT( const CStrBufT& ) throw();
CStrBufT& operator=( const CStrBufT& ) throw();
};
typedef CSimpleStringT< TCHAR > CSimpleString;
typedef CSimpleStringT< char > CSimpleStringA;
typedef CSimpleStringT< wchar_t > CSimpleStringW;
typedef CStrBufT< TCHAR > CStrBuf;
typedef CStrBufT< char > CStrBufA;
typedef CStrBufT< wchar_t > CStrBufW;
}; // namespace ATL
#endif // __ATLSIMPSTR_H__
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
5d6fb151499882cde3f34ea4c1d1a8839d208503 | 28c1a2cbe5cdfd5aa2d43f3e73639bc5bb22454d | /src/Particle.hpp | 7e2acd8d3adeaeb5f96a19a4fa9ce0d637e698d9 | [] | no_license | tazima10827/SFC_GP_particle_taji | b73253ca12f9ab5d629e3b65d30f4c2b79bde268 | fc5ee19d2523ab089f363d2d991fad94a6479d76 | refs/heads/master | 2020-03-21T15:08:52.942699 | 2018-06-26T06:51:57 | 2018-06-26T06:51:57 | 138,696,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | hpp | //
// medama.hpp
// helloobject
//
// Created by 田嶋智洋 on 2018/06/23.
//
#ifndef medama_hpp
#define medama_hpp
#include <stdio.h>
#include "ofMain.h"
class Medama{
public :
//property
float size;
ofColor color;
ofVec2f pos;
ofVec2f vel;
//初期値の設定 constructor
Medama();
//method
void setup();
void update();
void draw();
void setColor(ofColor col);
void setSize(float val);
};
#endif /* medama_hpp */
| [
"kapiha7@gmail.com"
] | kapiha7@gmail.com |
7aa3134056fee04ba8eb3c4049f1bbe1afb4fd8b | aa7eca0eeccc7c71678a90fc04c02dce9f47ec46 | /Codes_13TeV/PostAnalyzer_Run2015Data_2p5fbinv/PostAnalyzer_Qstar13TeV/LimitCode/BAT-0.9.2/src/BCDataSet.cxx | 4a9c7262aa68bff96749ca7d145d89f4f7817590 | [
"DOC"
] | permissive | rockybala/Analyses_codes | 86c055ebe45b8ec96ed7bcddc5dd9c559d643523 | cc727a3414bef37d2e2110b66a4cbab8ba2bacf2 | refs/heads/master | 2021-09-15T10:25:33.040778 | 2018-05-30T11:50:42 | 2018-05-30T11:50:42 | 133,632,693 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,601 | cxx | /*
* Copyright (C) 2008-2012, Daniel Kollar and Kevin Kroeninger.
* All rights reserved.
*
* For the licensing terms see doc/COPYING.
*/
// ---------------------------------------------------------
#include "BCDataSet.h"
#include "BCDataPoint.h"
#include "BCLog.h"
#include "BCErrorCodes.h"
#include <TFile.h>
#include <TTree.h>
#include <TString.h>
#include <iostream>
#include <fstream>
// ---------------------------------------------------------
BCDataSet::BCDataSet()
{
fBCDataVector = 0;
}
// ---------------------------------------------------------
BCDataSet::~BCDataSet()
{
if (fBCDataVector) {
int ndatapoints = int(fBCDataVector->size());
for (int i = 0; i < ndatapoints; ++i)
delete fBCDataVector->at(i);
fBCDataVector->clear();
delete fBCDataVector;
}
}
// ---------------------------------------------------------
BCDataSet::BCDataSet(const BCDataSet & bcdataset)
{
if (bcdataset.fBCDataVector) {
fBCDataVector = new BCDataVector();
for (int i = 0; i < int(bcdataset.fBCDataVector->size()); ++i) {
if (bcdataset.fBCDataVector->at(i))
fBCDataVector->push_back(new BCDataPoint(*(bcdataset.fBCDataVector->at(i))));
else
fBCDataVector->push_back(0);
}
}
else
fBCDataVector = 0;
}
// ---------------------------------------------------------
BCDataSet & BCDataSet::operator = (const BCDataSet & bcdataset)
{
if (bcdataset.fBCDataVector) {
fBCDataVector = new BCDataVector();
for (int i = 0; i < int(bcdataset.fBCDataVector->size()); ++i) {
if (bcdataset.fBCDataVector->at(i))
fBCDataVector->push_back(new BCDataPoint(*(bcdataset.fBCDataVector->at(i))));
else
fBCDataVector->push_back(0);
}
}
else
fBCDataVector = 0;
// return this
return *this;
}
// ---------------------------------------------------------
unsigned int BCDataSet::GetNDataPoints()
{
// check if vector exists. Return number of data points if true ...
if (fBCDataVector)
return fBCDataVector->size();
// ... or give out error and return 0 if not.
BCLog::OutError("BCDataSet::GetNDataPoints : DataSet not yet created.");
return 0;
}
// ---------------------------------------------------------
unsigned int BCDataSet::GetNValuesPerPoint()
{
// check if vector exists and contains datapoints
if (fBCDataVector && fBCDataVector->size() > 0)
return GetDataPoint(0)->GetNValues();
BCLog::OutError("BCDataSet::GetNValuesPerPoint : Data set doesn't exist yet");
return 0;
}
// ---------------------------------------------------------
BCDataPoint * BCDataSet::GetDataPoint(unsigned int index)
{
if (!fBCDataVector || GetNDataPoints()==0 )
{
BCLog::OutError("BCDataSet::GetDataPoint : Dataset is empty.");
return 0;
}
// check if index is within range. Return the data point if true ...
if(index < GetNDataPoints())
return fBCDataVector->at(index);
// ... or give out warning and return 0 if not.
BCLog::OutError("BCDataSet::GetDataPoint : Index out of range. Return 0.");
return 0;
}
// ---------------------------------------------------------
std::vector<double> BCDataSet::GetDataComponents( int index)
{
unsigned int N = GetNDataPoints();
std::vector<double> components( N , 0.0 );
BCDataPoint* point=0;
for (unsigned int i = 0; i < N; ++i) {
//rely on index checking in Get... methods
point = GetDataPoint(i);
components[i] = point->GetValue(index);
}
return components;
}
// ---------------------------------------------------------
int BCDataSet::ReadDataFromFileTree(const char * filename, const char * treename, const char * branchnames)
{
// open root file
TFile * file = new TFile(filename, "READ");
// check if file is open and warn if not.
if (!file->IsOpen())
{
BCLog::OutError(Form("BCDataSet::ReadDataFromFileTree : Could not open file %s.", filename));
return ERROR_FILENOTFOUND;
}
// get tree
TTree * tree = (TTree*) file->Get(treename);
// check if tree is there and warn if not.
if (!tree)
{
BCLog::OutError(Form("BCDataSet::ReadDataFromFileTree : Could not find TTree %s.", treename));
// close file
file->Close();
return ERROR_TREENOTFOUND;
}
// if data set contains data, clear data object container ...
if (fBCDataVector != 0)
{
fBCDataVector->clear();
BCLog::OutDetail("BCDataSet::ReadDataFromFileTree : Overwrite existing data.");
}
// ... or allocate memory for the vector if not.
else
fBCDataVector = new BCDataVector();
// get branch names.
// first, copy the branchnames into a std::string.
std::string branches(branchnames);
// define a vector of std::strings which contain the tree names.
std::vector<std::string> * branchnamevector = new std::vector<std::string>;
// the names are supposed to be separated by commas. find first comma
// entry in the string.
int temp_index = branches.find_first_of(",");
// reset number of branches
int nbranches = 0;
// repeat until the is nothing left in the string.
while(branches.size() > 0)
{
// temporary string which contains the name of the current branch
std::string branchname;
// get current branch name
// if there is no comma the current branchname corresponds to the whole string, ...
if (temp_index == -1)
branchname = branches;
// ... if there is a comma, copy that part of the string into the current branchname.
else
branchname.assign(branches, 0, temp_index);
// write branch name to a vector
branchnamevector->push_back(branchname);
// increase the number of branches found
nbranches++;
// cut remaining string with branchnames
// if there is no comma left empty the string, ...
if (temp_index == -1)
branches = "";
// ... if there is a comma remove the current branchname from the string.
else
branches.erase(0, temp_index + 1);
// find the next comma
temp_index = branches.find_first_of(",");
}
// create temporary vector with data and assign some zeros.
std::vector<double> data;
data.assign(nbranches, 0.0);
// set the branch address.
for (int i = 0; i < nbranches; i++)
tree->SetBranchAddress(branchnamevector->at(i).data(), &data.at(i));
// calculate maximum number of entries
int nentries = tree->GetEntries();
// check if there are any events in the tree and close file if not.
if (nentries <= 0)
{
BCLog::OutError(Form("BCDataSet::ReadDataFromFileTree : No events in TTree %s.", treename));
// close file
file->Close();
return ERROR_NOEVENTS;
}
// loop over entries
for (int ientry = 0; ientry < nentries; ientry++)
{
// get entry
tree->GetEntry(ientry);
// create data object
BCDataPoint * datapoint = new BCDataPoint(nbranches);
// copy data
for (int i = 0; i < nbranches; i++)
datapoint->SetValue(i, data.at(i));
// add data point to this data set.
AddDataPoint(datapoint);
}
// close file
file->Close();
// remove file pointer.
if (file)
delete file;
return 0;
}
// ---------------------------------------------------------
int BCDataSet::ReadDataFromFileTxt(const char * filename, int nbranches)
{
// open text file.
std::fstream file;
file.open(filename, std::fstream::in);
// check if file is open and warn if not.
if (!file.is_open())
{
BCLog::OutError(Form("BCDataSet::ReadDataFromFileText : Could not open file %s.", filename));
return ERROR_FILENOTFOUND;
}
// if data set contains data, clear data object container ...
if (fBCDataVector != 0)
{
fBCDataVector->clear();
BCLog::OutDetail("BCDataSet::ReadDataFromFileTxt : Overwrite existing data.");
}
// ... or allocate memory for the vector if not.
else
fBCDataVector = new BCDataVector();
// create temporary vector with data and assign some zeros.
std::vector<double> data;
data.assign(nbranches, 0.0);
// reset counter
int nentries = 0;
// read data and create data points.
while (!file.eof())
{
// read data from file
int i=0;
while(file >> data[i])
{
if (i==nbranches-1)
break;
i++;
}
// create data point.
if(i == nbranches-1)
{
BCDataPoint * datapoint = new BCDataPoint(nbranches);
// copy data into data point
for (int i = 0; i < nbranches; i++)
datapoint->SetValue(i, data.at(i));
// add data point to this data set.
AddDataPoint(datapoint);
// increase counter
nentries++;
}
}
// check if there are any events in the tree and close file if not.
if (nentries <= 0)
{
BCLog::OutError(Form("BCDataSet::ReadDataFromFileText : No events in the file %s.", filename));
// close file
file.close();
return ERROR_NOEVENTS;
}
// close file
file.close();
return 0;
}
// ---------------------------------------------------------
void BCDataSet::AddDataPoint(BCDataPoint * datapoint)
{
// check if memory for the vector has been allocated and
// allocate if not.
if (fBCDataVector == 0)
fBCDataVector = new BCDataVector();
// add data point to the data set.
fBCDataVector->push_back(datapoint);
}
// ---------------------------------------------------------
void BCDataSet::Reset()
{
// if memory has been allocated to the data set
// clear the content.
if (fBCDataVector != 0)
fBCDataVector->clear();
}
// ---------------------------------------------------------
void BCDataSet::Dump()
{
if (!fBCDataVector) {
BCLog::OutError("BCDataSet::Dump : Data set is empty. Nothing to dump.");
return;
}
BCLog::OutSummary("Data set summary:");
BCLog::OutSummary(Form("Number of points : %d", int(fBCDataVector->size())));
BCLog::OutSummary(Form("Number of values per point : %d", GetDataPoint(0)->GetNValues()));
unsigned int n = GetDataPoint(0)->GetNValues();
for (unsigned int i=0; i< fBCDataVector->size(); i++) {
BCLog::OutSummary(Form("Data point %5d : ", i));
for (unsigned int j=0; j<n; j++)
BCLog::OutSummary(Form("%d : %12.5g", j, GetDataPoint(i)->GetValue(j)));
}
}
// ---------------------------------------------------------
| [
"rgarg@cern.ch"
] | rgarg@cern.ch |
edbeb59d72f116c47d3ac248478b15f2848e6129 | 8601826b7773a7970b9cbd3fa9a32e4ddbf810f7 | /tensorflow/compiler/xla/pjrt/pjrt_executable.h | 3dc2be6a57d8582f1cc8ff7f2781792a64a13f8f | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | kustomzone/tensorflow | 306fdc2613869bc2c8199176864b041cdbb879b3 | d9ec8c5ecec9150c7eef2437eed19f35a503d355 | refs/heads/master | 2023-08-08T13:53:38.499211 | 2023-07-26T18:13:30 | 2023-07-26T18:28:00 | 73,427,220 | 0 | 0 | null | 2016-11-10T22:45:41 | 2016-11-10T22:45:41 | null | UTF-8 | C++ | false | false | 13,762 | h | /* Copyright 2022 The TensorFlow 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.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_PJRT_PJRT_EXECUTABLE_H_
#define TENSORFLOW_COMPILER_XLA_PJRT_PJRT_EXECUTABLE_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/client/executable_build_options.h"
#include "tensorflow/compiler/xla/hlo/ir/hlo_module.h"
#include "tensorflow/compiler/xla/pjrt/execute_options.pb.h"
#include "tensorflow/compiler/xla/pjrt/pjrt_common.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/compiler/xla/service/hlo_cost_analysis.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
namespace xla {
// Provides configuration for implementations that support compile and execute
// spanning multiple slices. A slice is a set of devices connected by dedicated
// high speed interconnect. Connectivity between slices is typically over data
// center networks. Concrete implementations of MultiSliceConfig contain
// environment specific information to enable communication between devices on
// different slices. Passed as options during compile and execute.
// Implementations that do not support this are allowed to pass nullptr.
class MultiSliceConfig {
public:
virtual ~MultiSliceConfig();
// Returns the total number of slices.
virtual int32_t NumSlices() const = 0;
// Returns the SliceID at this host - an integer in [0, NumSlices)
virtual int32_t SliceId() const = 0;
// Returns the number of devices on each slice indexed by SliceId.
virtual absl::flat_hash_map<int32_t, int32_t> NumDevicesPerSlice() const = 0;
// Returns a serialized proto representing MultiSliceConfig.
virtual std::string Serialize() const = 0;
};
struct CompileOptions {
// The layouts of the arguments that the computation should expect.
std::optional<std::vector<Shape>> argument_layouts;
// If true, the supplied computation expects its arguments to be wrapped in a
// tuple and passed as a single parameter.
bool parameter_is_tupled_arguments = false;
// XLA's compilation time options.
ExecutableBuildOptions executable_build_options;
// If true, the executable can be run on any device. May only be true if
// !executable_build_options.has_device_assignment(), so only applies to
// single-device executables. Beware: on GPUs, sometimes an executable
// compiled for one device doesn't run on another.
bool compile_portable_executable = false;
// XLA compilation profile version.
int64_t profile_version = 0;
// Set multi_slice_config to trigger compilation for DCN connected multi
// slice operation.
const MultiSliceConfig* multi_slice_config = nullptr;
// Key-value string pairs, parsed in order to set miscellaneous options,
// overriding if appropriate.
using OptionOverride = std::variant<std::string, bool, int64_t>;
std::vector<std::pair<std::string, OptionOverride>> env_option_overrides;
// Used to indicate the precision configuration.
PrecisionConfig::Precision matrix_unit_operand_precision =
PrecisionConfig::DEFAULT;
// Applies env_option_overrides to executable_build_options.debug_options().
Status ApplyAllOptionOverrides();
// Applies a single option to executable_build_options.debug_options().
Status ApplyOption(const std::string& key, const OptionOverride& value);
// Serialize the CompileOptions into a CompileOptionsProto.
StatusOr<CompileOptionsProto> ToProto() const;
// Deserialize the CompileOptionsProto into a CompileOptions.
static StatusOr<CompileOptions> FromProto(const CompileOptionsProto& proto);
};
struct LoadOptions {
// Origin of the subslice of the target topology to run computation on.
struct ComputationOrigin {
int x = 0;
int y = 0;
int z = 0;
};
std::optional<ComputationOrigin> computation_origin;
// multi_slice_config to associate with the executable during load of a multi
// slice operation.
const MultiSliceConfig* multi_slice_config = nullptr;
};
class ExecuteContext {
public:
virtual ~ExecuteContext() = default;
};
struct PjRtTransferMetadata {
// May be invalid if
// ExecuteOptions::use_major_to_minor_data_layout_for_callbacks is true for
// this execution.
Shape device_shape;
};
class PjRtChunk;
class PjRtTransferMetadata;
class CopyToDeviceStream;
struct SendCallback {
int64_t channel_id;
// The callback for retrieving the send value. It will be invoked once for
// each invocation of the corresponding Send op in the HLO program (So it can
// be invoked multiple times if it is in a loop). Currently there is no
// guarantee that the callback here will be invoked in the same order as their
// corresponding HLO Send ops. The callback can also return errors to indicate
// the execution should fail.
//
// IMPORTANT: the implementation might NOT signal the error to the execution,
// and the execution will run to completion with UNDEFINED DATA returned by
// the callback. If there is any potential control flow that depends on the
// value of the returned data, an error return is unsafe.
//
// TODO(chky): Currently the callback invocation order may not be consistent
// with the HLO send op invocation order, due to limitations in some PjRt
// implementation. Consider making it strictly the same order as HLO program.
std::function<Status(const PjRtTransferMetadata& metadata, PjRtChunk chunk,
size_t total_size_in_bytes, bool done)>
callback;
};
struct RecvCallback {
int64_t channel_id;
// The callback for feeding the recv value. It will be invoked once for each
// invocation of the corresponding Recv op in the HLO program (So it can be
// invoked multiple times if it is in a loop). Currently there is no
// guarantee that the callback here will be invoked in the same order as their
// corresponding HLO Recv ops.
std::function<void(const PjRtTransferMetadata& metadata,
std::unique_ptr<CopyToDeviceStream> stream)>
callback;
};
struct ExecuteOptions {
// If true, the client must pass a single PjRtBuffer which contains all of
// the arguments as a single XLA tuple, otherwise each argument must be
// passed in its own PjRtBuffer. May only be true if the executable was
// compiled with parameter_is_tupled_arguments==true.
bool arguments_are_tupled = false;
// If true, the computation must return a tuple, which will be destructured
// into its elements.
bool untuple_result = false;
// If non-zero, identifies this execution as part of a potentially
// multi-device launch. This can be used to detect scheduling errors, e.g. if
// multi-host programs are launched in different orders on different hosts,
// the launch IDs may be used by the runtime to detect the mismatch.
int32_t launch_id = 0;
// If non-null, an opaque context passed to an execution that may be used to
// supply additional arguments to a derived class of PjRtExecutable.
const ExecuteContext* context = nullptr;
// If true, check that the PjRtBuffer argument shapes match the compiled
// shapes. Otherwise, any shape with the right size on device may be passed.
bool strict_shape_checking = true;
// Set multi_slice_config when the computation spans multiple slices. The
// config should match what was used during compilation to generate this
// executable.
const MultiSliceConfig* multi_slice_config = nullptr;
// The send/recv callbacks for PjRt execution. The first level span is for
// multi-device parallel execution, the second level vector contains the
// callbacks for all send/recv ops in the executable. These callbacks can be
// stateful and the user code is responsible for managing the states here.
// These callbacks must outlive the execution.
absl::Span<const std::vector<SendCallback>> send_callbacks;
absl::Span<const std::vector<RecvCallback>> recv_callbacks;
// If true, send callbacks are passed PjRtChunks in major-to-minor layout, and
// recv functions should pass major-to-minor chunks to
// CopyToDeviceStream::AddChunk.
//
// If false, send callbacks are passed PjRtChunks in the on-device layout
// specified in the PjRtTransferMetadata, and recv functions should similarly
// pass device-layout chunks to CopyToDeviceStream::AddChunk.
bool use_major_to_minor_data_layout_for_callbacks = false;
// The `execution_mode` decides whether the execution will be invoked in the
// caller thread or launched to a separate thread. By default, the
// implementation may choose either strategy or use a heuristic to decide.
// Currently it is only applied to CPU implementations
enum class ExecutionMode { kDefault = 0, kSynchronous, kAsynchronous };
ExecutionMode execution_mode = ExecutionMode::kDefault;
// A set of indices denoting the input buffers that should not be donated.
// An input buffer may be non-donable, for example, if it is referenced more
// than once. Since such runtime information is not available at compile time,
// the compiler might mark the input as `may-alias`, which could lead PjRt to
// donate the input buffer when it should not. By defining this set of
// indices, a higher-level PjRt caller can instruct PjRtClient not to donate
// specific input buffers.
absl::flat_hash_set<int> non_donatable_input_indices;
absl::StatusOr<ExecuteOptionsProto> ToProto() const;
static absl::StatusOr<ExecuteOptions> FromProto(
const ExecuteOptionsProto& proto);
};
// Static device memory usage for a compiled program.
// The on-device memory needed to run an executable is at least
// generated_code_size_in_bytes
// + argument_size_in_bytes + output_size_in_bytes - alias_size_in_bytes
// + temp_size_in_bytes.
struct CompiledMemoryStats {
int64_t generated_code_size_in_bytes = 0;
int64_t argument_size_in_bytes = 0;
int64_t output_size_in_bytes = 0;
// How much argument is reused for output.
int64_t alias_size_in_bytes = 0;
int64_t temp_size_in_bytes = 0;
std::string serialized_hlo_proto = "";
std::string DebugString() const;
};
class PjRtExecutable {
public:
virtual ~PjRtExecutable() = default;
virtual int num_replicas() const = 0;
virtual int num_partitions() const = 0;
virtual int64_t SizeOfGeneratedCodeInBytes() const = 0;
// Unique name for this executable, e.g., HloModule name.
virtual absl::string_view name() const = 0;
// Return an HloModule (optimized) per partition.
virtual StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules()
const = 0;
// Returns an output Shape per program, the size should be equal to
// `GetHloModules()`.
virtual StatusOr<std::vector<Shape>> GetOutputShapes() const;
// Returns a list of lists of memory kind strings for output. The returned
// value is `[num_programs, num_output]`. The size of the outer list should be
// equal to `GetHloModules()`. Under SPMD, one can use
// `GetOutputMemoryKinds().front()`.
virtual StatusOr<std::vector<std::vector<absl::string_view>>>
GetOutputMemoryKinds() const = 0;
// Returns a list of parameter OpSharding protos.
virtual std::optional<std::vector<OpSharding>> GetParameterShardings() const;
// Returns a list of output OpSharding protos.
virtual std::optional<std::vector<OpSharding>> GetOutputShardings() const;
// Return memory stats that allow callers to estimate device memory usage
// when running this executable.
virtual StatusOr<CompiledMemoryStats> GetCompiledMemoryStats() const {
return Unimplemented("Retrieving CompiledMemoryStats is not supported.");
}
// Returns named values for cost properties of this executable (such as
// operations, size of input/outputs, and run time estimate). Properties may
// differ for different platforms.
virtual StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
GetCostAnalysis() const = 0;
// Serialize this executable into a string and return the value.
virtual StatusOr<std::string> SerializeExecutable() const {
return Unimplemented("Serializing executable is not supported.");
}
// Return a fingerprint of this executable.
virtual StatusOr<std::string> FingerprintExecutable() const {
return Unimplemented("Fingerprinting executable is not supported.");
}
virtual StatusOr<struct CompileOptions> GetCompileOptions() const {
return Unimplemented("CompileOptions not available.");
}
};
class PjRtExecutableUtil {
public:
static StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
RunHloCostAnalysis(const PjRtExecutable& executable,
HloCostAnalysis* hlo_cost_analysis);
static StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
RunHloCostAnalysis(
const std::vector<std::shared_ptr<xla::HloModule>>& hlo_modules,
HloCostAnalysis* hlo_cost_analysis);
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_PJRT_PJRT_EXECUTABLE_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
ab41d023070719bc70df588296572efd8c7f2feb | cc7661edca4d5fb2fc226bd6605a533f50a2fb63 | /System/CounterCreationData.h | 4d2b1e0620291d5ebd83d475b272a67b3d843ef4 | [
"MIT"
] | permissive | g91/Rust-C-SDK | 698e5b573285d5793250099b59f5453c3c4599eb | d1cce1133191263cba5583c43a8d42d8d65c21b0 | refs/heads/master | 2020-03-27T05:49:01.747456 | 2017-08-23T09:07:35 | 2017-08-23T09:07:35 | 146,053,940 | 1 | 0 | null | 2018-08-25T01:13:44 | 2018-08-25T01:13:44 | null | UTF-8 | C++ | false | false | 497 | h | #pragma once
#include "..\UnityEngine\UnicodeString*.h"
#include "..\System\Diagnostics\PerformanceCounterType.h"
namespace System
{
namespace Diagnostics
{
class CounterCreationData : public Object // 0x0
{
public:
UnityEngine::UnicodeString* help; // 0x10 (size: 0x8, flags: 0x1, type: 0xe)
UnityEngine::UnicodeString* name; // 0x18 (size: 0x8, flags: 0x1, type: 0xe)
System::Diagnostics::PerformanceCounterType type; // 0x20 (size: 0x4, flags: 0x1, type: 0x11)
}; // size = 0x28
}
| [
"info@cvm-solutions.co.uk"
] | info@cvm-solutions.co.uk |
2b65604fe08809fc4bb13fbdf3fdeee40675faef | 4cc18b15d9049898420c5a2feffb7cde0d3d140f | /E3/source/chi-squared-tfhe/main.cpp | 4aa39984583561b7b6bebd1df440ade59e82fced | [] | no_license | faberga/SoK | e2ec8693e6503cd15ea9b812469a841995aa7af4 | 12face92206e4eca660aa9b0b9ea3c7e8b63cb96 | refs/heads/master | 2023-07-20T09:35:01.792023 | 2022-08-06T07:58:46 | 2022-08-06T07:58:46 | 379,767,131 | 0 | 0 | null | 2021-06-24T01:05:23 | 2021-06-24T01:05:22 | null | UTF-8 | C++ | false | false | 710 | cpp | #include <iostream>
#include "e3int.h"
#include "../../src/e3key.h"
using SecureInt = TypeUint<32>;
int main()
{
// == inputs ====
SecureInt n0 = _2_Ep;
SecureInt n1 = _7_Ep;
SecureInt n2 = _9_Ep;
// == //END inputs ====
SecureInt alpha_half = ((n0 * n2) << 2) - (n1 * n1);
SecureInt alpha = (alpha_half*alpha_half);
SecureInt orange = (n0 << 1) + n1;
SecureInt beta_1 = (orange * orange) << 1;
SecureInt green = (n2 << 1) + n1;
SecureInt beta_2 = orange * green;
SecureInt beta_3 = (green * green) << 1;
std::cout << e3::decrypt(alpha) << '\n';
std::cout << e3::decrypt(beta_1) << '\n';
std::cout << e3::decrypt(beta_2) << '\n';
std::cout << e3::decrypt(beta_3) << '\n';
}
| [
"patrick.jattke@student.hpi.de"
] | patrick.jattke@student.hpi.de |
164bfac6eb6149b8130376e6257b26f968a458e0 | cb142069b8e6d605458658385df36ee85ec05561 | /Rafagan/Projeto Contra/MainPlayer/PlayerOne.cpp | 8ab2d94fcaf11e4f3eb47a192528aaa313739172 | [] | no_license | rafagan/contra-nes-first-level | 14a5ba4be705d6571e2f65151718e23a9bb460a6 | 2d7c94067a9dc85b37f9eda050e73d561ad3859f | refs/heads/master | 2020-05-19T14:55:50.108864 | 2019-05-05T19:29:25 | 2019-05-05T19:29:25 | 185,072,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,159 | cpp | #include "PlayerOne.h"
#include "../definitions.h"
#include "../Helper/Camera2D.h"
#include "../MainPlayer/statesMainPlayer.h"
#include "statesPlayerOne.h"
#include "../GameManager.h"
using namespace std;
using namespace math;
using namespace HeroSt;
bool PlayerOne::characterLoaded = false;
PlayerOne::PlayerOne(Level *level)
: Player(level)
{
this->typeName = "PlayerOne";
if(!characterLoaded){
Player::loadHero(typeName,"Res/Sprites/SpritesetHero1.png",box,frameSize);
characterLoaded = true;
}
this->typeId = Character::getCharacterTypeByName(this->typeName);
}
PlayerOne::~PlayerOne(void)
{
}
void PlayerOne::lateInit()
{
unsigned int d[4] = {C2D2_CIMA,C2D2_BAIXO,C2D2_ESQUERDA,C2D2_DIREITA};
this->eventPoll = unique_ptr<PlayerEventPool>(
new PlayerEventPool(this,d,
C2D2_Z,C2D2_X,C2D2_ENTER,C2D2_RSHIFT)
);
this->stateMachine.init(this,new Borning());
this->firstSt = false;
this->processInput = false;
this->ballons = Loader::loadSprite("Res/Ballons/Player1.png",200,150);
this->bIndex = -1;
}
void PlayerOne::handleMessageReceived( std::shared_ptr<Message<unsigned int>> message )
{
auto content = message->getMessageContent();
if(currentLevel->getNumberOfPlayers() == 1)
singleDialogue(content);
else
multiplayerDialogue(content);
if(myStruct->direcao==0)
this->setAnimation(0);
else
this->setAnimation(1);
}
void PlayerOne::singleDialogue(std::shared_ptr<unsigned int> content){
enum {D1 = 1,D2,D3,END_TALK};
switch(*content){
case D1:
this->bIndex = -1;
break;
case D2:
this->bIndex = 0;
break;
case D3:
bIndex = 1;
break;
case END_TALK:
bIndex = -1;
this->processInput = true;
stateMachine.changeState(new Idle());
this->sendMessageToGroup(3.0,"Runner",shared_ptr<unsigned int>(new unsigned int(2)));
break;
}
}
void PlayerOne::multiplayerDialogue(std::shared_ptr<unsigned int> content)
{
enum {D1 = 1,D2,D3,END_TALK};
switch(*content){
case D1:
this->bIndex = -1;
break;
case D2:
this->setDirection(180);
this->bIndex = 0;
this->sendMessageToGroup(3.0,"PlayerTwo",shared_ptr<unsigned int>(new unsigned int(2)));
this->sendMessageToMe(3.01,shared_ptr<unsigned int>(new unsigned int(1)));
break;
case D3:
bIndex = 1;
this->sendMessageToGroup(3.0,"PlayerTwo",shared_ptr<unsigned int>(new unsigned int(3)));
this->sendMessageToMe(3.01,shared_ptr<unsigned int>(new unsigned int(1)));
break;
case END_TALK:
this->setDirection(0);
bIndex = -1;
this->processInput = true;
stateMachine.changeState(new Idle());
this->sendMessageToGroup(0.0,"PlayerTwo",shared_ptr<unsigned int>(new unsigned int(4)));
this->sendMessageToGroup(3.0,"Runner",shared_ptr<unsigned int>(new unsigned int(2)));
break;
}
}
void PlayerOne::lateUpdate( float secs )
{
}
void PlayerOne::lateDraw() const
{
if(bIndex >= 0)
game->getRenderer()->drawSprite(ballons,bIndex,position - Vector2D(20,60),true);
}
State<Hero>* PlayerOne::getFirstStateLevelOne()
{
static bool jumped = false;
if(stateMachine.isInState(Idle()) && !jumped){
jumped = true;
return nullptr;
}
if(firstSt)
return nullptr;
firstSt = true;
return new IntroDialogueP1();
} | [
"rafagan@guizion.com"
] | rafagan@guizion.com |
068e1bad30fd4007ab153ce3e3a61c42ee70b040 | e99f958efd5bc03371189cc10da736f36b0f6c89 | /project_5/utils.cpp | 8d822cabf665d8292383f1776423f93fc7496800 | [] | no_license | poultergiest/cs378 | 0a2d01eb84bf33430dded6dbfd13f5362cda23f2 | 279e691ab46d6cba00bff5c9dce66149ac1f4f7e | refs/heads/master | 2016-09-05T10:00:49.488479 | 2013-12-13T18:54:31 | 2013-12-13T18:54:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,199 | cpp | #include "utils.h"
#include <math.h>
//--------------------------itos------------------------------------
// converts an integer to a string
//------------------------------------------------------------------
string itos(int arg)
{
ostringstream buffer;
//send the int to the ostringstream
buffer << arg;
//capture the string
return buffer.str();
}
//--------------------------ftos------------------------------------
// converts a float to a string
//------------------------------------------------------------------
string ftos(float arg)
{
ostringstream buffer;
//send the int to the ostringstream
buffer << arg;
//capture the string
return buffer.str();
}
//-------------------------------------Clamp()-----------------------------------------
//
// clamps the first argument between the second two
//
//-------------------------------------------------------------------------------------
void Clamp(double &arg, double min, double max)
{
if (arg < min)
{
arg = min;
}
if (arg > max)
{
arg = max;
}
}
bool init_app(const char * name, SDL_Surface * icon, uint32_t flags)
{
atexit(SDL_Quit);
if(SDL_Init(flags) < 0)
return 0;
SDL_WM_SetCaption(name, name);
SDL_WM_SetIcon(icon, NULL);
return 1;
}
void setPixel(struct rgbData data[][WIDTH], int x, int y, struct rgbData color) {
if (x < 0 || x >= WIDTH) return;
if (y < 0 || y >= HEIGHT) return;
data[y][x] = color;
}
void init_data(struct rgbData data[][WIDTH])
{
memset(data, 255, WIDTH*HEIGHT*sizeof(rgbData));
}
void drawcircle(struct rgbData data[][WIDTH], int x0, int y0, int radius, rgbData color) {
int f = 1 - radius;
int ddF_x = 1;
int ddF_y = -2 * radius;
int x = 0;
int y = radius;
setPixel(data,x0, y0 + radius, color);
setPixel(data,x0, y0 - radius, color);
setPixel(data,x0 + radius, y0, color);
setPixel(data,x0 - radius, y0, color);
while(x < y) {
// ddF_x == 2 * x + 1;
// ddF_y == -2 * y;
// f == x*x + y*y - radius*radius + 2*x - y + 1;
if(f >= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
setPixel(data,x0 + x, y0 + y,color);
setPixel(data,x0 - x, y0 + y,color);
setPixel(data,x0 + x, y0 - y,color);
setPixel(data,x0 - x, y0 - y,color);
setPixel(data,x0 + y, y0 + x,color);
setPixel(data,x0 - y, y0 + x,color);
setPixel(data,x0 + y, y0 - x,color);
setPixel(data,x0 - y, y0 - x,color);
}
}
void setPixelUnsafe(struct rgbData data[][WIDTH], int x, int y, struct rgbData color) {
data[y][x] = color;
}
unsigned char font8x8_basic[128][8] = {
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0000 (nul)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0001
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0002
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0003
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0004
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0005
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0006
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0007
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0008
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0009
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000A
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000B
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000C
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000D
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000E
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000F
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0010
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0011
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0012
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0013
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0014
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0015
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0016
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0017
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0018
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0019
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001A
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001B
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001C
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001D
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001E
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001F
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 (space)
{ 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!)
{ 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (")
{ 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#)
{ 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($)
{ 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%)
{ 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&)
{ 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (')
{ 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (()
{ 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ())
{ 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*)
{ 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,)
{ 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.)
{ 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/)
{ 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0)
{ 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1)
{ 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2)
{ 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3)
{ 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4)
{ 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5)
{ 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6)
{ 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7)
{ 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8)
{ 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9)
{ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:)
{ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (//)
{ 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<)
{ 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=)
{ 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>)
{ 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?)
{ 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@)
{ 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A)
{ 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B)
{ 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C)
{ 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D)
{ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E)
{ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F)
{ 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G)
{ 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H)
{ 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I)
{ 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J)
{ 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K)
{ 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L)
{ 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M)
{ 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N)
{ 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O)
{ 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P)
{ 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q)
{ 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R)
{ 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S)
{ 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T)
{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U)
{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V)
{ 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W)
{ 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X)
{ 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y)
{ 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z)
{ 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([)
{ 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\)
{ 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (])
{ 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_)
{ 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`)
{ 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a)
{ 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b)
{ 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c)
{ 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d)
{ 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e)
{ 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f)
{ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g)
{ 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h)
{ 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i)
{ 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j)
{ 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k)
{ 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l)
{ 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m)
{ 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n)
{ 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o)
{ 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p)
{ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q)
{ 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r)
{ 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s)
{ 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t)
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u)
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v)
{ 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w)
{ 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x)
{ 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y)
{ 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z)
{ 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({)
{ 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|)
{ 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (})
{ 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~)
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F
};
void drawchar(struct rgbData data[][WIDTH], int x0, int y0, char d, struct rgbData color) {
int set;
int mask;
unsigned char* bitmap = font8x8_basic[d];
for (int x=0; x < 8; x++) {
for (int y=0; y < 8; y++) {
set = bitmap[x] & 1 << y;
if (set)
setPixel(data, x0 + y, y0 + x, color);
}
}
}
void drawstring(struct rgbData data[][WIDTH], int x0, int y0, const char* d, struct rgbData color) {
for (int i = 0; i < strlen(d); ++i)
drawchar(data, x0 + i * 8, y0, d[i], color);
}
int sgn(int x) { return ((x<0)?-1:((x>0)?1:0)); }
void drawlineUnsafe(rgbData data[][WIDTH], int x1, int y1, int x2, int y2, struct rgbData color) {
int dx = x2 - x1;
int dy = y2 - y1;
int dxabs = abs(dx);
int dyabs = abs(dy);
int sdx = sgn(dx);
int sdy = sgn(dy);
int x = dyabs>>1;
int y = dxabs>>1;
int px = x1;
int py = y1;
if (dxabs >= dyabs) {
for (int i = 0; i < dxabs; ++i) {
y += dyabs;
if (y >= dxabs) {
y -= dxabs;
py+=sdy;
}
px+=sdx;
setPixelUnsafe(data,px,py, color);
}
} else {
for(int i=0; i < dyabs; ++i) {
x += dxabs;
if (x >= dyabs) {
x -= dyabs;
px += sdx;
}
py += sdy;
setPixelUnsafe(data,px,py,color);
}
}
}
const int INSIDE = 0; // 0000
const int LEFT = 1; // 0001
const int RIGHT = 2; // 0010
const int BOTTOM = 4; // 0100
const int TOP = 8; // 1000
// Compute the bit code for a point (x, y) using the clip rectangle
// bounded diagonally by (xmin, ymin), and (xmax, ymax)
OutCode ComputeOutCode(int x, int y) {
OutCode code = INSIDE; // initialised as being inside of clip window
if (x < 0) // to the left of clip window
code |= LEFT;
else if (x >= WIDTH) // to the right of clip window
code |= RIGHT;
if (y < 0) // below the clip window
code |= BOTTOM;
else if (y >= HEIGHT) // above the clip window
code |= TOP;
return code;
}
// Cohen–Sutherland clipping algorithm clips a line from
// P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with
// diagonal from (xmin, ymin) to (xmax, ymax).
void drawline(rgbData data[][WIDTH], int x0, int y0, int x1, int y1,
struct rgbData color) {
// compute outcodes for P0, P1, and whatever point lies outside the clip rectangle
OutCode outcode0 = ComputeOutCode(x0, y0);
OutCode outcode1 = ComputeOutCode(x1, y1);
bool accept = false;
while (true) {
if (!(outcode0 | outcode1)) { // Bitwise OR is 0. Trivially accept and get out of loop
accept = true;
break;
} else if (outcode0 & outcode1) { // Bitwise AND is not 0. Trivially reject and get out of loop
break;
} else {
// failed both tests, so calculate the line segment to clip
// from an outside point to an intersection with clip edge
double x, y;
// At least one endpoint is outside the clip rectangle; pick it.
OutCode outcodeOut = outcode0 ? outcode0 : outcode1;
// Now find the intersection point;
// use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * (y - y0)
if (outcodeOut & TOP) { // point is above the clip rectangle
x = x0 + (x1 - x0) * (HEIGHT - 1 - y0) / (double)(y1 - y0);
y = HEIGHT - 1;
} else if (outcodeOut & BOTTOM) { // point is below the clip rectangle
x = x0 + (x1 - x0) * (0 - y0) / (double)(y1 - y0);
y = 0;
} else if (outcodeOut & RIGHT) { // point is to the right of clip rectangle
y = y0 + (y1 - y0) * (WIDTH - 1 - x0) / (double)(x1 - x0);
x = WIDTH - 1;
} else if (outcodeOut & LEFT) { // point is to the left of clip rectangle
y = y0 + (y1 - y0) * (0 - x0) / (double)(x1 - x0);
x = 0;
}
// Now we move outside point to intersection point to clip
// and get ready for next pass.
if (outcodeOut == outcode0) {
x0 = (int)x;
y0 = (int)y;
outcode0 = ComputeOutCode(x0, y0);
} else {
x1 = (int)x;
y1 = (int)y;
outcode1 = ComputeOutCode(x1, y1);
}
}
}
if (accept)
drawlineUnsafe(data, x0, y0, x1, y1, color);
} | [
"jake.wilke@gmail.com"
] | jake.wilke@gmail.com |
f35cf2292e7afea26fa9ae7fe6d790a2f3de6f1a | 901cf07ded2e621e5a9bc34029741e785e1450b7 | /Internal_And_External_Sort/quicksort.cpp | fb2f924dc60d3135f2a14b03f86ffb19e0eb2f00 | [] | no_license | yashgupte21/CloudComputing | d5232364a91a4f09004b8f25654a902a1bbb15ae | a12b0acabfc654d36f58c40e8b6bc3a423ee6ee3 | refs/heads/master | 2022-11-27T23:42:20.160762 | 2020-08-06T18:27:58 | 2020-08-06T18:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | cpp | #include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <cstring>
#include "quicksort.h"
using namespace std;
void swap(char **s,char **t){
char* temp = *s;
*s = *t;
*t = temp;
}
//partition function
long long partition(char** arr,long low, long high){
char* pivot = arr[high];
long long i = low-1;
//In a loop, compare every element with pivot
//and if the current element is small, swap it with
//element at index i
string ps = string(pivot);
for (long long j = low; j < high; j++)
{
string js = string(arr[j]);
if(js.compare(0,10,ps) < 0){
//if(strncmp(arr[j],arr[i],10)){
i++;
swap(&arr[i],&arr[j]);
}
}
swap(arr[i+1],arr[high]);
return i+1;
}
//sorting function
void QuickSortHelper(char** arr,long long low,long long high){
if(low<high){
//Find the partitioning
long long pi = partition(arr,low,high);
QuickSortHelper(arr,low,pi-1);
QuickSortHelper(arr,pi+1,high);
}
}
void QuickSort(char** arr,long long low,long long high){
QuickSortHelper(arr,low,high);
}
void printArray(string arr[], long long size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
| [
"vgunda2@hawk.iit.edu"
] | vgunda2@hawk.iit.edu |
310904c846d7e7ef6cd0c0165bb1dfc0fe4dc81f | e78bd858acd0fdf9770446e083cca4782a0000f1 | /Source/GameJam/Private/Win.cpp | 0c5a231660c4115fa39223ae2da71364bb000544 | [] | no_license | AndiZE/WWF_GameJam | 41442a9fd32a21ba1daca46096ee1590aefd47dc | 6ae27a58fae2ef91b285fb699c4ae862269ba5f2 | refs/heads/master | 2021-08-08T13:03:47.758199 | 2020-10-06T12:56:37 | 2020-10-06T12:56:37 | 225,883,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Win.h"
| [
"andreaszechmeister@chello.at"
] | andreaszechmeister@chello.at |
0b481ca873a61fdbf19e8f3c526d98f906cc54b1 | 376883e26add80c6e3dc75fd3571b994d37eda51 | /src/signA/dialog/Dialog_SelDefSeries.h | 89b0b880ae272296e6cc5940bf78887444b19564 | [] | no_license | rpzhu/sa | 4375142a565e9ed058acd2d0f2729f6cfa499c73 | 1a01b4ab065d2b596496126b43140e8bda922a53 | refs/heads/master | 2022-11-28T12:36:27.491989 | 2020-07-30T01:22:08 | 2020-07-30T01:22:08 | 275,979,744 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | h | #ifndef DIALOG_SELDEFSERIES_H
#define DIALOG_SELDEFSERIES_H
#include <QDialog>
namespace Ui {
class Dialog_SelDefSeries;
}
class Dialog_SelDefSeries : public QDialog
{
Q_OBJECT
public:
explicit Dialog_SelDefSeries(QWidget *parent = 0);
~Dialog_SelDefSeries();
double getStartData(){return m_start;}
double getDetalData(){return m_detal;}
private slots:
void valueChanged_start(double d);
void valueChanged_detal(double d);
private:
Ui::Dialog_SelDefSeries *ui;
double m_detal;
double m_start;
const size_t m_size;
void refleshView();
};
#endif // DIALOG_SELDEFSERIES_H
| [
"872207648@qq.com"
] | 872207648@qq.com |
59731a146495f731db13c04abe01f28d2f1b4f32 | 88ae8695987ada722184307301e221e1ba3cc2fa | /components/media_router/common/providers/cast/channel/cast_socket_unittest.cc | 98172df8bb1bedeb17b9fbe81f48d74094f5b135 | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 45,783 | cc | // Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/media_router/common/providers/cast/channel/cast_socket.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include <vector>
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/sys_byteorder.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/timer/mock_timer.h"
#include "build/build_config.h"
#include "components/media_router/common/providers/cast/channel/cast_auth_util.h"
#include "components/media_router/common/providers/cast/channel/cast_framer.h"
#include "components/media_router/common/providers/cast/channel/cast_message_util.h"
#include "components/media_router/common/providers/cast/channel/cast_test_util.h"
#include "components/media_router/common/providers/cast/channel/cast_transport.h"
#include "components/media_router/common/providers/cast/channel/logger.h"
#include "content/public/test/browser_task_environment.h"
#include "crypto/rsa_private_key.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/address_list.h"
#include "net/base/net_errors.h"
#include "net/cert/pem.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/ssl_server_socket.h"
#include "net/socket/tcp_client_socket.h"
#include "net/socket/tcp_server_socket.h"
#include "net/ssl/ssl_info.h"
#include "net/ssl/ssl_server_config.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_test_util.h"
#include "services/network/network_context.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/openscreen/src/cast/common/channel/proto/cast_channel.pb.h"
const int64_t kDistantTimeoutMillis = 100000; // 100 seconds (never hit).
using ::testing::_;
using ::testing::A;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::InvokeArgument;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SaveArg;
using ::cast::channel::CastMessage;
namespace cast_channel {
namespace {
const char kAuthNamespace[] = "urn:x-cast:com.google.cast.tp.deviceauth";
// Returns an auth challenge message inline.
CastMessage CreateAuthChallenge() {
CastMessage output;
CreateAuthChallengeMessage(&output, AuthContext::Create());
return output;
}
// Returns an auth challenge response message inline.
CastMessage CreateAuthReply() {
CastMessage output;
output.set_protocol_version(CastMessage::CASTV2_1_0);
output.set_source_id("sender-0");
output.set_destination_id("receiver-0");
output.set_payload_type(CastMessage::BINARY);
output.set_payload_binary("abcd");
output.set_namespace_(kAuthNamespace);
return output;
}
CastMessage CreateTestMessage() {
CastMessage test_message;
test_message.set_protocol_version(CastMessage::CASTV2_1_0);
test_message.set_namespace_("ns");
test_message.set_source_id("source");
test_message.set_destination_id("dest");
test_message.set_payload_type(CastMessage::STRING);
test_message.set_payload_utf8("payload");
return test_message;
}
base::FilePath GetTestCertsDirectory() {
base::FilePath path;
base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.Append(FILE_PATH_LITERAL("components"));
path = path.Append(FILE_PATH_LITERAL("test"));
path = path.Append(FILE_PATH_LITERAL("data"));
path = path.Append(FILE_PATH_LITERAL("media_router"));
path = path.Append(FILE_PATH_LITERAL("common"));
path = path.Append(FILE_PATH_LITERAL("providers"));
path = path.Append(FILE_PATH_LITERAL("cast"));
path = path.Append(FILE_PATH_LITERAL("channel"));
return path;
}
class MockTCPSocket : public net::MockTCPClientSocket {
public:
MockTCPSocket(bool do_nothing, net::SocketDataProvider* socket_provider)
: net::MockTCPClientSocket(net::AddressList(), nullptr, socket_provider) {
do_nothing_ = do_nothing;
set_enable_read_if_ready(true);
}
MockTCPSocket(const MockTCPSocket&) = delete;
MockTCPSocket& operator=(const MockTCPSocket&) = delete;
int Connect(net::CompletionOnceCallback callback) override {
if (do_nothing_) {
// Stall the I/O event loop.
return net::ERR_IO_PENDING;
}
return net::MockTCPClientSocket::Connect(std::move(callback));
}
private:
bool do_nothing_;
};
class CompleteHandler {
public:
CompleteHandler() {}
CompleteHandler(const CompleteHandler&) = delete;
CompleteHandler& operator=(const CompleteHandler&) = delete;
MOCK_METHOD1(OnCloseComplete, void(int result));
MOCK_METHOD1(OnConnectComplete, void(CastSocket* socket));
MOCK_METHOD1(OnWriteComplete, void(int result));
MOCK_METHOD1(OnReadComplete, void(int result));
};
class TestCastSocketBase : public CastSocketImpl {
public:
TestCastSocketBase(network::mojom::NetworkContext* network_context,
const CastSocketOpenParams& open_params,
Logger* logger)
: CastSocketImpl(base::BindRepeating(
[](network::mojom::NetworkContext* network_context) {
return network_context;
},
network_context),
open_params,
logger,
AuthContext::Create()),
verify_challenge_result_(true),
verify_challenge_disallow_(false),
mock_timer_(new base::MockOneShotTimer()) {
SetPeerCertForTesting(
net::ImportCertFromFile(GetTestCertsDirectory(), "self_signed.pem"));
}
TestCastSocketBase(const TestCastSocketBase&) = delete;
TestCastSocketBase& operator=(const TestCastSocketBase&) = delete;
~TestCastSocketBase() override {}
void SetVerifyChallengeResult(bool value) {
verify_challenge_result_ = value;
}
void TriggerTimeout() { mock_timer_->Fire(); }
bool TestVerifyChannelPolicyNone() {
AuthResult authResult;
return VerifyChannelPolicy(authResult);
}
void DisallowVerifyChallengeResult() { verify_challenge_disallow_ = true; }
protected:
bool VerifyChallengeReply() override {
EXPECT_FALSE(verify_challenge_disallow_);
return verify_challenge_result_;
}
base::OneShotTimer* GetTimer() override { return mock_timer_.get(); }
// Simulated result of verifying challenge reply.
bool verify_challenge_result_;
bool verify_challenge_disallow_;
std::unique_ptr<base::MockOneShotTimer> mock_timer_;
};
class MockTestCastSocket : public TestCastSocketBase {
public:
static std::unique_ptr<MockTestCastSocket> CreateSecure(
network::mojom::NetworkContext* network_context,
const CastSocketOpenParams& open_params,
Logger* logger) {
return std::make_unique<MockTestCastSocket>(network_context, open_params,
logger);
}
using TestCastSocketBase::TestCastSocketBase;
MockTestCastSocket(network::mojom::NetworkContext* network_context,
const CastSocketOpenParams& open_params,
Logger* logger)
: TestCastSocketBase(network_context, open_params, logger) {}
MockTestCastSocket(const MockTestCastSocket&) = delete;
MockTestCastSocket& operator=(const MockTestCastSocket&) = delete;
~MockTestCastSocket() override {}
void SetupMockTransport() {
mock_transport_ = new MockCastTransport;
SetTransportForTesting(base::WrapUnique(mock_transport_.get()));
}
bool TestVerifyChannelPolicyAudioOnly() {
AuthResult authResult;
authResult.channel_policies |= AuthResult::POLICY_AUDIO_ONLY;
return VerifyChannelPolicy(authResult);
}
MockCastTransport* GetMockTransport() {
CHECK(mock_transport_);
return mock_transport_;
}
private:
raw_ptr<MockCastTransport> mock_transport_ = nullptr;
};
// TODO(https://crbug.com/928467): Remove this class.
class TestSocketFactory : public net::ClientSocketFactory {
public:
explicit TestSocketFactory(net::IPEndPoint ip) : ip_(ip) {}
TestSocketFactory(const TestSocketFactory&) = delete;
TestSocketFactory& operator=(const TestSocketFactory&) = delete;
~TestSocketFactory() override = default;
// Socket connection helpers.
void SetupTcpConnect(net::IoMode mode, int result) {
tcp_connect_data_ = std::make_unique<net::MockConnect>(mode, result, ip_);
}
void SetupSslConnect(net::IoMode mode, int result) {
ssl_connect_data_ = std::make_unique<net::MockConnect>(mode, result, ip_);
}
// Socket I/O helpers.
void AddWriteResult(const net::MockWrite& write) { writes_.push_back(write); }
void AddWriteResult(net::IoMode mode, int result) {
AddWriteResult(net::MockWrite(mode, result));
}
void AddWriteResultForData(net::IoMode mode, const std::string& msg) {
AddWriteResult(mode, msg.size());
}
void AddReadResult(const net::MockRead& read) { reads_.push_back(read); }
void AddReadResult(net::IoMode mode, int result) {
AddReadResult(net::MockRead(mode, result));
}
void AddReadResultForData(net::IoMode mode, const std::string& data) {
AddReadResult(net::MockRead(mode, data.c_str(), data.size()));
}
// Helpers for modifying other connection-related behaviors.
void SetupTcpConnectUnresponsive() { tcp_unresponsive_ = true; }
void SetTcpSocket(
std::unique_ptr<net::TransportClientSocket> tcp_client_socket) {
tcp_client_socket_ = std::move(tcp_client_socket);
}
void SetTLSSocketCreatedClosure(base::OnceClosure closure) {
tls_socket_created_ = std::move(closure);
}
void Pause() {
if (socket_data_provider_)
socket_data_provider_->Pause();
else
socket_data_provider_paused_ = true;
}
void Resume() { socket_data_provider_->Resume(); }
private:
std::unique_ptr<net::DatagramClientSocket> CreateDatagramClientSocket(
net::DatagramSocket::BindType,
net::NetLog*,
const net::NetLogSource&) override {
NOTIMPLEMENTED();
return nullptr;
}
std::unique_ptr<net::TransportClientSocket> CreateTransportClientSocket(
const net::AddressList&,
std::unique_ptr<net::SocketPerformanceWatcher>,
net::NetworkQualityEstimator*,
net::NetLog*,
const net::NetLogSource&) override {
if (tcp_client_socket_)
return std::move(tcp_client_socket_);
if (tcp_unresponsive_) {
socket_data_provider_ = std::make_unique<net::StaticSocketDataProvider>();
return std::unique_ptr<net::TransportClientSocket>(
new MockTCPSocket(true, socket_data_provider_.get()));
} else {
socket_data_provider_ =
std::make_unique<net::StaticSocketDataProvider>(reads_, writes_);
socket_data_provider_->set_connect_data(*tcp_connect_data_);
if (socket_data_provider_paused_)
socket_data_provider_->Pause();
return std::unique_ptr<net::TransportClientSocket>(
new MockTCPSocket(false, socket_data_provider_.get()));
}
}
std::unique_ptr<net::SSLClientSocket> CreateSSLClientSocket(
net::SSLClientContext* context,
std::unique_ptr<net::StreamSocket> nested_socket,
const net::HostPortPair& host_and_port,
const net::SSLConfig& ssl_config) override {
if (!ssl_connect_data_) {
// Test isn't overriding SSL socket creation.
return net::ClientSocketFactory::GetDefaultFactory()
->CreateSSLClientSocket(context, std::move(nested_socket),
host_and_port, ssl_config);
}
ssl_socket_data_provider_ = std::make_unique<net::SSLSocketDataProvider>(
ssl_connect_data_->mode, ssl_connect_data_->result);
if (tls_socket_created_)
std::move(tls_socket_created_).Run();
return std::make_unique<net::MockSSLClientSocket>(
std::move(nested_socket), net::HostPortPair(), net::SSLConfig(),
ssl_socket_data_provider_.get());
}
net::IPEndPoint ip_;
// Simulated connect data
std::unique_ptr<net::MockConnect> tcp_connect_data_;
std::unique_ptr<net::MockConnect> ssl_connect_data_;
// Simulated read / write data
std::vector<net::MockWrite> writes_;
std::vector<net::MockRead> reads_;
std::unique_ptr<net::StaticSocketDataProvider> socket_data_provider_;
std::unique_ptr<net::SSLSocketDataProvider> ssl_socket_data_provider_;
bool socket_data_provider_paused_ = false;
// If true, makes TCP connection process stall. For timeout testing.
bool tcp_unresponsive_ = false;
std::unique_ptr<net::TransportClientSocket> tcp_client_socket_;
base::OnceClosure tls_socket_created_;
};
class CastSocketTestBase : public testing::Test {
protected:
CastSocketTestBase()
: task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP),
logger_(new Logger()),
observer_(new MockCastSocketObserver()),
socket_open_params_(CreateIPEndPointForTest(),
base::Milliseconds(kDistantTimeoutMillis)),
client_socket_factory_(socket_open_params_.ip_endpoint) {}
CastSocketTestBase(const CastSocketTestBase&) = delete;
CastSocketTestBase& operator=(const CastSocketTestBase&) = delete;
~CastSocketTestBase() override {}
void SetUp() override {
EXPECT_CALL(*observer_, OnMessage(_, _)).Times(0);
auto context_builder = net::CreateTestURLRequestContextBuilder();
context_builder->set_client_socket_factory_for_testing(
&client_socket_factory_);
url_request_context_ = context_builder->Build();
network_context_ = std::make_unique<network::NetworkContext>(
nullptr, network_context_remote_.BindNewPipeAndPassReceiver(),
url_request_context_.get(),
/*cors_exempt_header_list=*/std::vector<std::string>());
}
// Runs all pending tasks in the message loop.
void RunPendingTasks() {
base::RunLoop run_loop;
run_loop.RunUntilIdle();
}
TestSocketFactory* client_socket_factory() { return &client_socket_factory_; }
content::BrowserTaskEnvironment task_environment_;
std::unique_ptr<net::URLRequestContext> url_request_context_;
std::unique_ptr<network::NetworkContext> network_context_;
mojo::Remote<network::mojom::NetworkContext> network_context_remote_;
raw_ptr<Logger> logger_;
CompleteHandler handler_;
std::unique_ptr<MockCastSocketObserver> observer_;
CastSocketOpenParams socket_open_params_;
TestSocketFactory client_socket_factory_;
};
class MockCastSocketTest : public CastSocketTestBase {
public:
MockCastSocketTest(const MockCastSocketTest&) = delete;
MockCastSocketTest& operator=(const MockCastSocketTest&) = delete;
protected:
MockCastSocketTest() {}
void TearDown() override {
if (socket_) {
EXPECT_CALL(handler_, OnCloseComplete(net::OK));
socket_->Close(base::BindOnce(&CompleteHandler::OnCloseComplete,
base::Unretained(&handler_)));
}
}
void CreateCastSocketSecure() {
socket_ = MockTestCastSocket::CreateSecure(network_context_.get(),
socket_open_params_, logger_);
}
void HandleAuthHandshake() {
socket_->SetupMockTransport();
CastMessage challenge_proto = CreateAuthChallenge();
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(challenge_proto), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
EXPECT_CALL(*socket_->GetMockTransport(), Start());
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
socket_->GetMockTransport()->current_delegate()->OnMessage(
CreateAuthReply());
RunPendingTasks();
}
std::unique_ptr<MockTestCastSocket> socket_;
};
class SslCastSocketTest : public CastSocketTestBase {
public:
SslCastSocketTest(const SslCastSocketTest&) = delete;
SslCastSocketTest& operator=(const SslCastSocketTest&) = delete;
protected:
SslCastSocketTest() {}
void TearDown() override {
if (socket_) {
EXPECT_CALL(handler_, OnCloseComplete(net::OK));
socket_->Close(base::BindOnce(&CompleteHandler::OnCloseComplete,
base::Unretained(&handler_)));
}
}
void CreateSockets() {
socket_ = std::make_unique<TestCastSocketBase>(
network_context_.get(), socket_open_params_, logger_);
server_cert_ =
net::ImportCertFromFile(GetTestCertsDirectory(), "self_signed.pem");
ASSERT_TRUE(server_cert_);
server_private_key_ = ReadTestKeyFromPEM("self_signed.pem");
ASSERT_TRUE(server_private_key_);
server_context_ = CreateSSLServerContext(
server_cert_.get(), *server_private_key_, server_ssl_config_);
tcp_server_socket_ =
std::make_unique<net::TCPServerSocket>(nullptr, net::NetLogSource());
ASSERT_EQ(net::OK,
tcp_server_socket_->ListenWithAddressAndPort("127.0.0.1", 0, 1));
net::IPEndPoint server_address;
ASSERT_EQ(net::OK, tcp_server_socket_->GetLocalAddress(&server_address));
tcp_client_socket_ = std::make_unique<net::TCPClientSocket>(
net::AddressList(server_address), nullptr, nullptr, nullptr,
net::NetLogSource());
std::unique_ptr<net::StreamSocket> accepted_socket;
accept_result_ = tcp_server_socket_->Accept(
&accepted_socket, base::BindOnce(&SslCastSocketTest::TcpAcceptCallback,
base::Unretained(this)));
connect_result_ = tcp_client_socket_->Connect(base::BindOnce(
&SslCastSocketTest::TcpConnectCallback, base::Unretained(this)));
while (accept_result_ == net::ERR_IO_PENDING ||
connect_result_ == net::ERR_IO_PENDING) {
RunPendingTasks();
}
ASSERT_EQ(net::OK, accept_result_);
ASSERT_EQ(net::OK, connect_result_);
ASSERT_TRUE(accepted_socket);
ASSERT_TRUE(tcp_client_socket_->IsConnected());
server_socket_ =
server_context_->CreateSSLServerSocket(std::move(accepted_socket));
ASSERT_TRUE(server_socket_);
client_socket_factory()->SetTcpSocket(std::move(tcp_client_socket_));
}
void ConnectSockets() {
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
net::TestCompletionCallback handshake_callback;
int server_ret = handshake_callback.GetResult(
server_socket_->Handshake(handshake_callback.callback()));
ASSERT_EQ(net::OK, server_ret);
}
void TcpAcceptCallback(int result) { accept_result_ = result; }
void TcpConnectCallback(int result) { connect_result_ = result; }
std::unique_ptr<crypto::RSAPrivateKey> ReadTestKeyFromPEM(
const base::StringPiece& name) {
base::FilePath key_path = GetTestCertsDirectory().AppendASCII(name);
std::string pem_data;
if (!base::ReadFileToString(key_path, &pem_data)) {
return nullptr;
}
const std::vector<std::string> headers({"PRIVATE KEY"});
net::PEMTokenizer pem_tokenizer(pem_data, headers);
if (!pem_tokenizer.GetNext()) {
return nullptr;
}
std::vector<uint8_t> key_vector(pem_tokenizer.data().begin(),
pem_tokenizer.data().end());
std::unique_ptr<crypto::RSAPrivateKey> key(
crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_vector));
return key;
}
int ReadExactLength(net::IOBuffer* buffer,
int buffer_length,
net::Socket* socket) {
scoped_refptr<net::DrainableIOBuffer> draining_buffer =
base::MakeRefCounted<net::DrainableIOBuffer>(buffer, buffer_length);
while (draining_buffer->BytesRemaining() > 0) {
net::TestCompletionCallback read_callback;
int read_result = read_callback.GetResult(server_socket_->Read(
draining_buffer.get(), draining_buffer->BytesRemaining(),
read_callback.callback()));
EXPECT_GT(read_result, 0);
draining_buffer->DidConsume(read_result);
}
return buffer_length;
}
int WriteExactLength(net::IOBuffer* buffer,
int buffer_length,
net::Socket* socket) {
scoped_refptr<net::DrainableIOBuffer> draining_buffer =
base::MakeRefCounted<net::DrainableIOBuffer>(buffer, buffer_length);
while (draining_buffer->BytesRemaining() > 0) {
net::TestCompletionCallback write_callback;
int write_result = write_callback.GetResult(server_socket_->Write(
draining_buffer.get(), draining_buffer->BytesRemaining(),
write_callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS));
EXPECT_GT(write_result, 0);
draining_buffer->DidConsume(write_result);
}
return buffer_length;
}
// Result values used for TCP socket setup. These should contain values from
// net::Error.
int accept_result_;
int connect_result_;
// Underlying TCP sockets for |socket_| to communicate with |server_socket_|
// when testing with the real SSL implementation.
std::unique_ptr<net::TransportClientSocket> tcp_client_socket_;
std::unique_ptr<net::TCPServerSocket> tcp_server_socket_;
std::unique_ptr<TestCastSocketBase> socket_;
// |server_socket_| is used for the *RealSSL tests in order to test the
// CastSocket over a real SSL socket. The other members below are used to
// initialize |server_socket_|.
std::unique_ptr<net::SSLServerSocket> server_socket_;
std::unique_ptr<net::SSLServerContext> server_context_;
std::unique_ptr<crypto::RSAPrivateKey> server_private_key_;
scoped_refptr<net::X509Certificate> server_cert_;
net::SSLServerConfig server_ssl_config_;
};
} // namespace
// Tests that the following connection flow works:
// - TCP connection succeeds (async)
// - SSL connection succeeds (async)
// - Cert is extracted successfully
// - Challenge request is sent (async)
// - Challenge response is received (async)
// - Credentials are verified successfuly
TEST_F(MockCastSocketTest, TestConnectFullSecureFlowAsync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC, net::OK);
HandleAuthHandshake();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
// Tests that the following connection flow works:
// - TCP connection succeeds (sync)
// - SSL connection succeeds (sync)
// - Cert is extracted successfully
// - Challenge request is sent (sync)
// - Challenge response is received (sync)
// - Credentials are verified successfuly
TEST_F(MockCastSocketTest, TestConnectFullSecureFlowSync) {
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::OK);
CreateCastSocketSecure();
HandleAuthHandshake();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
// Test that an AuthMessage with a mangled namespace triggers cancelation
// of the connection event loop.
TEST_F(MockCastSocketTest, TestConnectAuthMessageCorrupted) {
CreateCastSocketSecure();
socket_->SetupMockTransport();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC, net::OK);
CastMessage challenge_proto = CreateAuthChallenge();
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(challenge_proto), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
EXPECT_CALL(*socket_->GetMockTransport(), Start());
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
CastMessage mangled_auth_reply = CreateAuthReply();
mangled_auth_reply.set_namespace_("BOGUS_NAMESPACE");
socket_->GetMockTransport()->current_delegate()->OnMessage(
mangled_auth_reply);
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::TRANSPORT_ERROR, socket_->error_state());
// Verifies that the CastSocket's resources were torn down during channel
// close. (see http://crbug.com/504078)
EXPECT_EQ(nullptr, socket_->transport());
}
// Test connection error - TCP connect fails (async)
TEST_F(MockCastSocketTest, TestConnectTcpConnectErrorAsync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::ERR_FAILED);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_ERROR, socket_->error_state());
}
// Test connection error - TCP connect fails (sync)
TEST_F(MockCastSocketTest, TestConnectTcpConnectErrorSync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::ERR_FAILED);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_ERROR, socket_->error_state());
}
// Test connection error - timeout
TEST_F(MockCastSocketTest, TestConnectTcpTimeoutError) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnectUnresponsive();
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
EXPECT_CALL(*observer_, OnError(_, ChannelError::CONNECT_TIMEOUT));
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CONNECTING, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
socket_->TriggerTimeout();
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_TIMEOUT, socket_->error_state());
}
// Test connection error - TCP socket returns timeout
TEST_F(MockCastSocketTest, TestConnectTcpSocketTimeoutError) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS,
net::ERR_CONNECTION_TIMED_OUT);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
EXPECT_CALL(*observer_, OnError(_, ChannelError::CONNECT_TIMEOUT));
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_TIMEOUT, socket_->error_state());
EXPECT_EQ(net::ERR_CONNECTION_TIMED_OUT,
logger_->GetLastError(socket_->id()).net_return_value);
}
// Test connection error - SSL connect fails (async)
TEST_F(MockCastSocketTest, TestConnectSslConnectErrorAsync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::ERR_FAILED);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::AUTHENTICATION_ERROR, socket_->error_state());
}
// Test connection error - SSL connect fails (sync)
TEST_F(MockCastSocketTest, TestConnectSslConnectErrorSync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::ERR_FAILED);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::AUTHENTICATION_ERROR, socket_->error_state());
EXPECT_EQ(net::ERR_FAILED,
logger_->GetLastError(socket_->id()).net_return_value);
}
// Test connection error - SSL connect times out (sync)
TEST_F(MockCastSocketTest, TestConnectSslConnectTimeoutSync) {
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS,
net::ERR_CONNECTION_TIMED_OUT);
CreateCastSocketSecure();
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_TIMEOUT, socket_->error_state());
EXPECT_EQ(net::ERR_CONNECTION_TIMED_OUT,
logger_->GetLastError(socket_->id()).net_return_value);
}
// Test connection error - SSL connect times out (async)
TEST_F(MockCastSocketTest, TestConnectSslConnectTimeoutAsync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC,
net::ERR_CONNECTION_TIMED_OUT);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CONNECT_TIMEOUT, socket_->error_state());
}
// Test connection error - challenge send fails
TEST_F(MockCastSocketTest, TestConnectChallengeSendError) {
CreateCastSocketSecure();
socket_->SetupMockTransport();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::OK);
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(CreateAuthChallenge()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::ERR_CONNECTION_RESET));
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CAST_SOCKET_ERROR, socket_->error_state());
}
// Test connection error - connection is destroyed after the challenge is
// sent, with the async result still lurking in the task queue.
TEST_F(MockCastSocketTest, TestConnectDestroyedAfterChallengeSent) {
CreateCastSocketSecure();
socket_->SetupMockTransport();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::OK);
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(CreateAuthChallenge()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::ERR_CONNECTION_RESET));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
socket_.reset();
RunPendingTasks();
}
// Test connection error - challenge reply receive fails
TEST_F(MockCastSocketTest, TestConnectChallengeReplyReceiveError) {
CreateCastSocketSecure();
socket_->SetupMockTransport();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::OK);
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(CreateAuthChallenge()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
client_socket_factory()->AddReadResult(net::SYNCHRONOUS, net::ERR_FAILED);
EXPECT_CALL(*observer_, OnError(_, ChannelError::CAST_SOCKET_ERROR));
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
EXPECT_CALL(*socket_->GetMockTransport(), Start());
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
socket_->GetMockTransport()->current_delegate()->OnError(
ChannelError::CAST_SOCKET_ERROR);
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::CAST_SOCKET_ERROR, socket_->error_state());
}
TEST_F(MockCastSocketTest, TestConnectChallengeVerificationFails) {
CreateCastSocketSecure();
socket_->SetupMockTransport();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC, net::OK);
socket_->SetVerifyChallengeResult(false);
EXPECT_CALL(*observer_, OnError(_, ChannelError::AUTHENTICATION_ERROR));
CastMessage challenge_proto = CreateAuthChallenge();
EXPECT_CALL(*socket_->GetMockTransport(),
SendMessage_(EqualsProto(challenge_proto), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
EXPECT_CALL(*socket_->GetMockTransport(), Start());
socket_->AddObserver(observer_.get());
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
socket_->GetMockTransport()->current_delegate()->OnMessage(CreateAuthReply());
RunPendingTasks();
EXPECT_EQ(ReadyState::CLOSED, socket_->ready_state());
EXPECT_EQ(ChannelError::AUTHENTICATION_ERROR, socket_->error_state());
}
// Sends message data through an actual non-mocked CastTransport object,
// testing the two components in integration.
TEST_F(MockCastSocketTest, TestConnectEndToEndWithRealTransportAsync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC, net::OK);
// Set low-level auth challenge expectations.
CastMessage challenge = CreateAuthChallenge();
std::string challenge_str;
EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
client_socket_factory()->AddWriteResultForData(net::ASYNC, challenge_str);
// Set low-level auth reply expectations.
CastMessage reply = CreateAuthReply();
std::string reply_str;
EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
client_socket_factory()->AddReadResultForData(net::ASYNC, reply_str);
client_socket_factory()->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
// Make sure the data is ready by the TLS socket and not the TCP socket.
client_socket_factory()->Pause();
client_socket_factory()->SetTLSSocketCreatedClosure(
base::BindLambdaForTesting([&] { client_socket_factory()->Resume(); }));
CastMessage test_message = CreateTestMessage();
std::string test_message_str;
EXPECT_TRUE(MessageFramer::Serialize(test_message, &test_message_str));
client_socket_factory()->AddWriteResultForData(net::ASYNC, test_message_str);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
// Send the test message through a real transport object.
EXPECT_CALL(handler_, OnWriteComplete(net::OK));
socket_->transport()->SendMessage(
test_message, base::BindOnce(&CompleteHandler::OnWriteComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
// Same as TestConnectEndToEndWithRealTransportAsync, except synchronous.
TEST_F(MockCastSocketTest, TestConnectEndToEndWithRealTransportSync) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::SYNCHRONOUS, net::OK);
client_socket_factory()->SetupSslConnect(net::SYNCHRONOUS, net::OK);
// Set low-level auth challenge expectations.
CastMessage challenge = CreateAuthChallenge();
std::string challenge_str;
EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
client_socket_factory()->AddWriteResultForData(net::SYNCHRONOUS,
challenge_str);
// Set low-level auth reply expectations.
CastMessage reply = CreateAuthReply();
std::string reply_str;
EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
client_socket_factory()->AddReadResultForData(net::SYNCHRONOUS, reply_str);
client_socket_factory()->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
// Make sure the data is ready by the TLS socket and not the TCP socket.
client_socket_factory()->Pause();
client_socket_factory()->SetTLSSocketCreatedClosure(
base::BindLambdaForTesting([&] { client_socket_factory()->Resume(); }));
CastMessage test_message = CreateTestMessage();
std::string test_message_str;
EXPECT_TRUE(MessageFramer::Serialize(test_message, &test_message_str));
client_socket_factory()->AddWriteResultForData(net::SYNCHRONOUS,
test_message_str);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
// Send the test message through a real transport object.
EXPECT_CALL(handler_, OnWriteComplete(net::OK));
socket_->transport()->SendMessage(
test_message, base::BindOnce(&CompleteHandler::OnWriteComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
TEST_F(MockCastSocketTest, TestObservers) {
CreateCastSocketSecure();
// Test AddObserever
MockCastSocketObserver observer1;
MockCastSocketObserver observer2;
socket_->AddObserver(&observer1);
socket_->AddObserver(&observer1);
socket_->AddObserver(&observer2);
socket_->AddObserver(&observer2);
// Test notify observers
EXPECT_CALL(observer1, OnError(_, cast_channel::ChannelError::CONNECT_ERROR));
EXPECT_CALL(observer2, OnError(_, cast_channel::ChannelError::CONNECT_ERROR));
CastSocketImpl::CastSocketMessageDelegate delegate(socket_.get());
delegate.OnError(cast_channel::ChannelError::CONNECT_ERROR);
}
TEST_F(MockCastSocketTest, TestOpenChannelConnectingSocket) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnectUnresponsive();
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_CALL(handler_, OnConnectComplete(socket_.get())).Times(2);
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
socket_->TriggerTimeout();
RunPendingTasks();
}
TEST_F(MockCastSocketTest, TestOpenChannelConnectedSocket) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::OK);
client_socket_factory()->SetupSslConnect(net::ASYNC, net::OK);
HandleAuthHandshake();
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
}
TEST_F(MockCastSocketTest, TestOpenChannelClosedSocket) {
CreateCastSocketSecure();
client_socket_factory()->SetupTcpConnect(net::ASYNC, net::ERR_FAILED);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
RunPendingTasks();
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
socket_->Connect(base::BindOnce(&CompleteHandler::OnConnectComplete,
base::Unretained(&handler_)));
}
// https://crbug.com/874491, flaky on Win and Mac
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_FUCHSIA)
#define MAYBE_TestConnectEndToEndWithRealSSL \
DISABLED_TestConnectEndToEndWithRealSSL
#else
#define MAYBE_TestConnectEndToEndWithRealSSL TestConnectEndToEndWithRealSSL
#endif
// Tests connecting through an actual non-mocked CastTransport object and
// non-mocked SSLClientSocket, testing the components in integration.
TEST_F(SslCastSocketTest, MAYBE_TestConnectEndToEndWithRealSSL) {
CreateSockets();
ConnectSockets();
// Set low-level auth challenge expectations.
CastMessage challenge = CreateAuthChallenge();
std::string challenge_str;
EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
int challenge_buffer_length = challenge_str.size();
scoped_refptr<net::IOBuffer> challenge_buffer =
base::MakeRefCounted<net::IOBuffer>(challenge_buffer_length);
int read = ReadExactLength(challenge_buffer.get(), challenge_buffer_length,
server_socket_.get());
EXPECT_EQ(challenge_buffer_length, read);
EXPECT_EQ(challenge_str,
std::string(challenge_buffer->data(), challenge_buffer_length));
// Set low-level auth reply expectations.
CastMessage reply = CreateAuthReply();
std::string reply_str;
EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
scoped_refptr<net::StringIOBuffer> reply_buffer =
base::MakeRefCounted<net::StringIOBuffer>(reply_str);
int written = WriteExactLength(reply_buffer.get(), reply_buffer->size(),
server_socket_.get());
EXPECT_EQ(reply_buffer->size(), written);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
// Sends message data through an actual non-mocked CastTransport object and
// non-mocked SSLClientSocket, testing the components in integration.
TEST_F(SslCastSocketTest, DISABLED_TestMessageEndToEndWithRealSSL) {
CreateSockets();
ConnectSockets();
// Set low-level auth challenge expectations.
CastMessage challenge = CreateAuthChallenge();
std::string challenge_str;
EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
int challenge_buffer_length = challenge_str.size();
scoped_refptr<net::IOBuffer> challenge_buffer =
base::MakeRefCounted<net::IOBuffer>(challenge_buffer_length);
int read = ReadExactLength(challenge_buffer.get(), challenge_buffer_length,
server_socket_.get());
EXPECT_EQ(challenge_buffer_length, read);
EXPECT_EQ(challenge_str,
std::string(challenge_buffer->data(), challenge_buffer_length));
// Set low-level auth reply expectations.
CastMessage reply = CreateAuthReply();
std::string reply_str;
EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
scoped_refptr<net::StringIOBuffer> reply_buffer =
base::MakeRefCounted<net::StringIOBuffer>(reply_str);
int written = WriteExactLength(reply_buffer.get(), reply_buffer->size(),
server_socket_.get());
EXPECT_EQ(reply_buffer->size(), written);
EXPECT_CALL(handler_, OnConnectComplete(socket_.get()));
RunPendingTasks();
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
// Send a test message through the ssl socket.
CastMessage test_message = CreateTestMessage();
std::string test_message_str;
EXPECT_TRUE(MessageFramer::Serialize(test_message, &test_message_str));
int test_message_length = test_message_str.size();
scoped_refptr<net::IOBuffer> test_message_buffer =
base::MakeRefCounted<net::IOBuffer>(test_message_length);
EXPECT_CALL(handler_, OnWriteComplete(net::OK));
socket_->transport()->SendMessage(
test_message, base::BindOnce(&CompleteHandler::OnWriteComplete,
base::Unretained(&handler_)));
RunPendingTasks();
read = ReadExactLength(test_message_buffer.get(), test_message_length,
server_socket_.get());
EXPECT_EQ(test_message_length, read);
EXPECT_EQ(test_message_str,
std::string(test_message_buffer->data(), test_message_length));
EXPECT_EQ(ReadyState::OPEN, socket_->ready_state());
EXPECT_EQ(ChannelError::NONE, socket_->error_state());
}
} // namespace cast_channel
| [
"jengelh@inai.de"
] | jengelh@inai.de |
8608122505a883191f46d580376e87c37d6a7473 | 23fc3581dab931d13031dfd73be0c7fb4702079c | /GRAPH/cycleDetectionUndirectedBFS.cpp | de157451045687292761072dfa3ed4cbe7d2c2ef | [] | no_license | ritikgithub/DSA | e4b281632eb310895dc64bf1490122b2a5baa09c | 9a7c549388bfeea8b5cbf65de8a744b53ca91c6c | refs/heads/master | 2023-08-05T00:12:58.726173 | 2021-09-09T04:29:12 | 2021-09-09T04:29:12 | 404,584,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | cpp | //To detect cycle in undirected graph using BFS
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool iscycle(int i, vector<int>adj[], bool visited[]) {
queue<pair<int,int>> q;
visited[i]=true;
q.push({i,-1});
while(!q.empty()) {
int node = q.front().first;
int parent = q.front().second;
q.pop();
for(auto child : adj[node]) {
if(child!=parent) {
if(visited[child])
return true;
else {
visited[child]=true;
q.push({child,node});
}
}
}
}
return false;
}
bool isCycle(int V, vector<int>adj[])
{
bool visited[V]={false};
for(int i=0;i<V;i++) {
if(!visited[i]) {
if(iscycle(i,adj,visited))
return true;
}
}
return false;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int V, E;
cin >> V >> E;
vector<int>adj[V];
for(int i = 0; i < E; i++){
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Solution obj;
bool ans = obj.isCycle(V, adj);
if(ans)
cout << "1\n";
else cout << "0\n";
}
return 0;
} // } Driver Code Ends | [
"ritik.agarwal@globallogic.com"
] | ritik.agarwal@globallogic.com |
66bba43bd2b2f3e47c47743b8c4916f40cd7c1fd | 7aba80715edebc6894713240422f7242ef9cb87c | /NPA_Barometer.ino | 9f90a3e118eea7652a32e4cfe7d3999f0b87b412 | [] | no_license | BrianMitton/ArduinoSketches | 4655b50ab6697ebcd0ec36a72eb78fdefeca0add | 2aadfadc004c1eada42bcd19ee65cf1826787bf2 | refs/heads/master | 2020-07-03T10:51:02.905770 | 2016-11-19T01:30:11 | 2016-11-19T01:30:11 | 74,178,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,326 | ino | #include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
while (!Serial); // wait for serial monitor
Serial.println("\nI2C ");
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknow error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(1000); // wait 5 seconds
}
#define NPA201_BAROMETER 0x27
void loop()
{
short c;
short npa_status;
int bridge;
int temp;
int temperature;
int pressure;
Wire.requestFrom(NPA201_BAROMETER, 1); // request Status
while(Wire.available()) // slave may send less than requested
{
c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
Serial.println();
}
Wire.beginTransmission(0x27); // transmit to device (0x27)
// device address is specified in datasheet
Wire.write(0xAC); // sends read request
Wire.endTransmission();
do
{
c = 0;
Wire.requestFrom(NPA201_BAROMETER, 1); // request Status
while(Wire.available()) // slave may send less than requested
{
c = Wire.read(); // receive a byte as character
// Serial.print(c); // print the character
// Serial.println();
}
}while ((c & 0x20) != 0x00);
//delay(1000); // wait a sec
//Wire.beginTransmission(NPA201_BAROMETER);
Wire.requestFrom(NPA201_BAROMETER, 5); // request 6 bytes from slave device #2
// while(Wire.available()) // slave may send less than requested
// {
// c = Wire.read(); // receive a byte as character
// Serial.print(c); // print the character
// Serial.print(", "); // print
// }
npa_status = Wire.read(); // receive a byte
c = Wire.read(); // receive a byte
bridge = c;
bridge = bridge<<8;
c = Wire.read(); // receive a byte
bridge += c;
c = Wire.read(); // receive a byte
temp = c;
temp = temp<<8;
c = Wire.read(); // receive a byte
temp += c;
temperature = (((temp>>8) * (85+40))>>8) -40;
// Absolute pressure. Not adjusted for heigth above sea level
pressure = (((((long)bridge * ((1260-260)))>>8)+(260<<8))*10)>>8;
Serial.print ("Status: ");
Serial.print (npa_status);
Serial.print (", Bridge ");
Serial.print (bridge);
Serial.print (", Temperature ");
Serial.print (temperature);
Serial.print (", mBars ");
Serial.print (pressure/10);
Serial.print (".");
Serial.print (pressure%10);
Serial.println();
//error = Wire.endTransmission();
delay(2000); // wait
}
| [
"bmitton1@mindspring.com"
] | bmitton1@mindspring.com |
4638dc0c7177bdde6b52dc857231b5c388218d72 | 17c26fa226a7ec681409485852328fdaf8377239 | /DFD_CloudFinalProject/Source/AudioDSPComponents/VAOnePoleFilter.cpp | f0f01b3abf5a1f55a13749396612713e6095cab5 | [] | no_license | AndrewCloud01/DFD_Butterworth | c23ad908b8d582319304d776291ac127fbf2b6ef | 4ef22e2772a0bcd4dfaf9e1ea9ffc6af7b6bbbdd | refs/heads/master | 2021-09-09T18:45:54.704930 | 2018-03-18T23:52:47 | 2018-03-18T23:52:47 | 125,778,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,600 | cpp | /*
==============================================================================
VAOnePoleFilter.cpp
Created: 9 Jul 2015 8:20:19pm
Author: Joshua Marler
==============================================================================
*/
#include "VAOnePoleFilter.h"
VAOnePoleFilter::VAOnePoleFilter()
{
}
VAOnePoleFilter::~VAOnePoleFilter()
{
}
//Set variables and flush state registers in initialization function. Must be called before playback starts
void VAOnePoleFilter::initializeFilter(float initSampleRate, float initMinFrequency, float initMaxFrequency)
{
this->sampleRate = initSampleRate;
this->minFrequency = initMinFrequency;
this->maxFrequency = initMaxFrequency;
//clear the delay elements/state holders
z1[0] = 0.0;
z1[1] = 0.0;
}
void VAOnePoleFilter::setCutoff(float newCutoff)
{
this->cutoffFrequency = newCutoff;
//Cutoff prewarping, billinear transform filters - see Art Of VA Filter Design.
float wd = 2 * M_PI * this->cutoffFrequency; // Omega = 2piF
float T = 1/this->sampleRate; // Period
/* Desired analogue frequency / these are virtual analogue filters so this is the cutoff / frequency response we require for out filter algorithm */
float wa = (2/T) * tan(wd*T/2);
float g = wa * T/2;
G = g/(1.0 + g); // alpha
}
float VAOnePoleFilter::processFilter(float input, int channel)
{
float output = 0.0;
float v = (input - z1[channel]) * G;
float lowpassOutput = v + z1[channel];
//Update the z1 delay / state holder with new filter output for use in next sample
z1 [channel]= lowpassOutput + v;
float highpassOutput = input - lowpassOutput;
switch (this->filterType) {
case AudioFilter::filterTypeList::LowPass:
output = this->filterGain * lowpassOutput;
break;
case AudioFilter::filterTypeList::HighPass:
output = this->filterGain * highpassOutput;
break;
default:
break;
}
return output;
}
float VAOnePoleFilter::getMagnitudeResponse(float frequency) const
{
float magnitude = 0.0;
float T = 1/this->sampleRate;
float wdCutoff = 2 * M_PI * this->cutoffFrequency;
//Calculating pre-warped/analogue cutoff frequency to use in virtual analogue frequeny response calculations
float cutOff = (2/T) * tan(wdCutoff*T/2);
//Digital frequency to evaluate
float wdEval = 2 * M_PI * frequency;
float sValue = (2/T) * tan(wdEval*T/2);
/* This is the digital transfer function which is equal to the analogue transfer function
evaluated at H(s) where s = (2/T) * tan(wd*T/2) hence why the cutoff used is the pre warped analogue equivalent.
See Art Of VA Filter Design 3.8 Bilinear Transform Section */
switch (this->filterType) {
case AudioFilter::filterTypeList::LowPass:
//VA Lowpass Frequency response wc/s+wc
magnitude = cutOff/(sValue + cutOff);
break;
case AudioFilter::filterTypeList::HighPass:
//VA Highpass Frequency response s/s+wc
magnitude = sValue/(sValue + cutOff);
break;
default:
break;
}
magnitude = magnitude * this->filterGain;
//Convert to db for log db response display
magnitude = Decibels::gainToDecibels(magnitude);
return magnitude;
}
| [
"andrewcloud01@gmail.com"
] | andrewcloud01@gmail.com |
619d69f95500bbf6f58fe22a04b8a065d632d9a5 | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-elastictranscoder/source/model/JobOutput.cpp | 5a1512fea260c3415739fd0d111b8c21a8691ab4 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 7,920 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/elastictranscoder/model/JobOutput.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ElasticTranscoder
{
namespace Model
{
JobOutput::JobOutput() :
m_idHasBeenSet(false),
m_keyHasBeenSet(false),
m_thumbnailPatternHasBeenSet(false),
m_thumbnailEncryptionHasBeenSet(false),
m_rotateHasBeenSet(false),
m_presetIdHasBeenSet(false),
m_segmentDurationHasBeenSet(false),
m_statusHasBeenSet(false),
m_statusDetailHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_width(0),
m_widthHasBeenSet(false),
m_height(0),
m_heightHasBeenSet(false),
m_frameRateHasBeenSet(false),
m_fileSize(0),
m_fileSizeHasBeenSet(false),
m_durationMillis(0),
m_durationMillisHasBeenSet(false),
m_watermarksHasBeenSet(false),
m_albumArtHasBeenSet(false),
m_captionsHasBeenSet(false),
m_encryptionHasBeenSet(false),
m_appliedColorSpaceConversionHasBeenSet(false)
{
}
JobOutput::JobOutput(const JsonValue& jsonValue) :
m_idHasBeenSet(false),
m_keyHasBeenSet(false),
m_thumbnailPatternHasBeenSet(false),
m_thumbnailEncryptionHasBeenSet(false),
m_rotateHasBeenSet(false),
m_presetIdHasBeenSet(false),
m_segmentDurationHasBeenSet(false),
m_statusHasBeenSet(false),
m_statusDetailHasBeenSet(false),
m_duration(0),
m_durationHasBeenSet(false),
m_width(0),
m_widthHasBeenSet(false),
m_height(0),
m_heightHasBeenSet(false),
m_frameRateHasBeenSet(false),
m_fileSize(0),
m_fileSizeHasBeenSet(false),
m_durationMillis(0),
m_durationMillisHasBeenSet(false),
m_watermarksHasBeenSet(false),
m_albumArtHasBeenSet(false),
m_captionsHasBeenSet(false),
m_encryptionHasBeenSet(false),
m_appliedColorSpaceConversionHasBeenSet(false)
{
*this = jsonValue;
}
JobOutput& JobOutput::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
m_idHasBeenSet = true;
}
if(jsonValue.ValueExists("Key"))
{
m_key = jsonValue.GetString("Key");
m_keyHasBeenSet = true;
}
if(jsonValue.ValueExists("ThumbnailPattern"))
{
m_thumbnailPattern = jsonValue.GetString("ThumbnailPattern");
m_thumbnailPatternHasBeenSet = true;
}
if(jsonValue.ValueExists("ThumbnailEncryption"))
{
m_thumbnailEncryption = jsonValue.GetObject("ThumbnailEncryption");
m_thumbnailEncryptionHasBeenSet = true;
}
if(jsonValue.ValueExists("Rotate"))
{
m_rotate = jsonValue.GetString("Rotate");
m_rotateHasBeenSet = true;
}
if(jsonValue.ValueExists("PresetId"))
{
m_presetId = jsonValue.GetString("PresetId");
m_presetIdHasBeenSet = true;
}
if(jsonValue.ValueExists("SegmentDuration"))
{
m_segmentDuration = jsonValue.GetString("SegmentDuration");
m_segmentDurationHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = jsonValue.GetString("Status");
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("StatusDetail"))
{
m_statusDetail = jsonValue.GetString("StatusDetail");
m_statusDetailHasBeenSet = true;
}
if(jsonValue.ValueExists("Duration"))
{
m_duration = jsonValue.GetInt64("Duration");
m_durationHasBeenSet = true;
}
if(jsonValue.ValueExists("Width"))
{
m_width = jsonValue.GetInteger("Width");
m_widthHasBeenSet = true;
}
if(jsonValue.ValueExists("Height"))
{
m_height = jsonValue.GetInteger("Height");
m_heightHasBeenSet = true;
}
if(jsonValue.ValueExists("FrameRate"))
{
m_frameRate = jsonValue.GetString("FrameRate");
m_frameRateHasBeenSet = true;
}
if(jsonValue.ValueExists("FileSize"))
{
m_fileSize = jsonValue.GetInt64("FileSize");
m_fileSizeHasBeenSet = true;
}
if(jsonValue.ValueExists("DurationMillis"))
{
m_durationMillis = jsonValue.GetInt64("DurationMillis");
m_durationMillisHasBeenSet = true;
}
if(jsonValue.ValueExists("Watermarks"))
{
Array<JsonValue> watermarksJsonList = jsonValue.GetArray("Watermarks");
for(unsigned watermarksIndex = 0; watermarksIndex < watermarksJsonList.GetLength(); ++watermarksIndex)
{
m_watermarks.push_back(watermarksJsonList[watermarksIndex].AsObject());
}
m_watermarksHasBeenSet = true;
}
if(jsonValue.ValueExists("AlbumArt"))
{
m_albumArt = jsonValue.GetObject("AlbumArt");
m_albumArtHasBeenSet = true;
}
if(jsonValue.ValueExists("Captions"))
{
m_captions = jsonValue.GetObject("Captions");
m_captionsHasBeenSet = true;
}
if(jsonValue.ValueExists("Encryption"))
{
m_encryption = jsonValue.GetObject("Encryption");
m_encryptionHasBeenSet = true;
}
if(jsonValue.ValueExists("AppliedColorSpaceConversion"))
{
m_appliedColorSpaceConversion = jsonValue.GetString("AppliedColorSpaceConversion");
m_appliedColorSpaceConversionHasBeenSet = true;
}
return *this;
}
JsonValue JobOutput::Jsonize() const
{
JsonValue payload;
if(m_idHasBeenSet)
{
payload.WithString("Id", m_id);
}
if(m_keyHasBeenSet)
{
payload.WithString("Key", m_key);
}
if(m_thumbnailPatternHasBeenSet)
{
payload.WithString("ThumbnailPattern", m_thumbnailPattern);
}
if(m_thumbnailEncryptionHasBeenSet)
{
payload.WithObject("ThumbnailEncryption", m_thumbnailEncryption.Jsonize());
}
if(m_rotateHasBeenSet)
{
payload.WithString("Rotate", m_rotate);
}
if(m_presetIdHasBeenSet)
{
payload.WithString("PresetId", m_presetId);
}
if(m_segmentDurationHasBeenSet)
{
payload.WithString("SegmentDuration", m_segmentDuration);
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", m_status);
}
if(m_statusDetailHasBeenSet)
{
payload.WithString("StatusDetail", m_statusDetail);
}
if(m_durationHasBeenSet)
{
payload.WithInt64("Duration", m_duration);
}
if(m_widthHasBeenSet)
{
payload.WithInteger("Width", m_width);
}
if(m_heightHasBeenSet)
{
payload.WithInteger("Height", m_height);
}
if(m_frameRateHasBeenSet)
{
payload.WithString("FrameRate", m_frameRate);
}
if(m_fileSizeHasBeenSet)
{
payload.WithInt64("FileSize", m_fileSize);
}
if(m_durationMillisHasBeenSet)
{
payload.WithInt64("DurationMillis", m_durationMillis);
}
if(m_watermarksHasBeenSet)
{
Array<JsonValue> watermarksJsonList(m_watermarks.size());
for(unsigned watermarksIndex = 0; watermarksIndex < watermarksJsonList.GetLength(); ++watermarksIndex)
{
watermarksJsonList[watermarksIndex].AsObject(m_watermarks[watermarksIndex].Jsonize());
}
payload.WithArray("Watermarks", std::move(watermarksJsonList));
}
if(m_albumArtHasBeenSet)
{
payload.WithObject("AlbumArt", m_albumArt.Jsonize());
}
if(m_captionsHasBeenSet)
{
payload.WithObject("Captions", m_captions.Jsonize());
}
if(m_encryptionHasBeenSet)
{
payload.WithObject("Encryption", m_encryption.Jsonize());
}
if(m_appliedColorSpaceConversionHasBeenSet)
{
payload.WithString("AppliedColorSpaceConversion", m_appliedColorSpaceConversion);
}
return payload;
}
} // namespace Model
} // namespace ElasticTranscoder
} // namespace Aws | [
"henso@amazon.com"
] | henso@amazon.com |
15e2570d670f3b3a2cfa7742aed4c967fcd2f975 | 83271185c3e11031a1d4112d0e48100aafbb0ec9 | /x264_codec/src/main/cpp/x264_encoder.cpp | 0c11708d2ba00686319a6d8c37f800f69c8ed0b2 | [] | no_license | littledou/learnvideo | b97e2f4c52bbf89f022ad0ba3057d9fb46d79c35 | 6fa047b862fe835b04ec05dfcd22ee8f9c6a1c00 | refs/heads/main | 2023-06-02T12:23:53.977323 | 2021-06-17T08:27:06 | 2021-06-17T08:27:06 | 358,912,548 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 66 | cpp | //
// Created by loki on 2021/5/12.
//
#include "x264_encoder.h"
| [
"app_yoko@163.com"
] | app_yoko@163.com |
709fd270462f43f676b8b1238361dad194ce4652 | 0125a6196a78e0df78e458ebf4f57b6d9bb9cb8a | /Queues/include/LinkedQueue.h | 7052dd9239c33a16e197edee21c8e5b007dd60b4 | [
"MIT"
] | permissive | MinTimmy/C | 64eee8bc1f5e6c770dd778cb5146f34057c28d13 | b70a657747abc78748b3bc943733fec156fcd967 | refs/heads/master | 2020-04-24T21:49:15.472828 | 2019-08-05T03:34:56 | 2019-08-05T03:34:56 | 172,290,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | #ifndef LINKEDQUEUE_H
#define LINKEDQUEUE_H
class Node{
//friend class LinkedStack;
public:
Node(int n) : data(n), next(0) {};
Node() : data(0) , next(0) {};
private:
int data;
Node* next;
friend class LinkedQueue;
};
class LinkedQueue
{
public:
LinkedQueue();
~LinkedQueue();
int size() const;
bool isEmpty() const;
int front() const;
void enqueue( int );
void dequeue();
private:
Node* rearNode;
int LinkedQueueLength;
};
#endif // LINKEDQUEUE_H
| [
"timmygood6590@gmail.com"
] | timmygood6590@gmail.com |
255a36fd49b0c837419d2b5fc74fb27f205ec7ff | fede3d3e4a11950bf6bb75476e1821c8de53be3f | /CodingPractice/UglyNumbers.cpp | 26884b05147d21d2ccc078585e540118f108bdff | [] | no_license | Souvikcse/Functional-Programming | 94098f5b08e92da56fc8f775d75044d61847d5c3 | 7caf157d0d3834062172f0568a7e4575e3758e65 | refs/heads/master | 2020-07-14T18:04:52.833015 | 2020-05-01T11:38:35 | 2020-05-01T11:38:35 | 205,369,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
typedef long long int ll;
using namespace std;
vector<ll> v;
void find(int i, int n, int num){
if(v.size()==n)
return;
}
int main(){
int t;
cin>>t;
find(0, 10000);
sort(v.begin(), v.end());
while(t--){
int n;
cin>>n;
}
} | [
"sayanwinz@gmail.com"
] | sayanwinz@gmail.com |
78637e6b7cd2fdd237924092acd6c03e35e86bc2 | 08f934f490c375e3d481f638b246eb282f08a326 | /src/cpp/chess/disp/border.cpp | 5cca1518140072ba0f1f6209eb765c7539a5fda1 | [] | no_license | btobrien/chessworm | 2e21bb03f9fddffcb26ebee9982491012b81cef8 | 76dcc546ae00b3b7b80c99017222c7e9b9666088 | refs/heads/master | 2020-09-14T08:34:34.313780 | 2019-12-21T23:11:34 | 2019-12-21T23:11:34 | 94,467,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include <iostream>
#include <string>
const int BOARD_WIDTH = 8;
int main(int argc, char** argv) {
int width = (2 * BOARD_WIDTH) + 1;
if (argc > 1)
width = std::stoi(argv[1]);
std::cout << "\u250C";
for (int col = 0; col < width; col++)
std::cout << "\u2500";
std::cout << "\u2510" << std::endl;
std::string line;
while (getline(std::cin, line)) {
std::cout << "\u2502";
std::cout << line;
std::cout << "\u2502" << std::endl;
}
std::cout << "\u2514";
for (int col = 0; col < width; col++)
std::cout << "\u2500";
std::cout << "\u2518" << std::endl;
return 0;
}
| [
"bobrien@umich.edu"
] | bobrien@umich.edu |
82ea18c46e946f4ee7c793430a034887868ed90c | ef741f433ba4938577ef02957f6416e8cee23050 | /main.cpp | 6f5e909cdfcab9261150be3c3217626971a7e674 | [
"Apache-2.0"
] | permissive | ThomasYhub/Prime-factorization | 86287c3f598057ddebcc49af903b8fce2cf10d01 | cb7929a73ada490ae1c7877f825faa92be4caf8b | refs/heads/master | 2021-01-10T15:10:04.913419 | 2016-04-09T10:45:47 | 2016-04-09T10:45:47 | 55,838,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,902 | cpp | // このファイルはスタンダードmidiファイルをバイナリで吐き出す
// ヘッダチャンクには適当だと思われる値を入力してある
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
#define HEAD 8
uint32_t Count = 0;
const int Maxprime = 719;
const int N = 10000;
const int NumOfKey = 128;
//ファイルの末尾にバイナリを入れる
void pop_back(ofstream &ofs, char one_bite){
ofs.write((const char*)&one_bite, sizeof(one_bite));
Count++;
}
void sound_start(ofstream &ofs, char key, char vel, char waiting_time = 0){
pop_back(ofs,waiting_time);//待機時間
pop_back(ofs,0x90);//スタート
pop_back(ofs,key);//音程
pop_back(ofs,vel);//ベロシティ
}
void sound_stop(ofstream &ofs, char key, char vel, char waiting_time=120){
pop_back(ofs,waiting_time);//待機時間
pop_back(ofs,0x80);//エンド
pop_back(ofs,key);//音程
pop_back(ofs,vel);//ベロシティ
}
int main(void)
{
cout<<"Name file :";
string filename;
cin>>filename;
filename.append(".mid");
//out:書き込み専用 binary:バイナリモードで開く
ofstream ofs(filename, ios_base::out | ios_base::binary);
if (!ofs) {
cerr << "ファイルオープンに失敗" << endl;
exit(1);
}
//ヘッダチャンク
u_int32_t head[HEAD] = {
0x6468544D,
0x06000000,
0x01000100,
0x544DE001,
0x00006B72,
0xFF005800,
0x72500803,
0x6E657365,
};
for (int i=0; i<HEAD ; i++) {
ofs.write((const char*)&head[i], sizeof(head[i]));
}
Count=10;
pop_back(ofs,0x63);
pop_back(ofs,0x65);
//****************作りたいノイズに関するアルゴリズムを記述(本体)************************
//この部分は待機時間(0)に始まり待機時間(0)に終わる
//
//今回は時間軸を整数値に見立てiとし、鍵盤を一番低い音から順に素数に見立て、素因数分解をする
//音量は、素因数の量によって変化させる
//素数は2から数え、719(128個目の素数)まである。
//ベロシティは1biteで表されるため、最小値を0x0F=15とする。そのため、15*17=255=0xFF より、17の同じ素因数を持つものまで対応できる。
//始めは全て素数であると定義しておき,後ほど審査してふるい落とす(ふるい法)
//1000の中に128個以上の素数があると記憶していたためざっくり今回はN=1000まで調べる
bool is_prime_num[Maxprime+1];
for (int i=0;i<Maxprime+1;i++){
is_prime_num[i] = 1;
}
//2~Nまでその倍数をふるい落とす
for (int i=2; i<Maxprime+1; i++) {
//素数なら(始めは全て素数であると定義してある)d
if (is_prime_num[i]==1) {
//倍数をふるいにかける
int j=2;
while (i*j<=Maxprime+1 && i<Maxprime+1 && j<Maxprime+1) {
is_prime_num[i*j]=0;
j++;
}
}
//素数じゃなければ
else {//スルー
}
}
//素数を持つ配列を作る
int prime[NumOfKey];
fill_n(prime, NumOfKey, 0);
int countp=0;
for (int i=2; i<Maxprime+1; i++) {
if (countp>=NumOfKey) break; //鍵盤の数を素数の個数が超えてしまったら
else if (is_prime_num[i]) {
prime[countp]=i;
countp++;
}
}
cout<<prime[NumOfKey-1]<<endl;
//全ての整数値について、登場する素因数の個数を格納する配列を作成
int cntkey[N][NumOfKey];
fill_n(cntkey[0], N*NumOfKey, 0);
//和音を構成したい整数値の個数分ループ
for(int i_time = 1; i_time<=N; i_time++){
//素数128個分の出現個数を記録しておくための配列
fill_n(cntkey[0],NumOfKey,0);
//鍵盤の個数分ループ
int removing_i = i_time;
for(int key=0; key<NumOfKey; key++){
//素数であれば
while (removing_i != 0 && removing_i%prime[key]==0 && cntkey[i_time][key]< 17) {
cntkey[i_time][key]++;
removing_i/=prime[key];
cout<<prime[key]<<" ";
}
}
cout<<":"<<i_time<<endl;
}
for (int i_time=0; i_time<N; i_time++) {
bool is_first_note=true;
//和音開始
for (int key=0; key<NumOfKey; key++) {
if (cntkey[i_time][key]!=0) {
sound_start(ofs,127-key,15*cntkey[i_time][key]);
}
}
//和音それぞれを停止
for (int key=0; key<NumOfKey; key++) {
if (cntkey[i_time][key]!=0) {
if(is_first_note){
sound_stop(ofs,127-key,15*cntkey[i_time][key]);
is_first_note=false;
}
else sound_stop(ofs,127-key,15*cntkey[i_time][key],0);
}
}
}
pop_back(ofs,0x00);//待機時間
//*******************************************************************************
//末尾チャンク
pop_back(ofs,0xFF);
pop_back(ofs,0x2F);
pop_back(ofs,0x00);
//バイナリサイズの自動挿入
//シークバーの移動(beg=begin)
ofs.seekp( 18, ios::beg );
const uint32_t Sizedata=Count;
if(Sizedata>=0xFFFFFFFF){
cout<<"データセクションが長すぎます";
ofs.close();
exit(0);
}
else{
pop_back(ofs,Sizedata>>(3*8));
pop_back(ofs,(Sizedata>>(2*8))%(UCHAR_MAX+1));
pop_back(ofs,(Sizedata>>8)%(UCHAR_MAX+1));
pop_back(ofs,Sizedata%(UCHAR_MAX+1));
}
ofs.close();
return 0;
} | [
"akogi.tomy@gmail.com"
] | akogi.tomy@gmail.com |
6b6c283d74eba9b56638285ebef8aac19cce1903 | 07c3e4c4f82056e76285c81f14ea0fbb263ed906 | /Re-Abyss/app/components/Adv/Common/Command/ColorTag.hpp | 5474c60ddd94d0dffec4d96e14bab590b9ef4d04 | [] | no_license | tyanmahou/Re-Abyss | f030841ca395c6b7ca6f9debe4d0de8a8c0036b5 | bd36687ddabad0627941dbe9b299b3c715114240 | refs/heads/master | 2023-08-02T22:23:43.867123 | 2023-08-02T14:20:26 | 2023-08-02T14:20:26 | 199,132,051 | 9 | 1 | null | 2021-11-22T20:46:39 | 2019-07-27T07:28:34 | C++ | UTF-8 | C++ | false | false | 489 | hpp | #pragma once
#include <abyss/commons/Fwd.hpp>
#include <abyss/modules/Adv/base/ICommand.hpp>
#include <Siv3D/Optional.hpp>
#include <Siv3D/ColorF.hpp>
namespace abyss::Adv
{
class ColorTag :
public ICommand
{
public:
ColorTag(AdvObj* pObj, const s3d::Optional<s3d::ColorF>& color);
void onStart() override;
Coro::Fiber<> onCommand() override;
private:
AdvObj* m_pObj = nullptr;
s3d::Optional<s3d::ColorF> m_color;
};
}
| [
"tyanmahou@gmail.com"
] | tyanmahou@gmail.com |
3712c49919271319597542ce589f4cf81933617c | e8cdebc4bda1c2f955598e3f98a189eb3652ab60 | /libLogging/test/LevelTest.h | 7ecefcea48ce2ed082f987f2288788608f5e4589 | [
"BSD-3-Clause"
] | permissive | marcbejerano/cpp-tools | 0a40ac9f2ac22758fa7193d6df3e7eb761df2c04 | 9ef62064a5b826b8722ff96e423ffff2d85f49f1 | refs/heads/master | 2020-03-26T22:11:06.691644 | 2018-08-20T15:49:48 | 2018-08-20T15:49:48 | 145,438,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,134 | h | #ifndef _LEVEL_TEST_H_INCLUDED_
#define _LEVEL_TEST_H_INCLUDED_
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TextTestRunner.h>
class StandardLevelTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(StandardLevelTest);
CPPUNIT_TEST(testCtor);
CPPUNIT_TEST(testCtorArgs);
CPPUNIT_TEST(testCtorCopy);
CPPUNIT_TEST(testAssignment);
CPPUNIT_TEST(testIntLevel);
CPPUNIT_TEST(testGetStandardLevel);
CPPUNIT_TEST_SUITE_END();
void testCtor();
void testCtorArgs();
void testCtorCopy();
void testAssignment();
void testIntLevel();
void testGetStandardLevel();
};
class LevelTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE(LevelTest);
CPPUNIT_TEST(testCtor);
CPPUNIT_TEST(testCtorArgs);
CPPUNIT_TEST(testCtorCopy);
CPPUNIT_TEST(testAssignment);
CPPUNIT_TEST(testClone);
CPPUNIT_TEST(testCompareTo);
CPPUNIT_TEST(testEquals);
CPPUNIT_TEST(testHashCode);
CPPUNIT_TEST(testIntLevel);
CPPUNIT_TEST(testIsInRange);
CPPUNIT_TEST(testIsLessSpecificThan);
CPPUNIT_TEST(testIsMoreSpecificThan);
CPPUNIT_TEST(testName);
CPPUNIT_TEST(testToString);
CPPUNIT_TEST(testGetStandardLevel);
CPPUNIT_TEST(testForName);
CPPUNIT_TEST(testGetLevel);
CPPUNIT_TEST(testToLevel);
CPPUNIT_TEST_SUITE_END();
void testCtor();
void testCtorArgs();
void testCtorCopy();
void testAssignment();
void testClone();
void testCompareTo();
void testEquals();
void testHashCode();
void testIntLevel();
void testIsInRange();
void testIsLessSpecificThan();
void testIsMoreSpecificThan();
void testName();
void testToString();
void testGetStandardLevel();
void testForName();
void testGetLevel();
void testToLevel();
};
#endif // _LEVEL_TEST_H_INCLUDED_
| [
"marcbejerano@gmail.com"
] | marcbejerano@gmail.com |
de9cae82a246b513215633cdf58b1f6441c3154c | 8cfb0fcd24249b339090f0d75816b055b22ad418 | /G2API/oviewtrade.h | 01733fd09f0a9aac58bc57870d74224a96259e24 | [] | no_license | Siemekk/AST-World-Editor | febcec3fde6c04b81f24ac17a2c65a7e6c01fd75 | bd1c94a858fcb5b5cacaa7040073bf0e64ae0d41 | refs/heads/master | 2020-04-02T02:47:51.849427 | 2018-10-20T17:20:12 | 2018-10-20T17:20:12 | 153,928,460 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,303 | h | #pragma once
#include "ocnpcinventory.h"
#include "zViewObject.h"
//
// VIEW
//
class oCViewDialogInventory : public zCViewDialog
{
public:
zCLASS(oCViewDialogInventory);
// *********************************************************************************
// ** ENUMS & STRUCTURES
// *********************************************************************************
public:
static zCClassDef* classDef;
enum oEInventoryAlignment
{
oEInventoryAlignment_Left ,
oEInventoryAlignment_Right
}
oTInventoryAlignment, oTAlignmentInventory;
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
protected:
oCNpcInventory* Inventory ;
oEInventoryAlignment Alignment ;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
//
// GET/SET
//
public:
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x00689010)};
virtual void __fastcall Activate ( zBOOL bActive ) {XCALL(0x006890B0)};
void __fastcall SetInventory ( oCNpcInventory* pInventory ) {XCALL(0x006890D0)};
void __fastcall SetAlignment ( oEInventoryAlignment enuAlignment ) {XCALL(0x00689100)};
oCNpcInventory* __fastcall GetInventory ( void ) { return this->Inventory; }
oEInventoryAlignment __fastcall GetAlignment ( void ) { return this->Alignment; }
oCItem* __fastcall GetSelectedItem ( void ) {XCALL(0x00689110)};
int __fastcall GetSelectedItemCount( void ) {XCALL(0x00689130)};
oCItem* __fastcall RemoveSelectedItem ( void ) {XCALL(0x00689150)};
void __fastcall InsertItem ( oCItem* pItem ) {XCALL(0x006891E0)};
//
// INTERACTION
//
public:
virtual void __fastcall StartSelection ( void ) {XCALL(0x00689270)};
virtual void __fastcall StopSelection ( void ) {XCALL(0x006892D0)};
//
// EVENTS
//
public:
virtual zBOOL HandleEvent ( int nKey ) {XCALL(0x00689220)};
zBOOL __fastcall CanHandleLeft ( void ) {XCALL(0x00689200)};
zBOOL __fastcall CanHandleRight ( void ) {XCALL(0x00689210)};
//
// CON-/DESTRUCTION
//
public:
void oViewDialogInventory(void){XCALL(0x00689020)};
oCViewDialogInventory(){oViewDialogInventory();};
virtual ~oCViewDialogInventory(){XCALL(0x00689090)};
};
typedef oCViewDialogInventory *LPCViewDialogInventory, *LPCVIEWDIALOGINVENTORY;
//
// VIEW
//
class oCViewDialogStealContainer : public zCViewDialog
{
public:
zCLASS(oCViewDialogStealContainer);
// *********************************************************************************
// ** ENUMS & STRUCTURES
// *********************************************************************************
public:
static zCClassDef* classDef;
enum oEStealContainerAlignment
{
oEStealContainerAlignment_Left ,
oEStealContainerAlignment_Right
}
oTStealContainerAlignment, oTAlignmentStealContainer;
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
protected:
oCStealContainer* StealContainer ;
oEStealContainerAlignment Alignment ;
zUINT32 Value ;
zREAL ValueMultiplier ;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
//
// GET/SET
//
public:
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x0068A2F0)};
virtual void __fastcall Activate ( zBOOL bActive ) {XCALL(0x0068A3A0)};
void __fastcall SetStealContainer ( oCStealContainer* pStealContainer ) {XCALL(0x0068A3C0)};
void __fastcall SetAlignment ( oEStealContainerAlignment enuAlignment ) {XCALL(0x0068A3F0)};
void __fastcall SetValueMultiplier ( zREAL fValueMultiplier ) { this->ValueMultiplier = fValueMultiplier ; }
oCStealContainer* __fastcall GetStealContainer ( void ) { return this->StealContainer ; }
oEStealContainerAlignment __fastcall GetAlignment ( void ) { return this->Alignment ; }
zUINT32 __fastcall GetValue ( void ) { return this->Value ; }
zREAL __fastcall GetValueMultiplier ( void ) { return this->ValueMultiplier ; }
oCItem* __fastcall GetSelectedItem ( void ) {XCALL(0x0068A400)};
int __fastcall GetSelectedItemCount( void ) {XCALL(0x0068A420)};
oCItem* __fastcall RemoveSelectedItem ( void ) {XCALL(0x0068A440)};
void __fastcall InsertItem ( oCItem* pItem ) {XCALL(0x0068A500)};
void __fastcall TransferAllItemsTo ( oCNpcInventory* pInventory ) {XCALL(0x0068A5B0)};
protected:
void __fastcall RemoveItem ( oCItem* pItem ) {XCALL(0x0068A550)};
void __fastcall UpdateValue ( void ) {XCALL(0x0068A6B0)};
//
// INTERACTION
//
public:
virtual void __fastcall StartSelection ( void ) {XCALL(0x0068A7C0)};
virtual void __fastcall StopSelection ( void ) {XCALL(0x0068A820)};
//
// EVENTS
//
public:
virtual zBOOL HandleEvent ( int nKey ) {XCALL(0x0068A770)};
zBOOL __fastcall CanHandleLeft ( void ) {XCALL(0x0068A750)};
zBOOL __fastcall CanHandleRight ( void ) {XCALL(0x0068A760)};
//
// CON-/DESTRUCTION
//
public:
void oViewDialogStealContainer(void){XCALL(0x0068A300);};
oCViewDialogStealContainer(void){oViewDialogStealContainer();};
virtual ~oCViewDialogStealContainer(){XCALL(0x0068A380)};
};
typedef oCViewDialogStealContainer *LPCViewDialogStealContainer, *LPCVIEWDIALOGSTEALCONTAINER;
//
// VIEW
//
class oCViewDialogTrade : public zCViewDialog
{
public:
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x0068B010)};
zCLASS(oCViewDialogTrade);
// *********************************************************************************
// ** ENUMS & STRUCTURES
// *********************************************************************************
//protected:
public:
typedef
enum zETradeDialogSection
{
TRADE_SECTION_LEFT_INVENTORY ,
TRADE_SECTION_RIGHT_INVENTORY
}
zTTradeSection;
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
//protected:
public:
oCViewDialogStealContainer* DlgInventoryNpc ;
oCViewDialogInventory* DlgInventoryPlayer ;
zTTradeSection SectionTrade ;
oCNpc* NpcLeft ;
oCNpc* NpcRight ;
zINT TransferCount ;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
//
// HELPERS
//
protected:
void __fastcall AllDialogsDisable ( void ) {XCALL(0x0068B160)};
void __fastcall AllDialogsStop ( void ) {XCALL(0x0068B140)};
//
// GET/SET
//
public:
void __fastcall SetNpcLeft ( oCNpc* pNpc ) {XCALL(0x0068B180)};
void __fastcall SetNpcRight ( oCNpc* pNpc ) {XCALL(0x0068B290)};
//
// SELECTION
//
virtual void __fastcall StartSelection ( void ) {XCALL(0x0068B340)};
//
// GET/ SET
//
virtual zINT GetTransferCount () { return TransferCount; } ;
virtual void SetTransferCount (const zINT count) { TransferCount = count; } ;
virtual void IncTransferCount (const zINT count) { TransferCount += count; } ;
//
// EVENTS
//
public:
virtual zBOOL HandleEvent ( int nKey ) {XCALL(0x0068B3E0)};
void __fastcall Update ( void ) {XCALL(0x0068B750)};
protected:
zBOOL __fastcall OnKeyEnter ( void ) {XCALL(0x0068B770)};
zBOOL __fastcall OnKeyEsc ( void ) {XCALL(0x0068B780)};
zBOOL __fastcall OnMoveLeft ( void ) {XCALL(0x0068B790)};
zBOOL __fastcall OnMoveRight ( void ) {XCALL(0x0068BA60)};
zBOOL __fastcall OnTransferLeft ( zINT amount ) {XCALL(0x0068B840)};
zBOOL __fastcall OnTransferRight ( zINT amount ) {XCALL(0x0068BB10)};
zBOOL __fastcall OnSectionPrevious ( void ) {XCALL(0x0068BEA0)};
zBOOL __fastcall OnSectionNext ( void ) {XCALL(0x0068BF20)};
void __fastcall OnSection ( zTTradeSection enuSection ) {XCALL(0x0068BFA0)};
void __fastcall OnExit ( void ) {XCALL(0x0068C000)};
//
// CON-/DESTRUCTION
//
public:
void oViewDialogTrade (void) {XCALL(0x0068ADB0)};
oCViewDialogTrade () {oViewDialogTrade();};
virtual ~oCViewDialogTrade () {XCALL(0x0068B080)};
void UpdateViewSettings () {XCALL(0x0068AD10)};
static zCClassDef* classDef;
public:
zBOOL __fastcall OnTransferLeft_AST ( zINT amount );
zBOOL __fastcall OnTransferRight_AST ( zINT amount );
};
typedef oCViewDialogTrade *LPCViewDialogTrade, *LPCVIEWDIALOGTRADE;
//
// VIEW
//
class oCViewDialogItem : public zCViewDialog
{
public:
zCLASS(oCViewDialogItem);
static zCClassDef* classDef;
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x00689600)};
// *********************************************************************************
// ** ENUMS & STRUCTURES
// *********************************************************************************
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
protected:
oCItem* Item;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
public:
void __fastcall SetItem ( oCItem* pItem ) {XCALL(0x00689700)};
oCItem* __fastcall GetItem ( void ) { return this->Item; }
protected:
virtual void __fastcall Blit ( void ) {XCALL(0x00689740)};
//
// CON-/DESTRUCTION
//
public:
oCViewDialogItem(){oViewDialogItem();};
void oViewDialogItem(void){XCALL(0x00689610)}
virtual ~oCViewDialogItem(){XCALL(0x00689670)};
};
typedef oCViewDialogItem *LPCViewDialogItem, *LPCVIEWDIALOGITEM;
//
// VIEW
//
class oCViewDialogItemContainer : public zCViewDialog
{
public:
zCLASS(oCViewDialogItemContainer);
static zCClassDef* classDef;
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x00689A40)};
// *********************************************************************************
// ** ENUMS & STRUCTURES
// *********************************************************************************
public:
enum oEItemContainerAlignment
{
oEItemContainerAlignment_Left ,
oEItemContainerAlignment_Right
}
oTItemContainerAlignment, oTAlignmentItemContainer;
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
protected:
oCItemContainer* ItemContainer ;
oEItemContainerAlignment Alignment ;
zUINT32 Value ;
zREAL ValueMultiplier ;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
//
// GET/SET
//
public:
virtual void __fastcall Activate ( zBOOL bActive ) {XCALL(0x00689AF0)};
void __fastcall SetItemContainer ( oCItemContainer* pItemContainer ) {XCALL(0x00689B10)};
void __fastcall SetAlignment ( oEItemContainerAlignment enuAlignment ) {XCALL(0x00689B40)};
void __fastcall SetValueMultiplier ( zREAL fValueMultiplier ) { this->ValueMultiplier = fValueMultiplier ; }
oCItemContainer* __fastcall GetItemContainer ( void ) { return this->ItemContainer ; }
oEItemContainerAlignment __fastcall GetAlignment ( void ) { return this->Alignment ; }
zUINT32 __fastcall GetValue ( void ) { return this->Value ; }
zREAL __fastcall GetValueMultiplier ( void ) { return this->ValueMultiplier ; }
oCItem* __fastcall GetSelectedItem ( void ) {XCALL(0x00689B50)};
int __fastcall GetSelectedItemCount( void ) {XCALL(0x00689B70)};
oCItem* __fastcall RemoveSelectedItem ( void ) {XCALL(0x00689B90)};
void __fastcall InsertItem ( oCItem* pItem ) {XCALL(0x00689C00)};
void __fastcall TransferAllItemsTo ( oCNpcInventory* pInventory ) {XCALL(0x00689C40)};
protected:
void __fastcall RemoveItem ( oCItem* pItem ) {XCALL(0x00689C20)};
void __fastcall UpdateValue ( void ) {XCALL(0x00689D10)};
//
// INTERACTION
//
public:
virtual void __fastcall StartSelection ( void ) {XCALL(0x00689D90)};
virtual void __fastcall StopSelection ( void ) {XCALL(0x00689DF0)};
//
// EVENTS
//
public:
virtual zBOOL HandleEvent ( int nKey ) {XCALL(0x00689D40)};
zBOOL __fastcall CanHandleLeft ( void ) {XCALL(0x00689D20)};
zBOOL __fastcall CanHandleRight ( void ) {XCALL(0x00689D30)};
//
// CON-/DESTRUCTION
//
public:
void oViewDialogItemContainer(void){XCALL(0x00689A50)};
oCViewDialogItemContainer(){oViewDialogItemContainer();};
virtual ~oCViewDialogItemContainer(){XCALL(0x00689AD0)};
};
typedef oCViewDialogItemContainer *LPCViewDialogItemContainer, *LPCVIEWDIALOGITEMCONTAINER;
//
// VIEW
//
class zCViewDialogChoice : public zCViewDialog
{
public:
zCLASS(zCViewDialogChoice);
static zCClassDef* classDef;
virtual zCClassDef* _GetClassDef(void)const {XCALL(0x0068EA50)};
// *********************************************************************************
// ** ATTRIBUTES
// *********************************************************************************
protected:
zCOLOR ColorSelected ;
zCOLOR ColorGrayed ;
int ChoiceSelected ;
int Choices ;
int LineStart ;
// *********************************************************************************
// ** METHODS
// *********************************************************************************
//
// GET/SET
//
public:
void __fastcall SetColorActive ( zCOLOR& colActive ) { this->ColorSelected = colActive ; }
void __fastcall SetColorGrayed ( zCOLOR& colGrayed ) { this->ColorGrayed = colGrayed ; }
int __fastcall GetSelectedIndex ( void ) { return this->ChoiceSelected ; }
zSTRING __fastcall GetSelectedText ( void ) {XCALL(0x0068F550)};
protected:
zCViewText2* __fastcall GetSelection ( void ) {XCALL(0x0068F540)};
//
// ELEMENTS
//
public:
void __fastcall AddChoice ( zSTRING& strText, zBOOL bEnumerate = FALSE ) {XCALL(0x0068F710)};
void __fastcall RemoveChoice ( zSTRING& strText ) {XCALL(0x0068F9A0)};
void __fastcall RemoveChoice ( int nChoice ) {XCALL(0x0068F9B0)};
void __fastcall RemoveAllChoices ( void ) {XCALL(0x0068F9C0)};
//
// INTERACTION
//
public:
virtual void __fastcall StartSelection ( void ){XCALL(0x0068EF70)};
virtual void __fastcall StopSelection ( void ){XCALL(0x0068EFB0)};
//
// EVENTS
//
public:
virtual zBOOL HandleEvent ( int nKey ){XCALL(0x0068EBA0)};
//
// SELECTION
//
protected:
void __fastcall SelectPrevious ( void ){XCALL(0x0068F220)};
void __fastcall SelectNext ( void ){XCALL(0x0068F330)};
void __fastcall Select ( int nCoice ){XCALL(0x0068F440)};
void __fastcall HighlightSelected ( void ){XCALL(0x0068F620)};
void __fastcall ShowSelected ( void ){XCALL(0x0068F180)};
void __fastcall ScrollUp ( void ){XCALL(0x0068F050)};
void __fastcall ScrollDown ( void ){XCALL(0x0068F090)};
zBOOL __fastcall IsSelectedOutsideAbove ( void ){XCALL(0x0068F0D0)};
zBOOL __fastcall IsSelectedOutsideBelow ( void ){XCALL(0x0068F0F0)};
//
// RENDER
//
virtual void __fastcall BlitText ( void ){XCALL(0x0068EFE0)};
//
// CON-/DESTRUCTION
//
public:
void zViewDialogChoice(void){XCALL(0x0068EA60)};
zCViewDialogChoice(){zViewDialogChoice();};
virtual ~zCViewDialogChoice(){XCALL(0x0068EAE0)};
};
typedef zCViewDialogChoice *LPCViewDialogChoice, *LPCVIEWDIALOGCHOICE; | [
"Siemaczy1@gmail.com"
] | Siemaczy1@gmail.com |
619779ff51b11156c08f9fd68c3d14e71b84405d | 4da55187c399730f13c5705686f4b9af5d957a3f | /src/webots/scene_tree/WbPhysicsViewer.cpp | 0a5879b4998dca492ec3ecd6148de49c1ee2f0fa | [
"Apache-2.0"
] | permissive | Ewenwan/webots | 7111c5587100cf35a9993ab923b39b9e364e680a | 6b7b773d20359a4bcf29ad07384c5cf4698d86d3 | refs/heads/master | 2020-04-17T00:23:54.404153 | 2019-01-16T13:58:12 | 2019-01-16T13:58:12 | 166,048,591 | 2 | 0 | Apache-2.0 | 2019-01-16T13:53:50 | 2019-01-16T13:53:50 | null | UTF-8 | C++ | false | false | 11,270 | cpp | // Copyright 1996-2018 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WbPhysicsViewer.hpp"
#include "WbGuiRefreshOracle.hpp"
#include "WbSolid.hpp"
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
WbPhysicsViewer::WbPhysicsViewer(QWidget *parent) :
QWidget(parent),
mSolid(NULL),
mIsSelected(false),
mIncludingExcludingDescendants(new QComboBox(this)),
mRelativeAbsolute(new QComboBox(this)),
mMassLabel(new QLabel(this)),
mDensityLabel(new QLabel(this)),
mInertiaMatrixMainLabel(new QLabel(tr("inertia matrix:"), this)) {
void (QComboBox::*indexChangedSignal)(int) = &QComboBox::currentIndexChanged;
QGridLayout *gridLayout = new QGridLayout(this);
mIncludingExcludingDescendants->setMinimumHeight(mIncludingExcludingDescendants->sizeHint().height());
mIncludingExcludingDescendants->insertItem(0, tr("excluding descendants"));
mIncludingExcludingDescendants->insertItem(1, tr("including descendants"));
mIncludingExcludingDescendants->setToolTip(tr("Display mass properties of the selected solid only"));
gridLayout->addWidget(mIncludingExcludingDescendants, 0, 2, 1, 3, Qt::AlignVCenter);
connect(mIncludingExcludingDescendants, indexChangedSignal, this, &WbPhysicsViewer::updateIncludingExcludingDescendantsData);
// Mass
QLabel *label = new QLabel(tr("mass:"), this);
mMassLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
gridLayout->addWidget(label, 1, 0, 1, 2, Qt::AlignVCenter);
gridLayout->addWidget(mMassLabel, 1, 2, 1, 3, Qt::AlignVCenter);
// Density
label = new QLabel(tr("density:"), this);
mDensityLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
gridLayout->addWidget(label, 2, 0, 1, 2, Qt::AlignVCenter);
gridLayout->addWidget(mDensityLabel, 2, 2, 1, 3, Qt::AlignVCenter);
// Center of mass
label = new QLabel("CoM:", this);
label->setToolTip("Solid's center of mass");
QLabel *valueLabel = NULL;
for (int i = 0; i < 3; ++i) {
valueLabel = new QLabel(this);
valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
mCenterOfMassLabel.append(valueLabel);
}
mRelativeAbsolute->setMinimumHeight(mRelativeAbsolute->sizeHint().height());
mRelativeAbsolute->setToolTip(tr("Coordinates relative to selected's solid frame"));
connect(mRelativeAbsolute, indexChangedSignal, this, &WbPhysicsViewer::updateCoordinatesSystem);
gridLayout->addWidget(label, 3, 0, Qt::AlignVCenter);
gridLayout->addWidget(mRelativeAbsolute, 3, 1, Qt::AlignVCenter);
gridLayout->addWidget(mCenterOfMassLabel[0], 3, 2, Qt::AlignVCenter);
gridLayout->addWidget(mCenterOfMassLabel[1], 3, 3, Qt::AlignVCenter);
gridLayout->addWidget(mCenterOfMassLabel[2], 3, 4, Qt::AlignVCenter);
// Inertia matrix
mInertiaMatrixMainLabel->setToolTip("Inertia matrix expressed within the solid frame centered at CoM");
for (int i = 0; i < 9; ++i) {
valueLabel = new QLabel(this);
valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
mInertiaMatrixLabel.append(valueLabel);
}
gridLayout->addWidget(mInertiaMatrixLabel[0], 4, 2, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[1], 4, 3, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[2], 4, 4, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixMainLabel, 5, 0, 1, 2, Qt::AlignTop);
gridLayout->addWidget(mInertiaMatrixLabel[3], 5, 2, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[4], 5, 3, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[5], 5, 4, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[6], 6, 2, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[7], 6, 3, Qt::AlignVCenter);
gridLayout->addWidget(mInertiaMatrixLabel[8], 6, 4, Qt::AlignVCenter);
// Set labels to be modified by the main stylesheet
mInertiaMatrixLabel[0]->setObjectName("inertiaMatrixDiagonalCoefficientLabel");
mInertiaMatrixLabel[4]->setObjectName("inertiaMatrixDiagonalCoefficientLabel");
mInertiaMatrixLabel[8]->setObjectName("inertiaMatrixDiagonalCoefficientLabel");
mInertiaMatrixLabel[1]->setObjectName("inertiaMatrixPrimaryCoefficientLabel");
mInertiaMatrixLabel[2]->setObjectName("inertiaMatrixPrimaryCoefficientLabel");
mInertiaMatrixLabel[5]->setObjectName("inertiaMatrixPrimaryCoefficientLabel");
mInertiaMatrixLabel[3]->setObjectName("inertiaMatrixSecondaryCoefficientLabel");
mInertiaMatrixLabel[6]->setObjectName("inertiaMatrixSecondaryCoefficientLabel");
mInertiaMatrixLabel[7]->setObjectName("inertiaMatrixSecondaryCoefficientLabel");
gridLayout->setColumnStretch(0, 0);
gridLayout->setColumnStretch(1, 0);
gridLayout->setColumnStretch(2, 1);
gridLayout->setColumnStretch(3, 1);
gridLayout->setColumnStretch(4, 1);
mRelativeAbsolute->insertItem(0, tr("relative"));
mRelativeAbsolute->insertItem(1, tr("absolute"));
}
WbPhysicsViewer::~WbPhysicsViewer() {
mSolid = NULL;
}
void WbPhysicsViewer::clean() {
mSolid = NULL;
}
void WbPhysicsViewer::stopUpdating() {
if (mSolid) {
disconnect(mSolid, &WbSolid::massPropertiesChanged, this, &WbPhysicsViewer::update);
disconnect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this,
&WbPhysicsViewer::updateCenterOfMass);
disconnect(mSolid, &WbSolid::positionChangedArtificially, this, &WbPhysicsViewer::updateCenterOfMass);
}
}
void WbPhysicsViewer::show(WbSolid *solid) {
mSolid = solid;
if (mSolid)
connect(mSolid, &WbSolid::destroyed, this, &WbPhysicsViewer::clean, Qt::UniqueConnection);
if (mSolid && mIsSelected) {
connect(mSolid, &WbSolid::massPropertiesChanged, this, &WbPhysicsViewer::update, Qt::UniqueConnection);
connect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPhysicsViewer::updateCenterOfMass,
Qt::UniqueConnection);
connect(mSolid, &WbSolid::positionChangedArtificially, this, &WbPhysicsViewer::updateCenterOfMass, Qt::UniqueConnection);
}
}
bool WbPhysicsViewer::update() {
bool enabled = mSolid && (mSolid->globalMass() > 0.0);
if (mIsSelected && enabled && mSolid->areOdeObjectsCreated()) {
updateMass();
updateDensity();
updateCenterOfMass();
updateInertiaMatrix();
return enabled;
}
mMassLabel->clear();
mDensityLabel->clear();
for (int i = 0; i < 9; ++i)
mInertiaMatrixLabel[i]->clear();
for (int j = 0; j < 3; ++j)
mCenterOfMassLabel[j]->clear();
return enabled;
}
void WbPhysicsViewer::updateMass() {
const double lm = mSolid->mass();
const double gm = mSolid->globalMass();
if (gm > 0.0) {
const double currentMass = mIncludingExcludingDescendants->currentIndex() == LOCAL ? lm : gm;
mMassLabel->setText(QString("%1 kg").arg(WbPrecision::doubleToString(currentMass, WbPrecision::GUI_MEDIUM)));
} else
mMassLabel->clear();
}
void WbPhysicsViewer::updateDensity() {
const double d = mSolid->density();
const double ad = mSolid->averageDensity();
if (ad >= 0.0) {
const double currentDensity = mIncludingExcludingDescendants->currentIndex() == LOCAL ? d : ad;
mDensityLabel->setText(QString("%1 kg/m^3").arg(WbPrecision::doubleToString(currentDensity, WbPrecision::GUI_MEDIUM)));
} else
mDensityLabel->clear();
}
void WbPhysicsViewer::updateCenterOfMass() {
bool skipUpdate = WbGuiRefreshOracle::instance()->canRefreshNow() == false;
skipUpdate |= !mIsSelected || (!mSolid) || mSolid->areOdeObjectsCreated() == false;
if (skipUpdate)
return;
mSolid->updateGlobalCenterOfMass();
mCenterOfMass[LOCAL][RELATIVE] = mSolid->centerOfMass();
const WbMatrix4 &m = mSolid->matrix();
mCenterOfMass[LOCAL][ABSOLUTE] = m * mSolid->centerOfMass();
mCenterOfMass[GLOBAL][ABSOLUTE] = mSolid->globalCenterOfMass();
const double s = 1.0 / mSolid->absoluteScale().x();
mCenterOfMass[GLOBAL][RELATIVE] = m.pseudoInversed(mCenterOfMass[GLOBAL][ABSOLUTE]) * (s * s);
if (mSolid->globalMass() != 0.0) {
const WbVector3 &com = mCenterOfMass[mIncludingExcludingDescendants->currentIndex()][mRelativeAbsolute->currentIndex()];
for (int i = 0; i < 3; ++i)
mCenterOfMassLabel[i]->setText(WbPrecision::doubleToString(com[i], WbPrecision::GUI_MEDIUM));
} else {
for (int i = 0; i < 3; ++i)
mCenterOfMassLabel[i]->clear();
}
}
void WbPhysicsViewer::updateInertiaMatrix() {
if (mSolid->mass() != 0.0 && (mIncludingExcludingDescendants->currentIndex() == LOCAL)) {
mInertiaMatrixMainLabel->setText(tr("Inertia matrix:"));
const double *const I = mSolid->inertiaMatrix();
for (int i = 0; i < 3; ++i) {
mInertiaMatrixLabel[i]->setText(WbPrecision::doubleToString(I[i], WbPrecision::GUI_MEDIUM));
mInertiaMatrixLabel[i + 3]->setText(WbPrecision::doubleToString(I[i + 4], WbPrecision::GUI_MEDIUM));
mInertiaMatrixLabel[i + 6]->setText(WbPrecision::doubleToString(I[i + 8], WbPrecision::GUI_MEDIUM));
}
} else {
for (int i = 0; i < 9; ++i)
mInertiaMatrixLabel[i]->clear();
mInertiaMatrixMainLabel->clear();
}
}
void WbPhysicsViewer::setSelected(bool selected) {
mIsSelected = selected;
triggerPhysicsUpdates();
}
void WbPhysicsViewer::triggerPhysicsUpdates() {
if (mSolid == NULL)
return;
if (mIsSelected) {
connect(mSolid, &WbSolid::massPropertiesChanged, this, &WbPhysicsViewer::update, Qt::UniqueConnection);
connect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPhysicsViewer::updateCenterOfMass,
Qt::UniqueConnection);
connect(mSolid, &WbSolid::positionChangedArtificially, this, &WbPhysicsViewer::updateCenterOfMass, Qt::UniqueConnection);
update();
} else {
disconnect(mSolid, &WbSolid::massPropertiesChanged, this, &WbPhysicsViewer::update);
disconnect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this,
&WbPhysicsViewer::updateCenterOfMass);
disconnect(mSolid, &WbSolid::positionChangedArtificially, this, &WbPhysicsViewer::updateCenterOfMass);
}
}
void WbPhysicsViewer::updateCoordinatesSystem() {
if (mRelativeAbsolute->currentIndex() == RELATIVE)
mRelativeAbsolute->setToolTip(tr("Coordinates with respect to selected's solid frame"));
else
mRelativeAbsolute->setToolTip(tr("Coordinates with respect to world's frame"));
updateCenterOfMass();
}
void WbPhysicsViewer::updateIncludingExcludingDescendantsData() {
if (mIncludingExcludingDescendants->currentIndex() == LOCAL)
mIncludingExcludingDescendants->setToolTip(tr("Display mass properties of the selected solid only"));
else
mIncludingExcludingDescendants->setToolTip(
tr("Display averaged mass properties of the selected solid augmented by its descendants"));
update();
}
| [
"David.Mansolino@cyberbotics.com"
] | David.Mansolino@cyberbotics.com |
090ed8df211ea917d5ebb6482f2098cd943c0b94 | 966715244b0f937e48305f2753ebde5544809325 | /src/exception.cpp | 92b0ddeee0235c8e95317f51cfceac6ca14fb683 | [
"MIT"
] | permissive | DlinkLang/Dlink | 970569fb4e0be8bdf79948e418178ef3e110137c | bbe36adf3f1591bd27ad6edcd45d5ad33fcb1781 | refs/heads/master | 2020-03-22T20:09:47.423408 | 2018-11-19T12:13:39 | 2018-11-19T12:14:19 | 140,577,462 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp | #include <Dlink/exception.hpp>
namespace dlink
{
invalid_state::invalid_state(const std::string_view& message)
: std::runtime_error(message.data())
{}
} | [
"kmc7468@naver.com"
] | kmc7468@naver.com |
5399550224838582615dee2ba8c44d38d65b3c4d | 4e5c394c33f0a8adf0152742f01aebb5755c4581 | /code/sunlight/Config.h | c31547b90ac3ff6119a20641c9ee24672f7c74d6 | [] | no_license | dennistimmermann/iot-sunlight | f13ddcdd8e8f4020219feb0b19088491580068ec | 78380c1213bea326bfebce8c9d1ee61d1aa73e06 | refs/heads/master | 2021-01-01T05:11:36.027448 | 2016-05-30T10:04:42 | 2016-05-30T10:04:42 | 59,310,198 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,485 | h | #ifndef H_CONFIG
#define H_CONFIG
#include "Arduino.h"
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#define EEPROM_SSID 0
#define EEPROM_PASS 128
#define EEPROM_LAT 256
#define EEPROM_LON 384
const char HTTP_START[] PROGMEM = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title><style media=\"screen\">body{font-family:Arial Helvetica,sans-serif;text-align:center;color:#4e4e4e;}*{margin:2px;}</style></head><body>";
const char HTTP_END[] PROGMEM = "</body></html>";
const char SETUP_START[] PROGMEM = "<h1>FROM DAWN TILL DUSK</h1><form action=\"save\">";
const char SETUP_INPUT[] PROGMEM = "<div>{n}</div><input type=\"text\" name=\"{p}\" value=\"{v}\"><br>";
//const char SETUP_INPUT2 PROGMEM = "</div><input type=\"text\" name=\"";
//const char SETUP_INPUT3 PROGMEM = "\" value=\"";
//const char SETUP_INPUT4 PROGMEM = "\"><br>";
//const char SETUP_START[] PROGMEM = "<h1>FROM DAWN TILL DUSK</h1><form action=\"save\">";
const char SETUP_END[] PROGMEM = "<input type=\"submit\" value=\"SAVE\"></form>";
//ESP8266WebServer server(80);
class Config {
public:
void begin();
void handleRoot();
void handleSave();
void startAP(const char* ssid, const char* password);
void loop();
String getValue(int start);
void saveValue(int start, String value);
private:
String _ssid = "";
String _pass = "";
String _lat = "";
String _lon = "";
};
#endif H_CONFIG
| [
"timmermann.dennis@googlemail.com"
] | timmermann.dennis@googlemail.com |
f3a45a1b9897b446183c2ff15b6a7a0ce0005f9b | 4002b5b53ec36b42c393dbbcea1c0baa4c64e202 | /onlineml/classifiers/perceptron.h | ffed6db32cda2abf2b2f22bc7b35bfc339f7a86f | [
"MIT"
] | permissive | tma15/onlineml | 0dda6188807d64addb68c01b82ff0a3bd06d5733 | 4094e3f36f96671b2492b86341984689a27b1e7e | refs/heads/master | 2021-01-11T00:01:40.016719 | 2020-08-23T06:38:38 | 2020-08-23T06:38:38 | 59,888,293 | 1 | 0 | NOASSERTION | 2020-08-16T06:47:00 | 2016-05-28T09:59:37 | C++ | UTF-8 | C++ | false | false | 643 | h | #pragma once
#include "../classifier.h"
#include "../parameter.h"
namespace onlineml {
class Perceptron : public OnlineMLClassifier {
public:
Perceptron() {}
Perceptron(unsigned input_size, unsigned output_size)
: input_size_(input_size), output_size_(output_size) {
weight_ = Tensor({output_size, input_size});
}
float fit(const LabeledSparseVector &data);
unsigned predict(const SparseVector &vec);
void save(const std::string &file_name);
void load(const std::string &file_name);
private:
unsigned input_size_;
unsigned output_size_;
Tensor weight_;
};
} // namespace onlineml
| [
"takuyamakino15@gmail.com"
] | takuyamakino15@gmail.com |
2037d0159f895a61ac09d6a186844694a8ab0081 | d508027427b9a11a6bab0722479ee8d7b7eda72b | /3rd/include/3dsmax2010sdk/simpspl.h | 16872042b1f005263daf990e4685a42cca062ce5 | [] | no_license | gaoyakun/atom3d | 421bc029ee005f501e0adb6daed778662eb73bac | 129adf3ceca175faa8acf715c05e3c8f099399fe | refs/heads/master | 2021-01-10T18:28:50.562540 | 2019-12-06T13:17:00 | 2019-12-06T13:17:00 | 56,327,530 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,703 | h | //**************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// FILE: simpspl.h
// DESCRIPTION: Defines a simple spline object class to make spline
// primitives easier to create
// AUTHOR: Tom Hudson
// HISTORY: created 3 October 1995
//**************************************************************************/
#ifndef __SIMPSPL_H__
#define __SIMPSPL_H__
// Interpolation parameter block indices
#define IPB_STEPS 0
#define IPB_OPTIMIZE 1
#define IPB_ADAPTIVE 2
// Parameter block reference indices
// IMPORTANT: Reference #0 is ShapeObject's parameter block! (Starting with MAXr4)
#define SHAPEOBJPBLOCK 0 // ShapeObject's parameter block
#define USERPBLOCK SHAPE_OBJ_NUM_REFS // User's parameter block
#define IPBLOCK (SHAPE_OBJ_NUM_REFS + 1) // Interpolations parameter block
// Default interpolation settings
#define DEF_STEPS 6
#define DEF_OPTIMIZE TRUE
#define DEF_ADAPTIVE FALSE
#define DEF_RENDERABLE FALSE
#define DEF_DISPRENDERMESH FALSE
//#define DEF_USEVIEWPORT FALSE
#define DEF_RENDERABLE_THICKNESS 1.0f
#define DEF_RENDERABLE_SIDES 12
#define DEF_RENDERABLE_ANGLE 0.0f
#define DEF_GENUVS FALSE
// Special dialog handling
class SimpleSpline;
class SimpleSplineDlgProc : public ParamMapUserDlgProc {
private:
SimpleSpline *spl;
public:
SimpleSplineDlgProc(SimpleSpline *s) { spl = s; }
CoreExport INT_PTR DlgProc(TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);
CoreExport void DeleteThis();
};
/*! \sa Class ShapeObject.\n\n
\par Description:
Defines a simple spline object class to make spline primitives easier to
create. This class provides default implementations for most of the
<b>ShapeObject</b> methods. The plug-in derived from <b>SimpleSpline</b> must
only implement a handful of methods to create a shape plug-in.\n\n
SimpleSpline plug-ins use a Super Class ID of <b>SHAPE_CLASS_ID</b>.
\par Data Members:
<b>IParamBlock *ipblock;</b>\n\n
Interpolation parameter block (handled by <b>SimpleSpline</b>).\n\n
<b>IParamBlock *pblock;</b>\n\n
User's parameter block. See Class IParamBlock.\n\n
<b>static IParamMap *ipmapParam;</b>\n\n
The parameter map. See Class IParamMap.\n\n
<b>static int dlgSteps;</b>\n\n
The dialog steps settings.\n\n
<b>static BOOL dlgOptimize;</b>\n\n
The dialog Optimize toggle.\n\n
<b>static BOOL dlgAdaptive;</b>\n\n
The dialog Adaptive toggle.\n\n
<b>BezierShape shape;</b>\n\n
The Spline cache.\n\n
<b>Interval ivalid;</b>\n\n
The validity interval for the spline. See Class Interval.\n\n
<b>BOOL suspendSnap;</b>\n\n
Flag to suspend snapping used during creation.\n\n
<b>static SimpleSpline *editOb;</b>\n\n
This is the spline being edited in the command panel. */
class SimpleSpline: public ShapeObject {
private:
public:
IParamBlock *ipblock; // Interpolation parameter block (handled by SimpleSpline)
IParamBlock *pblock; // User's parameter block
static IParamMap *ipmapParam;
static int dlgSteps;
static BOOL dlgOptimize;
static BOOL dlgAdaptive;
// Spline cache
BezierShape shape;
Interval ivalid;
// Flag to suspend snapping -- Used during creation
BOOL suspendSnap;
CoreExport void UpdateShape(TimeValue t);
static SimpleSpline *editOb;
/*! \remarks Constructor. The validity interval is set to empty, and
the pblocks are set to NULL. */
CoreExport SimpleSpline();
/*! \remarks Destructor.\n\n
Clients of SimpleSpline need to implement these methods: */
CoreExport ~SimpleSpline();
void ShapeInvalid() { ivalid.SetEmpty(); }
// inherited virtual methods:
// From BaseObject
CoreExport int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt);
CoreExport void Snap(TimeValue t, INode* inode, SnapInfo *snap, IPoint2 *p, ViewExp *vpt);
CoreExport int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags);
CoreExport virtual void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev);
/*! \remarks This method is called when the user is finished editing object's
parameters. The system passes a flag into the <b>EndEditParams()</b>
method to indicate if the rollup page should be removed. If this flag
is TRUE, the plug-in must un-register the rollup page, and delete it
from the panel.
\par Parameters:
<b>IObjParam *ip</b>\n\n
This is an interface pointer passed in. The developer may use the
interface pointer to call methods such as
<b>DeleteRollupPage()</b>.\n\n
<b>ULONG flags</b>\n\n
The following flag may be set:\n\n
<b>END_EDIT_REMOVEUI</b>\n\n
If TRUE, the item's user interface should be removed.\n\n
<b>Animatable *next</b>\n\n
This parameter may be used in the motion and hierarchy branches of the
command panel. This pointer allows a plug-in to look at the ClassID of
the next item that was being edited, and if it is the same as this
item, to not replace the entire UI in the command panel. Note that for
items that are edited in the modifier branch this field can be ignored.
*/
CoreExport virtual void EndEditParams( IObjParam *ip, ULONG flags,Animatable *next);
IParamArray *GetParamBlock() {return pblock;}
CoreExport int GetParamBlockIndex(int id);
// From Object
CoreExport ObjectState Eval(TimeValue time);
CoreExport Interval ObjectValidity(TimeValue t);
CoreExport int CanConvertToType(Class_ID obtype);
CoreExport Object* ConvertToType(TimeValue t, Class_ID obtype);
CoreExport void GetCollapseTypes(Tab<Class_ID> &clist,Tab<MSTR*> &nlist);
CoreExport void BuildMesh(TimeValue t, Mesh &mesh);
// From ShapeObject
CoreExport ObjectHandle CreateTriObjRep(TimeValue t); // for rendering, also for deformation
CoreExport void GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box );
CoreExport void GetLocalBoundBox(TimeValue t, INode* inode, ViewExp* vxt, Box3& box );
CoreExport void GetDeformBBox(TimeValue t, Box3& box, Matrix3 *tm, BOOL useSel );
CoreExport int NumberOfVertices(TimeValue t, int curve);
CoreExport int NumberOfCurves();
CoreExport BOOL CurveClosed(TimeValue t, int curve);
CoreExport Point3 InterpCurve3D(TimeValue t, int curve, float param, int ptype=PARAM_SIMPLE);
CoreExport Point3 TangentCurve3D(TimeValue t, int curve, float param, int ptype=PARAM_SIMPLE);
CoreExport float LengthOfCurve(TimeValue t, int curve);
CoreExport int NumberOfPieces(TimeValue t, int curve);
CoreExport Point3 InterpPiece3D(TimeValue t, int curve, int piece, float param, int ptype=PARAM_SIMPLE);
CoreExport Point3 TangentPiece3D(TimeValue t, int curve, int piece, float param, int ptype=PARAM_SIMPLE);
CoreExport MtlID GetMatID(TimeValue t, int curve, int piece);
BOOL CanMakeBezier() { return TRUE; } // Return TRUE if can turn into a bezier representation
CoreExport void MakeBezier(TimeValue t, BezierShape &shape); // Create the bezier representation
CoreExport ShapeHierarchy &OrganizeCurves(TimeValue t, ShapeHierarchy *hier=NULL); // Ready for lofting, extrusion, etc.
CoreExport void MakePolyShape(TimeValue t, PolyShape &shape, int steps = PSHAPE_BUILTIN_STEPS, BOOL optimize = FALSE);
CoreExport int MakeCap(TimeValue t, MeshCapInfo &capInfo, int capType); // Makes a cap out of the shape
CoreExport int MakeCap(TimeValue t, PatchCapInfo &capInfo);
int NumRefs() { return 2 + ShapeObject::NumRefs();}
CoreExport RefTargetHandle GetReference(int i);
CoreExport void SetReference(int i, RefTargetHandle rtarg);
CoreExport RefResult NotifyRefChanged(Interval changeInt,RefTargetHandle hTarget,
PartID& partID, RefMessage message);
CoreExport void ReadyInterpParameterBlock();
void UnReadyInterpParameterBlock() { ipblock = NULL; }
// When clients are cloning themselves, they should call this
// method on the clone to copy SimpleSpline's data.
// NOTE: DEPRECATED! Use SimpleSplineClone(SimpleSpline *ssplSource, RemapDir& remap )
CoreExport void SimpleSplineClone( SimpleSpline *ssplSource );
// When clients are cloning themselves, they should call this
// method on the clone to copy SimpleSpline's data.
CoreExport void SimpleSplineClone( SimpleSpline *ssplSource, RemapDir& remap );
int NumSubs() { return 2 + ShapeObject::NumSubs(); }
CoreExport Animatable* SubAnim(int i);
CoreExport MSTR SubAnimName(int i);
// Animatable methods
CoreExport void DeleteThis();
CoreExport void FreeCaches();
// IO
CoreExport IOResult Save(ISave *isave);
CoreExport IOResult Load(ILoad *iload);
LRESULT CALLBACK TrackViewWinProc( HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam ){return(0);}
/*! \remarks Retrieves the name of the plug-in class. This is used internally for
debugging purposes.
\par Parameters:
<b>MSTR\& s</b>\n\n
The name is stored here. */
void GetClassName(MSTR& s) {s = GetObjectName();}
/*! \remarks This method retrieves the default name of the node when it is created.
\par Parameters:
<b>MSTR\& s</b>\n\n
The name is stored here. */
void InitNodeName(MSTR& s) {s = GetObjectName();}
// Clients of SimpleSpline need to implement these methods:
/*! \remarks Returns the unique Class_ID of the plug-in. See
Class Class_ID for more details. */
virtual Class_ID ClassID() = 0;
/*! \remarks This method is called to build the shape at the specified time and
store the results in <b>ashape</b>.
\par Parameters:
<b>TimeValue t</b>\n\n
The time to build the shape.\n\n
<b>BezierShape\& ashape</b>\n\n
The created shape is store here. */
virtual void BuildShape(TimeValue t,BezierShape& ashape) = 0;
/*! \remarks This method is called to have the plug-in clone itself.
The plug-in should clone all its references as well.
\par Parameters:
<b>RemapDir \&remap = DefaultRemapDir()</b>\n\n
This class is used for remapping references during a Clone.
\see class RemapDir, class DefaultRemapDir
\return A pointer to the cloned item. */
virtual RefTargetHandle Clone(RemapDir& remap = DefaultRemapDir()) = 0;
/*! \remarks This method allows the system to retrieve a callback object used in
creating the shape in the 3D viewports. This method returns a pointer
to an instance of a class derived from <b>CreateMouseCallBack</b>. This
class has a method <b>proc()</b> which is where the developer defines
the user/mouse interaction used during the shape creation phase.
\return A pointer to an instance of a class derived from
CreateMouseCallBack. */
virtual CreateMouseCallBack* GetCreateMouseCallBack() = 0;
/*! \remarks Returns TRUE if it is okay to display the shape at the time passed;
otherwise FALSE. Certain shapes may not want to be displayed at a
certain time, for example if their size goes to zero at some point.
\par Parameters:
<b>TimeValue t</b>\n\n
The time to check. */
virtual BOOL ValidForDisplay(TimeValue t) = 0;
/*! \remarks This is called if the user interface parameters needs to be updated
because the user moved to a new time. The UI controls must display
values for the current time.\n\n
If the plug-in uses a parameter map for handling its UI, it may call a
method of the parameter map to handle this:
<b>ipmapParam-\>Invalidate();</b>\n\n
If the plug-in does not use parameter maps, it should call the
<b>SetValue()</b> method on each of its controls that display a value,
for example the spinner controls. This will cause to the control to
update the value displayed. The code below shows how this may be done
for a spinner control. Note that <b>ip</b> and <b>pblock</b> are
assumed to be initialized interface and parameter block pointers\n\n
<b>(IObjParam *ip, IParamBlock *pblock).</b>\n\n
<b>float newval;</b>\n\n
<b>Interval valid=FOREVER;</b>\n\n
<b>TimeValue t=ip-\>GetTime();</b>\n\n
<b>// Get the value from the parameter block at the current
time.</b>\n\n
<b>pblock-\>GetValue( PB_ANGLE, t, newval, valid );</b>\n\n
<b>// Set the value. Note that the notify argument is passed as
FALSE.</b>\n\n
<b>// This ensures no messages are sent when the value changes.</b>\n\n
<b>angleSpin-\>SetValue( newval, FALSE );</b> */
virtual void InvalidateUI() {}
/*! \remarks This method returns the parameter dimension of the parameter whose
index is passed.
\par Parameters:
<b>int pbIndex</b>\n\n
The index of the parameter to return the dimension of.
\return Pointer to a ParamDimension. See
Class ParamDimension.
\par Default Implementation:
<b>{return defaultDim;}</b> */
virtual ParamDimension *GetParameterDim(int pbIndex) {return defaultDim;}
/*! \remarks Returns the name of the parameter whose index is passed.
\par Parameters:
<b>int pbIndex</b>\n\n
The index into the parameter block of the parameter to return the name
of.
\par Default Implementation:
<b>{return MSTR(_M("Parameter"));}</b> */
virtual MSTR GetParameterName(int pbIndex) {return MSTR(_M("Parameter"));}
/*! \remarks Returns TRUE if the Simple Spline should display vertex
ticks during its creation; otherwise FALSE.
\par Default Implementation:
<b>{ return TRUE; }</b> */
virtual BOOL DisplayVertTicksDuringCreation() { return TRUE; }
};
#endif // __SIMPSPL_H__
| [
"80844871@qq.com"
] | 80844871@qq.com |
b7e388cfa20ca80cb97d25806b080cb629ebc158 | ec6329672c8df1721cd59506658a3bcae2c8816d | /test_9_18_1/test_9_18_1/test1.cpp | a5fa5b6be366174d335551f06402898ef6eb42f4 | [] | no_license | luchunabf/initial | b78257ab343726a0e299c255a3d655dede961767 | 6682de0eda8380cfd5b28b66314d9c2a1c485fa1 | refs/heads/master | 2020-05-06T13:25:57.919237 | 2019-10-11T12:59:31 | 2019-10-11T12:59:31 | 180,136,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
//#include <string.h>
using namespace std;
class Person
{
public:
virtual void Tacket()
{
cout << "Person" << endl;
}
//private:
// int _data;
};
class Student : public Person
{
public:
virtual void Tacket()
{
cout << "Student" << endl;
}
};
void Func(Person& p)
{
p.Tacket();
}
int main()
{
/*Person p;
Person* p1 = &p;
p1->Tacket();
Student s;
p1 = &s;
p1->Tacket();*/
Person p;
Func(p);
Student s;
Func(s);
return 0;
} | [
"luchunabf@163.com"
] | luchunabf@163.com |
5d794f06d2d380661c92aba67a4ce4f96d7f903b | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/numeric/odeint/integrate/observer_collection.hpp | 97d9bb2222dfd4279973df994cf92ce1c9eba732 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:ce00dcf23b03417f7cdc7a8bcab17e383cba6158df3aa13ae9c2d65753b4b924
size 1375
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
cc2198223ed9514cabbc254835159db1ee26b9ea | 0bf5a4f159e45546ec3e9b094608e3e4439608a7 | /CCF CSP/201703-4. 地铁修建.cpp | b4952cffa0666168ac2e4c6806e003df9285ae7f | [
"ICU"
] | permissive | richenyunqi/CCF-CSP-and-PAT-solution | 4178694c8b213cf2aeb51f0846e99e7d47863d4a | 4e12e2dbe9a3822e357ba98799d82700f46beb24 | refs/heads/master | 2023-09-02T12:49:32.328292 | 2022-05-14T08:37:48 | 2022-05-14T08:37:48 | 162,964,774 | 668 | 118 | null | 2022-05-14T08:39:08 | 2018-12-24T07:45:38 | C++ | UTF-8 | C++ | false | false | 1,091 | cpp | #include <bits/stdc++.h>
using namespace std;
using gg = long long;
struct Edge { //边的类,存储两个端点u,v和边的权值cost
gg u, v, cost;
Edge(gg up, gg vp, gg cp) : u(up), v(vp), cost(cp) {}
};
vector<Edge> edges; //存储所有的边
vector<gg> ufs(1e5 + 5); //并查集
gg findRoot(gg x) { return ufs[x] == x ? x : ufs[x] = findRoot(ufs[x]); }
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
gg ni, mi;
cin >> ni >> mi;
while (mi--) {
gg ai, bi, ci;
cin >> ai >> bi >> ci;
edges.push_back(Edge(ai, bi, ci));
}
iota(ufs.begin(), ufs.end(), 0);
gg cost = 0; //存储最长边的长度
sort(edges.begin(), edges.end(),
[](const Edge& e1, const Edge& e2) { return e1.cost < e2.cost; });
for (gg i = 0; i < edges.size() and findRoot(1) != findRoot(ni); ++i) {
gg ua = findRoot(edges[i].u), ub = findRoot(edges[i].v);
if (ua != ub) {
cost = max(cost, edges[i].cost); //更新最长边
ufs[ua] = ub;
}
}
cout << cost;
return 0;
} | [
"csjiangfeng@gmail.com"
] | csjiangfeng@gmail.com |
e666e3b3044aa153d59f95050448d13b6af611e3 | 887f3a72757ff8f691c1481618944b727d4d9ff5 | /third_party/gecko_1.9.2/win32/gecko_sdk/include/nsIContentPrefService.h | ce6d81d8d96cba7c3f21a5a20d7b824e55e154dd | [] | no_license | zied-ellouze/gears | 329f754f7f9e9baa3afbbd652e7893a82b5013d1 | d3da1ed772ed5ae9b82f46f9ecafeb67070d6899 | refs/heads/master | 2020-04-05T08:27:05.806590 | 2015-09-03T13:07:39 | 2015-09-03T13:07:39 | 41,813,794 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,197 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.2-win32-xulrunner/build/toolkit/components/contentprefs/public/nsIContentPrefService.idl
*/
#ifndef __gen_nsIContentPrefService_h__
#define __gen_nsIContentPrefService_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIVariant; /* forward declaration */
class nsIURI; /* forward declaration */
class nsIPropertyBag2; /* forward declaration */
class nsIContentURIGrouper; /* forward declaration */
class mozIStorageConnection; /* forward declaration */
/* starting interface: nsIContentPrefObserver */
#define NS_ICONTENTPREFOBSERVER_IID_STR "746c7a02-f6c1-4869-b434-7c8b86e60e61"
#define NS_ICONTENTPREFOBSERVER_IID \
{0x746c7a02, 0xf6c1, 0x4869, \
{ 0xb4, 0x34, 0x7c, 0x8b, 0x86, 0xe6, 0x0e, 0x61 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIContentPrefObserver : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONTENTPREFOBSERVER_IID)
/**
* Called when a content pref is set to a different value.
*
* @param aGroup the group to which the pref belongs, or null
* if it's a global pref (applies to all URIs)
* @param aName the name of the pref that was set
* @param aValue the new value of the pref
*/
/* void onContentPrefSet (in AString aGroup, in AString aName, in nsIVariant aValue); */
NS_SCRIPTABLE NS_IMETHOD OnContentPrefSet(const nsAString & aGroup, const nsAString & aName, nsIVariant *aValue) = 0;
/**
* Called when a content pref is removed.
*
* @param aGroup the group to which the pref belongs, or null
* if it's a global pref (applies to all URIs)
* @param aName the name of the pref that was removed
*/
/* void onContentPrefRemoved (in AString aGroup, in AString aName); */
NS_SCRIPTABLE NS_IMETHOD OnContentPrefRemoved(const nsAString & aGroup, const nsAString & aName) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIContentPrefObserver, NS_ICONTENTPREFOBSERVER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICONTENTPREFOBSERVER \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefSet(const nsAString & aGroup, const nsAString & aName, nsIVariant *aValue); \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefRemoved(const nsAString & aGroup, const nsAString & aName);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICONTENTPREFOBSERVER(_to) \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefSet(const nsAString & aGroup, const nsAString & aName, nsIVariant *aValue) { return _to OnContentPrefSet(aGroup, aName, aValue); } \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefRemoved(const nsAString & aGroup, const nsAString & aName) { return _to OnContentPrefRemoved(aGroup, aName); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICONTENTPREFOBSERVER(_to) \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefSet(const nsAString & aGroup, const nsAString & aName, nsIVariant *aValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnContentPrefSet(aGroup, aName, aValue); } \
NS_SCRIPTABLE NS_IMETHOD OnContentPrefRemoved(const nsAString & aGroup, const nsAString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnContentPrefRemoved(aGroup, aName); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsContentPrefObserver : public nsIContentPrefObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICONTENTPREFOBSERVER
nsContentPrefObserver();
private:
~nsContentPrefObserver();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsContentPrefObserver, nsIContentPrefObserver)
nsContentPrefObserver::nsContentPrefObserver()
{
/* member initializers and constructor code */
}
nsContentPrefObserver::~nsContentPrefObserver()
{
/* destructor code */
}
/* void onContentPrefSet (in AString aGroup, in AString aName, in nsIVariant aValue); */
NS_IMETHODIMP nsContentPrefObserver::OnContentPrefSet(const nsAString & aGroup, const nsAString & aName, nsIVariant *aValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void onContentPrefRemoved (in AString aGroup, in AString aName); */
NS_IMETHODIMP nsContentPrefObserver::OnContentPrefRemoved(const nsAString & aGroup, const nsAString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
/* starting interface: nsIContentPrefService */
#define NS_ICONTENTPREFSERVICE_IID_STR "ea7d29eb-7095-476e-b5d9-13263f3ae243"
#define NS_ICONTENTPREFSERVICE_IID \
{0xea7d29eb, 0x7095, 0x476e, \
{ 0xb5, 0xd9, 0x13, 0x26, 0x3f, 0x3a, 0xe2, 0x43 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIContentPrefService : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONTENTPREFSERVICE_IID)
/**
* Get a pref.
*
* Besides the regular string, integer, boolean, etc. values, this method
* may return null (nsIDataType::VTYPE_EMPTY), which means the pref is set
* to NULL in the database, as well as undefined (nsIDataType::VTYPE_VOID),
* which means there is no record for this pref in the database.
*
* @param aURI the URI for which to get the pref, or null to get
* the global pref (applies to all URIs)
* @param aName the name of the pref to get
*
* @returns the value of the pref
*/
/* nsIVariant getPref (in nsIURI aURI, in AString aName); */
NS_SCRIPTABLE NS_IMETHOD GetPref(nsIURI *aURI, const nsAString & aName, nsIVariant **_retval NS_OUTPARAM) = 0;
/**
* Set a pref.
*
* @param aURI the URI for which to set the pref, or null to set
* the global pref (applies to all URIs)
* @param aName the name of the pref to set
* @param aValue the new value of the pref
*/
/* void setPref (in nsIURI aURI, in AString aName, in nsIVariant aValue); */
NS_SCRIPTABLE NS_IMETHOD SetPref(nsIURI *aURI, const nsAString & aName, nsIVariant *aValue) = 0;
/**
* Check whether or not a pref exists.
*
* @param aURI the URI for which to check for the pref
* @param aName the name of the pref to check for
*/
/* boolean hasPref (in nsIURI aURI, in AString aName); */
NS_SCRIPTABLE NS_IMETHOD HasPref(nsIURI *aURI, const nsAString & aName, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Remove a pref.
*
* @param aURI the URI for which to remove the pref
* @param aName the name of the pref to remove
*/
/* void removePref (in nsIURI aURI, in AString aName); */
NS_SCRIPTABLE NS_IMETHOD RemovePref(nsIURI *aURI, const nsAString & aName) = 0;
/**
* Remove all grouped prefs. Useful for removing references to the sites
* the user has visited when the user clears their private data.
*/
/* void removeGroupedPrefs (); */
NS_SCRIPTABLE NS_IMETHOD RemoveGroupedPrefs(void) = 0;
/**
* Remove all prefs with the given name.
*
* @param aName the setting name for which to remove prefs
*/
/* void removePrefsByName (in AString aName); */
NS_SCRIPTABLE NS_IMETHOD RemovePrefsByName(const nsAString & aName) = 0;
/**
* Get the prefs that apply to the given URI.
*
* @param aURI the URI for which to retrieve prefs
*
* @returns a property bag of prefs
*/
/* nsIPropertyBag2 getPrefs (in nsIURI aURI); */
NS_SCRIPTABLE NS_IMETHOD GetPrefs(nsIURI *aURI, nsIPropertyBag2 **_retval NS_OUTPARAM) = 0;
/**
* Get the prefs with the given name.
*
* @param aName the setting name for which to retrieve prefs
*
* @returns a property bag of prefs
*/
/* nsIPropertyBag2 getPrefsByName (in AString aName); */
NS_SCRIPTABLE NS_IMETHOD GetPrefsByName(const nsAString & aName, nsIPropertyBag2 **_retval NS_OUTPARAM) = 0;
/**
* Add an observer.
*
* @param aName the setting to observe, or null to add
* a generic observer that observes all settings
* @param aObserver the observer to add
*/
/* void addObserver (in AString aName, in nsIContentPrefObserver aObserver); */
NS_SCRIPTABLE NS_IMETHOD AddObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) = 0;
/**
* Remove an observer.
*
* @param aName the setting being observed, or null to remove
* a generic observer that observes all settings
* @param aObserver the observer to remove
*/
/* void removeObserver (in AString aName, in nsIContentPrefObserver aObserver); */
NS_SCRIPTABLE NS_IMETHOD RemoveObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) = 0;
/**
* The component that the service uses to determine the groups to which
* URIs belong. By default this is the "hostname grouper", which groups
* URIs by full hostname (a.k.a. site).
*/
/* readonly attribute nsIContentURIGrouper grouper; */
NS_SCRIPTABLE NS_IMETHOD GetGrouper(nsIContentURIGrouper * *aGrouper) = 0;
/**
* The database connection to the content preferences database.
* Useful for accessing and manipulating preferences in ways that are caller-
* specific or for which there is not yet a generic method, although generic
* functionality useful to multiple callers should generally be added to this
* unfrozen interface. Also useful for testing the database creation
* and migration code.
*/
/* readonly attribute mozIStorageConnection DBConnection; */
NS_SCRIPTABLE NS_IMETHOD GetDBConnection(mozIStorageConnection * *aDBConnection) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIContentPrefService, NS_ICONTENTPREFSERVICE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICONTENTPREFSERVICE \
NS_SCRIPTABLE NS_IMETHOD GetPref(nsIURI *aURI, const nsAString & aName, nsIVariant **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD SetPref(nsIURI *aURI, const nsAString & aName, nsIVariant *aValue); \
NS_SCRIPTABLE NS_IMETHOD HasPref(nsIURI *aURI, const nsAString & aName, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD RemovePref(nsIURI *aURI, const nsAString & aName); \
NS_SCRIPTABLE NS_IMETHOD RemoveGroupedPrefs(void); \
NS_SCRIPTABLE NS_IMETHOD RemovePrefsByName(const nsAString & aName); \
NS_SCRIPTABLE NS_IMETHOD GetPrefs(nsIURI *aURI, nsIPropertyBag2 **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetPrefsByName(const nsAString & aName, nsIPropertyBag2 **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD AddObserver(const nsAString & aName, nsIContentPrefObserver *aObserver); \
NS_SCRIPTABLE NS_IMETHOD RemoveObserver(const nsAString & aName, nsIContentPrefObserver *aObserver); \
NS_SCRIPTABLE NS_IMETHOD GetGrouper(nsIContentURIGrouper * *aGrouper); \
NS_SCRIPTABLE NS_IMETHOD GetDBConnection(mozIStorageConnection * *aDBConnection);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICONTENTPREFSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetPref(nsIURI *aURI, const nsAString & aName, nsIVariant **_retval NS_OUTPARAM) { return _to GetPref(aURI, aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD SetPref(nsIURI *aURI, const nsAString & aName, nsIVariant *aValue) { return _to SetPref(aURI, aName, aValue); } \
NS_SCRIPTABLE NS_IMETHOD HasPref(nsIURI *aURI, const nsAString & aName, PRBool *_retval NS_OUTPARAM) { return _to HasPref(aURI, aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD RemovePref(nsIURI *aURI, const nsAString & aName) { return _to RemovePref(aURI, aName); } \
NS_SCRIPTABLE NS_IMETHOD RemoveGroupedPrefs(void) { return _to RemoveGroupedPrefs(); } \
NS_SCRIPTABLE NS_IMETHOD RemovePrefsByName(const nsAString & aName) { return _to RemovePrefsByName(aName); } \
NS_SCRIPTABLE NS_IMETHOD GetPrefs(nsIURI *aURI, nsIPropertyBag2 **_retval NS_OUTPARAM) { return _to GetPrefs(aURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetPrefsByName(const nsAString & aName, nsIPropertyBag2 **_retval NS_OUTPARAM) { return _to GetPrefsByName(aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD AddObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) { return _to AddObserver(aName, aObserver); } \
NS_SCRIPTABLE NS_IMETHOD RemoveObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) { return _to RemoveObserver(aName, aObserver); } \
NS_SCRIPTABLE NS_IMETHOD GetGrouper(nsIContentURIGrouper * *aGrouper) { return _to GetGrouper(aGrouper); } \
NS_SCRIPTABLE NS_IMETHOD GetDBConnection(mozIStorageConnection * *aDBConnection) { return _to GetDBConnection(aDBConnection); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICONTENTPREFSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetPref(nsIURI *aURI, const nsAString & aName, nsIVariant **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPref(aURI, aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD SetPref(nsIURI *aURI, const nsAString & aName, nsIVariant *aValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPref(aURI, aName, aValue); } \
NS_SCRIPTABLE NS_IMETHOD HasPref(nsIURI *aURI, const nsAString & aName, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->HasPref(aURI, aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD RemovePref(nsIURI *aURI, const nsAString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemovePref(aURI, aName); } \
NS_SCRIPTABLE NS_IMETHOD RemoveGroupedPrefs(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveGroupedPrefs(); } \
NS_SCRIPTABLE NS_IMETHOD RemovePrefsByName(const nsAString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemovePrefsByName(aName); } \
NS_SCRIPTABLE NS_IMETHOD GetPrefs(nsIURI *aURI, nsIPropertyBag2 **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrefs(aURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetPrefsByName(const nsAString & aName, nsIPropertyBag2 **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrefsByName(aName, _retval); } \
NS_SCRIPTABLE NS_IMETHOD AddObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) { return !_to ? NS_ERROR_NULL_POINTER : _to->AddObserver(aName, aObserver); } \
NS_SCRIPTABLE NS_IMETHOD RemoveObserver(const nsAString & aName, nsIContentPrefObserver *aObserver) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveObserver(aName, aObserver); } \
NS_SCRIPTABLE NS_IMETHOD GetGrouper(nsIContentURIGrouper * *aGrouper) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetGrouper(aGrouper); } \
NS_SCRIPTABLE NS_IMETHOD GetDBConnection(mozIStorageConnection * *aDBConnection) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDBConnection(aDBConnection); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsContentPrefService : public nsIContentPrefService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICONTENTPREFSERVICE
nsContentPrefService();
private:
~nsContentPrefService();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsContentPrefService, nsIContentPrefService)
nsContentPrefService::nsContentPrefService()
{
/* member initializers and constructor code */
}
nsContentPrefService::~nsContentPrefService()
{
/* destructor code */
}
/* nsIVariant getPref (in nsIURI aURI, in AString aName); */
NS_IMETHODIMP nsContentPrefService::GetPref(nsIURI *aURI, const nsAString & aName, nsIVariant **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void setPref (in nsIURI aURI, in AString aName, in nsIVariant aValue); */
NS_IMETHODIMP nsContentPrefService::SetPref(nsIURI *aURI, const nsAString & aName, nsIVariant *aValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean hasPref (in nsIURI aURI, in AString aName); */
NS_IMETHODIMP nsContentPrefService::HasPref(nsIURI *aURI, const nsAString & aName, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removePref (in nsIURI aURI, in AString aName); */
NS_IMETHODIMP nsContentPrefService::RemovePref(nsIURI *aURI, const nsAString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removeGroupedPrefs (); */
NS_IMETHODIMP nsContentPrefService::RemoveGroupedPrefs()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removePrefsByName (in AString aName); */
NS_IMETHODIMP nsContentPrefService::RemovePrefsByName(const nsAString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIPropertyBag2 getPrefs (in nsIURI aURI); */
NS_IMETHODIMP nsContentPrefService::GetPrefs(nsIURI *aURI, nsIPropertyBag2 **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIPropertyBag2 getPrefsByName (in AString aName); */
NS_IMETHODIMP nsContentPrefService::GetPrefsByName(const nsAString & aName, nsIPropertyBag2 **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void addObserver (in AString aName, in nsIContentPrefObserver aObserver); */
NS_IMETHODIMP nsContentPrefService::AddObserver(const nsAString & aName, nsIContentPrefObserver *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removeObserver (in AString aName, in nsIContentPrefObserver aObserver); */
NS_IMETHODIMP nsContentPrefService::RemoveObserver(const nsAString & aName, nsIContentPrefObserver *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIContentURIGrouper grouper; */
NS_IMETHODIMP nsContentPrefService::GetGrouper(nsIContentURIGrouper * *aGrouper)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute mozIStorageConnection DBConnection; */
NS_IMETHODIMP nsContentPrefService::GetDBConnection(mozIStorageConnection * *aDBConnection)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIContentPrefService_h__ */
| [
"gears.daemon@fe895e04-df30-0410-9975-d76d301b4276"
] | gears.daemon@fe895e04-df30-0410-9975-d76d301b4276 |
85b6e02654bbd44654c43d32e31151cb1cc05229 | 493ac26ce835200f4844e78d8319156eae5b21f4 | /CHT_heat_transfer/constant/solid_12/polyMesh/faces | 8aa3ae377356f1ba1801a9ea50bfa6a2ba0c54cc | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,925 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class faceList;
location "constant/solid_12/polyMesh";
object faces;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
979
(
4(308 355 526 479)
4(308 479 509 338)
4(355 263 434 526)
4(338 509 434 263)
4(305 292 463 476)
4(292 306 477 463)
4(305 476 413 242)
4(242 413 477 306)
4(108 309 480 235)
4(109 234 481 310)
4(310 481 480 309)
4(257 428 543 372)
4(295 372 543 466)
4(378 295 466 549)
4(378 549 428 257)
4(291 305 476 462)
4(291 462 467 296)
4(305 389 560 476)
4(296 467 560 389)
4(331 240 411 502)
4(332 331 502 503)
4(370 541 411 240)
4(332 503 541 370)
4(346 301 472 517)
4(343 514 472 301)
4(259 346 517 430)
4(259 430 514 343)
4(358 529 473 302)
4(342 302 473 513)
4(258 429 529 358)
4(258 342 513 429)
4(354 525 475 304)
4(340 304 475 511)
4(261 432 525 354)
4(261 340 511 432)
4(293 383 554 464)
4(256 427 554 383)
4(309 480 427 256)
4(309 293 464 480)
4(357 363 534 528)
4(363 294 465 534)
4(357 528 433 262)
4(262 433 465 294)
4(317 267 438 488)
4(317 488 471 300)
4(267 356 527 438)
4(300 471 527 356)
4(328 499 439 268)
4(328 301 472 499)
4(268 439 517 346)
4(326 269 440 497)
4(326 497 473 302)
4(269 358 529 440)
4(303 474 442 271)
4(341 512 474 303)
4(360 271 442 531)
4(341 360 531 512)
4(321 272 443 492)
4(321 492 475 304)
4(272 354 525 443)
4(317 310 481 488)
4(368 539 481 310)
4(267 438 539 368)
4(324 495 508 337)
4(299 470 495 324)
4(266 337 508 437)
4(299 266 437 470)
4(285 456 464 293)
4(318 383 554 489)
4(285 318 489 456)
4(290 4 15 461)
4(277 448 218 125)
4(290 461 448 277)
4(330 501 521 350)
4(297 468 501 330)
4(264 350 521 435)
4(297 264 435 468)
4(329 345 516 500)
4(298 329 500 469)
4(265 436 516 345)
4(298 469 436 265)
4(307 478 445 274)
4(363 534 478 307)
4(357 274 445 528)
4(314 273 444 485)
4(314 485 479 308)
4(273 355 526 444)
4(316 289 460 487)
4(396 567 460 289)
4(388 316 487 559)
4(388 559 567 396)
4(325 351 522 496)
4(325 496 497 326)
4(351 269 440 522)
4(406 577 12 7)
4(309 480 577 406)
4(322 493 518 347)
4(303 474 493 322)
4(271 347 518 442)
4(284 359 530 455)
4(284 455 492 321)
4(359 272 443 530)
4(282 453 490 319)
4(324 495 453 282)
4(337 319 490 508)
4(327 498 520 349)
4(327 328 499 498)
4(349 520 439 268)
4(283 353 524 454)
4(283 454 485 314)
4(353 273 444 524)
4(315 486 519 348)
4(307 478 486 315)
4(274 348 519 445)
4(106 289 460 199)
4(6 13 487 316)
4(313 484 447 276)
4(313 327 498 484)
4(276 447 520 349)
4(312 483 446 275)
4(330 501 483 312)
4(350 275 446 521)
4(329 313 484 500)
4(345 516 447 276)
4(312 483 496 325)
4(275 351 522 446)
4(282 453 460 289)
4(319 396 567 490)
4(322 493 454 283)
4(347 353 524 518)
4(315 486 455 284)
4(348 359 530 519)
4(311 482 137 48)
4(251 47 138 422)
4(311 251 422 482)
4(373 544 543 372)
4(373 288 459 544)
4(288 257 428 459)
4(316 487 452 281)
4(388 400 571 559)
4(281 452 571 400)
4(239 410 136 49)
4(239 311 482 410)
4(317 110 233 488)
4(314 122 221 485)
4(283 454 222 121)
4(308 479 220 123)
4(338 124 219 509)
4(324 104 201 495)
4(299 470 202 103)
4(282 453 200 105)
4(329 500 226 117)
4(298 118 225 469)
4(322 120 223 493)
4(303 474 224 119)
4(325 99 206 496)
4(312 483 207 98)
4(315 486 213 92)
4(284 93 212 455)
4(330 97 208 501)
4(297 468 209 96)
4(321 492 211 94)
4(304 95 210 475)
4(327 498 228 115)
4(313 116 227 484)
4(300 111 232 471)
4(62 240 411 195)
4(61 196 502 331)
4(50 334 505 135)
4(239 410 505 334)
4(318 489 194 63)
4(240 411 489 318)
4(328 114 229 499)
4(301 472 230 113)
4(100 205 497 326)
4(307 478 214 91)
4(323 494 165 20)
4(254 19 166 425)
4(323 254 425 494)
4(320 84 173 491)
4(250 421 172 85)
4(250 320 491 421)
4(291 290 461 462)
4(292 463 461 290)
4(363 90 215 534)
4(294 465 216 89)
4(241 412 164 21)
4(241 323 494 412)
4(302 101 204 473)
4(238 409 129 56)
4(333 55 130 504)
4(238 333 504 409)
4(319 46 139 490)
4(251 319 490 422)
4(331 502 565 394)
4(332 278 449 503)
4(278 394 565 449)
4(342 513 203 102)
4(299 470 513 342)
4(343 112 231 514)
4(300 343 514 471)
4(334 395 566 505)
4(335 506 450 279)
4(279 450 566 395)
4(335 334 505 506)
4(337 45 140 508)
4(96 209 511 340)
4(118 341 512 225)
4(57 365 536 128)
4(238 409 536 365)
4(241 412 507 336)
4(22 336 507 163)
4(54 131 537 366)
4(55 237 408 130)
4(237 366 537 408)
4(252 253 424 423)
4(252 423 457 286)
4(286 457 535 364)
4(253 364 535 424)
4(297 468 572 401)
4(340 401 572 511)
4(341 512 573 402)
4(298 402 573 469)
4(263 83 174 434)
4(320 263 434 491)
4(243 248 419 414)
4(88 243 414 217)
4(5 14 419 248)
4(372 26 159 543)
4(373 544 158 27)
4(65 256 427 192)
4(64 193 554 383)
4(296 467 414 243)
4(287 248 419 458)
4(296 287 458 467)
4(7 12 407 236)
4(236 407 510 339)
4(107 339 510 198)
4(44 141 437 266)
4(291 374 545 462)
4(4 15 545 374)
4(253 424 417 246)
4(246 417 416 245)
4(252 245 416 423)
4(270 280 451 441)
4(246 270 441 417)
4(253 424 451 280)
4(245 416 407 236)
4(245 244 415 416)
4(244 7 12 415)
4(387 281 452 558)
4(387 558 441 270)
4(281 280 451 452)
4(60 197 565 394)
4(51 395 566 134)
4(68 356 527 189)
4(67 190 438 267)
4(74 183 516 345)
4(75 265 436 182)
4(31 348 519 154)
4(30 155 445 274)
4(70 187 517 346)
4(71 268 439 186)
4(69 188 430 259)
4(72 185 520 349)
4(73 276 447 184)
4(36 352 523 149)
4(35 150 432 261)
4(352 261 432 523)
4(37 264 435 148)
4(264 352 523 435)
4(34 151 525 354)
4(32 359 530 153)
4(29 156 528 357)
4(33 152 443 272)
4(38 350 521 147)
4(259 356 527 430)
4(79 347 518 178)
4(78 179 442 271)
4(28 157 433 262)
4(39 275 446 146)
4(80 353 524 177)
4(40 351 522 145)
4(42 143 529 358)
4(43 258 429 142)
4(82 175 526 355)
4(41 144 440 269)
4(81 176 444 273)
4(77 180 531 360)
4(260 431 531 360)
4(76 181 431 260)
4(362 533 437 266)
4(43 142 533 362)
4(361 265 436 532)
4(76 361 532 181)
4(365 536 449 278)
4(58 278 449 127)
4(252 423 426 255)
4(344 255 426 515)
4(286 344 515 457)
4(366 279 450 537)
4(53 132 450 279)
4(262 433 544 373)
4(294 288 459 465)
4(256 368 539 427)
4(66 191 539 368)
4(246 417 510 339)
4(18 242 413 167)
4(17 168 551 380)
4(242 380 551 413)
4(25 160 466 295)
4(24 161 562 391)
4(295 391 562 466)
4(338 277 448 509)
4(248 257 428 419)
4(249 420 459 288)
4(248 419 420 249)
4(374 545 414 243)
4(244 285 456 415)
4(244 415 418 247)
4(247 418 464 293)
4(371 542 166 19)
4(242 413 542 371)
4(86 171 548 377)
4(377 548 561 390)
4(87 390 561 170)
4(367 257 428 538)
4(287 367 538 458)
4(245 416 540 369)
4(255 369 540 426)
4(250 421 548 377)
4(387 6 13 558)
4(391 23 162 562)
4(336 507 549 378)
4(391 562 507 336)
4(394 59 126 565)
4(395 566 133 52)
4(89 249 420 216)
4(369 285 456 540)
4(371 542 560 389)
4(254 389 560 425)
4(384 555 556 385)
4(286 457 555 384)
4(364 385 556 535)
4(388 559 422 251)
4(397 568 412 241)
4(392 563 568 397)
4(392 323 494 563)
4(237 408 555 384)
4(333 384 555 504)
4(378 549 568 397)
4(367 397 568 538)
4(379 550 536 365)
4(386 238 409 557)
4(386 557 550 379)
4(290 461 552 381)
4(376 381 552 547)
4(277 376 547 448)
4(306 477 552 381)
4(299 470 575 404)
4(404 575 429 258)
4(332 379 550 503)
4(247 406 577 418)
4(382 370 541 553)
4(318 382 553 489)
4(366 385 556 537)
4(335 506 556 385)
4(260 431 573 402)
4(339 387 558 510)
4(370 255 426 541)
4(393 564 515 344)
4(370 541 564 393)
4(399 570 491 320)
4(338 509 570 399)
4(362 533 575 404)
4(392 563 458 287)
4(398 280 451 569)
4(405 398 569 576)
4(405 576 546 375)
4(375 546 451 280)
4(16 169 574 403)
4(380 403 574 551)
4(250 376 547 421)
4(376 399 570 547)
4(311 400 571 482)
4(369 540 553 382)
4(87 170 574 403)
4(361 402 573 532)
4(352 523 572 401)
4(377 381 552 548)
4(392 563 560 389)
4(364 535 569 398)
4(386 557 555 384)
4(344 515 557 386)
4(335 398 569 506)
4(334 505 576 405)
4(379 393 564 550)
4(306 477 561 390)
4(239 375 546 410)
4(400 571 546 375)
4(380 551 561 390)
4(308 338 263 355)
4(305 242 306 292)
4(109 310 309 108)
4(378 257 372 295)
4(291 296 389 305)
4(332 370 240 331)
4(259 343 301 346)
4(258 358 302 342)
4(261 354 304 340)
4(309 256 383 293)
4(357 262 294 363)
4(317 300 356 267)
4(328 268 346 301)
4(326 302 358 269)
4(341 303 271 360)
4(321 304 354 272)
4(267 368 310 317)
4(299 324 337 266)
4(285 293 383 318)
4(290 277 125 4)
4(297 330 350 264)
4(298 265 345 329)
4(363 307 274 357)
4(314 308 355 273)
4(388 396 289 316)
4(325 326 269 351)
4(309 406 7 108)
4(303 322 347 271)
4(284 321 272 359)
4(324 282 319 337)
4(327 349 268 328)
4(283 314 273 353)
4(307 315 348 274)
4(106 6 316 289)
4(313 276 349 327)
4(330 312 275 350)
4(329 345 276 313)
4(312 325 351 275)
4(319 282 289 396)
4(322 283 353 347)
4(315 284 359 348)
4(311 48 47 251)
4(373 372 257 288)
4(316 281 400 388)
4(239 49 48 311)
4(310 109 110 317)
4(314 283 121 122)
4(338 308 123 124)
4(324 299 103 104)
4(289 282 105 106)
4(329 117 118 298)
4(322 303 119 120)
4(325 312 98 99)
4(315 92 93 284)
4(330 297 96 97)
4(321 94 95 304)
4(327 115 116 313)
4(317 110 111 300)
4(62 61 331 240)
4(49 239 334 50)
4(240 318 63 62)
4(301 113 114 328)
4(99 100 326 325)
4(308 314 122 123)
4(307 91 92 315)
4(115 327 328 114)
4(323 20 19 254)
4(250 85 84 320)
4(305 292 290 291)
4(294 89 90 363)
4(284 93 94 321)
4(283 322 120 121)
4(241 21 20 323)
4(302 326 100 101)
4(282 324 104 105)
4(313 116 117 329)
4(312 330 97 98)
4(238 56 55 333)
4(251 47 46 319)
4(332 331 394 278)
4(299 342 102 103)
4(300 111 112 343)
4(335 279 395 334)
4(91 307 363 90)
4(319 46 45 337)
4(96 340 304 95)
4(118 119 303 341)
4(101 102 342 302)
4(113 301 343 112)
4(56 238 365 57)
4(21 241 336 22)
4(55 54 366 237)
4(252 286 364 253)
4(96 297 401 340)
4(118 341 402 298)
4(320 84 83 263)
4(88 5 248 243)
4(372 373 27 26)
4(65 64 383 256)
4(296 243 248 287)
4(7 236 339 107)
4(44 266 337 45)
4(290 4 374 291)
4(253 246 245 252)
4(246 253 280 270)
4(245 236 7 244)
4(387 270 280 281)
4(61 60 394 331)
4(50 334 395 51)
4(68 67 267 356)
4(75 74 345 265)
4(31 30 274 348)
4(71 70 346 268)
4(70 69 259 346)
4(73 72 349 276)
4(72 71 268 349)
4(74 73 276 345)
4(36 35 261 352)
4(37 36 352 264)
4(35 34 354 261)
4(32 31 348 359)
4(30 29 357 274)
4(34 33 272 354)
4(33 32 359 272)
4(38 37 264 350)
4(69 68 356 259)
4(78 271 347 79)
4(29 28 262 357)
4(39 38 350 275)
4(79 347 353 80)
4(40 39 275 351)
4(43 42 358 258)
4(82 355 263 83)
4(42 41 269 358)
4(81 273 355 82)
4(41 40 351 269)
4(77 360 271 78)
4(76 260 360 77)
4(80 353 273 81)
4(43 362 266 44)
4(76 75 265 361)
4(57 365 278 58)
4(286 252 255 344)
4(54 53 279 366)
4(262 373 288 294)
4(309 310 368 256)
4(67 66 368 267)
4(245 246 339 236)
4(256 368 66 65)
4(18 17 380 242)
4(26 25 295 372)
4(25 24 391 295)
4(124 125 277 338)
4(248 249 288 257)
4(291 374 243 296)
4(244 247 293 285)
4(242 371 19 18)
4(86 377 390 87)
4(287 248 257 367)
4(252 245 369 255)
4(28 27 373 262)
4(85 250 377 86)
4(281 316 6 387)
4(24 3 23 391)
4(391 336 378 295)
4(60 1 59 394)
4(51 395 52 2)
4(89 294 288 249)
4(245 244 285 369)
4(4 88 243 374)
4(19 371 389 254)
4(286 384 385 364)
4(388 251 319 396)
4(392 397 241 323)
4(55 237 384 333)
4(257 378 397 367)
4(386 379 365 238)
4(277 290 381 376)
4(318 383 64 63)
4(306 381 290 292)
4(397 378 336 241)
4(299 404 258 342)
4(278 365 379 332)
4(244 7 406 247)
4(318 240 370 382)
4(279 335 385 366)
4(360 260 402 341)
4(246 270 387 339)
4(384 237 366 385)
4(370 393 344 255)
4(338 399 320 263)
4(266 362 404 299)
4(392 287 367 397)
4(405 375 280 398)
4(242 305 389 371)
4(17 16 403 380)
4(107 339 387 6)
4(250 320 399 376)
4(22 336 391 23)
4(251 388 400 311)
4(255 369 382 370)
4(87 403 16 0)
4(265 298 402 361)
4(264 352 401 297)
4(377 250 376 381)
4(338 277 376 399)
4(58 278 394 59)
4(53 52 395 279)
4(287 392 389 296)
4(253 364 398 280)
4(344 386 384 286)
4(238 333 384 386)
4(323 254 389 392)
4(340 401 352 261)
4(76 361 402 260)
4(334 405 398 335)
4(318 382 369 285)
4(293 247 406 309)
4(43 258 404 362)
4(386 344 393 379)
4(381 306 390 377)
4(335 398 364 385)
4(311 400 375 239)
4(370 332 379 393)
4(334 239 375 405)
4(280 375 400 281)
4(242 380 390 306)
4(380 403 87 390)
4(248 5 89 249)
4(343 259 356 300)
4(109 108 235 234)
4(4 125 218 15)
4(108 7 12 235)
4(106 199 13 6)
4(109 234 233 110)
4(122 121 222 221)
4(124 123 220 219)
4(104 103 202 201)
4(106 105 200 199)
4(117 226 225 118)
4(120 119 224 223)
4(99 98 207 206)
4(92 213 212 93)
4(97 96 209 208)
4(94 211 210 95)
4(115 228 227 116)
4(110 233 232 111)
4(113 230 229 114)
4(99 206 205 100)
4(123 122 221 220)
4(91 214 213 92)
4(115 114 229 228)
4(89 216 215 90)
4(93 212 211 94)
4(121 120 223 222)
4(101 100 205 204)
4(105 104 201 200)
4(116 227 226 117)
4(98 97 208 207)
4(103 102 203 202)
4(111 232 231 112)
4(91 90 215 214)
4(96 95 210 209)
4(118 225 224 119)
4(101 204 203 102)
4(113 112 231 230)
4(88 217 14 5)
4(7 107 198 12)
4(124 219 218 125)
4(4 15 217 88)
4(107 6 13 198)
4(5 14 216 89)
4(479 526 434 509)
4(476 463 477 413)
4(234 235 480 481)
4(549 466 543 428)
4(462 476 560 467)
4(503 502 411 541)
4(430 517 472 514)
4(429 513 473 529)
4(432 511 475 525)
4(480 464 554 427)
4(528 534 465 433)
4(488 438 527 471)
4(499 472 517 439)
4(497 440 529 473)
4(512 531 442 474)
4(492 443 525 475)
4(438 488 481 539)
4(470 437 508 495)
4(456 489 554 464)
4(461 15 218 448)
4(468 435 521 501)
4(469 500 516 436)
4(534 528 445 478)
4(485 444 526 479)
4(559 487 460 567)
4(496 522 440 497)
4(480 235 12 577)
4(474 442 518 493)
4(455 530 443 492)
4(495 508 490 453)
4(498 499 439 520)
4(454 524 444 485)
4(478 445 519 486)
4(199 460 487 13)
4(484 498 520 447)
4(501 521 446 483)
4(500 484 447 516)
4(483 446 522 496)
4(490 567 460 453)
4(493 518 524 454)
4(486 519 530 455)
4(482 422 138 137)
4(544 459 428 543)
4(487 559 571 452)
4(410 482 137 136)
4(481 488 233 234)
4(485 221 222 454)
4(509 219 220 479)
4(495 201 202 470)
4(460 199 200 453)
4(500 469 225 226)
4(493 223 224 474)
4(496 206 207 483)
4(486 455 212 213)
4(501 208 209 468)
4(492 475 210 211)
4(498 484 227 228)
4(488 471 232 233)
4(195 411 502 196)
4(136 135 505 410)
4(411 195 194 489)
4(472 499 229 230)
4(206 496 497 205)
4(479 220 221 485)
4(478 486 213 214)
4(228 229 499 498)
4(494 425 166 165)
4(421 491 173 172)
4(476 462 461 463)
4(465 534 215 216)
4(455 492 211 212)
4(454 222 223 493)
4(412 494 165 164)
4(473 204 205 497)
4(453 200 201 495)
4(484 500 226 227)
4(483 207 208 501)
4(409 504 130 129)
4(422 490 139 138)
4(503 449 565 502)
4(470 202 203 513)
4(471 514 231 232)
4(506 505 566 450)
4(214 215 534 478)
4(490 508 140 139)
4(209 210 475 511)
4(225 512 474 224)
4(204 473 513 203)
4(230 231 514 472)
4(129 128 536 409)
4(164 163 507 412)
4(130 408 537 131)
4(423 424 535 457)
4(209 511 572 468)
4(225 469 573 512)
4(491 434 174 173)
4(217 414 419 14)
4(543 159 158 544)
4(192 427 554 193)
4(467 458 419 414)
4(12 198 510 407)
4(141 140 508 437)
4(461 462 545 15)
4(424 423 416 417)
4(417 441 451 424)
4(416 415 12 407)
4(558 452 451 441)
4(196 502 565 197)
4(135 134 566 505)
4(189 527 438 190)
4(182 436 516 183)
4(154 519 445 155)
4(186 439 517 187)
4(187 517 430 188)
4(184 447 520 185)
4(185 520 439 186)
4(183 516 447 184)
4(149 523 432 150)
4(148 435 523 149)
4(150 432 525 151)
4(153 530 519 154)
4(155 445 528 156)
4(151 525 443 152)
4(152 443 530 153)
4(147 521 435 148)
4(188 430 527 189)
4(179 178 518 442)
4(156 528 433 157)
4(146 446 521 147)
4(178 177 524 518)
4(145 522 446 146)
4(142 429 529 143)
4(175 174 434 526)
4(143 529 440 144)
4(176 175 526 444)
4(144 440 522 145)
4(180 179 442 531)
4(181 180 531 431)
4(177 176 444 524)
4(142 141 437 533)
4(181 532 436 182)
4(128 127 449 536)
4(457 515 426 423)
4(131 537 450 132)
4(433 465 459 544)
4(480 427 539 481)
4(190 438 539 191)
4(416 407 510 417)
4(427 192 191 539)
4(167 413 551 168)
4(159 543 466 160)
4(160 466 562 161)
4(219 509 448 218)
4(419 428 459 420)
4(462 467 414 545)
4(415 456 464 418)
4(413 167 166 542)
4(171 170 561 548)
4(458 538 428 419)
4(423 426 540 416)
4(157 433 544 158)
4(172 171 548 421)
4(452 558 13 487)
4(161 562 162 10)
4(562 466 549 507)
4(197 565 126 8)
4(134 9 133 566)
4(216 420 459 465)
4(416 540 456 415)
4(15 545 414 217)
4(166 425 560 542)
4(457 535 556 555)
4(559 567 490 422)
4(563 494 412 568)
4(130 504 555 408)
4(428 538 568 549)
4(557 409 536 550)
4(448 547 552 461)
4(489 194 193 554)
4(477 463 461 552)
4(568 412 507 549)
4(470 513 429 575)
4(449 503 550 536)
4(415 418 577 12)
4(489 553 541 411)
4(450 537 556 506)
4(531 512 573 431)
4(417 510 558 441)
4(555 556 537 408)
4(541 426 515 564)
4(509 434 491 570)
4(437 470 575 533)
4(563 568 538 458)
4(576 569 451 546)
4(413 542 560 476)
4(168 551 574 169)
4(198 13 558 510)
4(421 547 570 491)
4(163 162 562 507)
4(422 482 571 559)
4(426 541 553 540)
4(170 11 169 574)
4(436 532 573 469)
4(435 468 572 523)
4(548 552 547 421)
4(509 570 547 448)
4(127 126 565 449)
4(132 450 566 133)
4(458 467 560 563)
4(424 451 569 535)
4(515 457 555 557)
4(409 557 555 504)
4(494 563 560 425)
4(511 432 523 572)
4(181 431 573 532)
4(505 506 569 576)
4(489 456 540 553)
4(464 480 577 418)
4(142 533 575 429)
4(557 550 564 515)
4(552 548 561 477)
4(506 556 535 569)
4(482 410 546 571)
4(541 564 550 503)
4(505 576 546 410)
4(451 452 571 546)
4(413 477 561 551)
4(551 561 170 574)
4(419 420 216 14)
4(514 471 527 430)
4(55 56 129 130)
4(75 182 183 74)
4(24 161 10 3)
4(87 0 11 170)
4(49 50 135 136)
4(49 136 137 48)
4(60 197 8 1)
4(51 134 135 50)
4(85 172 173 84)
4(61 62 195 196)
4(81 82 175 176)
4(83 174 175 82)
4(63 64 193 194)
4(65 192 193 64)
4(84 173 174 83)
4(62 63 194 195)
4(70 71 186 187)
4(76 77 180 181)
4(27 158 159 26)
4(30 155 156 29)
4(31 154 155 30)
4(78 79 178 179)
4(48 137 138 47)
4(72 185 186 71)
4(32 153 154 31)
4(74 183 184 73)
4(46 139 140 45)
4(47 138 139 46)
4(78 179 180 77)
4(29 156 157 28)
4(38 39 146 147)
4(45 140 141 44)
4(38 147 148 37)
4(54 131 132 53)
4(42 43 142 143)
4(41 42 143 144)
4(55 130 131 54)
4(33 34 151 152)
4(65 66 191 192)
4(72 73 184 185)
4(68 69 188 189)
4(37 148 149 36)
4(70 187 188 69)
4(67 190 191 66)
4(67 68 189 190)
4(40 41 144 145)
4(52 133 9 2)
4(32 33 152 153)
4(28 157 158 27)
4(35 36 149 150)
4(75 76 181 182)
4(40 145 146 39)
4(81 176 177 80)
4(44 141 142 43)
4(35 150 151 34)
4(52 53 132 133)
4(80 177 178 79)
4(59 126 127 58)
4(21 164 165 20)
4(20 165 166 19)
4(24 25 160 161)
4(1 8 126 59)
4(61 196 197 60)
4(51 2 9 134)
4(26 159 160 25)
4(23 162 163 22)
4(19 166 167 18)
4(87 170 171 86)
4(56 57 128 129)
4(0 16 169 11)
4(21 22 163 164)
4(17 18 167 168)
4(85 86 171 172)
4(3 10 162 23)
4(17 168 169 16)
4(58 127 128 57)
)
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
3db4c2f1f6fa918929559cee00ebe34cc5ddb43f | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazetest/src/mathtest/dvecdvecouter/V4aV6a.cpp | e1e2d252c5e414fbc0ea998f642178a8249a1b81 | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,635 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dvecdvecouter/V4aV6a.cpp
// \brief Source file for the V4aV6a dense vector/dense vector outer product math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecouter/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V4aV6a'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Vector type definitions
typedef blaze::StaticVector<TypeA,4UL> V4a;
typedef blaze::StaticVector<TypeA,6UL> V6a;
// Creator type definitions
typedef blazetest::Creator<V4a> CV4a;
typedef blazetest::Creator<V6a> CV6a;
// Running the tests
RUN_DVECDVECOUTER_OPERATION_TEST( CV4a(), CV6a() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"jonathan.doucette@alumni.ubc.ca"
] | jonathan.doucette@alumni.ubc.ca |
d1a953748ffc6f58625892180aa866aca7d4b6f4 | aa6642d00b74b4c4862bd78806d5d766d40ec299 | /Lecture11/src/sepChain.cpp | 1f58a826b363112fffff94587ab2e653007a6f5d | [] | no_license | alexnour/sp21-cse-20312 | 36a90f000138ca76d23cd65ae3e83cf4de997857 | 47899a56579bc6d255302be3e1275ac7ee7e8b3b | refs/heads/main | 2023-03-19T15:26:17.543680 | 2021-03-11T00:09:54 | 2021-03-11T00:09:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,046 | cpp | /**********************************************
* File: sepChain.cpp
* Author: Matthew Morrison
* Email: matt.morrison@nd.edu
*
* Shows a basic example of separate chaining
**********************************************/
#include <iterator>
#include <string>
#include <iostream>
#include "../include/DynArr.h"
#include "../include/LinearProbe.h"
const int numBuckets = 7;
/********************************************
* Function Name : HashFunc
* Pre-conditions : int value
* Post-conditions: int
*
* Hash Function: value % numBuckets
********************************************/
int HashFunc(int value){
return value % numBuckets;
}
/********************************************
* Function Name : HashFunc
* Pre-conditions : std::string value
* Post-conditions: int
*
* Hash Function returns size of string % numBuckets
********************************************/
int HashFunc(std::string value){
return (int)value.size() % numBuckets;
}
/********************************************
* Function Name : insertVal
* Pre-conditions : HashTable<int, DynArr<T> >& sepChain, T value
* Post-conditions: none
*
* Inserts the value into a Separate Chain Hash
********************************************/
template<class T>
void insertVal(HashTable<int, DynArr<T> >& sepChain, T value){
// sepChain[ HashFunc(value) ] returns the vector with a call by reference
sepChain[ HashFunc(value) ].push_back(value);
}
template<class T>
void printHash(HashTable<int, DynArr<T> >& sepChain){
// Iterating through all buckets
for(int i = 0; i < numBuckets; i++){
std::cout << i << ": " << sepChain[i] << std::endl;
}
}
/********************************************
* Function Name : main
* Pre-conditions :
* Post-conditions: int
*
* Main driver function. Solution
********************************************/
int main(){
HashTable<int, DynArr<int> > sepChain;
/* Initialize List */
for(int i = 0; i < numBuckets; i++){
// Create a temporary
DynArr<int> temp;
sepChain.insert( {i, temp} );
}
/* Insert 4, 13, 8, 10, 5, 15 */
insertVal(sepChain, 4); insertVal(sepChain, 13);
insertVal(sepChain, 8); insertVal(sepChain, 10);
insertVal(sepChain, 5); insertVal(sepChain, 15);
/* Print the Hash */
std::cout << sepChain << std::endl << std::endl;
/* Print the Hash, only the buckets we need */
printHash(sepChain);
std::cout << char(10);
HashTable<int, DynArr< std::string > > separStr;
/* Initialize List */
for(int i = 0; i < numBuckets; i++){
DynArr< std::string > temp;
separStr.insert( {i, temp} );
}
/* Insert words of length 4, 13, 8, 10, 5, 15 */
insertVal(separStr, std::string("data"));
insertVal(separStr, std::string("enlightenment"));
insertVal(separStr, std::string("morrison"));
insertVal(separStr, std::string("structures"));
insertVal(separStr, std::string("pizza"));
insertVal(separStr, std::string("rumpelstiltskin"));
/* Print the Hash */
std::cout << separStr << std::endl << std::endl;
/* Print the Hash */
printHash(separStr);
return 0;
}
| [
"mmorri22@nd.edu"
] | mmorri22@nd.edu |
471476884f53ab6a98a0c6a18878ab89db9518c0 | d4f0ce5ffa72e2d3e69febe3afb8143390cc6d81 | /qcadactions/src/rs_actionsnapintersectionmanual.h | c4ce3608d3f52e17231633559dcaa9d40f96d991 | [] | no_license | jacklibj/2.0.5.0-1-community.src | bdb841c662e6ae7ab3b74c79e48bd5b33fa6dded | 6e92447db30440c26437a2b5de165338dfe4d1c3 | refs/heads/master | 2020-05-21T00:46:32.456342 | 2013-04-08T03:12:57 | 2013-04-08T03:12:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,210 | h | /****************************************************************************
** $Id: rs_actionsnapintersectionmanual.h 1062 2004-01-16 21:51:20Z andrew $
**
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
**
** This file is part of the qcadlib Library project.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid qcadlib Professional Edition licenses may use
** this file in accordance with the qcadlib Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.ribbonsoft.com for further details.
**
** Contact info@ribbonsoft.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef RS_ACTIONSNAPINTERSECTIONMANUAL_H
#define RS_ACTIONSNAPINTERSECTIONMANUAL_H
#include "rs_previewactioninterface.h"
/**
* This action class can handle user events to trim entities.
*
* @author Andrew Mustun
*/
class RS_ActionSnapIntersectionManual : public RS_PreviewActionInterface {
Q_OBJECT
public:
/**
* Action States.
*/
enum Status {
ChooseEntity1, /**< Choosing the 1st entity. */
ChooseEntity2 /**< Choosing the 2nd entity. */
};
public:
RS_ActionSnapIntersectionManual(RS_EntityContainer& container,
RS_GraphicView& graphicView);
~RS_ActionSnapIntersectionManual() {}
static QAction* createGUIAction(RS2::ActionType /*type*/, QObject* /*parent*/);
virtual void init(int status=0);
virtual void trigger();
virtual void mouseMoveEvent(RS_MouseEvent* e);
virtual void mouseReleaseEvent(RS_MouseEvent* e);
virtual void updateMouseButtonHints();
virtual void updateMouseCursor();
virtual void updateToolBar();
private:
RS_Entity* entity1;
RS_Entity* entity2;
RS_Vector coord;
};
#endif
| [
"worinco@163.com"
] | worinco@163.com |
7601bb43d9b6b3bc10c3b571d2c11b6d4326175f | 8acdfe5db8da1e5d81be386e684d1af52e46e961 | /bhuman2ros/src/CommBase.cpp | 4a97927f476ac05203b547661998269ef3f1de67 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | uchile-robotics/nao-backpack | e9d78599dc373b4cb00d12a2104d52ba0d74cac1 | 985872aaa449ae25c4acc28c68f2bca923495f80 | refs/heads/master | 2021-03-27T11:34:25.977724 | 2017-07-12T04:44:43 | 2017-07-12T04:44:43 | 85,327,456 | 22 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,703 | cpp | /**
* @file CommBase.cpp
* This file implements a template of communication threads between ROS and B-Human
*
* This file uses part of the BHuman Code Release 2016 <a href="https://github.com/bhuman/BHumanCodeRelease"</a>)
*
* @author <a href="mailto:mmattamala@ing.uchile.cl">Matias Mattamala</a>
*/
#include "CommBase.h"
namespace bhuman2ros
{
CommBase::CommBase(std::string name, std::string ip, int port, int buf_size, int rate, boost::mutex& mutex)
: name_(name), ip_(ip), port_(port), m_buf_size_(buf_size), tmp_buf_size_(2048), rate_(rate)
{
mutex_ = boost::shared_ptr<boost::mutex>(&mutex);
// configure UDP
configureSocket();
// prepare buffers
queue_.setSize(m_buf_size_);
out_queue_.setSize(m_buf_size_);
m_buf_ = new char [m_buf_size_];
tmp_buf_ = new char[tmp_buf_size_];
}
CommBase::~CommBase()
{
if(m_buf_)
delete [] m_buf_;
if(tmp_buf_)
delete [] tmp_buf_;
}
bool CommBase::main()
{
ros::Rate thread_rate(rate_);
{
boost::mutex::scoped_lock lock(*mutex_);
Global::theStreamHandler = &stream_handler_;
}
while(ros::ok())
{
time = ros::Time::now();
bool sent = sendMessages();
bool received = receiveMessages();
if(received)
{
queue_.handleAllMessages(*this);
queue_.clear();
}
else
{
thread_rate.sleep();
}
}
}
void CommBase::configureSocket()
{
socket_.setBlocking(false);
socket_.setBroadcast(false);
socket_.bind("0.0.0.0", port_);
socket_.setTarget(ip_.c_str(), port_);
socket_.setTTL(0);
socket_.setLoopback(false);
}
} //bhuman2ros
| [
"mmattamala@ing.uchile.cl"
] | mmattamala@ing.uchile.cl |
a2c806b521d4ac22e9b7f804fdb55c520c274188 | 04f2c13225801b4a0192e082b4354d38e0162804 | /source/LightManager.cpp | 7d209f6a66cbd93799f970b5ad7a80a3b15bc84f | [] | no_license | EricPolman/software-rasterizer | 7c6ffbbc2bc429f653efb06b3168d0b0c62e361c | eb2fc86af684d72fd659557da99002dc76aa86c0 | refs/heads/master | 2021-01-20T08:44:17.100229 | 2015-01-26T11:21:51 | 2015-01-26T11:21:51 | 29,857,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 97 | cpp | #include "LightManager.h"
LightManager::LightManager()
{
}
LightManager::~LightManager()
{
}
| [
"eric@ericpolman.com"
] | eric@ericpolman.com |
3fdfca0eee48dd24d8042a4f76ad86a61f3ed8f9 | 0b4300aa6cb5401e7cd86d68cf9d978e3b6395b8 | /Analysis/RpcPro2DB/include/EnhancedVars.hpp | f3a2cc4e06d0751b8eff2652aef5232fbc73cee5 | [] | no_license | kaikai581/graduate-svn-repo | 1e62d7f9f3cb5c32d27b9e53d28f44c495226f7d | c1838d30b8f420302e5d12d6deb648f9ab1cc987 | refs/heads/master | 2022-02-24T03:55:32.339211 | 2022-02-08T15:49:45 | 2022-02-08T15:49:45 | 232,512,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,890 | hpp | #ifndef ENHANCEDVARS_HPP
#define ENHANCEDVARS_HPP
#include "RawVars.hpp"
class EnhancedTreeVars;
class EnhancedVars : public RawVars
{
public:
static unsigned int eventId;
static unsigned int runNumber;
static unsigned int fileNumber;
unsigned int nModules;
rpc::mReadoutClusters mRpcCluster;
/// gather strips to form clusters in a whole readout
rpc::roSpuriousIndex roSpuIdx;
rpc::roTrackPairIdx roXTrackPairIdx;
rpc::roTrackPairIdx roYTrackPairIdx;
/// These variables are the same as previous 2 for 4-fold events.
/// For 3-fold, strips with IDs the same as those in the unpaired layer
/// are fired artificially
rpc::roTrackPairIdx roXForcedTrackPairIdx;
rpc::roTrackPairIdx roYForcedTrackPairIdx;
/*
* number of unfired strips between 2 clusters of different layers
* only applicable to events with exactly 1 cluster per layer
* return value:
* 0-6: number of unfired strips between the 2 clusters
* -1 : the two clusters overlap
* -2 : non-applicable events
*/
std::map<rpc::mId, int> roXClusterDistance;
std::map<rpc::mId, int> roYClusterDistance;
/// cluster center of mass variables for reconstruction
rpc::roClusterCMS roClCMS;
/// track center of mass
rpc::roTrackCMS roXTrackCMS;
rpc::roTrackCMS roYTrackCMS;
rpc::roTrackCMS roXForcedTrackCMS;
rpc::roTrackCMS roYForcedTrackCMS;
EnhancedVars(){};
EnhancedVars(PerCalibReadoutHeader*);
virtual ~EnhancedVars(){};
void printClusterCMS();
void printClusters();
void printClusterDistance();
void printModTrackCMS(rpc::mId);
void printTracks();
void printForcedTracks();
void printSpurios();
void fillTreeVars(EnhancedTreeVars&);
rpc::mReadoutClusters getRoInCluster() {return mRpcCluster;};
protected:
void clusterizeModule();
rpc::mTrackCMS findPairedLayerTrackCMS(const rpc::mTrackPairIdx&, rpc::lClusterCMS, rpc::lClusterCMS);
/// methonds of finding tracks and spurious hits
virtual void findTracksSpurious();
rpc::mTrackPairIdx findPairTracksSpurious(const rpc::mLayerClusters&, const rpc::mLayerClusters&, rpc::mLayerClusters&, rpc::mLayerClusters&);
virtual rpc::mTrackPairIdx pairForcedClusters(rpc::mLayerClusters, rpc::mLayerClusters);
void findClusterDistance();
void findRoClusterCMS();
void findRoTrackCMS();
double findClusterUnitCMS(const rpc::clusterUnit&);
rpc::mLayerClusters clusterizeLayer(const rpc::mStripsInLayer&);
int findPairClusterDistance(const rpc::clusterUnit&, const rpc::clusterUnit&);
unsigned int nStripsInCommon(const rpc::clusterUnit&, const rpc::clusterUnit&);
};
#endif
| [
"kaikai581@hotmail.com"
] | kaikai581@hotmail.com |
6507d75b04dcbcd2880f1605cd441e438bed0f34 | f80795913b6fbbfbc1501ca1e04140d1dac1d70e | /10.0.14393.0/winrt/internal/Windows.Phone.Management.Deployment.1.h | 33265d5646855eb154d5ace5d69c8801edb21c39 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | jjhegedus/cppwinrt | 13fffb02f2e302b57e0f2cac74e02a9e2d94b9cf | fb3238a29cf70edd154de8d2e36b2379e25cc2c4 | refs/heads/master | 2021-01-09T06:21:16.273638 | 2017-02-05T05:34:37 | 2017-02-05T05:34:37 | 80,971,093 | 1 | 0 | null | 2017-02-05T05:27:18 | 2017-02-05T05:27:17 | null | UTF-8 | C++ | false | false | 9,818 | h | // C++ for the Windows Runtime v1.0.161012.5
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Phone.Management.Deployment.0.h"
#include "Windows.Foundation.0.h"
#include "Windows.Management.Deployment.0.h"
#include "Windows.Foundation.Collections.1.h"
#include "Windows.Foundation.1.h"
#include "Windows.ApplicationModel.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Phone::Management::Deployment {
struct __declspec(uuid("96592f8d-856c-4426-a947-b06307718078")) __declspec(novtable) IEnterprise : Windows::IInspectable
{
virtual HRESULT __stdcall get_Id(GUID * value) = 0;
virtual HRESULT __stdcall get_Name(hstring * value) = 0;
virtual HRESULT __stdcall get_WorkplaceId(int32_t * value) = 0;
virtual HRESULT __stdcall get_EnrollmentValidFrom(Windows::Foundation::DateTime * value) = 0;
virtual HRESULT __stdcall get_EnrollmentValidTo(Windows::Foundation::DateTime * value) = 0;
virtual HRESULT __stdcall get_Status(winrt::Windows::Phone::Management::Deployment::EnterpriseStatus * value) = 0;
};
struct __declspec(uuid("20f9f390-2c69-41d8-88e6-e4b3884026cb")) __declspec(novtable) IEnterpriseEnrollmentManager : Windows::IInspectable
{
virtual HRESULT __stdcall get_EnrolledEnterprises(Windows::Foundation::Collections::IVectorView<Windows::Phone::Management::Deployment::Enterprise> ** result) = 0;
virtual HRESULT __stdcall get_CurrentEnterprise(Windows::Phone::Management::Deployment::IEnterprise ** result) = 0;
virtual HRESULT __stdcall abi_ValidateEnterprisesAsync(Windows::Foundation::IAsyncAction ** result) = 0;
virtual HRESULT __stdcall abi_RequestEnrollmentAsync(hstring enrollmentToken, Windows::Foundation::IAsyncOperation<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> ** result) = 0;
virtual HRESULT __stdcall abi_RequestUnenrollmentAsync(Windows::Phone::Management::Deployment::IEnterprise * enterprise, Windows::Foundation::IAsyncOperation<bool> ** result) = 0;
};
struct __declspec(uuid("9ff71ce6-90db-4342-b326-1729aa91301c")) __declspec(novtable) IEnterpriseEnrollmentResult : Windows::IInspectable
{
virtual HRESULT __stdcall get_EnrolledEnterprise(Windows::Phone::Management::Deployment::IEnterprise ** result) = 0;
virtual HRESULT __stdcall get_Status(winrt::Windows::Phone::Management::Deployment::EnterpriseEnrollmentStatus * value) = 0;
};
struct __declspec(uuid("929aa738-8d49-42ac-80c9-b4ad793c43f2")) __declspec(novtable) IInstallationManagerStatics : Windows::IInspectable
{
virtual HRESULT __stdcall abi_AddPackageAsync(hstring title, Windows::Foundation::IUriRuntimeClass * sourceLocation, Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> ** asyncInfo) = 0;
virtual HRESULT __stdcall abi_AddPackagePreloadedAsync(hstring title, Windows::Foundation::IUriRuntimeClass * sourceLocation, hstring instanceId, hstring offerId, Windows::Foundation::IUriRuntimeClass * license, Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> ** asyncInfo) = 0;
virtual HRESULT __stdcall abi_GetPendingPackageInstalls(Windows::Foundation::Collections::IIterable<Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t>> ** items) = 0;
virtual HRESULT __stdcall abi_FindPackagesForCurrentPublisher(Windows::Foundation::Collections::IIterable<Windows::ApplicationModel::Package> ** items) = 0;
virtual HRESULT __stdcall abi_FindPackages(Windows::Foundation::Collections::IIterable<Windows::ApplicationModel::Package> ** items) = 0;
};
struct __declspec(uuid("7c6c2cbd-fa4a-4c8e-ab97-d959452f19e5")) __declspec(novtable) IInstallationManagerStatics2 : Windows::IInspectable
{
virtual HRESULT __stdcall abi_RemovePackageAsync(hstring packageFullName, winrt::Windows::Management::Deployment::RemovalOptions removalOptions, Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> ** asyncInfo) = 0;
virtual HRESULT __stdcall abi_RegisterPackageAsync(Windows::Foundation::IUriRuntimeClass * manifestUri, Windows::Foundation::Collections::IIterable<Windows::Foundation::Uri> * dependencyPackageUris, winrt::Windows::Management::Deployment::DeploymentOptions deploymentOptions, Windows::Foundation::IAsyncOperationWithProgress<Windows::Phone::Management::Deployment::PackageInstallResult, uint32_t> ** asyncInfo) = 0;
virtual HRESULT __stdcall abi_FindPackagesByNamePublisher(hstring packageName, hstring packagePublisher, Windows::Foundation::Collections::IIterable<Windows::ApplicationModel::Package> ** items) = 0;
};
struct __declspec(uuid("33e8eed5-0f7e-4473-967c-7d6e1c0e7de1")) __declspec(novtable) IPackageInstallResult : Windows::IInspectable
{
virtual HRESULT __stdcall get_ProductId(hstring * value) = 0;
virtual HRESULT __stdcall get_InstallState(winrt::Windows::Management::Deployment::PackageInstallState * value) = 0;
};
struct __declspec(uuid("7149d909-3ff9-41ed-a717-2bc65ffc61d2")) __declspec(novtable) IPackageInstallResult2 : Windows::IInspectable
{
virtual HRESULT __stdcall get_ErrorText(hstring * value) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Phone::Management::Deployment::Enterprise> { using default_interface = Windows::Phone::Management::Deployment::IEnterprise; };
template <> struct traits<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult> { using default_interface = Windows::Phone::Management::Deployment::IEnterpriseEnrollmentResult; };
template <> struct traits<Windows::Phone::Management::Deployment::PackageInstallResult> { using default_interface = Windows::Phone::Management::Deployment::IPackageInstallResult; };
}
namespace Windows::Phone::Management::Deployment {
template <typename T> struct impl_IEnterprise;
template <typename T> struct impl_IEnterpriseEnrollmentManager;
template <typename T> struct impl_IEnterpriseEnrollmentResult;
template <typename T> struct impl_IInstallationManagerStatics;
template <typename T> struct impl_IInstallationManagerStatics2;
template <typename T> struct impl_IPackageInstallResult;
template <typename T> struct impl_IPackageInstallResult2;
}
namespace impl {
template <> struct traits<Windows::Phone::Management::Deployment::IEnterprise>
{
using abi = ABI::Windows::Phone::Management::Deployment::IEnterprise;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IEnterprise<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IEnterpriseEnrollmentManager>
{
using abi = ABI::Windows::Phone::Management::Deployment::IEnterpriseEnrollmentManager;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IEnterpriseEnrollmentManager<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IEnterpriseEnrollmentResult>
{
using abi = ABI::Windows::Phone::Management::Deployment::IEnterpriseEnrollmentResult;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IEnterpriseEnrollmentResult<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IInstallationManagerStatics>
{
using abi = ABI::Windows::Phone::Management::Deployment::IInstallationManagerStatics;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IInstallationManagerStatics<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IInstallationManagerStatics2>
{
using abi = ABI::Windows::Phone::Management::Deployment::IInstallationManagerStatics2;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IInstallationManagerStatics2<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IPackageInstallResult>
{
using abi = ABI::Windows::Phone::Management::Deployment::IPackageInstallResult;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IPackageInstallResult<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::IPackageInstallResult2>
{
using abi = ABI::Windows::Phone::Management::Deployment::IPackageInstallResult2;
template <typename D> using consume = Windows::Phone::Management::Deployment::impl_IPackageInstallResult2<D>;
};
template <> struct traits<Windows::Phone::Management::Deployment::Enterprise>
{
using abi = ABI::Windows::Phone::Management::Deployment::Enterprise;
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.Management.Deployment.Enterprise"; }
};
template <> struct traits<Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.Management.Deployment.EnterpriseEnrollmentManager"; }
};
template <> struct traits<Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult>
{
using abi = ABI::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult;
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.Management.Deployment.EnterpriseEnrollmentResult"; }
};
template <> struct traits<Windows::Phone::Management::Deployment::InstallationManager>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.Management.Deployment.InstallationManager"; }
};
template <> struct traits<Windows::Phone::Management::Deployment::PackageInstallResult>
{
using abi = ABI::Windows::Phone::Management::Deployment::PackageInstallResult;
static constexpr const wchar_t * name() noexcept { return L"Windows.Phone.Management.Deployment.PackageInstallResult"; }
};
}
}
| [
"josuen@microsoft.com"
] | josuen@microsoft.com |
50c6241387cc04a1e402231bad23d08cd265b0d4 | dafd7c0de75202c854925370c86ee523d9f2fb05 | /17.cpp | 16e38a9a78749cab82cfc95b95fada43cb6525ae | [] | no_license | csillagg/euler | c3b574062329b5715b5680e3b2d5e74884cc614b | b7bd9ed08aa135145c023776e8cc0fe566f0790a | refs/heads/master | 2021-09-18T07:53:52.132457 | 2018-07-11T13:14:01 | 2018-07-11T13:14:01 | 114,776,613 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | cpp | #include <iostream>
using namespace std;
int egyjegyu(int szam) {
int ered;
if (szam == 1 || szam == 2 || szam == 6) {
ered = 3;
} else if (szam == 4 || szam == 5 || szam == 9) {
ered = 4;
} else if (szam == 7 || szam == 8 || szam == 3) {
ered = 5;
}
return ered;
}
int ketjegyu (int szam) {
int ered;
if (szam == 10) {
ered = 3;
} else if (szam == 20 || szam == 30 || szam == 80 || szam == 90 || szam == 11 || szam == 12) {
ered = 6;
} else if (szam == 70 || szam == 15 || szam == 16) {
ered = 7;
} else if (szam == 40 || szam == 50 || szam == 60){
ered = 5;
} else if (szam == 13 || szam == 14 || szam == 18 || szam == 19) {
ered = 8;
} else if (szam == 17) {
ered = 9;
} else {
int a = szam % 10;
if (szam - a == 20 || szam - a == 30 || szam - a == 80 || szam - a == 90) {
ered = 6 + egyjegyu(a);
} else if (szam - a == 70) {
ered = 7 + egyjegyu(a);
} else if (szam - a == 40 || szam - a == 50 || szam - a == 60) {
ered = 5 + egyjegyu(a);
}
}
return ered;
}
int haromjegyu (int szam) {
int ered;
if (szam % 100 == 0) {
ered = egyjegyu(szam/100) + 7;
} else {
int a = szam % 100;
ered = egyjegyu((szam-a)/100) + 7 + ketjegyu(a) + 3;
}
return ered;
}
int main()
{
int ered = 0;
for (int i = 1; i <= 9; i++) {
ered += egyjegyu(i);
}
for (int i = 10; i <= 99; i++) {
ered += ketjegyu(i);
}
for (int i = 100; i <= 999; i++) {
ered += haromjegyu(i);
}
cout << ered + 11;
return 0;
} | [
"csilli97@freemail.hu"
] | csilli97@freemail.hu |
78c58c9df37cff7ed75e2069b7d8b63743284cce | 6e5aca8a2d93092dbb8ad130d4bc904b49b938f9 | /algorithm/daiziguizhong/radix-sort.cc | f2c661062c7f0f24437deb29742a1de2a886c2d1 | [] | no_license | ljshou/workspace | 6a1b79f0b222cefee8d751fe5c32c726466fa38e | 7cc1067f22cca9e56511f89be7e24420fe894090 | refs/heads/master | 2016-09-05T13:30:42.402922 | 2016-02-28T15:35:40 | 2016-02-28T15:35:40 | 26,074,693 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | cc | /**
* @file radix-sort.cc
* @brief
* @author L.J.SHOU, shoulinjun@126.com
* @version 0.1.00
* @date 2015-01-26
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int RADIX = 10;
int front[RADIX];
int rear[RADIX];
struct Node {
string key;
int link;
Node(const string &str = ""):
key(str), link(-1) {}
};
int getDigit(const string &str, int i)
{
if(i >= str.size()) return 0;
return str[str.size()-i-1] - '0';
}
void PrintList(const vector<Node> &vec)
{
int current = vec[0].link;
while(current != 0) {
cout << vec[current].key << " ";
current = vec[current].link;
}
cout << endl;
}
/**
* vec[0]----dummy node
*/
void RadixSort(vector<Node> &vec, int d)
{
const int n = vec.size();
if(n < 3) return;
for(int i=0; i<n-1; ++i) {
vec[i].link = i+1;
}
vec[n-1].link = 0;
int digit = 0;
for(int i=0; i<d; ++i) {
//clear state
for(int j=0; j<RADIX; ++j) front[j] = 0;
int current = vec[0].link;
while(current != 0) {
digit = getDigit(vec[current].key, i);
if(front[digit] == 0) {
front[digit] = rear[digit] = current;
}
else {
vec[rear[digit]].link = current;
rear[digit] = current;
}
current = vec[current].link;
}
int last = 0;
//link all lists togethor
for(int j=0; j<RADIX; ++j) {
if(front[j] != 0) {
if(last == 0) {
vec[0].link = front[j];
}
else {
vec[last].link = front[j];
}
last = rear[j];
}
}
vec[last].link = 0;
}
PrintList(vec);
}
void Test()
{
vector<Node> vec{{""}, {"123"}, {"12"}, {"1"}, {"4"},
{"270"}, {"100"}, {"99"}};
RadixSort(vec, 3);
}
int main(void)
{
Test();
return 0;
}
| [
"shoulinjun@126.com"
] | shoulinjun@126.com |
40776563c1a992aec769f7dc53157596ba20d4e2 | c3a0f82e6d0fb3e8fb49afc042560e5787e42141 | /codeforces/1238/D.cpp | 86bc6ee7a462aeaa72524705c3236da6081a23c8 | [] | no_license | SahajGupta11/Codeforces-submissions | 04abcd8b0632e7cdd2748d8b475eed152d00ed1b | 632f87705ebe421f954a59d99428e7009d021db1 | refs/heads/master | 2023-02-05T08:06:53.500395 | 2019-09-18T16:16:00 | 2020-12-22T14:32:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | cpp | #include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
using namespace std;
#define cerr if(0)cerr
#define watch(x) cerr << (#x) << " is " << (x) << endl
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define max3(x,y,z) max(x,max(y,z))
#define min3(x,y,z) min(x,min(y,z))
#define MOD 1000000007 //1e9 + 7
#define INF 2000000000 //2e9
#define DESPACITO 1000000000000000000 //1e18
#define PI acos(-1);
#define E 998244353
#define ins insert
#define pb push_back
#define mp make_pair
#define sz(x) (int)(x).size()
#define X first
#define Y second
#define lb lower_bound
#define ub upper_bound
#define int long long
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 1e5 + 5;
int32_t main() {
IOS;
int i, n, prv = -1, cnt = 0, ans = 0;
bool flag = 0;
string s;
cin >> n >> s;
for(flag = 0, i = 0; i < n; i++) {
if (s[i] == 'A' and !flag)
flag = 1, prv = i;
if (s[i] == 'A' and flag)
ans += max(0, i-prv-1), prv = i, cnt = 0;
if (s[i] == 'B' and flag)
cnt++;
}
if (cnt) ans += max(0, i-prv-1);
for(cnt = 0, flag = 0, i = 0; i < n; i++) {
if (s[i] == 'B' and !flag)
flag = 1, prv = i;
if (s[i] == 'B' and flag)
ans += max(0, i-prv-1), prv = i;
if (s[i] == 'A' and flag)
cnt++;
}
if (cnt) ans += max(0, i-prv-1);
reverse(s.begin(), s.end());
for(cnt = 0, flag = 0, i = 0; i < n; i++) {
if (s[i] == 'B' and !flag)
flag = 1, prv = i;
if (s[i] == 'B' and flag)
ans += max(0, i-prv-2), prv = i;
if (s[i] == 'A' and flag)
cnt++;
}
if (cnt) ans += max(0, i-prv-2);
for(cnt = 0, flag = 0, i = 0; i < n; i++) {
if (s[i] == 'A' and !flag)
flag = 1, prv = i;
if (s[i] == 'A' and flag)
ans += max(0, i-prv-2), prv = i;
if (s[i] == 'B' and flag)
cnt++;
}
if (cnt) ans += max(0, i-prv-2);
ans = n*(n-1)/2 - ans;
cout << ans;
return 0;
}
| [
"ghriday.bits@gmail.com"
] | ghriday.bits@gmail.com |
2140cef9fb4988df7aa14cc60d3260cb4e175150 | 087147cb085697d1176e431902a0f5834ae31b7f | /src/seurobot/include/seurobot/action_engine.hpp | af095bdb3670f9f5bbaa1a504c98dc1b16e7bb1f | [] | no_license | Exception0x0194/SEURoboCup2020 | 58a235a03a80a1b3effde7a806308e6e2e95cb0b | d7d6c5516cfd8444e0cb0eab997a479a6f450403 | refs/heads/master | 2023-01-04T22:51:09.485447 | 2020-10-17T13:30:02 | 2020-10-17T13:30:02 | 303,361,204 | 1 | 0 | null | 2020-10-16T06:51:23 | 2020-10-12T10:49:29 | C++ | UTF-8 | C++ | false | false | 845 | hpp | #pragma once
#include <seurobot/seu_robot.hpp>
#include <seumath/math.hpp>
#include <common/msg/body_angles.hpp>
namespace seurobot
{
class ActionEngine
{
public:
ActionEngine(std::string act_file, std::shared_ptr<SeuRobot> robot);
std::vector<common::msg::BodyAngles> runAction(std::string act, int idx=100);
std::vector<std::string> getActions();
ActMap& get_act_map()
{
return act_map_;
}
PosMap& get_pos_map()
{
return pos_map_;
}
private:
std::vector< std::map<RobotMotion, RobotPose> >
get_poses(std::map<RobotMotion, RobotPose> &pos1,
std::map<RobotMotion, RobotPose> &pos2, int act_time);
bool get_degs(PoseMap &act_pose, common::msg::BodyAngles &bAngles);
private:
ActMap act_map_;
PosMap pos_map_;
std::shared_ptr<SeuRobot> robot_;
};
}
| [
"rockylc@163.com"
] | rockylc@163.com |
fef1a6f3df2609bbb58eef7e5a2f6aef90005b80 | 8f903e8dbcc30e98c005c22108003f7a0c461538 | /app_mesh.cpp | afa9ede08068046e566ff334d515656c695d9930 | [
"MIT"
] | permissive | blu/hello-chromeos-gles2 | 90938b4230885023b9bf413c41c477c40429a559 | d9e0626b78ef67aee0db96e39a3d0038aad8bb7d | refs/heads/master | 2023-08-14T00:54:45.981023 | 2023-07-29T17:48:51 | 2023-07-29T17:48:51 | 146,986,090 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,617 | cpp | #if PLATFORM_GL
#include <GL/gl.h>
#include <GL/glext.h>
#include "gles_gl_mapping.hpp"
#else
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "gles_ext.h"
#endif // PLATFORM_GL
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <cmath>
#include <string>
#include <sstream>
#include "scoped.hpp"
#include "stream.hpp"
#include "vectsimd.hpp"
#include "rendIndexedTrilist.hpp"
#include "rendSkeleton.hpp"
#include "util_misc.hpp"
#include "pure_macro.hpp"
#include "rendVertAttr.hpp"
using util::scoped_ptr;
using util::scoped_functor;
using util::deinit_resources_t;
namespace sk {
#define SETUP_VERTEX_ATTR_POINTERS_MASK ( \
SETUP_VERTEX_ATTR_POINTERS_MASK_vertex)
#include "rendVertAttr_setupVertAttrPointers.hpp"
#undef SETUP_VERTEX_ATTR_POINTERS_MASK
struct Vertex {
GLfloat pos[3];
};
} // namespace sk
namespace { // anonymous
const char arg_prefix[] = "-";
const char arg_app[] = "app";
const char arg_anim_step[] = "anim_step";
const char arg_mesh[] = "mesh";
const char arg_rot_axes[] = "rot_axes";
const char* g_mesh_filename = "asset/mesh/tetra.mesh";
float g_angle;
float g_angle_step = .0125f;
float g_rot_axis[] = { 1.f, 1.f, 1.f };
simd::matx4 g_matx_fit;
#if PLATFORM_EGL
EGLDisplay g_display = EGL_NO_DISPLAY;
EGLContext g_context = EGL_NO_CONTEXT;
#endif
enum {
TEX__DUMMY, // avoid zero-sized declarations
TEX_COUNT,
TEX_FORCE_UINT = -1U
};
enum {
PROG_SKIN,
PROG_COUNT,
PROG_FORCE_UINT = -1U
};
enum {
UNI_LP_OBJ,
UNI_VP_OBJ,
UNI_MVP,
UNI_COUNT,
UNI_FORCE_UINT = -1U
};
enum {
MESH_SKIN,
MESH_COUNT,
MESH_FORCE_UINT = -1U
};
enum {
VBO_SKIN_VTX,
VBO_SKIN_IDX,
VBO_COUNT,
VBO_FORCE_UINT = -1U
};
GLint g_uni[PROG_COUNT][UNI_COUNT];
#if PLATFORM_GL_OES_vertex_array_object
GLuint g_vao[PROG_COUNT];
#endif
GLuint g_tex[TEX_COUNT];
GLuint g_vbo[VBO_COUNT];
GLuint g_shader_vert[PROG_COUNT];
GLuint g_shader_frag[PROG_COUNT];
GLuint g_shader_prog[PROG_COUNT];
unsigned g_num_faces[MESH_COUNT];
GLenum g_index_type;
rend::ActiveAttrSemantics g_active_attr_semantics[PROG_COUNT];
} // namespace
bool hook::set_num_drawcalls(
const unsigned)
{
return false;
}
unsigned hook::get_num_drawcalls()
{
return 1;
}
bool hook::requires_depth()
{
return true;
}
static bool parse_cli(
const unsigned argc,
const char* const* argv)
{
bool cli_err = false;
const unsigned prefix_len = strlen(arg_prefix);
for (unsigned i = 1; i < argc && !cli_err; ++i) {
if (strncmp(argv[i], arg_prefix, prefix_len) ||
strcmp(argv[i] + prefix_len, arg_app)) {
continue;
}
if (++i < argc) {
if (i + 1 < argc && !strcmp(argv[i], arg_mesh)) {
g_mesh_filename = argv[i + 1];
i += 1;
continue;
}
else
if (i + 1 < argc && !strcmp(argv[i], arg_anim_step)) {
if (1 == sscanf(argv[i + 1], "%f", &g_angle_step) && 0.f < g_angle_step) {
i += 1;
continue;
}
}
else
if (i + 3 < argc && !strcmp(argv[i], arg_rot_axes)) {
unsigned axis[3];
if (1 == sscanf(argv[i + 1], "%u", axis + 0) &&
1 == sscanf(argv[i + 2], "%u", axis + 1) &&
1 == sscanf(argv[i + 3], "%u", axis + 2)) {
g_rot_axis[0] = axis[0] ? 1.f : 0.f;
g_rot_axis[1] = axis[1] ? 1.f : 0.f;
g_rot_axis[2] = axis[2] ? 1.f : 0.f;
i += 3;
continue;
}
}
}
cli_err = true;
}
if (cli_err) {
stream::cerr << "app options:\n"
"\t" << arg_prefix << arg_app << " " << arg_mesh <<
" <filename>\t\t\t\t: use specified mesh file of coordinates and indices\n"
"\t" << arg_prefix << arg_app << " " << arg_anim_step <<
" <step>\t\t\t\t: use specified animation step; entire animation is 1.0\n"
"\t" << arg_prefix << arg_app << " " << arg_rot_axes <<
" <int> <int> <int>\t\t\t: rotate mesh around the specified mask for x, y and z axes; default is 1 1 1 -- all axes\n\n";
}
return !cli_err;
}
namespace { // anonymous
template < unsigned PROG_T >
inline bool
bindVertexBuffersAndPointers()
{
assert(false);
return false;
}
template <>
inline bool
bindVertexBuffersAndPointers< PROG_SKIN >()
{
glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKIN_VTX]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_vbo[VBO_SKIN_IDX]);
DEBUG_GL_ERR()
return sk::setupVertexAttrPointers< sk::Vertex >(g_active_attr_semantics[PROG_SKIN]);
}
bool check_context(
const char* prefix)
{
bool context_correct = true;
#if PLATFORM_EGL
if (g_display != eglGetCurrentDisplay()) {
stream::cerr << prefix << " encountered foreign display\n";
context_correct = false;
}
if (g_context != eglGetCurrentContext()) {
stream::cerr << prefix << " encountered foreign context\n";
context_correct = false;
}
#endif
return context_correct;
}
} // namespace
bool
hook::deinit_resources()
{
if (!check_context(__FUNCTION__))
return false;
for (unsigned i = 0; i < sizeof(g_shader_prog) / sizeof(g_shader_prog[0]); ++i) {
glDeleteProgram(g_shader_prog[i]);
g_shader_prog[i] = 0;
}
for (unsigned i = 0; i < sizeof(g_shader_vert) / sizeof(g_shader_vert[0]); ++i) {
glDeleteShader(g_shader_vert[i]);
g_shader_vert[i] = 0;
}
for (unsigned i = 0; i < sizeof(g_shader_frag) / sizeof(g_shader_frag[0]); ++i) {
glDeleteShader(g_shader_frag[i]);
g_shader_frag[i] = 0;
}
glDeleteTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex);
memset(g_tex, 0, sizeof(g_tex));
#if PLATFORM_GL_OES_vertex_array_object
glDeleteVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao);
memset(g_vao, 0, sizeof(g_vao));
#endif
glDeleteBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo);
memset(g_vbo, 0, sizeof(g_vbo));
#if PLATFORM_EGL
g_display = EGL_NO_DISPLAY;
g_context = EGL_NO_CONTEXT;
#endif
return true;
}
namespace { // anonymous
#if DEBUG && PLATFORM_GL_KHR_debug
void debugProc(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam)
{
fprintf(stderr, "log: %s\n", message);
}
#endif
} // namespace
bool
hook::init_resources(
const unsigned argc,
const char* const * argv)
{
if (!parse_cli(argc, argv))
return false;
#if DEBUG && PLATFORM_GL_KHR_debug
glDebugMessageCallbackKHR(debugProc, NULL);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR);
glEnable(GL_DEBUG_OUTPUT_KHR);
DEBUG_GL_ERR()
glDebugMessageInsertKHR(
GL_DEBUG_SOURCE_APPLICATION_KHR,
GL_DEBUG_TYPE_OTHER_KHR,
GLuint(42),
GL_DEBUG_SEVERITY_HIGH_KHR,
GLint(-1),
"testing 1, 2, 3");
DEBUG_GL_ERR()
#endif
#if PLATFORM_EGL
g_display = eglGetCurrentDisplay();
if (EGL_NO_DISPLAY == g_display) {
stream::cerr << __FUNCTION__ << " encountered nil display\n";
return false;
}
g_context = eglGetCurrentContext();
if (EGL_NO_CONTEXT == g_context) {
stream::cerr << __FUNCTION__ << " encountered nil context\n";
return false;
}
#endif
scoped_ptr< deinit_resources_t, scoped_functor > on_error(deinit_resources);
/////////////////////////////////////////////////////////////////
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
const GLclampf red = .25f;
const GLclampf green = .25f;
const GLclampf blue = .25f;
const GLclampf alpha = 0.f;
glClearColor(red, green, blue, alpha);
glClearDepthf(1.f);
/////////////////////////////////////////////////////////////////
glGenTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex);
for (unsigned i = 0; i < sizeof(g_tex) / sizeof(g_tex[0]); ++i)
assert(g_tex[i]);
/////////////////////////////////////////////////////////////////
for (unsigned i = 0; i < PROG_COUNT; ++i)
for (unsigned j = 0; j < UNI_COUNT; ++j)
g_uni[i][j] = -1;
/////////////////////////////////////////////////////////////////
g_shader_vert[PROG_SKIN] = glCreateShader(GL_VERTEX_SHADER);
assert(g_shader_vert[PROG_SKIN]);
if (!util::setupShader(g_shader_vert[PROG_SKIN], "asset/shader/blinn.glslv")) {
stream::cerr << __FUNCTION__ << " failed at setupShader\n";
return false;
}
g_shader_frag[PROG_SKIN] = glCreateShader(GL_FRAGMENT_SHADER);
assert(g_shader_frag[PROG_SKIN]);
if (!util::setupShader(g_shader_frag[PROG_SKIN], "asset/shader/blinn.glslf")) {
stream::cerr << __FUNCTION__ << " failed at setupShader\n";
return false;
}
g_shader_prog[PROG_SKIN] = glCreateProgram();
assert(g_shader_prog[PROG_SKIN]);
if (!util::setupProgram(
g_shader_prog[PROG_SKIN],
g_shader_vert[PROG_SKIN],
g_shader_frag[PROG_SKIN]))
{
stream::cerr << __FUNCTION__ << " failed at setupProgram\n";
return false;
}
g_uni[PROG_SKIN][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "mvp");
g_uni[PROG_SKIN][UNI_LP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "lp_obj");
g_uni[PROG_SKIN][UNI_VP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "vp_obj");
g_active_attr_semantics[PROG_SKIN].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Vertex"));
/////////////////////////////////////////////////////////////////
#if PLATFORM_GL_OES_vertex_array_object
glGenVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao);
for (unsigned i = 0; i < sizeof(g_vao) / sizeof(g_vao[0]); ++i)
assert(g_vao[i]);
#endif
glGenBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo);
for (unsigned i = 0; i < sizeof(g_vbo) / sizeof(g_vbo[0]); ++i)
assert(g_vbo[i]);
float bbox_min[3];
float bbox_max[3];
if (!util::fill_indexed_trilist_from_file_P(
g_mesh_filename,
g_vbo[VBO_SKIN_VTX],
g_vbo[VBO_SKIN_IDX],
g_num_faces[MESH_SKIN],
g_index_type,
bbox_min,
bbox_max))
{
stream::cerr << __FUNCTION__ << " failed at fill_indexed_trilist_from_file_P\n";
return false;
}
const float centre[3] = {
(bbox_min[0] + bbox_max[0]) * .5f,
(bbox_min[1] + bbox_max[1]) * .5f,
(bbox_min[2] + bbox_max[2]) * .5f
};
const float extent[3] = {
(bbox_max[0] - bbox_min[0]) * .5f,
(bbox_max[1] - bbox_min[1]) * .5f,
(bbox_max[2] - bbox_min[2]) * .5f
};
const float rcp_extent = 1.f / fmaxf(fmaxf(extent[0], extent[1]), extent[2]);
g_matx_fit = simd::matx4(
rcp_extent, 0.f, 0.f, 0.f,
0.f, rcp_extent, 0.f, 0.f,
0.f, 0.f, rcp_extent, 0.f,
-centre[0] * rcp_extent,
-centre[1] * rcp_extent,
-centre[2] * rcp_extent, 1.f);
#if PLATFORM_GL_OES_vertex_array_object
glBindVertexArrayOES(g_vao[PROG_SKIN]);
if (!bindVertexBuffersAndPointers< PROG_SKIN >() || (DEBUG_LITERAL && util::reportGLError())) {
stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SKIN\n";
return false;
}
for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i)
glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]);
DEBUG_GL_ERR()
glBindVertexArrayOES(0);
#endif // PLATFORM_GL_OES_vertex_array_object
on_error.reset();
return true;
}
namespace { // anonymous
class matx4_rotate : public simd::matx4 {
matx4_rotate();
matx4_rotate(const matx4_rotate&);
public:
matx4_rotate(
const float a,
const float x,
const float y,
const float z)
{
const float sin_a = sinf(a);
const float cos_a = cosf(a);
static_cast< simd::matx4& >(*this) = simd::matx4(
x * x + cos_a * (1 - x * x), x * y - cos_a * (x * y) + sin_a * z, x * z - cos_a * (x * z) - sin_a * y, 0.f,
y * x - cos_a * (y * x) - sin_a * z, y * y + cos_a * (1 - y * y), y * z - cos_a * (y * z) + sin_a * x, 0.f,
z * x - cos_a * (z * x) + sin_a * y, z * y - cos_a * (z * y) - sin_a * x, z * z + cos_a * (1 - z * z), 0.f,
0.f, 0.f, 0.f, 1.f);
}
};
class matx4_ortho : public simd::matx4
{
matx4_ortho();
matx4_ortho(const matx4_ortho&);
public:
matx4_ortho(
const float l,
const float r,
const float b,
const float t,
const float n,
const float f)
{
static_cast< simd::matx4& >(*this) = simd::matx4(
2.f / (r - l), 0.f, 0.f, 0.f,
0.f, 2.f / (t - b), 0.f, 0.f,
0.f, 0.f, 2.f / (n - f), 0.f,
(r + l) / (l - r), (t + b) / (b - t), (f + n) / (n - f), 1.f);
}
};
class matx4_persp : public simd::matx4
{
matx4_persp();
matx4_persp(const matx4_persp&);
public:
matx4_persp(
const float l,
const float r,
const float b,
const float t,
const float n,
const float f)
{
static_cast< simd::matx4& >(*this) = simd::matx4(
2.f * n / (r - l), 0.f, 0.f, 0.f,
0.f, 2.f * n / (t - b), 0.f, 0.f,
(r + l) / (r - l), (t + b) / (t - b), (f + n) / (n - f), -1.f,
0.f, 0.f, 2.f * f * n / (n - f), 0.f);
}
};
} // namespace
bool
hook::render_frame(GLuint /* primary_fbo */)
{
if (!check_context(__FUNCTION__))
return false;
const simd::matx4 r0 = matx4_rotate(g_rot_axis[0] * g_angle, 1.f, 0.f, 0.f);
const simd::matx4 r1 = matx4_rotate(g_rot_axis[1] * g_angle, 0.f, 1.f, 0.f);
const simd::matx4 r2 = matx4_rotate(g_rot_axis[2] * g_angle, 0.f, 0.f, 1.f);
const simd::matx4 p0 = simd::matx4().mul(r0, r1);
const simd::matx4 p1 = simd::matx4().mul(p0, r2);
g_angle += g_angle_step;
const float z_offset = -2.375f;
const simd::vect4 translate(0.f, 0.f, z_offset, 0.f);
simd::matx4 mv = simd::matx4().mul(g_matx_fit, p1);
mv.set(3, simd::vect4().add(mv[3], translate));
const float l = -.5f;
const float r = .5f;
const float b = -.5f;
const float t = .5f;
const float n = 1.f;
const float f = 4.f;
const matx4_persp proj(l, r, b, t, n, f);
const simd::matx4 mvp = simd::matx4().mul(mv, proj);
const simd::vect3 lp_obj = simd::vect3(
mv[0][0] + mv[0][2],
mv[1][0] + mv[1][2],
mv[2][0] + mv[2][2]).normalise();
GLint vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
const float aspect = float(vp[3]) / vp[2];
const rend::dense_matx4 dense_mvp = rend::dense_matx4(
mvp[0][0] * aspect, mvp[0][1], mvp[0][2], mvp[0][3],
mvp[1][0] * aspect, mvp[1][1], mvp[1][2], mvp[1][3],
mvp[2][0] * aspect, mvp[2][1], mvp[2][2], mvp[2][3],
mvp[3][0] * aspect, mvp[3][1], mvp[3][2], mvp[3][3]);
/////////////////////////////////////////////////////////////////
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(g_shader_prog[PROG_SKIN]);
DEBUG_GL_ERR()
if (-1 != g_uni[PROG_SKIN][UNI_MVP]) {
glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_MVP],
1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp));
DEBUG_GL_ERR()
}
if (-1 != g_uni[PROG_SKIN][UNI_LP_OBJ]) {
const GLfloat nonlocal_light[4] = {
lp_obj[0],
lp_obj[1],
lp_obj[2],
0.f
};
glUniform4fv(g_uni[PROG_SKIN][UNI_LP_OBJ], 1, nonlocal_light);
DEBUG_GL_ERR()
}
if (-1 != g_uni[PROG_SKIN][UNI_VP_OBJ]) {
const GLfloat nonlocal_viewer[4] = {
mv[0][2],
mv[1][2],
mv[2][2],
0.f
};
glUniform4fv(g_uni[PROG_SKIN][UNI_VP_OBJ], 1, nonlocal_viewer);
DEBUG_GL_ERR()
}
#if PLATFORM_GL_OES_vertex_array_object
glBindVertexArrayOES(g_vao[PROG_SKIN]);
DEBUG_GL_ERR()
#else
if (!bindVertexBuffersAndPointers< PROG_SKIN >())
return false;
for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i)
glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]);
DEBUG_GL_ERR()
#endif
glDrawElements(GL_TRIANGLES, g_num_faces[MESH_SKIN] * 3, g_index_type, 0);
DEBUG_GL_ERR()
#if PLATFORM_GL_OES_vertex_array_object == 0
for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i)
glDisableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]);
DEBUG_GL_ERR()
#endif
return true;
}
| [
"blu.dark@gmail.com"
] | blu.dark@gmail.com |
625ea0ed58f9ed65d795744c2c43db14a293d115 | 6edb11d5782492565cd251266927859b62d1d49b | /第15章 面向对象程序设计/Disc_quote.cpp | fdc77587fafbd79d56a1350507660871b00d15e1 | [] | no_license | a1anpro/myCpp-Primer | 9253ab86fbdd55996dc2e7709a3ac87e9f98015a | f7cef1a950b79fc01256dc4bb80a9b80573ecc95 | refs/heads/master | 2021-01-15T21:30:32.131806 | 2017-09-03T01:18:51 | 2017-09-03T01:18:51 | 99,871,225 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 484 | cpp | #include "Disc_quote.h"
double Bulk_quote::net_price(size_t n) const {
if (n >= min_qty){
return price * (1-discount) * n;
}
else{
return price * n;
}
}
double Limit_quote::net_price(size_t n) const {
if (n < min_qty){
return n * price;
}
else if (n < max_qty){
//这个区间是打折的
return n * price * (1 - discount);
}
else{//超过这个区间,剩余的不打折
return max_qty * price * (1 - discount) + (n - max_qty) * price;
}
}
| [
"alanyanhui@gmail.com"
] | alanyanhui@gmail.com |
1b333df43dc53dadc8fe8df1aa4dce3b899b2df1 | d3d29f2b01a4f1fa479ace728da0fc40d9b9afe3 | /app/src/main/cpp/FFmpegVedio.cpp | 94e36fd99c3a033e9460bfbd6839f95f8a5eeb37 | [] | no_license | ITFlyPig/anything_player | 790e687cb72c3a6b51bce6ddbd0d94c59190bcc1 | 0f52f05346978e206beb567901c0282d11f24127 | refs/heads/master | 2021-08-15T02:51:29.671707 | 2017-11-17T07:58:35 | 2017-11-17T07:58:35 | 111,074,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,474 | cpp | //
// Created by david on 2017/9/27.
//
#include "FFmpegVedio.h"
FFmpegVedio::FFmpegVedio(){
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
}
static void (*video_call)(AVFrame *frame);
int FFmpegVedio::get(AVPacket *packet) {
pthread_mutex_lock(&mutex);
while (isPlay) {
if (!queue.empty()) {
// 从队列取出一个packet clone一个 给入参对象
if (av_packet_ref(packet, queue.front())) {
break;
}
// 取成功了 弹出队列 销毁packet
AVPacket *pkt = queue.front();
queue.pop();
av_free(pkt);
break;
} else {
// 如果队列里面没有数据的话 一直等待阻塞
pthread_cond_wait(&cond, &mutex);
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
int FFmpegVedio::put(AVPacket *packet) {
AVPacket *packet1 = (AVPacket *) av_malloc(sizeof(AVPacket));
if (av_copy_packet(packet1, packet)) {
LOGE("克隆失败");
// 克隆失败
return 0;
}
LOGE("压入一帧视频数据");
pthread_mutex_lock(&mutex);
queue.push(packet1);
// 给消费者解锁
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return 1;
}
void *play_vedio(void *arg){
FFmpegVedio *vedio = (FFmpegVedio *) arg;
//像素数据(解码数据)
AVFrame *frame = av_frame_alloc();
//转换rgba
SwsContext *sws_ctx = sws_getContext(
vedio->codec->width, vedio->codec->height,vedio->codec->pix_fmt,
vedio->codec->width,vedio->codec->height, AV_PIX_FMT_RGBA,
SWS_BILINEAR, 0, 0, 0);
AVFrame *rgb_frame = av_frame_alloc();
int out_size = av_image_get_buffer_size(AV_PIX_FMT_RGBA,vedio->codec->width,
vedio->codec->height, 1);
LOGE("上下文宽%d 高%d",vedio->codec->width, vedio->codec->height);
uint8_t *out_buffer = (uint8_t *) malloc(sizeof(uint8_t) * out_size);
av_image_fill_arrays(rgb_frame->data, rgb_frame->linesize, out_buffer,
AV_PIX_FMT_RGBA,
vedio->codec->width,vedio->codec->height, 1);
int len ,got_frame, framecount = 0;
LOGE("宽 %d ,高 %d ",vedio->codec->width,vedio->codec->height);
//编码数据
AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
//6.一阵一阵读取压缩的视频数据AVPacket
double last_play //上一帧的播放时间
,play //当前帧的播放时间
, last_delay // 上一次播放视频的两帧视频间隔时间
,delay //两帧视频间隔时间
,audio_clock //音频轨道 实际播放时间
,diff //音频帧与视频帧相差时间
,sync_threshold
,start_time //从第一帧开始的绝对时间
,pts
,actual_delay//真正需要延迟时间
;//两帧间隔合理间隔时间
start_time = av_gettime() / 1000000.0;
while (vedio->isPlay) {
LOGE("视频 解码 一帧 %d",vedio->queue.size());
// 消费者取到一帧数据 没有 阻塞
vedio->get(packet);
len = avcodec_decode_video2(vedio->codec,frame, &got_frame, packet);
if (!got_frame) {
continue;
}
// 转码成rgb
int code=sws_scale(sws_ctx, (const uint8_t *const *)frame->data, frame->linesize, 0,
vedio->codec->height,
rgb_frame->data, rgb_frame->linesize);
LOGE("输出%d ,%d",code,len);
LOGE("宽%d 高%d 行字节 %d 状态%d ====%d",frame->width,frame->height,rgb_frame->linesize[0],got_frame,vedio->codec->height);
// 得到了rgb_frame 下节课讲绘制 frame rgb pcm frame
if ((pts = av_frame_get_best_effort_timestamp(frame)) == AV_NOPTS_VALUE) {
pts = 0;
}
play = pts * av_q2d(vedio->time_base);
// 纠正时间
play = vedio->synchronize(frame, play);
delay = play - last_play;
if (delay <= 0 || delay > 1) {
delay = last_delay;
}
audio_clock = vedio->audio->clock;
last_delay = delay;
last_play = play;
//音频与视频的时间差
diff = vedio->clock - audio_clock;
// 在合理范围外 才会延迟 加快
sync_threshold = (delay > 0.01 ? 0.01 : delay);
if (fabs(diff) < 10) {
if (diff <= -sync_threshold) {
delay = 0;
} else if (diff >=sync_threshold) {
delay = 2 * delay;
}
}
start_time += delay;
actual_delay=start_time-av_gettime()/1000000.0;
if (actual_delay < 0.01) {
actual_delay = 0.01;
}
av_usleep(actual_delay*1000000.0+6000);
video_call(rgb_frame);
// av_packet_unref(packet);
// av_frame_unref(rgb_frame);
// av_frame_unref(frame);
}
LOGE("free packet");
av_free(packet);
LOGE("free packet ok");
LOGE("free packet");
av_frame_free(&frame);
av_frame_free(&rgb_frame);
sws_freeContext(sws_ctx);
size_t size = vedio->queue.size();
for (int i = 0; i < size; ++i) {
AVPacket *pkt = vedio->queue.front();
av_free(pkt);
vedio->queue.pop();
}
LOGE("VIDEO EXIT");
pthread_exit(0);
}
void FFmpegVedio::play() {
isPlay = 1;
pthread_create(&p_playid, 0, play_vedio, this);
}
void FFmpegVedio::stop() {
LOGE("VIDEO stop");
pthread_mutex_lock(&mutex);
isPlay = 0;
//因为可能卡在 deQueue
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(p_playid, 0);
LOGE("VIDEO join pass");
if (this->codec) {
if (avcodec_is_open(this->codec))
avcodec_close(this->codec);
avcodec_free_context(&this->codec);
this->codec = 0;
}
LOGE("VIDEO close");
}
void FFmpegVedio::setAvCodecContext(AVCodecContext *codecContext) {
codec = codecContext;
}
void FFmpegVedio::setPlayCall(void (*call1)(AVFrame *)) {
video_call=call1;
}
double FFmpegVedio::synchronize(AVFrame *frame, double play) {
//clock是当前播放的时间位置
if (play != 0)
clock=play;
else //pst为0 则先把pts设为上一帧时间
play = clock;
//可能有pts为0 则主动增加clock
//frame->repeat_pict = 当解码时,这张图片需要要延迟多少
//需要求出扩展延时:
//extra_delay = repeat_pict / (2*fps) 显示这样图片需要延迟这么久来显示
double repeat_pict = frame->repeat_pict;
//使用AvCodecContext的而不是stream的
double frame_delay = av_q2d(codec->time_base);
//如果time_base是1,25 把1s分成25份,则fps为25
//fps = 1/(1/25)
double fps = 1 / frame_delay;
//pts 加上 这个延迟 是显示时间
double extra_delay = repeat_pict / (2 * fps);
double delay = extra_delay + frame_delay;
// LOGI("extra_delay:%f",extra_delay);
clock += delay;
return play;
}
void FFmpegVedio::setAudio(FFmpegAudio *audio) {
this->audio = audio;
}
FFmpegVedio::~FFmpegVedio() {
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
}
| [
"wangyuelin@163.com"
] | wangyuelin@163.com |
6923abb846f23eed0c4e7af687bea1e3718f8f5d | 9b2a3151a7de6271f1618a482adbe4137aca6824 | /Coj/c++/1600-Big powers/main.cpp | 06a689153c2791003001c2dba5f627b410b274db | [] | no_license | LuisEnriqueSosaHernandez/Programas-coj-otros | 4bb8f24b785144366ad4ebd65fc41571fec44f4f | ef24094e347e0d7b21a021cdd1e32954ff72a486 | refs/heads/master | 2020-04-05T14:36:04.355386 | 2017-07-19T20:34:56 | 2017-07-19T20:34:56 | 94,712,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | #include <iostream>
using namespace std;
long long int potencia(long long int base,long long int exponente,long long int modulo){
if(exponente==0){
return 1;
}
if(exponente%2==0){
long long int aux=(potencia(base,exponente/2,modulo)%modulo);
return (aux*aux)%modulo;
}else{
return (base%modulo)*(potencia(base,exponente-1,modulo))%modulo;
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
int i;
long b,c;
cin>>b;
cin>>c;
while(b!=0&&c!=0){
cout<<potencia(b,c,10)<<"\n";
cin>>b;
cin>>c;
}
return 0;
}
| [
"kiquesasuke@gmail.com"
] | kiquesasuke@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.