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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3b9cbd5509e1eaca38d6d378695f34dfba8b500f | 3d5c4df6e541876e132e7d8829b8d943d268022a | /Source/PuzzelPlatformer/PuzzelPlatformerInstance.h | 72ddf4647b82df24d1d8c64c6d50f9a45dc92ffc | [] | no_license | Reetro/PuzzelPlatformer | bae6960d36866f7ea3e4c734486e738934ae31fb | fc0a87a6609496113f356dae963835aec540a7b6 | refs/heads/master | 2020-12-03T18:56:52.479027 | 2020-03-26T20:46:02 | 2020-03-26T20:46:02 | 231,439,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/GameInstance.h"
#include "MenuSystem/MenuInterface.h"
#include "PuzzelPlatformerInstance.generated.h"
class UUserWidget;
class UMainMenu;
class UMenuWidget;
/**
*
*/
UCLASS()
class PUZZELPLATFORMER_API UPuzzelPlatformerInstance : public UGameInstance, public IMenuInterface
{
GENERATED_BODY()
public:
UPuzzelPlatformerInstance();
UFUNCTION(exec)
virtual void Host() override;
UFUNCTION(exec)
virtual void Join(const FString& Address) override;
UFUNCTION(exec)
virtual void LeaveGame() override;
UFUNCTION(exec, BlueprintCallable)
void LoadGameMenu();
UFUNCTION(exec, BlueprintCallable)
void LoadInGameMenu();
private:
TSubclassOf<UUserWidget> MenuClass;
TSubclassOf<UUserWidget> InGameMenuClass;
UMainMenu* Menu;
UMenuWidget* InGameMenu;
};
| [
"thegamerboy7@gmail.com"
] | thegamerboy7@gmail.com |
e9ab04148ff8340f9f759fb201c7f87efef931e2 | 1552109747933e429903e04cb110690bac2d30ca | /Binary_search.cpp | 2d6887cb3cb88b639f7d80d1cb4a05f45b652351 | [] | no_license | surendra172001/cpp-programs | c01aaca4a66cb311df2d430f39511f803d0b4870 | 8829307b03f330ced22dcc4c872a20ead01c02e5 | refs/heads/master | 2021-03-24T01:21:33.765532 | 2020-03-21T11:47:14 | 2020-03-21T11:47:14 | 247,502,567 | 0 | 0 | null | 2020-03-21T11:47:15 | 2020-03-15T16:14:16 | C++ | UTF-8 | C++ | false | false | 871 | cpp | #include <iostream>
using namespace std;
int Binary_search(int a[], int start, int end, int k)
{
if (start <= end)
{
int middle = (start + end) / 2;
if (a[middle] == k)
{
return 1;
}
else if (a[middle] > k)
{
return Binary_search(a, start, middle - 1, k);
}
else if (a[middle] < k)
{
return Binary_search(a, middle + 1, end, k);
}
else
return (-1);
}
return -1;
}
int main()
{
int T, N, x, k, a[100], p[20], temp, i;
cin >> T;
temp = T;
x = 0;
while (temp--)
{
cin >> N >> k;
for (i = 0; i < N; i++)
cin >> a[i];
p[x] = Binary_search(a, 0, N - 1, k);
x++;
}
for (i = 0; i < T; i++)
{
cout << p[i] << endl;
}
return 0;
}
| [
"sap172001@gmail.com"
] | sap172001@gmail.com |
89e74ea082727b25c4e700d59a91019b673d76c7 | c61c802fea3e3ccca3f611f8a3d9fe72a8053504 | /src/globalevent.h | 4bb272d7d7c6c76bad6d4c674e9c347e84225591 | [] | no_license | Johncorex/perfect-source | fce01617061641d04f9c36d4696b34fc219dae38 | 2d37b382ecf25364388ed4a8e390c3fb6e1577b9 | refs/heads/master | 2020-07-25T14:41:15.983264 | 2019-09-13T19:50:23 | 2019-09-13T19:50:23 | 208,326,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,936 | h | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef FS_GLOBALEVENT_H_B3FB9B848EA3474B9AFC326873947E3C
#define FS_GLOBALEVENT_H_B3FB9B848EA3474B9AFC326873947E3C
#include "baseevents.h"
#include "const.h"
enum GlobalEvent_t {
GLOBALEVENT_NONE,
GLOBALEVENT_TIMER,
GLOBALEVENT_STARTUP,
GLOBALEVENT_SHUTDOWN,
GLOBALEVENT_RECORD,
};
class GlobalEvent;
using GlobalEvent_ptr = std::unique_ptr<GlobalEvent>;
using GlobalEventMap = std::map<std::string, GlobalEvent>;
class GlobalEvents final : public BaseEvents
{
public:
GlobalEvents();
~GlobalEvents();
// non-copyable
GlobalEvents(const GlobalEvents&) = delete;
GlobalEvents& operator=(const GlobalEvents&) = delete;
void startup() const;
void timer();
void think();
void execute(GlobalEvent_t type) const;
GlobalEventMap getEventMap(GlobalEvent_t type);
static void clearMap(GlobalEventMap& map);
private:
std::string getScriptBaseName() const override {
return "globalevents";
}
void clear() override;
Event_ptr getEvent(const std::string& nodeName) override;
bool registerEvent(Event_ptr event, const pugi::xml_node& node) override;
LuaScriptInterface& getScriptInterface() override {
return scriptInterface;
}
LuaScriptInterface scriptInterface;
GlobalEventMap thinkMap, serverMap, timerMap;
int32_t thinkEventId = 0, timerEventId = 0;
};
class GlobalEvent final : public Event
{
public:
explicit GlobalEvent(LuaScriptInterface* interface);
bool configureEvent(const pugi::xml_node& node) override;
bool executeRecord(uint32_t current, uint32_t old);
bool executeEvent() const;
GlobalEvent_t getEventType() const {
return eventType;
}
const std::string& getName() const {
return name;
}
uint32_t getInterval() const {
return interval;
}
int64_t getNextExecution() const {
return nextExecution;
}
void setNextExecution(int64_t time) {
nextExecution = time;
}
private:
GlobalEvent_t eventType = GLOBALEVENT_NONE;
std::string getScriptEventName() const override;
std::string name;
int64_t nextExecution = 0;
uint32_t interval = 0;
};
#endif | [
"gjohnes2018@gmail.com"
] | gjohnes2018@gmail.com |
624b1d70b272548175c065be8a1f4eb9e096c7d5 | 144d5b81b1c2af1c9f7fc9f4a398d3e6544a1d51 | /Source/smokeview/glui_bounds.cpp | 8b935fa2c808b5af923edc1d4293c328e5067b64 | [
"NIST-Software"
] | permissive | harboljc/smv | 22e7318272e6581676ee499779baf9ff75065031 | 01feb253e0edd90b6dbd416f925470f8c8dd589b | refs/heads/master | 2022-04-21T12:29:54.259846 | 2020-04-22T19:18:30 | 2020-04-22T19:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167,311 | cpp | #define CPP
#include "options.h"
#include <stdio.h>
#include <string.h>
#include GLUT_H
#include <math.h>
#include "smokeviewvars.h"
#include "IOscript.h"
#include "MALLOCC.h"
#include "glui_smoke.h"
#include "glui_bounds.h"
GLUI_Rollout *ROLLOUT_slice_bound=NULL;
GLUI_Rollout *ROLLOUT_slice_chop=NULL;
GLUI_Rollout *ROLLOUT_part_bound=NULL;
GLUI_Rollout *ROLLOUT_part_chop=NULL;
GLUI_Rollout *ROLLOUT_zone_bound=NULL;
#ifdef pp_MEMDEBUG
#define MEMCHECK 1
#endif
GLUI *glui_bounds=NULL;
#ifdef pp_NEWBOUND_DIALOG
GLUI_Button *BUTTON_slice_percentile = NULL;
#endif
GLUI_Button *BUTTON_globalalpha = NULL;
GLUI_Button *BUTTON_updatebound = NULL;
GLUI_Button *BUTTON_reloadbound=NULL;
GLUI_Button *BUTTON_compress=NULL;
GLUI_Button *BUTTON_step=NULL;
GLUI_Button *BUTTON_script_stop=NULL;
GLUI_Button *BUTTON_script_start=NULL;
GLUI_Button *BUTTON_script_saveini=NULL;
GLUI_Button *BUTTON_script_render=NULL;
GLUI_Button *BUTTON_update_line_contour=NULL;
GLUI_Button *BUTTON_ini_load=NULL;
GLUI_Button *BUTTON_script_setsuffix=NULL;
GLUI_Button *BUTTON_script_runscript=NULL;
GLUI_Button *BUTTON_SETTIME=NULL;
GLUI_Button *BUTTON_EVAC = NULL;
GLUI_Button *BUTTON_PART = NULL;
GLUI_Button *BUTTON_SLICE = NULL;
GLUI_Button *BUTTON_VSLICE = NULL;
GLUI_Button *BUTTON_PLOT3D = NULL;
GLUI_Button *BUTTON_3DSMOKE = NULL;
GLUI_Button *BUTTON_BOUNDARY = NULL;
GLUI_Button *BUTTON_ISO = NULL;
#ifdef pp_NEWBOUND_DIALOG
GLUI_Button *BUTTON_slice_global_bounds = NULL;
GLUI_Button *BUTTON_slice_global_bounds_loaded = NULL;
GLUI_Button *BUTTON_slice_percentile_bounds = NULL;
#endif
GLUI_Listbox *LIST_colortable = NULL;
GLUI_Listbox *LIST_iso_colorbar = NULL;
#ifdef pp_MEMDEBUG
GLUI_Rollout *ROLLOUT_memcheck=NULL;
#endif
GLUI_Rollout *ROLLOUT_boundary_temp_threshold;
GLUI_Rollout *ROLLOUT_boundary_duplicates;
GLUI_Rollout *ROLLOUT_iso_settings;
GLUI_Rollout *ROLLOUT_iso_bounds;
GLUI_Rollout *ROLLOUT_iso_color;
GLUI_Rollout *ROLLOUT_script = NULL;
GLUI_Rollout *ROLLOUT_config = NULL;
GLUI_Rollout *ROLLOUT_boundary_bound = NULL;
GLUI_Rollout *ROLLOUT_boundary_chop = NULL;
GLUI_Rollout *ROLLOUT_plot3d_bound = NULL;
GLUI_Rollout *ROLLOUT_plot3d_chop = NULL;
GLUI_Rollout *ROLLOUT_autoload=NULL;
GLUI_Rollout *ROLLOUT_compress=NULL;
GLUI_Rollout *ROLLOUT_plot3d=NULL,*ROLLOUT_part=NULL,*ROLLOUT_slice=NULL,*ROLLOUT_bound=NULL,*ROLLOUT_iso=NULL;
GLUI_Rollout *ROLLOUT_iso_colors = NULL;
GLUI_Rollout *ROLLOUT_smoke3d=NULL,*ROLLOUT_volsmoke3d=NULL;
GLUI_Rollout *ROLLOUT_time=NULL,*ROLLOUT_colorbar=NULL;
GLUI_Rollout *ROLLOUT_outputpatchdata=NULL;
GLUI_Rollout *ROLLOUT_boundimmersed = NULL;
GLUI_Rollout *ROLLOUT_filebounds = NULL;
GLUI_Rollout *ROLLOUT_showhide = NULL;
GLUI_Rollout *ROLLOUT_slice_average = NULL;
GLUI_Rollout *ROLLOUT_slice_histogram = NULL;
GLUI_Rollout *ROLLOUT_slice_vector = NULL;
GLUI_Rollout *ROLLOUT_line_contour = NULL;
GLUI_Rollout *ROLLOUT_slicedups = NULL;
GLUI_Rollout *ROLLOUT_vector = NULL;
GLUI_Rollout *ROLLOUT_isosurface = NULL;
GLUI_Rollout *ROLLOUT_boundary_settings = NULL;
GLUI_Rollout *ROLLOUT_particle_settings=NULL;
#ifndef pp_NEWBOUND_DIALOG
GLUI_Panel *PANEL_slice_bound = NULL;
#endif
GLUI_Panel *PANEL_partread = NULL;
#ifdef pp_SLICETHREAD
GLUI_Panel *PANEL_sliceread = NULL;
#endif
GLUI_Panel *PANEL_boundary_outline_type = NULL;
GLUI_Panel *PANEL_iso1 = NULL;
GLUI_Panel *PANEL_iso2 = NULL;
GLUI_Panel *PANEL_geomexp = NULL;
GLUI_Panel *PANEL_slice_smoke = NULL;
GLUI_Panel *PANEL_immersed = NULL;
GLUI_Panel *PANEL_immersed_region = NULL;
GLUI_Panel *PANEL_immersed_drawas = NULL;
GLUI_Panel *PANEL_immersed_outlinetype = NULL;
GLUI_Panel *PANEL_where = NULL;
GLUI_Panel *PANEL_sliceshow=NULL;
GLUI_Panel *PANEL_slicedup = NULL;
GLUI_Panel *PANEL_vectorslicedup = NULL;
GLUI_Panel *PANEL_iso_eachlevel = NULL;
GLUI_Panel *PANEL_iso_alllevels = NULL;
GLUI_Panel *PANEL_files = NULL;
GLUI_Panel *PANEL_bounds = NULL;
GLUI_Panel *PANEL_zone_a=NULL, *PANEL_zone_b=NULL;
GLUI_Panel *PANEL_evac_direction=NULL;
GLUI_Panel *PANEL_pan1=NULL;
GLUI_Panel *PANEL_pan2=NULL;
GLUI_Panel *PANEL_run=NULL;
GLUI_Panel *PANEL_record=NULL;
GLUI_Panel *PANEL_script1=NULL;
GLUI_Panel *PANEL_script1a=NULL;
GLUI_Panel *PANEL_script1b=NULL;
GLUI_Panel *PANEL_script1c=NULL;
GLUI_Panel *PANEL_script2a=NULL;
GLUI_Panel *PANEL_script2b=NULL;
GLUI_Panel *PANEL_script3=NULL;
GLUI_Panel *PANEL_transparency2=NULL;
GLUI_Panel *PANEL_time2=NULL;
GLUI_Panel *PANEL_time1a=NULL;
GLUI_Panel *PANEL_time2a=NULL;
GLUI_Panel *PANEL_time2b=NULL;
GLUI_Panel *PANEL_time2c=NULL;
GLUI_Panel *PANEL_outputpatchdata=NULL;
#ifdef pp_SLICETHREAD
GLUI_Spinner *SPINNER_nslicethread_ids = NULL;
#endif
GLUI_Spinner *SPINNER_npartthread_ids = NULL;
GLUI_Spinner *SPINNER_iso_outline_ioffset = NULL;
GLUI_Spinner *SPINNER_histogram_width_factor = NULL;
GLUI_Spinner *SPINNER_histogram_nbuckets=NULL;
GLUI_Spinner *SPINNER_iso_level = NULL;
GLUI_Spinner *SPINNER_iso_colors[4];
GLUI_Spinner *SPINNER_iso_transparency;
GLUI_Spinner *SPINNER_transparent_level = NULL;
GLUI_Spinner *SPINNER_line_contour_num=NULL;
GLUI_Spinner *SPINNER_line_contour_width=NULL;
GLUI_Spinner *SPINNER_line_contour_min=NULL;
GLUI_Spinner *SPINNER_line_contour_max=NULL;
GLUI_Spinner *SPINNER_timebounds=NULL;
GLUI_Spinner *SPINNER_tload_begin=NULL;
GLUI_Spinner *SPINNER_tload_end=NULL;
GLUI_Spinner *SPINNER_tload_skip=NULL;
GLUI_Spinner *SPINNER_plot3d_vectorpointsize=NULL,*SPINNER_plot3d_vectorlinewidth=NULL,*SPINNER_plot3d_vectorlinelength=NULL;
GLUI_Spinner *SPINNER_sliceaverage=NULL;
GLUI_Spinner *SPINNER_smoke3dzipstep=NULL;
GLUI_Spinner *SPINNER_slicezipstep=NULL;
GLUI_Spinner *SPINNER_isozipstep=NULL;
GLUI_Spinner *SPINNER_boundzipstep=NULL;
GLUI_Spinner *SPINNER_partstreaklength=NULL;
GLUI_Spinner *SPINNER_partpointsize=NULL;
GLUI_Spinner *SPINNER_isopointsize=NULL;
GLUI_Spinner *SPINNER_isolinewidth=NULL;
GLUI_Spinner *SPINNER_plot3dpointsize=NULL;
GLUI_Spinner *SPINNER_plot3dlinewidth=NULL;
GLUI_Spinner *SPINNER_streaklinewidth=NULL;
GLUI_Spinner *SPINNER_vectorpointsize=NULL;
GLUI_Spinner *SPINNER_vectorlinewidth=NULL;
GLUI_Spinner *SPINNER_vectorlinelength=NULL;
GLUI_Spinner *SPINNER_slicevectorskip=NULL;
GLUI_Spinner *SPINNER_plot3dvectorskip=NULL;
GLUI_Listbox *LIST_scriptlist=NULL;
GLUI_Listbox *LIST_ini_list=NULL;
GLUI_EditText *EDIT_iso_valmin=NULL;
GLUI_EditText *EDIT_iso_valmax=NULL;
GLUI_EditText *EDIT_zone_min=NULL, *EDIT_zone_max=NULL;
GLUI_EditText *EDIT_ini=NULL;
GLUI_EditText *EDIT_renderdir=NULL;
GLUI_EditText *EDIT_rendersuffix=NULL;
GLUI_EditText *EDIT_slice_min=NULL, *EDIT_slice_max=NULL;
GLUI_EditText *EDIT_slice_chopmin=NULL, *EDIT_slice_chopmax=NULL;
GLUI_EditText *EDIT_patch_chopmin=NULL, *EDIT_patch_chopmax=NULL;
GLUI_EditText *EDIT_part_chopmin=NULL, *EDIT_part_chopmax=NULL;
GLUI_EditText *EDIT_patch_min=NULL, *EDIT_patch_max=NULL;
GLUI_EditText *EDIT_part_min=NULL, *EDIT_part_max=NULL;
GLUI_EditText *EDIT_p3_min=NULL, *EDIT_p3_max=NULL;
GLUI_EditText *EDIT_p3_chopmin=NULL, *EDIT_p3_chopmax=NULL;
GLUI_Checkbox *CHECKBOX_show_boundary_outline=NULL;
#ifdef pp_SLICETHREAD
GLUI_Checkbox *CHECKBOX_slice_multithread = NULL;
#endif
GLUI_Checkbox *CHECKBOX_part_multithread = NULL;
GLUI_Checkbox *CHECKBOX_partfast = NULL;
GLUI_Checkbox *CHECKBOX_show_slice_shaded = NULL;
GLUI_Checkbox *CHECKBOX_show_slice_outlines = NULL;
GLUI_Checkbox *CHECKBOX_show_slice_points = NULL;
GLUI_Checkbox *CHECKBOX_show_iso_shaded=NULL;
GLUI_Checkbox *CHECKBOX_show_iso_outline=NULL;
GLUI_Checkbox *CHECKBOX_show_iso_points=NULL;
GLUI_Checkbox *CHECKBOX_boundary_load_incremental=NULL;
GLUI_Checkbox *CHECKBOX_slice_load_incremental=NULL;
GLUI_Checkbox *CHECKBOX_histogram_show_numbers=NULL;
GLUI_Checkbox *CHECKBOX_histogram_show_graph=NULL;
GLUI_Checkbox *CHECKBOX_histogram_show_outline=NULL;
GLUI_Checkbox *CHECKBOX_color_vector_black = NULL;
GLUI_Checkbox *CHECKBOX_show_node_slices_and_vectors=NULL;
GLUI_Checkbox *CHECKBOX_show_cell_slices_and_vectors=NULL;
GLUI_Checkbox *CHECKBOX_cache_boundarydata=NULL;
GLUI_Checkbox *CHECKBOX_showpatch_both=NULL;
GLUI_Checkbox *CHECKBOX_showchar=NULL, *CHECKBOX_showonlychar;
GLUI_Checkbox *CHECKBOX_script_step=NULL;
GLUI_Checkbox *CHECKBOX_show_evac_slices=NULL;
GLUI_Checkbox *CHECKBOX_constant_coloring=NULL;
GLUI_Checkbox *CHECKBOX_show_evac_color=NULL;
GLUI_Checkbox *CHECKBOX_data_coloring=NULL;
GLUI_Checkbox *CHECKBOX_sort2=NULL;
GLUI_Checkbox *CHECKBOX_smooth2=NULL;
GLUI_Checkbox *CHECKBOX_overwrite_all=NULL;
GLUI_Checkbox *CHECKBOX_compress_autoloaded=NULL;
GLUI_Checkbox *CHECKBOX_erase_all=NULL;
GLUI_Checkbox *CHECKBOX_multi_task=NULL;
GLUI_Checkbox *CHECKBOX_slice_setchopmin=NULL;
GLUI_Checkbox *CHECKBOX_slice_setchopmax=NULL;
GLUI_Checkbox *CHECKBOX_p3_setchopmin=NULL, *CHECKBOX_p3_setchopmax=NULL;
GLUI_Checkbox *CHECKBOX_patch_setchopmin=NULL, *CHECKBOX_patch_setchopmax=NULL;
GLUI_Checkbox *CHECKBOX_part_setchopmin=NULL, *CHECKBOX_part_setchopmax=NULL;
GLUI_Checkbox *CHECKBOX_showtracer=NULL;
GLUI_Checkbox *CHECKBOX_cellcenter_slice_interp=NULL;
GLUI_Checkbox *CHECKBOX_skip_subslice=NULL;
GLUI_Checkbox *CHECKBOX_turb_slice=NULL;
GLUI_Checkbox *CHECKBOX_average_slice=NULL;
GLUI_Checkbox *CHECKBOX_cache_qdata=NULL;
GLUI_Checkbox *CHECKBOX_use_tload_begin=NULL;
GLUI_Checkbox *CHECKBOX_use_tload_end=NULL;
GLUI_Checkbox *CHECKBOX_use_tload_skip=NULL;
GLUI_Checkbox *CHECKBOX_research_mode=NULL;
GLUI_RadioGroup *RADIO_iso_setmin=NULL;
GLUI_RadioGroup *RADIO_iso_setmax=NULL;
GLUI_RadioGroup *RADIO_transparency_option=NULL;
GLUI_RadioGroup *RADIO_slice_celltype=NULL;
GLUI_RadioGroup *RADIO_slice_edgetype=NULL;
GLUI_RadioGroup *RADIO_boundary_edgetype = NULL;
GLUI_RadioGroup *RADIO_show_slice_in_obst=NULL;
GLUI_RadioGroup *RADIO_boundaryslicedup = NULL;
GLUI_RadioGroup *RADIO_slicedup = NULL;
GLUI_RadioGroup *RADIO_vectorslicedup = NULL;
GLUI_RadioGroup *RADIO_histogram_static=NULL;
GLUI_RadioGroup *RADIO_showhide = NULL;
GLUI_RadioGroup *RADIO_contour_type = NULL;
GLUI_RadioGroup *RADIO_zone_setmin=NULL, *RADIO_zone_setmax=NULL;
GLUI_RadioGroup *RADIO_bf=NULL, *RADIO_p3=NULL,*RADIO_slice=NULL;
GLUI_RadioGroup *RADIO_part5=NULL;
GLUI_RadioGroup *RADIO_plot3d_isotype=NULL;
GLUI_RadioGroup *RADIO_plot3d_display=NULL;
#ifndef pp_NEWBOUND_DIALOG
GLUI_RadioGroup *RADIO_slice_setmin=NULL, *RADIO_slice_setmax=NULL;
#endif
GLUI_RadioGroup *RADIO_patch_setmin=NULL, *RADIO_patch_setmax=NULL;
GLUI_RadioGroup *RADIO_part_setmin=NULL, *RADIO_part_setmax=NULL;
#ifdef pp_MEMDEBUG
GLUI_RadioGroup *RADIO_memcheck=NULL;
#endif
GLUI_RadioGroup *RADIO_p3_setmin=NULL, *RADIO_p3_setmax=NULL;
#ifdef pp_NEWBOUND_DIALOG
GLUI_RadioGroup *RADIO_slice_loaded_only = NULL;
#endif
GLUI_RadioButton *RADIOBUTTON_plot3d_iso_hidden=NULL;
GLUI_RadioButton *RADIOBUTTON_zone_permin=NULL;
GLUI_RadioButton *RADIOBUTTON_zone_permax=NULL;
GLUI_RadioButton *RADIO_part_setmin_percentile=NULL;
GLUI_RadioButton *RADIO_part_setmax_percentile=NULL;
GLUI_StaticText *STATIC_bound_min_unit=NULL;
GLUI_StaticText *STATIC_bound_max_unit=NULL;
GLUI_StaticText *STATIC_slice_min_unit=NULL;
GLUI_StaticText *STATIC_slice_max_unit=NULL;
#ifdef pp_NEWBOUND_DIALOG
GLUI_StaticText *STATIC_slice_min = NULL;
GLUI_StaticText *STATIC_slice_max = NULL;
#endif
GLUI_StaticText *STATIC_part_min_unit=NULL;
GLUI_StaticText *STATIC_part_max_unit=NULL;
GLUI_StaticText *STATIC_plot3d_min_unit=NULL;
GLUI_StaticText *STATIC_plot3d_max_unit=NULL;
GLUI_StaticText *STATIC_bound_cmin_unit=NULL;
GLUI_StaticText *STATIC_bound_cmax_unit=NULL;
GLUI_StaticText *STATIC_slice_cmin_unit=NULL;
GLUI_StaticText *STATIC_slice_cmax_unit=NULL;
GLUI_StaticText *STATIC_part_cmin_unit=NULL;
GLUI_StaticText *STATIC_part_cmax_unit=NULL;
GLUI_StaticText *STATIC_plot3d_cmin_unit=NULL;
GLUI_StaticText *STATIC_plot3d_cmax_unit=NULL;
#define ZONE_ROLLOUT 0
#define SMOKE3D_ROLLOUT 1
#define BOUNDARY_ROLLOUT 2
#define ISO_ROLLOUT 3
#define PART_ROLLOUT 4
#define EVAC_ROLLOUT 5
#define PLOT3D_ROLLOUT 6
#define SLICE_ROLLOUT 7
#define ISO_ROLLOUT_BOUNDS 0
#define ISO_ROLLOUT_SETTINGS 1
#define ISO_ROLLOUT_COLOR 2
#define SLICE_BOUND 0
#define SLICE_CHOP 1
#define SLICE_AVERAGE_ROLLOUT 2
#define SLICE_VECTOR_ROLLOUT 3
#define LINE_CONTOUR_ROLLOUT 4
#define SLICE_HISTOGRAM_ROLLOUT 5
#define SLICE_DUP_ROLLOUT 6
#define SLICE_SETTINGS_ROLLOUT 7
#define PLOT3D_BOUND 0
#define PLOT3D_CHOP 1
#define PLOT3D_VECTOR_ROLLOUT 2
#define PLOT3D_ISOSURFACE_ROLLOUT 3
#define LOAD_ROLLOUT 0
#define SHOWHIDE_ROLLOUT 1
#define COMPRESS_ROLLOUT 2
#define SCRIPT_ROLLOUT 3
#define CONFIG_ROLLOUT 4
#define FILEBOUNDS_ROLLOUT 5
#define TIME_ROLLOUT 6
#define MEMCHECK_ROLLOUT 7
procdata boundprocinfo[8], fileprocinfo[8], plot3dprocinfo[4];
int nboundprocinfo = 0, nfileprocinfo = 0, nplot3dprocinfo=0;
procdata isoprocinfo[3], subboundprocinfo[6], sliceprocinfo[8], particleprocinfo[3];
int nisoprocinfo=0, nsubboundprocinfo=0, nsliceprocinfo=0, nparticleprocinfo=0;
/* ------------------ UpdateGluiPartFast ------------------------ */
extern "C" void UpdateGluiPartFast(void){
if(CHECKBOX_partfast!=NULL)CHECKBOX_partfast->set_int_val(partfast);
if(CHECKBOX_part_multithread!=NULL)CHECKBOX_part_multithread->set_int_val(part_multithread);
PartBoundCB(PARTFAST);
}
/* ------------------ UpdateListIsoColorobar ------------------------ */
extern "C" void UpdateListIsoColorobar(void){
if(LIST_iso_colorbar!=NULL)LIST_iso_colorbar->set_int_val(iso_colorbar_index);
}
/* ------------------ UpdateGluiIsoBounds ------------------------ */
extern "C" void UpdateGluiIsoBounds(void){
if(setisomin==PERCENTILE_MIN||setisomin==GLOBAL_MIN){
if(setisomin==PERCENTILE_MIN)glui_iso_valmin=iso_percentile_min;
if(setisomin==GLOBAL_MIN)glui_iso_valmin=iso_global_min;
if(EDIT_iso_valmin!=NULL)EDIT_iso_valmin->set_float_val(glui_iso_valmin);
}
if(setisomax==PERCENTILE_MAX||setisomax==GLOBAL_MAX){
if(setisomax==PERCENTILE_MAX)glui_iso_valmax=iso_percentile_max;
if(setisomax==GLOBAL_MAX)glui_iso_valmax=iso_global_max;
if(EDIT_iso_valmax!=NULL)EDIT_iso_valmax->set_float_val(glui_iso_valmax);
}
}
/* ------------------ LoadIncrementalCB1 ------------------------ */
extern "C" void LoadIncrementalCB1(int var){
if(CHECKBOX_boundary_load_incremental!=NULL)CHECKBOX_boundary_load_incremental->set_int_val(load_incremental);
if(CHECKBOX_slice_load_incremental!=NULL)CHECKBOX_slice_load_incremental->set_int_val(load_incremental);
}
/* ------------------ UpdateVectorpointsize ------------------------ */
extern "C" void UpdateVectorpointsize(void){
if(SPINNER_vectorpointsize!=NULL)SPINNER_vectorpointsize->set_int_val(vectorpointsize);
}
/* ------------------ UpdateSliceDupDialog ------------------------ */
extern "C" void UpdateSliceDupDialog(void){
if(RADIO_boundaryslicedup != NULL)RADIO_boundaryslicedup->set_int_val(boundaryslicedup_option);
if(RADIO_slicedup != NULL)RADIO_slicedup->set_int_val(slicedup_option);
if(RADIO_vectorslicedup != NULL)RADIO_vectorslicedup->set_int_val(vectorslicedup_option);
}
/* ------------------ UpdateImmersedControls ------------------------ */
extern "C" void UpdateImmersedControls(void){
}
/* ------------------ UpdateIsoControls ------------------------ */
void UpdateIsoControls(void){
if(use_transparency_data==1){
if(SPINNER_iso_colors[3] != NULL)SPINNER_iso_colors[3]->enable();
if(SPINNER_iso_transparency != NULL)SPINNER_iso_transparency->enable();
if(BUTTON_updatebound != NULL)BUTTON_updatebound->enable();
}
else{
if(SPINNER_iso_colors[3] != NULL)SPINNER_iso_colors[3]->disable();
if(SPINNER_iso_transparency != NULL)SPINNER_iso_transparency->disable();
if(BUTTON_updatebound != NULL)BUTTON_updatebound->disable();
}
}
/* ------------------ UpdateHistogramType ------------------------ */
extern "C" void UpdateHistogramType(void){
RADIO_histogram_static->set_int_val(histogram_static);
CHECKBOX_histogram_show_graph->set_int_val(histogram_show_graph);
CHECKBOX_histogram_show_numbers->set_int_val(histogram_show_numbers);
CHECKBOX_histogram_show_outline->set_int_val(histogram_show_outline);
}
/* ------------------ UpdateShowSliceInObst ------------------------ */
extern "C" void UpdateShowSliceInObst(void){
RADIO_show_slice_in_obst->set_int_val(show_slice_in_obst);
if(show_slice_in_obst!=show_slice_in_obst_old){
SliceBoundCB(FILEUPDATE);
show_slice_in_obst_old = show_slice_in_obst;
}
}
/* ------------------ UpdateIsoColorlevel ------------------------ */
extern "C" void UpdateIsoColorlevel(void){
IsoBoundCB(ISO_LEVEL);
IsoBoundCB(ISO_COLORS);
}
/* ------------------ ParticleRolloutCB ------------------------ */
void ParticleRolloutCB(int var){
ToggleRollout(particleprocinfo, nparticleprocinfo, var);
}
/* ------------------ Plot3dRolloutCB ------------------------ */
void Plot3dRolloutCB(int var){
ToggleRollout(plot3dprocinfo, nplot3dprocinfo, var);
}
/* ------------------ SliceRolloutCB ------------------------ */
void SliceRolloutCB(int var){
ToggleRollout(sliceprocinfo, nsliceprocinfo, var);
}
/* ------------------ IsoRolloutCB ------------------------ */
void IsoRolloutCB(int var){
ToggleRollout(isoprocinfo, nisoprocinfo, var);
}
/* ------------------ BoundRolloutCB ------------------------ */
void BoundRolloutCB(int var){
ToggleRollout(boundprocinfo, nboundprocinfo, var);
if(nzoneinfo>0){
if(var==ZONE_ROLLOUT){
SliceBoundCB(SETZONEVALMINMAX);
}
if(var==SLICE_ROLLOUT){
list_slice_index = CLAMP(list_slice_index,0,nlist_slice_index-1);
RADIO_slice->set_int_val(list_slice_index);
SliceBoundCB(FILETYPEINDEX);
}
}
}
/* ------------------ SubBoundRolloutCB ------------------------ */
void SubBoundRolloutCB(int var){
ToggleRollout(subboundprocinfo, nsubboundprocinfo, var);
}
/* ------------------ FileRolloutCB ------------------------ */
void FileRolloutCB(int var){
ToggleRollout(fileprocinfo, nfileprocinfo, var);
}
/* ------------------ UpdateGluiZoneBounds ------------------------ */
extern "C" void UpdateGluiZoneBounds(void){
if(EDIT_zone_min!=NULL)EDIT_zone_min->set_float_val(zonemin);
if(EDIT_zone_max!=NULL)EDIT_zone_max->set_float_val(zonemax);
}
/* ------------------ UpdateGluiVecFactor ------------------------ */
extern "C" void UpdateGluiVecFactor(void){
if(SPINNER_plot3d_vectorlinelength!=NULL)SPINNER_plot3d_vectorlinelength->set_float_val(vecfactor);
if(SPINNER_vectorlinelength!=NULL)SPINNER_vectorlinelength->set_float_val(vecfactor);
}
/* ------------------ UpdateGluiPartSetBounds ------------------------ */
extern "C" void UpdateGluiPartSetBounds(int minbound_type, int maxbound_type){
if(RADIO_part_setmin!=NULL)RADIO_part_setmin->set_int_val(minbound_type);
if(RADIO_part_setmax!=NULL)RADIO_part_setmax->set_int_val(maxbound_type);
PartBoundCB(FILETYPEINDEX);
}
/* ------------------ UpdateGluiPartUnits ------------------------ */
extern "C" void UpdateGluiPartUnits(void){
if(STATIC_part_min_unit!=NULL){
if(partmin_unit!=NULL){
STATIC_part_min_unit->set_name((char *)partmin_unit);
}
else{
STATIC_part_min_unit->set_name((char *)"");
}
}
if(STATIC_part_cmin_unit!=NULL){
if(partmin_unit!=NULL){
STATIC_part_cmin_unit->set_name((char *)partmin_unit);
}
else{
STATIC_part_cmin_unit->set_name((char *)"");
}
}
if(STATIC_part_max_unit!=NULL){
if(partmax_unit!=NULL){
STATIC_part_max_unit->set_name((char *)partmax_unit);
}
else{
STATIC_part_max_unit->set_name((char *)"");
}
}
if(STATIC_part_cmax_unit!=NULL){
if(partmax_unit!=NULL){
STATIC_part_cmax_unit->set_name((char *)partmax_unit);
}
else{
STATIC_part_cmax_unit->set_name((char *)"");
}
}
}
/* ------------------ UpdateGluiPlot3D_units ------------------------ */
extern "C" void UpdateGluiPlot3D_units(void){
if(STATIC_plot3d_min_unit!=NULL&&plot3dmin_unit!=NULL){
STATIC_plot3d_min_unit->set_name((char *)plot3dmin_unit);
}
if(STATIC_plot3d_max_unit!=NULL&&plot3dmax_unit!=NULL){
STATIC_plot3d_max_unit->set_name((char *)plot3dmax_unit);
}
if(STATIC_plot3d_cmin_unit!=NULL&&plot3dmin_unit!=NULL){
STATIC_plot3d_cmin_unit->set_name((char *)plot3dmin_unit);
}
if(STATIC_plot3d_cmax_unit!=NULL&&plot3dmax_unit!=NULL){
STATIC_plot3d_cmax_unit->set_name((char *)plot3dmax_unit);
}
}
/* ------------------ UpdateGluiSliceUnits ------------------------ */
extern "C" void UpdateGluiSliceUnits(void){
if(STATIC_slice_min_unit!=NULL&&glui_slicemin_unit!=NULL){
STATIC_slice_min_unit->set_name((char *)glui_slicemin_unit);
}
if(STATIC_slice_max_unit!=NULL&&glui_slicemax_unit!=NULL){
STATIC_slice_max_unit->set_name((char *)glui_slicemax_unit);
}
if(STATIC_slice_cmin_unit!=NULL&&glui_slicemin_unit!=NULL){
STATIC_slice_cmin_unit->set_name((char *)glui_slicemin_unit);
}
if(STATIC_slice_cmax_unit!=NULL&&glui_slicemax_unit!=NULL){
STATIC_slice_cmax_unit->set_name((char *)glui_slicemax_unit);
}
}
/* ------------------ UpdateGluiBoundaryUnits ------------------------ */
extern "C" void UpdateGluiBoundaryUnits(void){
if(STATIC_bound_min_unit!=NULL&&patchmin_unit!=NULL){
STATIC_bound_min_unit->set_name((char *)patchmin_unit);
}
if(STATIC_bound_max_unit!=NULL&&patchmax_unit!=NULL){
STATIC_bound_max_unit->set_name((char *)patchmax_unit);
}
if(STATIC_bound_cmin_unit!=NULL&&patchmin_unit!=NULL){
STATIC_bound_cmin_unit->set_name((char *)patchmin_unit);
}
if(STATIC_bound_cmax_unit!=NULL&&patchmax_unit!=NULL){
STATIC_bound_cmax_unit->set_name((char *)patchmax_unit);
}
}
/* ------------------ UpdateResearchMode ------------------------ */
extern "C" void UpdateResearchMode(void){
SliceBoundCB(RESEARCH_MODE);
if(CHECKBOX_research_mode!=NULL)CHECKBOX_research_mode->set_int_val(research_mode);
}
/* ------------------ UpdateScriptStop ------------------------ */
extern "C" void UpdateScriptStop(void){
if(BUTTON_script_start!=NULL)BUTTON_script_start->enable();
if(BUTTON_script_stop!=NULL)BUTTON_script_stop->disable();
if(BUTTON_script_runscript!=NULL)BUTTON_script_runscript->enable();
if(EDIT_renderdir!=NULL)EDIT_renderdir->enable();
}
/* ------------------ UpdateScriptStart ------------------------ */
extern "C" void UpdateScriptStart(void){
if(BUTTON_script_start!=NULL)BUTTON_script_start->disable();
if(BUTTON_script_stop!=NULL)BUTTON_script_stop->enable();
if(BUTTON_script_runscript!=NULL)BUTTON_script_runscript->disable();
if(EDIT_renderdir!=NULL)EDIT_renderdir->disable();
}
/* ------------------ UpdateScriptStep ------------------------ */
extern "C" void UpdateScriptStep(void){
CHECKBOX_script_step->set_int_val(script_step);
if(script_step==1){
BUTTON_step->enable();
}
else{
BUTTON_step->disable();
}
}
/* ------------------ UpdateEvacParms ------------------------ */
extern "C" void UpdateEvacParms(void){
if(CHECKBOX_show_evac_slices!=NULL)CHECKBOX_show_evac_slices->set_int_val(show_evac_slices);
if(CHECKBOX_constant_coloring!=NULL)CHECKBOX_constant_coloring->set_int_val(constant_evac_coloring);
if(CHECKBOX_data_coloring!=NULL)CHECKBOX_data_coloring->set_int_val(data_evac_coloring);
if(CHECKBOX_show_evac_color!=NULL)CHECKBOX_show_evac_color->set_int_val(show_evac_colorbar);
}
/* ------------------ UpdateGluiPlot3D ------------------------ */
extern "C" void UpdateGluiPlot3D(void){
Plot3DBoundCB(UNLOAD_QDATA);
}
/* ------------------ PartBoundCBInit ------------------------ */
extern "C" void PartBoundCBInit(void){
PartBoundCB(FILETYPEINDEX);
}
/* ------------------ ColorTableCompare ------------------------ */
int ColorTableCompare(const void *arg1, const void *arg2){
colortabledata *cti, *ctj;
int i, j;
i = *(int *)arg1;
j = *(int *)arg2;
cti = colortableinfo + i;
ctj = colortableinfo + j;
return(strcmp(cti->label, ctj->label));
}
/* ------------------ UpdateColorTableList ------------------------ */
extern "C" void UpdateColorTableList(int ncolortableinfo_old){
int i, *order=NULL;
if(LIST_colortable==NULL)return;
for(i = -1; i<ncolortableinfo_old; i++){
LIST_colortable->delete_item(i);
}
if(ncolortableinfo>0){
NewMemory((void **)&order, ncolortableinfo*sizeof(int));
for(i = 0; i < ncolortableinfo; i++){
order[i] = i;
}
qsort((int *)order, (size_t)ncolortableinfo, sizeof(int), ColorTableCompare);
}
for(i = -1; i<ncolortableinfo; i++){
if(i==-1){
LIST_colortable->add_item(i, "Custom");
}
else{
colortabledata *cti;
cti = colortableinfo+order[i];
LIST_colortable->add_item(i, cti->label);
}
}
if(ncolortableinfo>0){
FREEMEMORY(order);
}
}
/* ------------------ FileShowCB ------------------------ */
extern "C" void FileShowCB(int var){
updatemenu = 1;
switch(var){
case FILESHOW_sizes:
GetFileSizes();
break;
case FILESHOW_plot3d:
switch(showhide_option){
case SHOWALL_FILES:
case SHOWONLY_FILE:
Plot3DShowMenu(SHOWALL_PLOT3D);
break;
case HIDEALL_FILES:
Plot3DShowMenu(HIDEALL_PLOT3D);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_evac:
switch(showhide_option){
case SHOWALL_FILES:
EvacShowMenu(SHOWALL_EVAC);
break;
case SHOWONLY_FILE:
EvacShowMenu(SHOWALL_EVAC);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
break;
case HIDEALL_FILES:
EvacShowMenu(HIDEALL_EVAC);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_particle:
switch(showhide_option){
case SHOWALL_FILES:
ParticleShowMenu(SHOWALL_PARTICLE);
break;
case SHOWONLY_FILE:
ParticleShowMenu(SHOWALL_PARTICLE);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
break;
case HIDEALL_FILES:
ParticleShowMenu(HIDEALL_PARTICLE);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_slice:
switch(showhide_option){
case SHOWALL_FILES:
ShowHideSliceMenu(GLUI_SHOWALL_SLICE);
break;
case SHOWONLY_FILE:
ShowHideSliceMenu(GLUI_SHOWALL_SLICE);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
break;
case HIDEALL_FILES:
ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_vslice:
switch(showhide_option){
case SHOWALL_FILES:
ShowVSliceMenu(GLUI_SHOWALL_VSLICE);
break;
case SHOWONLY_FILE:
ShowVSliceMenu(GLUI_SHOWALL_VSLICE);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
break;
case HIDEALL_FILES:
ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_boundary:
switch(showhide_option){
case SHOWALL_FILES:
ShowBoundaryMenu(GLUI_SHOWALL_BOUNDARY);
break;
case SHOWONLY_FILE:
ShowBoundaryMenu(GLUI_SHOWALL_BOUNDARY);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
break;
case HIDEALL_FILES:
ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_3dsmoke:
switch(showhide_option){
case SHOWALL_FILES:
Smoke3DShowMenu(SHOWALL_SMOKE3D);
break;
case SHOWONLY_FILE:
Smoke3DShowMenu(SHOWALL_SMOKE3D);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
if(nisoloaded != 0)IsoShowMenu(HIDEALL_ISO);
break;
case HIDEALL_FILES:
Smoke3DShowMenu(HIDEALL_SMOKE3D);
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILESHOW_isosurface:
switch(showhide_option){
case SHOWALL_FILES:
IsoShowMenu(SHOWALL_ISO);
break;
case SHOWONLY_FILE:
IsoShowMenu(SHOWALL_ISO);
if(nevacloaded != 0)EvacShowMenu(HIDEALL_EVAC);
if(nsmoke3dloaded != 0)Smoke3DShowMenu(HIDEALL_SMOKE3D);
if(npatchloaded != 0)ShowBoundaryMenu(GLUI_HIDEALL_BOUNDARY);
if(npartloaded != 0)ParticleShowMenu(HIDEALL_PARTICLE);
if(nvsliceloaded != 0)ShowVSliceMenu(GLUI_HIDEALL_VSLICE);
if(nsliceloaded != 0)ShowHideSliceMenu(GLUI_HIDEALL_SLICE);
break;
case HIDEALL_FILES:
IsoShowMenu(HIDEALL_ISO);
break;
default:
ASSERT(FFALSE);
break;
}
break;
default:
break;
}
}
#ifdef pp_MEMDEBUG
/* ------------------ MemcheckCB ------------------------ */
void MemcheckCB(int var){
switch(var){
case MEMCHECK:
set_memcheck(list_memcheck_index);
break;
default:
ASSERT(FFALSE);
break;
}
}
#endif
/* ------------------ BoundsDlgCB ------------------------ */
void BoundsDlgCB(int var){
switch(var){
case CLOSE_BOUNDS:
glui_bounds->hide();
updatemenu = 1;
break;
case SAVE_SETTINGS_BOUNDS:
WriteIni(LOCAL_INI, NULL);
break;
case COMPRESS_FILES:
PRINTF("compressing\n");
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ ImmersedBoundCB ------------------------ */
#define SHOW_POLYGON_EDGES 0
#define SHOW_TRIANGLE_EDGES 1
#define HIDE_EDGES 2
extern "C" void ImmersedBoundCB(int var){
updatemenu = 1;
switch(var){
int i;
case IMMERSED_SWITCH_CELLTYPE:
glui_slice_edgetype = slice_edgetypes[slice_celltype];
glui_show_slice_shaded = show_slice_shaded[slice_celltype];
glui_show_slice_outlines = show_slice_outlines[slice_celltype];
glui_show_slice_points = show_slice_points[slice_celltype];
for(i=0;i<3;i++){
switch(slice_edgetypes[i]){
case IMMERSED_POLYGON:
case IMMERSED_TRIANGLE:
show_slice_outlines[i]=1;
break;
case IMMERSED_HIDDEN:
show_slice_outlines[i]=0;
break;
}
}
if(RADIO_slice_edgetype!=NULL)RADIO_slice_edgetype->set_int_val(glui_slice_edgetype);
if(CHECKBOX_show_slice_shaded!=NULL)CHECKBOX_show_slice_shaded->set_int_val(glui_show_slice_shaded);
if(CHECKBOX_show_slice_outlines!=NULL)CHECKBOX_show_slice_outlines->set_int_val(glui_show_slice_outlines);
if(CHECKBOX_show_slice_points!=NULL)CHECKBOX_show_slice_points->set_int_val(glui_show_slice_points);
break;
case IMMERSED_SET_DRAWTYPE:
if(glui_show_slice_outlines == 0){
glui_slice_edgetype = IMMERSED_HIDDEN;
}
else{
if(glui_slice_edgetype == IMMERSED_HIDDEN)glui_slice_edgetype = IMMERSED_TRIANGLE;
}
slice_edgetypes[slice_celltype] = glui_slice_edgetype;
show_slice_shaded[slice_celltype] = glui_show_slice_shaded;
show_slice_outlines[slice_celltype] = glui_show_slice_outlines;
show_slice_points[slice_celltype] = glui_show_slice_points;
if(RADIO_slice_edgetype!=NULL)RADIO_slice_edgetype->set_int_val(glui_slice_edgetype);
break;
case IMMERSED_SWITCH_EDGETYPE:
switch (glui_slice_edgetype){
case SHOW_POLYGON_EDGES:
case SHOW_TRIANGLE_EDGES:
glui_show_slice_outlines=1;
break;
case HIDE_EDGES:
glui_show_slice_outlines=0;
break;
default:
ASSERT(FFALSE);
break;
}
ImmersedBoundCB(IMMERSED_SET_DRAWTYPE);
if(CHECKBOX_show_slice_outlines!=NULL)CHECKBOX_show_slice_outlines->set_int_val(glui_show_slice_outlines);
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ BoundBoundCB ------------------------ */
void BoundBoundCB(int var){
int i;
switch(var){
case SHOW_BOUNDARY_OUTLINE:
if(ngeom_data==0)break;
if(show_boundary_outline==1&&boundary_edgetype==IMMERSED_HIDDEN)boundary_edgetype = IMMERSED_POLYGON;
if(show_boundary_outline==0&&boundary_edgetype!=IMMERSED_HIDDEN)boundary_edgetype = IMMERSED_HIDDEN;
if(boundary_edgetype!=RADIO_boundary_edgetype->get_int_val())RADIO_boundary_edgetype->set_int_val(boundary_edgetype);
break;
case BOUNDARY_EDGETYPE:
if(boundary_edgetype==IMMERSED_HIDDEN&&show_boundary_outline==1)show_boundary_outline=0;
if(boundary_edgetype!=IMMERSED_HIDDEN&&show_boundary_outline==0)show_boundary_outline=1;
if(show_boundary_outline!=CHECKBOX_show_boundary_outline->get_int_val())CHECKBOX_show_boundary_outline->set_int_val(show_boundary_outline);
break;
case UPDATE_BOUNDARYSLICEDUPS:
UpdateBoundarySliceDups();
updatemenu = 1;
break;
case SHOWPATCH_BOTH:
updatefacelists = 1;
updatehiddenfaces = 1;
break;
case CACHE_BOUNDARYDATA:
if(cache_boundarydata == 0){
BUTTON_updatebound->disable();
}
else{
BUTTON_updatebound->enable();
}
break;
case VALMAX:
case VALMIN:
break;
case HIDEPATCHSURFACE:
updatefacelists = 1;
break;
case FRAMELOADING:
boundframestep = boundframeskip + 1;
boundzipstep = boundzipskip + 1;
updatemenu = 1;
break;
case CHOPUPDATE:
UpdateChopColors();
break;
case SETCHOPMINVAL:
UpdateChopColors();
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index]);
switch(setpatchchopmin){
case DISABLE:
EDIT_patch_chopmin->disable();
break;
case ENABLE:
EDIT_patch_chopmin->enable();
break;
default:
ASSERT(FFALSE);
break;
}
UpdateHideBoundarySurface();
break;
case SETCHOPMAXVAL:
UpdateChopColors();
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index]);
switch(setpatchchopmax){
case DISABLE:
EDIT_patch_chopmax->disable();
break;
case ENABLE:
EDIT_patch_chopmax->enable();
break;
default:
ASSERT(FFALSE);
break;
}
UpdateHideBoundarySurface();
break;
case CHOPVALMIN:
ASSERT(EDIT_patch_min != NULL);
EDIT_patch_min->set_float_val(patchmin);
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index]);
UpdateChopColors();
break;
case CHOPVALMAX:
ASSERT(EDIT_patch_max != NULL);
EDIT_patch_max->set_float_val(patchmax);
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index]);
UpdateChopColors();
break;
case SHOWCHAR:
if(CHECKBOX_showchar != NULL&&CHECKBOX_showonlychar != NULL){
if(vis_threshold == 1){
CHECKBOX_showonlychar->enable();
}
else{
CHECKBOX_showonlychar->disable();
}
}
updatemenu = 1;
updatefacelists = 1;
break;
case FILETYPEINDEX:
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index_old]);
Global2LocalBoundaryBounds(patchlabellist[list_patch_index]);
EDIT_patch_min->set_float_val(patchmin);
EDIT_patch_max->set_float_val(patchmax);
EDIT_patch_chopmin->set_float_val(patchchopmin);
EDIT_patch_chopmax->set_float_val(patchchopmax);
BoundBoundCB(SETVALMIN);
BoundBoundCB(SETVALMAX);
if(RADIO_patch_setmin != NULL)RADIO_patch_setmin->set_int_val(setpatchmin);
if(RADIO_patch_setmax != NULL)RADIO_patch_setmax->set_int_val(setpatchmax);
if(CHECKBOX_patch_setchopmin != NULL)CHECKBOX_patch_setchopmin->set_int_val(setpatchchopmin);
if(CHECKBOX_patch_setchopmax != NULL)CHECKBOX_patch_setchopmax->set_int_val(setpatchchopmax);
switch(setpatchchopmin){
case DISABLE:
EDIT_patch_chopmin->disable();
break;
case ENABLE:
EDIT_patch_chopmin->enable();
break;
default:
ASSERT(FFALSE);
break;
}
switch(setpatchchopmax){
case DISABLE:
EDIT_patch_chopmax->disable();
break;
case ENABLE:
EDIT_patch_chopmax->enable();
break;
default:
ASSERT(FFALSE);
break;
}
list_patch_index_old = list_patch_index;
UpdateHideBoundarySurface();
break;
case SETVALMIN:
switch(setpatchmin){
case PERCENTILE_MIN:
case GLOBAL_MIN:
EDIT_patch_min->disable();
break;
case SET_MIN:
EDIT_patch_min->enable();
break;
default:
ASSERT(FFALSE);
break;
}
BoundBoundCB(FILEUPDATE);
break;
case SETVALMAX:
switch(setpatchmax){
case PERCENTILE_MAX:
case GLOBAL_MAX:
EDIT_patch_max->disable();
break;
case SET_MAX:
EDIT_patch_max->enable();
break;
default:
ASSERT(FFALSE);
break;
}
BoundBoundCB(FILEUPDATE);
break;
case FILEUPDATE:
Local2GlobalBoundaryBounds(patchlabellist[list_patch_index]);
break;
case FILEUPDATEDATA:
UpdateAllBoundaryColors();
break;
case FILERELOAD:
BoundBoundCB(FILEUPDATE);
for(i = 0;i < npatchinfo;i++){
patchdata *patchi;
patchi = patchinfo + i;
if(patchi->loaded == 0)continue;
LoadBoundaryMenu(i);
}
EDIT_patch_min->set_float_val(patchmin);
EDIT_patch_max->set_float_val(patchmax);
break;
case COMPRESS_FILES:
CompressSVZip();
break;
case COMPRESS_AUTOLOADED:
updatemenu = 1;
break;
case OVERWRITE:
if(overwrite_all == 1){
CHECKBOX_erase_all->set_int_val(0);
}
updatemenu = 1;
break;
case ERASE:
if(erase_all == 1){
CHECKBOX_overwrite_all->set_int_val(0);
}
updatemenu = 1;
break;
case STARTUP:
BoundsDlgCB(SAVE_SETTINGS_BOUNDS);
break;
case SAVE_FILE_LIST:
Set3DSmokeStartup();
BoundsDlgCB(SAVE_SETTINGS_BOUNDS);
break;
case LOAD_FILES:
LoadFiles();
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ Smoke3dBoundCB ------------------------ */
void Smoke3dBoundCB(int var){
switch(var){
case FRAMELOADING:
smoke3dframestep = smoke3dframeskip + 1;
smoke3dzipstep = smoke3dzipskip + 1;
updatemenu = 1;
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ TimeBoundCB ------------------------ */
void TimeBoundCB(int var){
updatemenu = 1;
switch(var){
case SET_TIME:
SetTimeVal(glui_time);
break;
case TBOUNDS:
if(use_tload_begin == 1 || use_tload_end == 1 || use_tload_skip == 1){
UpdateTBounds();
}
break;
case TBOUNDS_USE:
if(use_tload_begin == 1){
SPINNER_tload_begin->enable();
}
else{
SPINNER_tload_begin->disable();
}
if(use_tload_end == 1){
SPINNER_tload_end->enable();
}
else{
SPINNER_tload_end->disable();
}
if(use_tload_skip == 1){
SPINNER_tload_skip->enable();
}
else{
SPINNER_tload_skip->disable();
}
UpdateTBounds();
break;
case RELOAD_ALL_DATA:
ReloadMenu(RELOAD_ALL_NOW);
break;
case RELOAD_INCREMENTAL_DATA:
ReloadMenu(RELOAD_INCREMENTAL_NOW);
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ ScriptCB ------------------------ */
void ScriptCB(int var){
char label[1024];
char *name;
int id;
int len, i;
int set_renderlabel;
switch(var){
case SCRIPT_STEP_NOW:
Keyboard('^', FROM_SMOKEVIEW);
break;
case SCRIPT_CANCEL_NOW:
current_script_command = NULL;
runscript = 0;
first_frame_index = 0;
script_startframe = -1;
script_skipframe = -1;
script_step = 0;
GluiScriptEnable();
render_status = RENDER_OFF;
break;
case SCRIPT_RENDER_DIR:
strcpy(label, script_renderdir);
TrimBack(label);
name = TrimFront(label);
set_renderlabel = 0;
if(name != NULL&&strlen(name) != strlen(script_renderdir)){
strcpy(script_renderdir, name);
set_renderlabel = 1;
}
name = script_renderdir;
len = strlen(script_renderdir);
if(len == 0)break;
for(i = 0;i < len;i++){
#ifdef WIN32
if(name[i] == '/'){
set_renderlabel = 1;
name[i] = '\\';
}
#else
if(name[i] == '\\'){
set_renderlabel = 1;
name[i] = '/';
}
#endif
}
#ifdef WIN32
if(name[len - 1] != '\\'){
set_renderlabel = 1;
strcat(name, dirseparator);
}
#else
if(name[len - 1] != '/'){
set_renderlabel = 1;
strcat(name, dirseparator);
}
#endif
if(set_renderlabel == 1){
EDIT_renderdir->set_text(script_renderdir);
}
break;
case SCRIPT_RENDER:
Keyboard('r', FROM_SMOKEVIEW);
break;
case SCRIPT_RENDER_SUFFIX:
{
char *suffix;
TrimBack(script_renderfilesuffix);
suffix = TrimFront(script_renderfilesuffix);
strcpy(script_renderfile, "");
if(strlen(suffix) > 0){
strcpy(script_renderfile, fdsprefix);
strcat(script_renderfile, "_");
strcat(script_renderfile, suffix);
strcpy(label, _("Render: "));
strcat(label, script_renderfile);
}
else{
strcpy(label, _("Render"));
}
BUTTON_script_render->set_name(label);
}
break;
case SCRIPT_START:
ScriptMenu(SCRIPT_START_RECORDING);
break;
case SCRIPT_STOP:
ScriptMenu(SCRIPT_STOP_RECORDING);
break;
case SCRIPT_RUNSCRIPT:
name = 5 + BUTTON_script_runscript->name;
PRINTF("running script: %s\n", name);
ScriptMenu(LIST_scriptlist->get_int_val());
break;
case SCRIPT_LIST:
id = LIST_scriptlist->get_int_val();
name = GetScriptFileName(id);
if(name != NULL&&strlen(name) > 0){
strcpy(label, _("Run:"));
strcat(label, name);
BUTTON_script_runscript->set_name(label);
}
break;
case SCRIPT_SAVEINI:
name = 5 + BUTTON_script_saveini->name;
if(strlen(name) > 0){
inifiledata *inifile;
strcpy(script_filename, name);
inifile = InsertIniFile(name);
WriteIni(SCRIPT_INI, script_filename);
if(inifile != NULL&&LIST_ini_list != NULL){
LIST_ini_list->add_item(inifile->id, inifile->file);
}
}
WriteIni(LOCAL_INI, NULL);
break;
case SCRIPT_LOADINI:
{
char *ini_filename;
id = LIST_ini_list->get_int_val();
ini_filename = GetIniFileName(id);
if(ini_filename == NULL)break;
if(strcmp(ini_filename, caseini_filename) == 0){
ReadIni(NULL);
}
else if(id >= 0){
char *script_filename2;
if(strlen(ini_filename) == 0)break;
script_filename2 = script_filename;
strcpy(script_filename, ini_filename);
windowresized = 0;
ReadIni(script_filename2);
}
if(scriptoutstream != NULL){
fprintf(scriptoutstream, "LOADINIFILE\n");
fprintf(scriptoutstream, " %s\n", ini_filename);
}
}
break;
case SCRIPT_STEP:
UpdateScriptStep();
updatemenu = 1;
break;
case SCRIPT_EDIT_INI:
strcpy(label, _("Save"));
strcat(label, fdsprefix);
TrimBack(script_inifile_suffix);
if(strlen(script_inifile_suffix) > 0){
strcat(label, "_");
strcat(label, script_inifile_suffix);
}
strcat(label, ".ini");
BUTTON_script_saveini->set_name(label);
break;
case SCRIPT_SETSUFFIX:
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ SliceBoundMenu ------------------------ */
#ifdef pp_NEWBOUND_DIALOG
void GenerateSliceBoundDialog(void){
GLUI_Panel *PANEL_a=NULL, *PANEL_b=NULL, *PANEL_c, *PANEL_d = NULL, *PANEL_e = NULL;
ROLLOUT_slice_bound = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Bound data"), false, 0, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice_bound, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slice_bound, 0, glui_bounds);
PANEL_a = glui_bounds->add_panel_to_panel(ROLLOUT_slice_bound, "", GLUI_PANEL_NONE);
EDIT_slice_min = glui_bounds->add_edittext_to_panel(PANEL_a, "", GLUI_EDITTEXT_FLOAT, &glui_slicemin, VALMIN, SliceBoundCB);
glui_bounds->add_column_to_panel(PANEL_a, false);
STATIC_slice_min_unit = glui_bounds->add_statictext_to_panel(PANEL_a, "xx");
STATIC_slice_min_unit->set_w(10);
STATIC_slice_min = glui_bounds->add_statictext_to_panel(PANEL_a, "min");
STATIC_slice_min->set_w(4);
PANEL_b = glui_bounds->add_panel_to_panel(ROLLOUT_slice_bound, "", GLUI_PANEL_NONE);
EDIT_slice_max = glui_bounds->add_edittext_to_panel(PANEL_b, "", GLUI_EDITTEXT_FLOAT, &glui_slicemax, VALMAX, SliceBoundCB);
glui_bounds->add_column_to_panel(PANEL_b, false);
STATIC_slice_max_unit = glui_bounds->add_statictext_to_panel(PANEL_b, "yy");
STATIC_slice_max_unit->set_w(10);
STATIC_slice_max = glui_bounds->add_statictext_to_panel(PANEL_b, "max");
STATIC_slice_max->set_w(4);
PANEL_c = glui_bounds->add_panel_to_panel(ROLLOUT_slice_bound, "Set/Show Bounds");
BUTTON_slice_percentile_bounds = glui_bounds->add_button_to_panel(PANEL_c, _("Percentile"), PERCENTILE_BOUNDS_LOADED, SliceBoundCB);
BUTTON_slice_global_bounds = glui_bounds->add_button_to_panel(PANEL_c, _("Global"), GLOBAL_BOUNDS, SliceBoundCB);
RADIO_slice_loaded_only = glui_bounds->add_radiogroup_to_panel(PANEL_c, &slice_loaded_only, SLICE_LOADED_ONLY, SliceBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_slice_loaded_only, "all");
glui_bounds->add_radiobutton_to_group(RADIO_slice_loaded_only, "loaded");
SliceBoundCB(SLICE_LOADED_ONLY);
glui_bounds->add_button_to_panel(ROLLOUT_slice_bound, _("Update"), FILEUPDATE, SliceBoundCB);
ROLLOUT_slice_chop = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Truncate data"), false, 1, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice_chop, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slice_chop, 1, glui_bounds);
PANEL_d = glui_bounds->add_panel_to_panel(ROLLOUT_slice_chop, "", GLUI_PANEL_NONE);
EDIT_slice_chopmin = glui_bounds->add_edittext_to_panel(PANEL_d, "", GLUI_EDITTEXT_FLOAT, &glui_slicechopmin, CHOPVALMIN, SliceBoundCB);
glui_bounds->add_column_to_panel(PANEL_d, false);
STATIC_slice_cmin_unit = glui_bounds->add_statictext_to_panel(PANEL_d, "xx");
STATIC_slice_cmin_unit->set_w(10);
glui_bounds->add_column_to_panel(PANEL_d, false);
CHECKBOX_slice_setchopmin = glui_bounds->add_checkbox_to_panel(PANEL_d, _("Below"), &glui_setslicechopmin, SETCHOPMINVAL, SliceBoundCB);
PANEL_e = glui_bounds->add_panel_to_panel(ROLLOUT_slice_chop, "", GLUI_PANEL_NONE);
EDIT_slice_chopmax = glui_bounds->add_edittext_to_panel(PANEL_e, "", GLUI_EDITTEXT_FLOAT, &glui_slicechopmax, CHOPVALMAX, SliceBoundCB);
glui_bounds->add_column_to_panel(PANEL_e, false);
STATIC_slice_cmax_unit = glui_bounds->add_statictext_to_panel(PANEL_e, "xx");
glui_bounds->add_column_to_panel(PANEL_e, false);
STATIC_slice_cmax_unit->set_w(10);
CHECKBOX_slice_setchopmax = glui_bounds->add_checkbox_to_panel(PANEL_e, _("Above"), &glui_setslicechopmax, SETCHOPMAXVAL, SliceBoundCB);
}
#endif
/* ------------------ BoundMenu ------------------------ */
void GenerateBoundDialogs(GLUI_Rollout **bound_rollout, GLUI_Rollout **chop_rollout, GLUI_Panel *PANEL_panel, char *button_title,
GLUI_EditText **EDIT_con_min, GLUI_EditText **EDIT_con_max,
GLUI_RadioGroup **RADIO_con_setmin, GLUI_RadioGroup **RADIO_con_setmax,
GLUI_RadioButton **RADIO_CON_setmin_percentile, GLUI_RadioButton **RADIO_CON_setmax_percentile,
GLUI_Checkbox **CHECKBOX_con_setchopmin, GLUI_Checkbox **CHECKBOX_con_setchopmax,
GLUI_EditText **EDIT_con_chopmin, GLUI_EditText **EDIT_con_chopmax,
GLUI_StaticText **STATIC_con_min_unit, GLUI_StaticText **STATIC_con_max_unit,
GLUI_StaticText **STATIC_con_cmin_unit, GLUI_StaticText **STATIC_con_cmax_unit,
GLUI_Button **BUTTON_update, GLUI_Button **BUTTON_reload,
GLUI_Panel **PANEL_bound,
int *setminval, int *setmaxval,
float *minval, float *maxval,
int *setchopminval, int *setchopmaxval,
float *chopminval, float *chopmaxval,
int updatebounds,
int truncatebounds,
GLUI_Update_CB FILE_CB,
GLUI_Update_CB PROC_CB, procdata *procinfo, int *nprocinfo){
GLUI_RadioButton *percentile_min, *percentile_max;
GLUI_Panel *PANEL_a, *PANEL_b, *PANEL_c;
GLUI_Rollout *PANEL_e = NULL, *PANEL_g = NULL;
GLUI_Panel *PANEL_f = NULL, *PANEL_h = NULL;
PANEL_g = glui_bounds->add_rollout_to_panel(PANEL_panel, _("Bound data"), false, 0, PROC_CB);
if(PANEL_bound!=NULL)*PANEL_bound = PANEL_g;
INSERT_ROLLOUT(PANEL_g, glui_bounds);
if(bound_rollout!=NULL){
*bound_rollout = PANEL_g;
ADDPROCINFO(procinfo, *nprocinfo, PANEL_g, 0, glui_bounds);
}
PANEL_a = glui_bounds->add_panel_to_panel(PANEL_g, "", GLUI_PANEL_NONE);
*EDIT_con_min = glui_bounds->add_edittext_to_panel(PANEL_a, "", GLUI_EDITTEXT_FLOAT, minval, VALMIN, FILE_CB);
if(*setminval==0){
(*EDIT_con_min)->disable();
}
glui_bounds->add_column_to_panel(PANEL_a, false);
if(STATIC_con_min_unit!=NULL){
*STATIC_con_min_unit = glui_bounds->add_statictext_to_panel(PANEL_a, "xx");
glui_bounds->add_column_to_panel(PANEL_a, false);
(*STATIC_con_min_unit)->set_w(10);
}
*RADIO_con_setmin = glui_bounds->add_radiogroup_to_panel(PANEL_a, setminval, SETVALMIN, FILE_CB);
percentile_min = glui_bounds->add_radiobutton_to_group(*RADIO_con_setmin, _("percentile min"));
if(RADIO_CON_setmin_percentile!=NULL)*RADIO_CON_setmin_percentile = percentile_min;
glui_bounds->add_radiobutton_to_group(*RADIO_con_setmin, _("set min"));
glui_bounds->add_radiobutton_to_group(*RADIO_con_setmin, _("global min"));
PANEL_b = glui_bounds->add_panel_to_panel(PANEL_g, "", GLUI_PANEL_NONE);
*EDIT_con_max = glui_bounds->add_edittext_to_panel(PANEL_b, "", GLUI_EDITTEXT_FLOAT, maxval, VALMAX, FILE_CB);
if(*setminval==0){
(*EDIT_con_max)->disable();
}
glui_bounds->add_column_to_panel(PANEL_b, false);
if(STATIC_con_max_unit!=NULL){
*STATIC_con_max_unit = glui_bounds->add_statictext_to_panel(PANEL_b, "yy");
glui_bounds->add_column_to_panel(PANEL_b, false);
(*STATIC_con_max_unit)->set_w(10);
}
*RADIO_con_setmax = glui_bounds->add_radiogroup_to_panel(PANEL_b, setmaxval, SETVALMAX, FILE_CB);
percentile_max = glui_bounds->add_radiobutton_to_group(*RADIO_con_setmax, _("percentile max"));
if(RADIO_CON_setmax_percentile!=NULL)*RADIO_CON_setmax_percentile = percentile_max;
glui_bounds->add_radiobutton_to_group(*RADIO_con_setmax, _("set max"));
glui_bounds->add_radiobutton_to_group(*RADIO_con_setmax, _("global max"));
PANEL_c = glui_bounds->add_panel_to_panel(PANEL_g, "", GLUI_PANEL_NONE);
if(updatebounds==UPDATE_BOUNDS){
glui_bounds->add_button_to_panel(PANEL_c, _("Update"), FILEUPDATE, FILE_CB);
}
else if(updatebounds==RELOAD_BOUNDS){
glui_bounds->add_button_to_panel(PANEL_c, button_title, FILERELOAD, FILE_CB);
}
else{
BUTTON_updatebound = glui_bounds->add_button_to_panel(PANEL_c, _("Update using cached data"), FILEUPDATEDATA, FILE_CB);
BUTTON_reloadbound = glui_bounds->add_button_to_panel(PANEL_c, button_title, FILERELOAD, FILE_CB);
}
if(EDIT_con_chopmin!=NULL&&EDIT_con_chopmax!=NULL&&CHECKBOX_con_setchopmin!=NULL&&CHECKBOX_con_setchopmax!=NULL){
PANEL_e = glui_bounds->add_rollout_to_panel(PANEL_panel, _("Truncate data"), false, 1, PROC_CB);
INSERT_ROLLOUT(PANEL_e, glui_bounds);
if(chop_rollout!=NULL){
*chop_rollout = PANEL_e;
ADDPROCINFO(procinfo, *nprocinfo, PANEL_e, 1, glui_bounds);
}
PANEL_f = glui_bounds->add_panel_to_panel(PANEL_e, "", GLUI_PANEL_NONE);
*EDIT_con_chopmin = glui_bounds->add_edittext_to_panel(PANEL_f, "", GLUI_EDITTEXT_FLOAT, chopminval, CHOPVALMIN, FILE_CB);
glui_bounds->add_column_to_panel(PANEL_f, false);
if(STATIC_con_cmin_unit!=NULL){
*STATIC_con_cmin_unit = glui_bounds->add_statictext_to_panel(PANEL_f, "xx");
(*STATIC_con_cmin_unit)->set_w(10);
glui_bounds->add_column_to_panel(PANEL_f, false);
}
*CHECKBOX_con_setchopmin = glui_bounds->add_checkbox_to_panel(PANEL_f, _("Below"), setchopminval, SETCHOPMINVAL, FILE_CB);
PANEL_h = glui_bounds->add_panel_to_panel(PANEL_e, "", GLUI_PANEL_NONE);
*EDIT_con_chopmax = glui_bounds->add_edittext_to_panel(PANEL_h, "", GLUI_EDITTEXT_FLOAT, chopmaxval, CHOPVALMAX, FILE_CB);
glui_bounds->add_column_to_panel(PANEL_h, false);
if(STATIC_con_cmax_unit!=NULL){
*STATIC_con_cmax_unit = glui_bounds->add_statictext_to_panel(PANEL_h, "xx");
glui_bounds->add_column_to_panel(PANEL_h, false);
(*STATIC_con_cmax_unit)->set_w(10);
}
*CHECKBOX_con_setchopmax = glui_bounds->add_checkbox_to_panel(PANEL_h, _("Above"), setchopmaxval, SETCHOPMAXVAL, FILE_CB);
if(truncatebounds==TRUNCATE_BOUNDS){
glui_bounds->add_button_to_panel(PANEL_e, _("Update"), CHOPUPDATE, FILE_CB);
}
}
}
/* ------------------ GluiBoundsSetup ------------------------ */
extern "C" void GluiBoundsSetup(int main_window){
int i;
int nradio;
int have_part, have_evac;
update_glui_bounds=0;
if(glui_bounds!=NULL){
glui_bounds->close();
glui_bounds=NULL;
}
overwrite_all=0;
glui_bounds = GLUI_Master.create_glui( "Files/Bounds",0,0,0 );
glui_bounds->hide();
PANEL_files = glui_bounds->add_panel("Files", true);
ROLLOUT_autoload = glui_bounds->add_rollout_to_panel(PANEL_files,_("Auto load"), false, LOAD_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_autoload, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_autoload, LOAD_ROLLOUT, glui_bounds);
glui_bounds->add_checkbox_to_panel(ROLLOUT_autoload, _("Auto load at startup"),
&loadfiles_at_startup, STARTUP, BoundBoundCB);
glui_bounds->add_button_to_panel(ROLLOUT_autoload, _("Save auto load file list"), SAVE_FILE_LIST, BoundBoundCB);
glui_bounds->add_button_to_panel(ROLLOUT_autoload, _("Auto load now"), LOAD_FILES, BoundBoundCB);
// -------------- Show/Hide Loaded files -------------------
if(npartinfo > 0 || nsliceinfo > 0 || nvsliceinfo > 0 || nisoinfo > 0 || npatchinfo || nsmoke3dinfo > 0 || nplot3dinfo > 0){
ROLLOUT_showhide = glui_bounds->add_rollout_to_panel(PANEL_files,_("Show/Hide"), false, SHOWHIDE_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_showhide, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_showhide, SHOWHIDE_ROLLOUT, glui_bounds);
RADIO_showhide = glui_bounds->add_radiogroup_to_panel(ROLLOUT_showhide, &showhide_option);
glui_bounds->add_radiobutton_to_group(RADIO_showhide, _("Show"));
glui_bounds->add_radiobutton_to_group(RADIO_showhide, _("Show only"));
glui_bounds->add_radiobutton_to_group(RADIO_showhide, _("Hide"));
glui_bounds->add_column_to_panel(ROLLOUT_showhide, false);
if(nevac > 0){}
if(npartinfo > 0 && nevac != npartinfo)BUTTON_PART = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Particle", FILESHOW_particle, FileShowCB);
if(nevac > 0)BUTTON_EVAC = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Evacuation", FILESHOW_evac, FileShowCB);
if(nsliceinfo > 0)BUTTON_SLICE = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Slice", FILESHOW_slice, FileShowCB);
if(nvsliceinfo > 0)BUTTON_VSLICE = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Vector", FILESHOW_vslice, FileShowCB);
if(nisoinfo > 0)BUTTON_ISO = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Isosurface", FILESHOW_isosurface, FileShowCB);
if(npatchinfo > 0)BUTTON_BOUNDARY = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Boundary", FILESHOW_boundary, FileShowCB);
if(nsmoke3dinfo > 0)BUTTON_3DSMOKE = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "3D smoke/fire", FILESHOW_3dsmoke, FileShowCB);
if(nplot3dinfo > 0)BUTTON_PLOT3D = glui_bounds->add_button_to_panel(ROLLOUT_showhide, "Plot3D", FILESHOW_plot3d, FileShowCB);
glui_bounds->add_button_to_panel(ROLLOUT_showhide, "File Sizes", FILESHOW_sizes, FileShowCB);
UpdateShowHideButtons();
}
#ifdef pp_COMPRESS
if(smokezippath != NULL && (npatchinfo > 0 || nsmoke3dinfo > 0 || nsliceinfo > 0)){
ROLLOUT_compress = glui_bounds->add_rollout_to_panel(PANEL_files,_("Compress"), false, COMPRESS_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_compress, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_compress, COMPRESS_ROLLOUT, glui_bounds);
CHECKBOX_erase_all = glui_bounds->add_checkbox_to_panel(ROLLOUT_compress, _("Erase compressed files"),
&erase_all, ERASE, BoundBoundCB);
CHECKBOX_overwrite_all = glui_bounds->add_checkbox_to_panel(ROLLOUT_compress, _("Overwrite compressed files"),
&overwrite_all, OVERWRITE, BoundBoundCB);
CHECKBOX_compress_autoloaded = glui_bounds->add_checkbox_to_panel(ROLLOUT_compress, _("Compress only autoloaded files"),
&compress_autoloaded, COMPRESS_AUTOLOADED, BoundBoundCB);
if(nsliceinfo > 0){
SPINNER_slicezipstep = glui_bounds->add_spinner_to_panel(ROLLOUT_compress, _("Slice frame Skip"), GLUI_SPINNER_INT, &slicezipskip,
FRAMELOADING, SliceBoundCB);
SPINNER_slicezipstep->set_int_limits(0, 100);
}
if(nisoinfo > 0){
SPINNER_isozipstep = glui_bounds->add_spinner_to_panel(ROLLOUT_compress, _("Compressed file frame skip"), GLUI_SPINNER_INT, &isozipskip,
FRAMELOADING, IsoBoundCB);
SPINNER_isozipstep->set_int_limits(0, 100);
}
if(nsmoke3dinfo > 0){
SPINNER_smoke3dzipstep = glui_bounds->add_spinner_to_panel(ROLLOUT_compress, _("3D smoke frame skip"), GLUI_SPINNER_INT, &smoke3dzipskip,
FRAMELOADING, Smoke3dBoundCB);
SPINNER_smoke3dzipstep->set_int_limits(0, 100);
}
if(npatchinfo > 0){
SPINNER_boundzipstep = glui_bounds->add_spinner_to_panel(ROLLOUT_compress, _("Boundary file frame skip"),
GLUI_SPINNER_INT, &boundzipskip, FRAMELOADING, BoundBoundCB);
SPINNER_boundzipstep->set_int_limits(0, 100);
}
BUTTON_compress = glui_bounds->add_button_to_panel(ROLLOUT_compress, _("Run smokezip"), COMPRESS_FILES, BoundBoundCB);
}
#endif
ROLLOUT_script = glui_bounds->add_rollout_to_panel(PANEL_files,_("Scripts"), false, SCRIPT_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_script, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_script, SCRIPT_ROLLOUT, glui_bounds);
PANEL_script1 = glui_bounds->add_panel_to_panel(ROLLOUT_script, _("Script files"), false);
PANEL_record = glui_bounds->add_panel_to_panel(PANEL_script1, _("Record"), true);
PANEL_script1a = glui_bounds->add_panel_to_panel(PANEL_record, "", false);
BUTTON_script_start = glui_bounds->add_button_to_panel(PANEL_script1a, _("Start"), SCRIPT_START, ScriptCB);
glui_bounds->add_column_to_panel(PANEL_script1a, false);
BUTTON_script_stop = glui_bounds->add_button_to_panel(PANEL_script1a, _("Stop"), SCRIPT_STOP, ScriptCB);
BUTTON_script_stop->disable();
PANEL_run = glui_bounds->add_panel_to_panel(PANEL_script1, _("Run"), true);
PANEL_script1b = glui_bounds->add_panel_to_panel(PANEL_run, "", false);
BUTTON_script_runscript = glui_bounds->add_button_to_panel(PANEL_script1b, _("Run script"), SCRIPT_RUNSCRIPT, ScriptCB);
glui_bounds->add_column_to_panel(PANEL_script1b, false);
CHECKBOX_script_step = glui_bounds->add_checkbox_to_panel(PANEL_run, _("Step through script"), &script_step, SCRIPT_STEP, ScriptCB);
BUTTON_step = glui_bounds->add_button_to_panel(PANEL_run, _("Next"), SCRIPT_STEP_NOW, ScriptCB);
UpdateScriptStep();
glui_bounds->add_button_to_panel(PANEL_run, _("Cancel script"), SCRIPT_CANCEL_NOW, ScriptCB);
LIST_scriptlist = glui_bounds->add_listbox_to_panel(PANEL_script1b, _("Select:"), &script_index, SCRIPT_LIST, ScriptCB);
{
scriptfiledata *scriptfile;
for(scriptfile = first_scriptfile.next; scriptfile->next != NULL; scriptfile = scriptfile->next){
char *file;
int len;
file = scriptfile->file;
if(file == NULL)continue;
if(FILE_EXISTS(file) == NO)continue;
len = strlen(file);
if(len <= 0)continue;
LIST_scriptlist->add_item(scriptfile->id, file);
}
ScriptCB(SCRIPT_LIST);
}
ROLLOUT_config = glui_bounds->add_rollout_to_panel(PANEL_files, "Config", false, CONFIG_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_config, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_config, CONFIG_ROLLOUT, glui_bounds);
PANEL_script2a = glui_bounds->add_panel_to_panel(ROLLOUT_config, "", false);
EDIT_ini = glui_bounds->add_edittext_to_panel(PANEL_script2a, "suffix:", GLUI_EDITTEXT_TEXT, script_inifile_suffix, SCRIPT_EDIT_INI, ScriptCB);
glui_bounds->add_column_to_panel(PANEL_script2a, false);
BUTTON_script_setsuffix = glui_bounds->add_button_to_panel(PANEL_script2a, _("Set"), SCRIPT_SETSUFFIX, ScriptCB);
glui_bounds->add_column_to_panel(PANEL_script2a, false);
BUTTON_script_saveini = glui_bounds->add_button_to_panel(PANEL_script2a, _("Save:"), SCRIPT_SAVEINI, ScriptCB);
ScriptCB(SCRIPT_EDIT_INI);
PANEL_script2b = glui_bounds->add_panel_to_panel(ROLLOUT_config, "", false);
ini_index = -2;
LIST_ini_list = glui_bounds->add_listbox_to_panel(PANEL_script2b, _("Select:"), &ini_index);
{
inifiledata *inifile;
for(inifile = first_inifile.next; inifile->next != NULL; inifile = inifile->next){
if(inifile->file != NULL&&FILE_EXISTS(inifile->file) == YES){
if(ini_index == -2)ini_index = inifile->id;
LIST_ini_list->add_item(inifile->id, inifile->file);
}
}
}
glui_bounds->add_column_to_panel(PANEL_script2b, false);
BUTTON_ini_load = glui_bounds->add_button_to_panel(PANEL_script2b, _("Load"), SCRIPT_LOADINI, ScriptCB);
PANEL_script3 = glui_bounds->add_panel_to_panel(ROLLOUT_script, _("Render"), true);
EDIT_renderdir = glui_bounds->add_edittext_to_panel(PANEL_script3, _("directory:"),
GLUI_EDITTEXT_TEXT, script_renderdir, SCRIPT_RENDER_DIR, ScriptCB);
EDIT_renderdir->set_w(260);
PANEL_script1c = glui_bounds->add_panel_to_panel(PANEL_script3, "", false);
BUTTON_script_render = glui_bounds->add_button_to_panel(PANEL_script1c, _("Render"), SCRIPT_RENDER, ScriptCB);
glui_bounds->add_column_to_panel(PANEL_script1c, false);
EDIT_rendersuffix = glui_bounds->add_edittext_to_panel(PANEL_script1c, _("suffix:"),
GLUI_EDITTEXT_TEXT, script_renderfilesuffix, SCRIPT_RENDER_SUFFIX, ScriptCB);
EDIT_rendersuffix->set_w(130);
ScriptCB(SCRIPT_RENDER_SUFFIX);
// ----------------------------------- Bounds ----------------------------------------
PANEL_bounds = glui_bounds->add_panel("Bounds",true);
ROLLOUT_filebounds = glui_bounds->add_rollout_to_panel(PANEL_bounds,_("Data"), false, FILEBOUNDS_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_filebounds, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_filebounds, FILEBOUNDS_ROLLOUT, glui_bounds);
/* zone (cfast) */
if(nzoneinfo>0){
ROLLOUT_zone_bound = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,_("Zone/slice temperatures"),false,ZONE_ROLLOUT,BoundRolloutCB);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_zone_bound, ZONE_ROLLOUT, glui_bounds);
PANEL_zone_a = glui_bounds->add_panel_to_panel(ROLLOUT_zone_bound,"",GLUI_PANEL_NONE);
EDIT_zone_min = glui_bounds->add_edittext_to_panel(PANEL_zone_a,"",GLUI_EDITTEXT_FLOAT,&zonemin,ZONEVALMINMAX,SliceBoundCB);
if(setzonemin==0){
EDIT_zone_min->disable();
if(EDIT_slice_min!=NULL)EDIT_slice_min->disable();
}
else{
EDIT_zone_min->enable();
if(EDIT_slice_min!=NULL)EDIT_slice_min->enable();
}
glui_bounds->add_column_to_panel(PANEL_zone_a,false);
RADIO_zone_setmin = glui_bounds->add_radiogroup_to_panel(PANEL_zone_a,&setzonemin,SETZONEVALMINMAX,SliceBoundCB);
RADIOBUTTON_zone_permin=glui_bounds->add_radiobutton_to_group(RADIO_zone_setmin,_("percentile min"));
glui_bounds->add_radiobutton_to_group(RADIO_zone_setmin,_("set min"));
glui_bounds->add_radiobutton_to_group(RADIO_zone_setmin,_("global min"));
PANEL_zone_b = glui_bounds->add_panel_to_panel(ROLLOUT_zone_bound,"",GLUI_PANEL_NONE);
EDIT_zone_max = glui_bounds->add_edittext_to_panel(PANEL_zone_b,"",GLUI_EDITTEXT_FLOAT,&zonemax,ZONEVALMINMAX,SliceBoundCB);
if(setzonemax==0){
EDIT_zone_max->disable();
if(EDIT_slice_max!=NULL)EDIT_slice_max->disable();
}
else{
EDIT_zone_max->enable();
if(EDIT_slice_max!=NULL)EDIT_slice_max->enable();
}
glui_bounds->add_column_to_panel(PANEL_zone_b,false);
RADIO_zone_setmax = glui_bounds->add_radiogroup_to_panel(PANEL_zone_b,&setzonemax,SETZONEVALMINMAX,SliceBoundCB);
RADIOBUTTON_zone_permax=glui_bounds->add_radiobutton_to_group(RADIO_zone_setmax,_("percentile max"));
glui_bounds->add_radiobutton_to_group(RADIO_zone_setmax,_("set max"));
glui_bounds->add_radiobutton_to_group(RADIO_zone_setmax,_("global max"));
RADIOBUTTON_zone_permin->disable();
RADIOBUTTON_zone_permax->disable();
SliceBoundCB(SETZONEVALMINMAX);
}
// ----------------------------------- 3D smoke ----------------------------------------
if(nsmoke3dinfo>0||nvolrenderinfo>0){
ROLLOUT_smoke3d = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,_("3D smoke"),false,SMOKE3D_ROLLOUT,BoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_smoke3d, glui_bounds);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_smoke3d, SMOKE3D_ROLLOUT, glui_bounds);
}
// ----------------------------------- Boundary ----------------------------------------
if(npatchinfo>0){
glui_active=1;
ROLLOUT_bound = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,_("Boundary"),false,BOUNDARY_ROLLOUT,BoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_bound, glui_bounds);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_bound, BOUNDARY_ROLLOUT, glui_bounds);
nradio=0;
for(i=0;i<npatchinfo;i++){
patchdata *patchi;
patchi = patchinfo + i;
if(patchi->firstshort==1)nradio++;
}
if(nradio>1){
RADIO_bf = glui_bounds->add_radiogroup_to_panel(ROLLOUT_bound, &list_patch_index, FILETYPEINDEX, BoundBoundCB);
for(i=0;i<npatchinfo;i++){
patchdata *patchi;
patchi = patchinfo + i;
if(patchi->firstshort==1)glui_bounds->add_radiobutton_to_group(RADIO_bf,patchi->label.shortlabel);
}
#ifdef pp_FSEEK
CHECKBOX_boundary_load_incremental=glui_bounds->add_checkbox_to_panel(ROLLOUT_bound, _("incremental data loading"), &load_incremental, BOUNDARY_LOAD_INCREMENTAL, LoadIncrementalCB);
LoadIncrementalCB(BOUNDARY_LOAD_INCREMENTAL);
#endif
glui_bounds->add_column_to_panel(ROLLOUT_bound,false);
}
GenerateBoundDialogs(&ROLLOUT_boundary_bound,&ROLLOUT_boundary_chop,ROLLOUT_bound,_("Reload Boundary File(s)"),
&EDIT_patch_min,&EDIT_patch_max,&RADIO_patch_setmin,&RADIO_patch_setmax,NULL,NULL,
&CHECKBOX_patch_setchopmin, &CHECKBOX_patch_setchopmax,
&EDIT_patch_chopmin, &EDIT_patch_chopmax,
&STATIC_bound_min_unit,&STATIC_bound_max_unit,
&STATIC_bound_cmin_unit,&STATIC_bound_cmax_unit,
&BUTTON_updatebound, &BUTTON_reloadbound,
NULL,
&setpatchmin,&setpatchmax,&patchmin,&patchmax,
&setpatchchopmin, &setpatchchopmax,
&patchchopmin, &patchchopmax,
UPDATERELOAD_BOUNDS,DONT_TRUNCATE_BOUNDS,
BoundBoundCB,
SubBoundRolloutCB,subboundprocinfo,&nsubboundprocinfo);
UpdateBoundaryListIndex2(patchinfo->label.shortlabel);
UpdateHideBoundarySurface();
BoundBoundCB(CACHE_BOUNDARYDATA);
ROLLOUT_outputpatchdata = glui_bounds->add_rollout_to_panel(ROLLOUT_bound,_("Output data"),false,
BOUNDARY_OUTPUT_ROLLOUT,SubBoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_outputpatchdata, glui_bounds);
ADDPROCINFO(subboundprocinfo, nsubboundprocinfo, ROLLOUT_outputpatchdata, BOUNDARY_OUTPUT_ROLLOUT, glui_bounds);
glui_bounds->add_checkbox_to_panel(ROLLOUT_outputpatchdata,_("Output data to file"),&output_patchdata);
PANEL_outputpatchdata = glui_bounds->add_panel_to_panel(ROLLOUT_outputpatchdata,"",GLUI_PANEL_NONE);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"tmin",GLUI_SPINNER_FLOAT,&patchout_tmin);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"xmin",GLUI_SPINNER_FLOAT,&patchout_xmin);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"ymin",GLUI_SPINNER_FLOAT,&patchout_ymin);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"zmin",GLUI_SPINNER_FLOAT,&patchout_zmin);
glui_bounds->add_column_to_panel(PANEL_outputpatchdata,false);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"tmax",GLUI_SPINNER_FLOAT,&patchout_tmax);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"xmax",GLUI_SPINNER_FLOAT,&patchout_xmax);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"ymax",GLUI_SPINNER_FLOAT,&patchout_ymax);
glui_bounds->add_spinner_to_panel(PANEL_outputpatchdata,"zmax",GLUI_SPINNER_FLOAT,&patchout_zmax);
if(activate_threshold==1){
ROLLOUT_boundary_temp_threshold = glui_bounds->add_rollout_to_panel(ROLLOUT_bound,_("Temperature threshold"),false,BOUNDARY_THRESHOLD_ROLLOUT,SubBoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_boundary_temp_threshold, glui_bounds);
ADDPROCINFO(subboundprocinfo, nsubboundprocinfo, ROLLOUT_boundary_temp_threshold, BOUNDARY_THRESHOLD_ROLLOUT, glui_bounds);
CHECKBOX_showchar=glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_temp_threshold,_("Show"),&vis_threshold,SHOWCHAR,BoundBoundCB);
CHECKBOX_showonlychar=glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_temp_threshold,_("Show only threshold"),&vis_onlythreshold,SHOWCHAR,BoundBoundCB);
{
char label[256];
strcpy(label,"Temperature (");
strcat(label,degC);
strcat(label,") ");
glui_bounds->add_spinner_to_panel(ROLLOUT_boundary_temp_threshold,label,GLUI_SPINNER_FLOAT,&temp_threshold);
}
BoundBoundCB(SHOWCHAR);
}
ROLLOUT_boundary_settings = glui_bounds->add_rollout_to_panel(ROLLOUT_bound, _("Settings"),false, BOUNDARY_SETTINGS_ROLLOUT, SubBoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_boundary_settings, glui_bounds);
ADDPROCINFO(subboundprocinfo, nsubboundprocinfo, ROLLOUT_boundary_settings, BOUNDARY_SETTINGS_ROLLOUT, glui_bounds);
if(ngeom_data > 0){
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_settings, _("shaded"), &show_boundary_shaded);
CHECKBOX_show_boundary_outline=glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_settings, _("outline"), &show_boundary_outline, SHOW_BOUNDARY_OUTLINE, BoundBoundCB);
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_settings, _("points"), &show_boundary_points);
PANEL_boundary_outline_type = glui_bounds->add_panel_to_panel(ROLLOUT_boundary_settings,"outline type");
RADIO_boundary_edgetype = glui_bounds->add_radiogroup_to_panel(PANEL_boundary_outline_type, &boundary_edgetype, BOUNDARY_EDGETYPE, BoundBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_boundary_edgetype, _("polygon"));
glui_bounds->add_radiobutton_to_group(RADIO_boundary_edgetype, _("triangle"));
glui_bounds->add_radiobutton_to_group(RADIO_boundary_edgetype, _("none"));
BoundBoundCB(BOUNDARY_EDGETYPE);
BoundBoundCB(SHOW_BOUNDARY_OUTLINE);
PANEL_geomexp = glui_bounds->add_panel_to_panel(ROLLOUT_boundary_settings,"experimental");
glui_bounds->add_checkbox_to_panel(PANEL_geomexp, _("smooth normals"), &geomdata_smoothnormals);
glui_bounds->add_checkbox_to_panel(PANEL_geomexp, _("smooth color/data"), &geomdata_smoothcolors);
glui_bounds->add_checkbox_to_panel(PANEL_geomexp, _("lighting"), &geomdata_lighting);
glui_bounds->add_spinner_to_panel(ROLLOUT_boundary_settings, "line width", GLUI_SPINNER_FLOAT, &geomboundary_linewidth);
glui_bounds->add_spinner_to_panel(ROLLOUT_boundary_settings, "point size", GLUI_SPINNER_FLOAT, &geomboundary_pointsize);
glui_bounds->add_separator_to_panel(ROLLOUT_boundary_settings);
}
CHECKBOX_cache_boundarydata = glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_settings, _("Cache boundary data"), &cache_boundarydata, CACHE_BOUNDARYDATA, BoundBoundCB);
CHECKBOX_showpatch_both = glui_bounds->add_checkbox_to_panel(ROLLOUT_boundary_settings, _("Display exterior data"), &showpatch_both, SHOWPATCH_BOTH, BoundBoundCB);
if(nboundaryslicedups > 0){
ROLLOUT_boundary_duplicates = glui_bounds->add_rollout_to_panel(ROLLOUT_bound, "Duplicates", false,BOUNDARY_DUPLICATE_ROLLOUT,SubBoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_boundary_duplicates, glui_bounds);
ADDPROCINFO(subboundprocinfo, nsubboundprocinfo, ROLLOUT_boundary_duplicates, BOUNDARY_DUPLICATE_ROLLOUT, glui_bounds);
RADIO_boundaryslicedup = glui_bounds->add_radiogroup_to_panel(ROLLOUT_boundary_duplicates, &boundaryslicedup_option,UPDATE_BOUNDARYSLICEDUPS,BoundBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_boundaryslicedup, _("Keep all"));
glui_bounds->add_radiobutton_to_group(RADIO_boundaryslicedup, _("Keep fine"));
glui_bounds->add_radiobutton_to_group(RADIO_boundaryslicedup, _("Keep coarse"));
}
}
// ----------------------------------- Isosurface ----------------------------------------
if(nisoinfo>0){
ROLLOUT_iso = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds, "Isosurface", false, ISO_ROLLOUT, BoundRolloutCB);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_iso, ISO_ROLLOUT, glui_bounds);
if(niso_bounds>0){
ROLLOUT_iso_bounds = glui_bounds->add_rollout_to_panel(ROLLOUT_iso, "Bound data", true, ISO_ROLLOUT_BOUNDS, IsoRolloutCB);
INSERT_ROLLOUT(ROLLOUT_iso_bounds, glui_bounds);
ADDPROCINFO(isoprocinfo, nisoprocinfo, ROLLOUT_iso_bounds, ISO_ROLLOUT_BOUNDS, glui_bounds);
PANEL_iso1 = glui_bounds->add_panel_to_panel(ROLLOUT_iso_bounds, "", GLUI_PANEL_NONE);
EDIT_iso_valmin = glui_bounds->add_edittext_to_panel(PANEL_iso1, "", GLUI_EDITTEXT_FLOAT, &glui_iso_valmin, ISO_VALMIN, IsoBoundCB);
glui_bounds->add_column_to_panel(PANEL_iso1, false);
RADIO_iso_setmin = glui_bounds->add_radiogroup_to_panel(PANEL_iso1, &setisomin, ISO_SETVALMIN, IsoBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmin, _("percentile min"));
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmin, _("set min"));
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmin, _("global min"));
IsoBoundCB(ISO_SETVALMIN);
PANEL_iso2 = glui_bounds->add_panel_to_panel(ROLLOUT_iso_bounds, "", GLUI_PANEL_NONE);
EDIT_iso_valmax = glui_bounds->add_edittext_to_panel(PANEL_iso2, "", GLUI_EDITTEXT_FLOAT, &glui_iso_valmax, ISO_VALMAX, IsoBoundCB);
glui_bounds->add_column_to_panel(PANEL_iso2, false);
RADIO_iso_setmax = glui_bounds->add_radiogroup_to_panel(PANEL_iso2, &setisomax, ISO_SETVALMAX, IsoBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmax, _("percentile max"));
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmax, _("set max"));
glui_bounds->add_radiobutton_to_group(RADIO_iso_setmax, _("global max"));
IsoBoundCB(ISO_SETVALMAX);
}
ROLLOUT_iso_settings = glui_bounds->add_rollout_to_panel(ROLLOUT_iso, "Settings", true, ISO_ROLLOUT_SETTINGS, IsoRolloutCB);
INSERT_ROLLOUT(ROLLOUT_iso_settings, glui_bounds);
ADDPROCINFO(isoprocinfo, nisoprocinfo, ROLLOUT_iso_settings, ISO_ROLLOUT_SETTINGS, glui_bounds);
visAIso = show_iso_shaded*1+show_iso_outline*2+show_iso_points*4;
CHECKBOX_show_iso_shaded = glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("shaded"), &show_iso_shaded, ISO_SURFACE, IsoBoundCB);
CHECKBOX_show_iso_outline = glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("outline"), &show_iso_outline, ISO_OUTLINE, IsoBoundCB);
CHECKBOX_show_iso_points = glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("points"), &show_iso_points, ISO_POINTS, IsoBoundCB);
SPINNER_isolinewidth = glui_bounds->add_spinner_to_panel(ROLLOUT_iso_settings, _("line width"), GLUI_SPINNER_FLOAT, &isolinewidth);
SPINNER_isolinewidth->set_float_limits(1.0, 10.0);
SPINNER_iso_outline_ioffset = glui_bounds->add_spinner_to_panel(ROLLOUT_iso_settings, "outline offset", GLUI_SPINNER_INT, &iso_outline_ioffset, ISO_OUTLINE_IOFFSET, IsoBoundCB);
SPINNER_iso_outline_ioffset->set_int_limits(0, 200);
SPINNER_isopointsize = glui_bounds->add_spinner_to_panel(ROLLOUT_iso_settings, _("point size"), GLUI_SPINNER_FLOAT, &isopointsize);
SPINNER_isopointsize->set_float_limits(1.0, 10.0);
glui_bounds->add_separator_to_panel(ROLLOUT_iso_settings);
#ifdef pp_BETA
CHECKBOX_sort2 = glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("Sort transparent surfaces:"), &sort_iso_triangles, SORT_SURFACES, SliceBoundCB);
#endif
CHECKBOX_smooth2 = glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("Smooth isosurfaces"), &smooth_iso_normal, SMOOTH_SURFACES, SliceBoundCB);
glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_settings, _("wrapup in background"), &iso_multithread);
ROLLOUT_iso_color = glui_bounds->add_rollout_to_panel(ROLLOUT_iso, "Color/transparency", false, ISO_ROLLOUT_COLOR, IsoRolloutCB);
INSERT_ROLLOUT(ROLLOUT_iso_color, glui_bounds);
ADDPROCINFO(isoprocinfo, nisoprocinfo, ROLLOUT_iso_color, ISO_ROLLOUT_COLOR, glui_bounds);
RADIO_transparency_option = glui_bounds->add_radiogroup_to_panel(ROLLOUT_iso_color, &iso_transparency_option,ISO_TRANSPARENCY_OPTION,IsoBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_transparency_option, _("transparent(constant)"));
glui_bounds->add_radiobutton_to_group(RADIO_transparency_option, _("transparent(varying)"));
glui_bounds->add_radiobutton_to_group(RADIO_transparency_option, _("opaque"));
IsoBoundCB(ISO_TRANSPARENCY_OPTION);
PANEL_iso_alllevels = glui_bounds->add_panel_to_panel(ROLLOUT_iso_color, "All levels", true);
SPINNER_iso_transparency = glui_bounds->add_spinner_to_panel(PANEL_iso_alllevels, "alpha", GLUI_SPINNER_INT, &glui_iso_transparency, ISO_TRANSPARENCY, IsoBoundCB);
BUTTON_updatebound = glui_bounds->add_button_to_panel(PANEL_iso_alllevels, _("Apply"), GLOBAL_ALPHA, IsoBoundCB);
PANEL_iso_eachlevel = glui_bounds->add_panel_to_panel(ROLLOUT_iso_color, "Each level", true);
SPINNER_iso_level = glui_bounds->add_spinner_to_panel(PANEL_iso_eachlevel, "level:", GLUI_SPINNER_INT, &glui_iso_level, ISO_LEVEL, IsoBoundCB);
SPINNER_iso_level->set_int_limits(1, MAX_ISO_COLORS);
LIST_colortable = glui_bounds->add_listbox_to_panel(PANEL_iso_eachlevel, _("Color:"), &i_colortable_list, COLORTABLE_LIST, IsoBoundCB);
SPINNER_iso_colors[0] = glui_bounds->add_spinner_to_panel(PANEL_iso_eachlevel, "red:", GLUI_SPINNER_INT, glui_iso_colors+0, ISO_COLORS, IsoBoundCB);
SPINNER_iso_colors[1] = glui_bounds->add_spinner_to_panel(PANEL_iso_eachlevel, "green:", GLUI_SPINNER_INT, glui_iso_colors+1, ISO_COLORS, IsoBoundCB);
SPINNER_iso_colors[2] = glui_bounds->add_spinner_to_panel(PANEL_iso_eachlevel, "blue:", GLUI_SPINNER_INT, glui_iso_colors+2, ISO_COLORS, IsoBoundCB);
SPINNER_iso_colors[3] = glui_bounds->add_spinner_to_panel(PANEL_iso_eachlevel, "alpha:", GLUI_SPINNER_INT, glui_iso_colors+3, ISO_COLORS, IsoBoundCB);
UpdateColorTableList(-1);
SPINNER_iso_colors[0]->set_int_limits(0, 255, GLUI_LIMIT_CLAMP);
SPINNER_iso_colors[1]->set_int_limits(0, 255, GLUI_LIMIT_CLAMP);
SPINNER_iso_colors[2]->set_int_limits(0, 255, GLUI_LIMIT_CLAMP);
SPINNER_iso_colors[3]->set_int_limits(1, 255, GLUI_LIMIT_CLAMP);
IsoBoundCB(ISO_LEVEL);
IsoBoundCB(ISO_COLORS);
if(ncolorbars>0){
LIST_iso_colorbar = glui_bounds->add_listbox_to_panel(ROLLOUT_iso_color, "colormap:", &iso_colorbar_index, ISO_COLORBAR_LIST, IsoBoundCB);
for(i = 0; i<ncolorbars; i++){
colorbardata *cbi;
cbi = colorbarinfo+i;
cbi->label_ptr = cbi->label;
LIST_iso_colorbar->add_item(i, cbi->label_ptr);
}
LIST_iso_colorbar->set_int_val(iso_colorbar_index);
IsoBoundCB(ISO_COLORBAR_LIST);
}
glui_bounds->add_spinner_to_panel(ROLLOUT_iso_color, "min:", GLUI_SPINNER_FLOAT, &iso_valmin);
glui_bounds->add_spinner_to_panel(ROLLOUT_iso_color, "max:", GLUI_SPINNER_FLOAT, &iso_valmax);
glui_bounds->add_checkbox_to_panel(ROLLOUT_iso_color,_("Show"),&show_iso_color);
}
/* Particle File Bounds */
have_part = 0;
have_evac = 0;
if(npartinfo > 0 && nevac != npartinfo)have_part = 1;
if(nevac > 0)have_evac = 1;
if(have_part==1||have_evac==1){
char label[100];
strcpy(label, "");
if(have_part == 1)strcat(label, "Particle");
if(have_part == 1 && have_evac == 1)strcat(label, "/");
if(have_evac == 1)strcat(label, "Evac");
glui_active=1;
ROLLOUT_part = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,label,false,PART_ROLLOUT,BoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_part, glui_bounds);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_part, PART_ROLLOUT, glui_bounds);
if(npart5prop>0){
ipart5prop=0;
ipart5prop_old=0;
RADIO_part5 = glui_bounds->add_radiogroup_to_panel(ROLLOUT_part,&ipart5prop,FILETYPEINDEX,PartBoundCB);
for(i=0;i<npart5prop;i++){
partpropdata *partpropi;
partpropi = part5propinfo + i;
glui_bounds->add_radiobutton_to_group(RADIO_part5,partpropi->label->shortlabel);
}
glui_bounds->add_column_to_panel(ROLLOUT_part,false);
{
partpropdata *propi;
propi = part5propinfo;
setpartmin=propi->setvalmin;
setpartmax=propi->setvalmax;
setpartchopmin=propi->setchopmin;
setpartchopmax=propi->setchopmax;
}
PartBoundCB(FILETYPEINDEX);
PartBoundCB(SETVALMIN);
PartBoundCB(SETVALMAX);
}
{
char boundmenulabel[100];
strcpy(boundmenulabel, "Reload ");
strcat(boundmenulabel, label);
strcat(boundmenulabel, " File");
if(npartinfo > 1)strcat(boundmenulabel, "s");
GenerateBoundDialogs(&ROLLOUT_part_bound,&ROLLOUT_part_chop,ROLLOUT_part,boundmenulabel,
&EDIT_part_min,&EDIT_part_max,&RADIO_part_setmin,&RADIO_part_setmax,
&RADIO_part_setmin_percentile,&RADIO_part_setmax_percentile,
&CHECKBOX_part_setchopmin, &CHECKBOX_part_setchopmax,
&EDIT_part_chopmin, &EDIT_part_chopmax,
&STATIC_part_min_unit,&STATIC_part_max_unit,
NULL,NULL,
NULL,NULL,
NULL,
&setpartmin,&setpartmax,&partmin,&partmax,
&setpartchopmin,&setpartchopmax,&partchopmin,&partchopmax,
RELOAD_BOUNDS,DONT_TRUNCATE_BOUNDS,
PartBoundCB,
ParticleRolloutCB,particleprocinfo,&nparticleprocinfo
);
RADIO_part_setmin_percentile->disable();
RADIO_part_setmax_percentile->disable();
PartBoundCB(FILETYPEINDEX);
ROLLOUT_particle_settings = glui_bounds->add_rollout_to_panel(ROLLOUT_part,"Settings",false,
PARTICLE_SETTINGS, ParticleRolloutCB);
INSERT_ROLLOUT(ROLLOUT_particle_settings, glui_bounds);
ADDPROCINFO(particleprocinfo, nparticleprocinfo, ROLLOUT_particle_settings, PARTICLE_SETTINGS, glui_bounds);
SPINNER_partpointsize=glui_bounds->add_spinner_to_panel(ROLLOUT_particle_settings,_("Particle size"),GLUI_SPINNER_FLOAT,&partpointsize);
SPINNER_partpointsize->set_float_limits(1.0,100.0);
SPINNER_streaklinewidth=glui_bounds->add_spinner_to_panel(ROLLOUT_particle_settings,_("Streak line width"),GLUI_SPINNER_FLOAT,&streaklinewidth);
SPINNER_streaklinewidth->set_float_limits(1.0,100.0);
SPINNER_partstreaklength=glui_bounds->add_spinner_to_panel(ROLLOUT_particle_settings,_("Streak length (s)"),GLUI_SPINNER_FLOAT,&float_streak5value,STREAKLENGTH,PartBoundCB);
SPINNER_partstreaklength->set_float_limits(0.0,tmax_part);
CHECKBOX_showtracer=glui_bounds->add_checkbox_to_panel(ROLLOUT_particle_settings,_("Always show tracers"),&show_tracers_always,TRACERS,PartBoundCB);
PANEL_partread=glui_bounds->add_panel_to_panel(ROLLOUT_particle_settings,_("Particle loading"));
CHECKBOX_partfast = glui_bounds->add_checkbox_to_panel(PANEL_partread, _("Fast loading(streaks disabled)"), &partfast, PARTFAST, PartBoundCB);
CHECKBOX_part_multithread = glui_bounds->add_checkbox_to_panel(PANEL_partread, _("Parallel loading"), &part_multithread);
SPINNER_npartthread_ids = glui_bounds->add_spinner_to_panel(PANEL_partread, _("Files loaded at once"), GLUI_SPINNER_INT, &npartthread_ids);
if(npartinfo>1){
SPINNER_npartthread_ids->set_int_limits(1,MIN(npartinfo,MAX_PART_THREADS));
}
else{
SPINNER_npartthread_ids->set_int_limits(1,1);
}
PartBoundCB(PARTFAST);
}
PartBoundCB(FILETYPEINDEX);
}
if(have_evac==1){
glui_active=1;
glui_bounds->add_checkbox_to_panel(ROLLOUT_part,_("Select avatar"),&select_avatar);
CHECKBOX_show_evac_slices=glui_bounds->add_checkbox_to_panel(ROLLOUT_part,_("Show slice menus"),&show_evac_slices,SHOW_EVAC_SLICES,SliceBoundCB);
PANEL_evac_direction=glui_bounds->add_panel_to_panel(ROLLOUT_part,_("Direction vectors"));
CHECKBOX_constant_coloring=glui_bounds->add_checkbox_to_panel(PANEL_evac_direction,_("Constant coloring"),&constant_evac_coloring,SHOW_EVAC_SLICES,SliceBoundCB);
CHECKBOX_data_coloring=glui_bounds->add_checkbox_to_panel(PANEL_evac_direction,_("Data coloring"),&data_evac_coloring,DATA_EVAC_COLORING,SliceBoundCB);
CHECKBOX_show_evac_color=glui_bounds->add_checkbox_to_panel(PANEL_evac_direction,_("Show colorbar (when data coloring)"),&show_evac_colorbar,SHOW_EVAC_SLICES,SliceBoundCB);
glui_bounds->add_checkbox_to_panel(ROLLOUT_part,_("View from selected Avatar"),&view_from_selected_avatar);
}
// ----------------------------------- Plot3D ----------------------------------------
if(nplot3dinfo>0){
glui_active=1;
ROLLOUT_plot3d = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,"Plot3D",false,PLOT3D_ROLLOUT,BoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_plot3d, glui_bounds);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_plot3d, PLOT3D_ROLLOUT, glui_bounds);
RADIO_p3 = glui_bounds->add_radiogroup_to_panel(ROLLOUT_plot3d,&list_p3_index,FILETYPEINDEX,Plot3DBoundCB);
for(i=0;i<MAXPLOT3DVARS;i++){
glui_bounds->add_radiobutton_to_group(RADIO_p3,plot3dinfo[0].label[i].shortlabel);
}
CHECKBOX_cache_qdata = glui_bounds->add_checkbox_to_panel(ROLLOUT_plot3d, _("Cache Plot3D data"), &cache_qdata, UNLOAD_QDATA, Plot3DBoundCB);
glui_bounds->add_column_to_panel(ROLLOUT_plot3d,false);
GenerateBoundDialogs(&ROLLOUT_plot3d_bound, &ROLLOUT_plot3d_chop, ROLLOUT_plot3d, "Reload Plot3D file(s)",
&EDIT_p3_min, &EDIT_p3_max, &RADIO_p3_setmin, &RADIO_p3_setmax, NULL, NULL,
&CHECKBOX_p3_setchopmin, &CHECKBOX_p3_setchopmax,
&EDIT_p3_chopmin, &EDIT_p3_chopmax,
&STATIC_plot3d_min_unit, &STATIC_plot3d_max_unit,
&STATIC_plot3d_cmin_unit, &STATIC_plot3d_cmax_unit,
NULL, NULL,
NULL,
&setp3min_temp, &setp3max_temp, &p3min_temp, &p3max_temp,
&setp3chopmin_temp, &setp3chopmax_temp, &p3chopmin_temp, &p3chopmax_temp,
RELOAD_BOUNDS, TRUNCATE_BOUNDS,
Plot3DBoundCB,
Plot3dRolloutCB,plot3dprocinfo,&nplot3dprocinfo
);
ROLLOUT_vector = glui_bounds->add_rollout_to_panel(ROLLOUT_plot3d,_("Vector"),false,PLOT3D_VECTOR_ROLLOUT, Plot3dRolloutCB);
INSERT_ROLLOUT(ROLLOUT_vector, glui_bounds);
ADDPROCINFO(plot3dprocinfo, nplot3dprocinfo, ROLLOUT_vector, PLOT3D_VECTOR_ROLLOUT, glui_bounds);
glui_bounds->add_checkbox_to_panel(ROLLOUT_vector,_("Show vectors"),&visVector,UPDATEPLOT,Plot3DBoundCB);
SPINNER_plot3d_vectorpointsize=glui_bounds->add_spinner_to_panel(ROLLOUT_vector,_("Point size"),GLUI_SPINNER_FLOAT,&vectorpointsize,UPDATE_VECTOR,Plot3DBoundCB);
SPINNER_plot3d_vectorpointsize->set_float_limits(1.0,10.0);
SPINNER_plot3d_vectorlinewidth=glui_bounds->add_spinner_to_panel(ROLLOUT_vector,_("Vector width"),GLUI_SPINNER_FLOAT,&vectorlinewidth,UPDATE_VECTOR,Plot3DBoundCB);
SPINNER_plot3d_vectorlinewidth->set_float_limits(1.0,10.0);
SPINNER_plot3d_vectorlinelength=glui_bounds->add_spinner_to_panel(ROLLOUT_vector,_("Vector length"),GLUI_SPINNER_FLOAT,&vecfactor,UPDATE_VECTOR,Plot3DBoundCB);
SPINNER_plot3d_vectorlinelength->set_float_limits(0.0,20.0);
SPINNER_plot3dvectorskip=glui_bounds->add_spinner_to_panel(ROLLOUT_vector,_("Vector skip"),GLUI_SPINNER_INT,&vectorskip,PLOT3D_VECTORSKIP,Plot3DBoundCB);
SPINNER_plot3dvectorskip->set_int_limits(1,4);
ROLLOUT_isosurface = glui_bounds->add_rollout_to_panel(ROLLOUT_plot3d,"Isosurface",false,PLOT3D_ISOSURFACE_ROLLOUT, Plot3dRolloutCB);
INSERT_ROLLOUT(ROLLOUT_isosurface, glui_bounds);
ADDPROCINFO(plot3dprocinfo, nplot3dprocinfo, ROLLOUT_isosurface, PLOT3D_ISOSURFACE_ROLLOUT, glui_bounds);
PANEL_pan1 = glui_bounds->add_panel_to_panel(ROLLOUT_isosurface,"",GLUI_PANEL_NONE);
glui_bounds->add_checkbox_to_panel(PANEL_pan1,"Show isosurface",&visiso,PLOTISO,Plot3DBoundCB);
SPINNER_plot3dpointsize=glui_bounds->add_spinner_to_panel(PANEL_pan1,_("Point size"),GLUI_SPINNER_FLOAT,
&plot3dpointsize);
SPINNER_plot3dpointsize->set_float_limits(1.0,10.0);
SPINNER_plot3dlinewidth=glui_bounds->add_spinner_to_panel(PANEL_pan1,_("Line width"),GLUI_SPINNER_FLOAT,
&plot3dlinewidth);
SPINNER_plot3dlinewidth->set_float_limits(1.0,10.0);
// glui_bounds->add_column_to_panel(ROLLOUT_isosurface);
PANEL_pan2 = glui_bounds->add_panel_to_panel(ROLLOUT_isosurface,"",GLUI_PANEL_NONE);
RADIO_plot3d_isotype=glui_bounds->add_radiogroup_to_panel(PANEL_pan2,&p3dsurfacetype,PLOTISOTYPE,Plot3DBoundCB);
RADIOBUTTON_plot3d_iso_hidden=glui_bounds->add_radiobutton_to_group(RADIO_plot3d_isotype,_("Hidden"));
glui_bounds->add_radiobutton_to_group(RADIO_plot3d_isotype,_("shaded"));
glui_bounds->add_radiobutton_to_group(RADIO_plot3d_isotype,_("outline"));
glui_bounds->add_radiobutton_to_group(RADIO_plot3d_isotype,_("points"));
RADIOBUTTON_plot3d_iso_hidden->disable();
p3min_temp=p3min[0];
p3max_temp=p3max[0];
p3chopmin_temp=p3chopmin[0];
p3chopmax_temp=p3chopmax[0];
glui_bounds->add_column_to_panel(ROLLOUT_plot3d,false);
Plot3DBoundCB(FILETYPEINDEX);
Plot3DBoundCB(UNLOAD_QDATA);
}
// ----------------------------------- Slice ----------------------------------------
if(nsliceinfo>0){
int index;
glui_active=1;
ROLLOUT_slice = glui_bounds->add_rollout_to_panel(ROLLOUT_filebounds,"Slice",false,SLICE_ROLLOUT,BoundRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice, glui_bounds);
ADDPROCINFO(boundprocinfo, nboundprocinfo, ROLLOUT_slice, SLICE_ROLLOUT, glui_bounds);
RADIO_slice = glui_bounds->add_radiogroup_to_panel(ROLLOUT_slice,&list_slice_index,FILETYPEINDEX,SliceBoundCB);
index=0;
for(i=0;i<nsliceinfo;i++){
if(sliceinfo[i].firstshort_slice==1){
GLUI_RadioButton *RADIOBUTTON_slicetype;
RADIOBUTTON_slicetype=glui_bounds->add_radiobutton_to_group(RADIO_slice,sliceinfo[i].label.shortlabel);
if(strcmp(sliceinfo[i].label.shortlabel,_("Fire line"))==0){
RADIOBUTTON_slicetype->disable();
fire_line_index=index;
}
if(nzoneinfo>0&&strcmp(sliceinfo[i].label.shortlabel, _("TEMP"))==0){
slicebounds[index].dlg_valmin = zonemin;
slicebounds[index].dlg_valmax = zonemax;
#ifndef pp_NEWBOUND_DIALOG
slicebounds[index].dlg_setvalmin = setzonemin;
slicebounds[index].dlg_setvalmax = setzonemax;
#endif
}
index++;
}
}
nlist_slice_index = index;
glui_bounds->add_column_to_panel(ROLLOUT_slice,false);
#ifdef pp_NEWBOUND_DIALOG
glui_slicemin = slicebounds[list_slice_index].dlg_valmin;
glui_slicemax = slicebounds[list_slice_index].dlg_valmax;
GenerateSliceBoundDialog();
#else
GenerateBoundDialogs(&ROLLOUT_slice_bound,&ROLLOUT_slice_chop,ROLLOUT_slice,"Reload Slice File(s)",
&EDIT_slice_min,&EDIT_slice_max,&RADIO_slice_setmin,&RADIO_slice_setmax,NULL,NULL,
&CHECKBOX_slice_setchopmin, &CHECKBOX_slice_setchopmax,
&EDIT_slice_chopmin, &EDIT_slice_chopmax,
&STATIC_slice_min_unit,&STATIC_slice_max_unit,
&STATIC_slice_cmin_unit,&STATIC_slice_cmax_unit,
NULL,NULL,
&PANEL_slice_bound,
&glui_setslicemin,&glui_setslicemax,&glui_slicemin,&glui_slicemax,
&glui_setslicechopmin, &glui_setslicechopmax,
&glui_slicechopmin, &glui_slicechopmax,
UPDATE_BOUNDS,DONT_TRUNCATE_BOUNDS,
SliceBoundCB,
SliceRolloutCB, sliceprocinfo, &nsliceprocinfo
);
#endif
ROLLOUT_slice_histogram = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Histogram"), false, SLICE_HISTOGRAM_ROLLOUT, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice_histogram, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slice_histogram, SLICE_HISTOGRAM_ROLLOUT, glui_bounds);
RADIO_histogram_static = glui_bounds->add_radiogroup_to_panel(ROLLOUT_slice_histogram,&histogram_static);
glui_bounds->add_radiobutton_to_group(RADIO_histogram_static,_("each time"));
glui_bounds->add_radiobutton_to_group(RADIO_histogram_static,_("all times"));
SPINNER_histogram_width_factor=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_histogram, _("val at left"), GLUI_SPINNER_FLOAT,&histogram_width_factor);
SPINNER_histogram_width_factor->set_float_limits(1.0,100.0);
SPINNER_histogram_nbuckets=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_histogram, _("bins"), GLUI_SPINNER_INT,&histogram_nbuckets,UPDATE_HISTOGRAM,SliceBoundCB);
SPINNER_histogram_nbuckets->set_int_limits(3,255);
CHECKBOX_histogram_show_numbers = glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_histogram, _("percentages"), &histogram_show_numbers, INIT_HISTOGRAM, SliceBoundCB);
CHECKBOX_histogram_show_graph=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_histogram, _("graph"), &histogram_show_graph, INIT_HISTOGRAM, SliceBoundCB);
CHECKBOX_histogram_show_outline=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_histogram, _("outline"), &histogram_show_outline);
ROLLOUT_slice_average=glui_bounds->add_rollout_to_panel(ROLLOUT_slice,_("Average data"),false,SLICE_AVERAGE_ROLLOUT,SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice_average, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slice_average, SLICE_AVERAGE_ROLLOUT, glui_bounds);
CHECKBOX_average_slice=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_average,_("Average slice data"),&slice_average_flag);
SPINNER_sliceaverage=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_average,_("Time interval"),GLUI_SPINNER_FLOAT,&slice_average_interval);
SPINNER_sliceaverage->set_float_limits(0.0,MAX(120.0,tour_tstop));
glui_bounds->add_button_to_panel(ROLLOUT_slice_average,_("Reload"),ALLFILERELOAD,SliceBoundCB);
ROLLOUT_slice_vector = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Vector"), false, SLICE_VECTOR_ROLLOUT, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slice_vector, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slice_vector, SLICE_VECTOR_ROLLOUT, glui_bounds);
SPINNER_vectorpointsize = glui_bounds->add_spinner_to_panel(ROLLOUT_slice_vector, _("Point size"), GLUI_SPINNER_FLOAT,
&vectorpointsize,UPDATE_VECTOR,SliceBoundCB);
SPINNER_vectorpointsize->set_float_limits(1.0,20.0);
SPINNER_vectorlinewidth=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_vector,_("Vector width"),GLUI_SPINNER_FLOAT,&vectorlinewidth,UPDATE_VECTOR,SliceBoundCB);
SPINNER_vectorlinewidth->set_float_limits(1.0,20.0);
SPINNER_vectorlinelength=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_vector,_("Vector length"),GLUI_SPINNER_FLOAT,&vecfactor,UPDATE_VECTOR,SliceBoundCB);
SPINNER_vectorlinelength->set_float_limits(0.0,20.0);
SPINNER_slicevectorskip=glui_bounds->add_spinner_to_panel(ROLLOUT_slice_vector,_("Vector skip"),GLUI_SPINNER_INT,&vectorskip,SLICE_VECTORSKIP,SliceBoundCB);
SPINNER_slicevectorskip->set_int_limits(1,4);
CHECKBOX_color_vector_black = glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_vector, _("Color black"), &color_vector_black);
CHECKBOX_show_node_slices_and_vectors=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_vector,_("Show vectors and node centered slices"),&show_node_slices_and_vectors);
CHECKBOX_show_node_slices_and_vectors=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice_vector,_("Show vectors and cell centered slices"),&show_cell_slices_and_vectors);
ROLLOUT_line_contour = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Line contours"), false, LINE_CONTOUR_ROLLOUT, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_line_contour, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_line_contour, LINE_CONTOUR_ROLLOUT, glui_bounds);
slice_line_contour_min = 0.0;
slice_line_contour_max=1.0;
SPINNER_line_contour_min=glui_bounds->add_spinner_to_panel(ROLLOUT_line_contour,_("Min"),GLUI_SPINNER_FLOAT,
&slice_line_contour_min,LINE_CONTOUR_VALUE,SliceBoundCB);
SPINNER_line_contour_max=glui_bounds->add_spinner_to_panel(ROLLOUT_line_contour,_("Max"),GLUI_SPINNER_FLOAT,
&slice_line_contour_max,LINE_CONTOUR_VALUE,SliceBoundCB);
slice_line_contour_num=1;
SPINNER_line_contour_num=glui_bounds->add_spinner_to_panel(ROLLOUT_line_contour,_("Number of contours"),GLUI_SPINNER_INT,
&slice_line_contour_num,LINE_CONTOUR_VALUE,SliceBoundCB);
SPINNER_line_contour_width=glui_bounds->add_spinner_to_panel(ROLLOUT_line_contour,_("contour width"),GLUI_SPINNER_FLOAT,&slice_line_contour_width);
SPINNER_line_contour_width->set_float_limits(1.0,10.0);
RADIO_contour_type = glui_bounds->add_radiogroup_to_panel(ROLLOUT_line_contour,&slice_contour_type);
glui_bounds->add_radiobutton_to_group(RADIO_contour_type,_("line"));
#ifdef _DEBUG
glui_bounds->add_radiobutton_to_group(RADIO_contour_type,_("stepped"));
#endif
BUTTON_update_line_contour=glui_bounds->add_button_to_panel(ROLLOUT_line_contour,_("Update contours"),UPDATE_LINE_CONTOUR_VALUE,SliceBoundCB);
glui_bounds->add_checkbox_to_panel(ROLLOUT_line_contour,_("Show contours"),&vis_slice_contours);
if(n_embedded_meshes>0){
CHECKBOX_skip_subslice=glui_bounds->add_checkbox_to_panel(ROLLOUT_slice,_("Skip coarse sub-slice"),&skip_slice_in_embedded_mesh);
}
if(nslicedups > 0){
ROLLOUT_slicedups = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, _("Duplicates"), false, SLICE_DUP_ROLLOUT, SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_slicedups, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_slicedups, SLICE_DUP_ROLLOUT, glui_bounds);
PANEL_slicedup = glui_bounds->add_panel_to_panel(ROLLOUT_slicedups,"slices",true);
RADIO_slicedup = glui_bounds->add_radiogroup_to_panel(PANEL_slicedup, &slicedup_option,UPDATE_SLICEDUPS,SliceBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_slicedup, _("Keep all"));
glui_bounds->add_radiobutton_to_group(RADIO_slicedup, _("Keep fine"));
glui_bounds->add_radiobutton_to_group(RADIO_slicedup, _("Keep coarse"));
PANEL_vectorslicedup = glui_bounds->add_panel_to_panel(ROLLOUT_slicedups,"vector slices",true);
RADIO_vectorslicedup = glui_bounds->add_radiogroup_to_panel(PANEL_vectorslicedup, &vectorslicedup_option, UPDATE_SLICEDUPS, SliceBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_vectorslicedup, _("Keep all"));
glui_bounds->add_radiobutton_to_group(RADIO_vectorslicedup, _("Keep fine"));
glui_bounds->add_radiobutton_to_group(RADIO_vectorslicedup, _("Keep coarse"));
}
ROLLOUT_boundimmersed = glui_bounds->add_rollout_to_panel(ROLLOUT_slice, "Settings",false,SLICE_SETTINGS_ROLLOUT,SliceRolloutCB);
INSERT_ROLLOUT(ROLLOUT_boundimmersed, glui_bounds);
ADDPROCINFO(sliceprocinfo, nsliceprocinfo, ROLLOUT_boundimmersed, SLICE_SETTINGS_ROLLOUT, glui_bounds);
if(ngeom_data > 0){
PANEL_immersed = glui_bounds->add_panel_to_panel(ROLLOUT_boundimmersed, "slice(geometry)", true);
PANEL_immersed_region = glui_bounds->add_panel_to_panel(PANEL_immersed, "region", true);
RADIO_slice_celltype = glui_bounds->add_radiogroup_to_panel(PANEL_immersed_region, &slice_celltype, IMMERSED_SWITCH_CELLTYPE, ImmersedBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_slice_celltype, "gas");
glui_bounds->add_radiobutton_to_group(RADIO_slice_celltype, "solid(geometry)");
glui_bounds->add_radiobutton_to_group(RADIO_slice_celltype, "cut cell");
glui_bounds->add_column_to_panel(PANEL_immersed, false);
PANEL_immersed_drawas = glui_bounds->add_panel_to_panel(PANEL_immersed, "draw as", true);
CHECKBOX_show_slice_shaded = glui_bounds->add_checkbox_to_panel(PANEL_immersed_drawas, "shaded", &glui_show_slice_shaded, IMMERSED_SET_DRAWTYPE, ImmersedBoundCB);
CHECKBOX_show_slice_outlines = glui_bounds->add_checkbox_to_panel(PANEL_immersed_drawas, "outline", &glui_show_slice_outlines, IMMERSED_SET_DRAWTYPE, ImmersedBoundCB);
CHECKBOX_show_slice_points = glui_bounds->add_checkbox_to_panel(PANEL_immersed_drawas, "points", &glui_show_slice_points, IMMERSED_SET_DRAWTYPE, ImmersedBoundCB);
glui_bounds->add_spinner_to_panel(PANEL_immersed_drawas, "line width", GLUI_SPINNER_FLOAT, &geomslice_linewidth);
glui_bounds->add_spinner_to_panel(PANEL_immersed_drawas, "point size", GLUI_SPINNER_FLOAT, &geomslice_pointsize);
glui_bounds->add_column_to_panel(PANEL_immersed, false);
PANEL_immersed_outlinetype = glui_bounds->add_panel_to_panel(PANEL_immersed, "outline type", true);
RADIO_slice_edgetype = glui_bounds->add_radiogroup_to_panel(PANEL_immersed_outlinetype, &glui_slice_edgetype, IMMERSED_SWITCH_EDGETYPE, ImmersedBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_slice_edgetype, _("polygon"));
glui_bounds->add_radiobutton_to_group(RADIO_slice_edgetype, _("triangle"));
glui_bounds->add_radiobutton_to_group(RADIO_slice_edgetype, _("none"));
ImmersedBoundCB(IMMERSED_SWITCH_CELLTYPE);
ImmersedBoundCB(IMMERSED_SWITCH_EDGETYPE);
}
PANEL_sliceshow = glui_bounds->add_panel_to_panel(ROLLOUT_boundimmersed, "slice(regular)", true);
RADIO_show_slice_in_obst = glui_bounds->add_radiogroup_to_panel(PANEL_sliceshow, &show_slice_in_obst, SLICE_IN_OBST, SliceBoundCB);
glui_bounds->add_radiobutton_to_group(RADIO_show_slice_in_obst, "gas");
glui_bounds->add_radiobutton_to_group(RADIO_show_slice_in_obst, "gas and solid(obst)");
glui_bounds->add_radiobutton_to_group(RADIO_show_slice_in_obst, "solid(obst)");
SPINNER_transparent_level = glui_bounds->add_spinner_to_panel(ROLLOUT_boundimmersed, _("Transparent level"), GLUI_SPINNER_FLOAT, &transparent_level, TRANSPARENTLEVEL, SliceBoundCB);
SPINNER_transparent_level->set_float_limits(0.0, 1.0);
if(nfedinfo>0){
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, "Regenerate FED data", ®enerate_fed);
}
CHECKBOX_research_mode = glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("Research display mode"), &research_mode, RESEARCH_MODE, SliceBoundCB);
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("Output data to file"), &output_slicedata);
#ifdef pp_FSEEK
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("incremental data loading"), &load_incremental, SLICE_LOAD_INCREMENTAL, LoadIncrementalCB);
LoadIncrementalCB(SLICE_LOAD_INCREMENTAL);
#endif
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("Use C for slice input"), &use_cslice);
glui_bounds->add_spinner_to_panel(ROLLOUT_boundimmersed,"slice offset",GLUI_SPINNER_FLOAT,&sliceoffset_all);
if(nterraininfo>0){
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("terrain slice overlap"), &terrain_slice_overlap);
}
PANEL_slice_smoke = glui_bounds->add_panel_to_panel(ROLLOUT_boundimmersed, "slice fire", true);
glui_bounds->add_checkbox_to_panel(PANEL_slice_smoke, _("max blending"), &slices3d_max_blending);
glui_bounds->add_checkbox_to_panel(PANEL_slice_smoke, _("show all 3D slices"), &showall_3dslices);
#ifdef pp_SLICETHREAD
PANEL_sliceread = glui_bounds->add_panel_to_panel(ROLLOUT_boundimmersed, "Slice file loading", true);
CHECKBOX_slice_multithread = glui_bounds->add_checkbox_to_panel(PANEL_sliceread, _("Parallel loading"), &slice_multithread);
SPINNER_nslicethread_ids = glui_bounds->add_spinner_to_panel(PANEL_sliceread, _("Files loaded at once"), GLUI_SPINNER_INT, &nslicethread_ids);
if(nsliceinfo>1){
SPINNER_nslicethread_ids->set_int_limits(1, MIN(nsliceinfo, MAX_SLICE_THREADS));
}
else{
SPINNER_nslicethread_ids->set_int_limits(1, 1);
}
#endif
#ifdef pp_SMOKETEST
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("opacity adjustment"), &slice_opacity_adjustment);
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("sort slices"), &sort_slices);
glui_bounds->add_checkbox_to_panel(ROLLOUT_boundimmersed, _("show sorted slice labels"), &show_sort_labels);
#endif
SliceBoundCB(FILETYPEINDEX);
}
// ----------------------------------- Time ----------------------------------------
ROLLOUT_time = glui_bounds->add_rollout_to_panel(PANEL_bounds,"Time", false, TIME_ROLLOUT, FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_time, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_time, TIME_ROLLOUT, glui_bounds);
PANEL_time1a = glui_bounds->add_panel_to_panel(ROLLOUT_time,"",false);
SPINNER_timebounds=glui_bounds->add_spinner_to_panel(PANEL_time1a,_("Time:"),GLUI_SPINNER_FLOAT,&glui_time);
glui_bounds->add_spinner_to_panel(PANEL_time1a, _("Offset:"), GLUI_SPINNER_FLOAT, &timeoffset);
glui_bounds->add_column_to_panel(PANEL_time1a,false);
SPINNER_timebounds->set_float_limits(0.0,3600.0*24);
BUTTON_SETTIME=glui_bounds->add_button_to_panel(PANEL_time1a,_("Set"),SET_TIME,TimeBoundCB);
PANEL_time2 = glui_bounds->add_panel_to_panel(ROLLOUT_time,_("Data loading"),true);
PANEL_time2a = glui_bounds->add_panel_to_panel(PANEL_time2,"",false);
SPINNER_tload_begin=glui_bounds->add_spinner_to_panel(PANEL_time2a,_("min time"),GLUI_SPINNER_FLOAT,&tload_begin,TBOUNDS,TimeBoundCB);
glui_bounds->add_column_to_panel(PANEL_time2a,false);
CHECKBOX_use_tload_begin=glui_bounds->add_checkbox_to_panel(PANEL_time2a,"",&use_tload_begin,TBOUNDS_USE,TimeBoundCB);
PANEL_time2b = glui_bounds->add_panel_to_panel(PANEL_time2,"",false);
SPINNER_tload_end=glui_bounds->add_spinner_to_panel(PANEL_time2b,_("max time"),GLUI_SPINNER_FLOAT,&tload_end,TBOUNDS,TimeBoundCB);
glui_bounds->add_column_to_panel(PANEL_time2b,false);
CHECKBOX_use_tload_end=glui_bounds->add_checkbox_to_panel(PANEL_time2b,"",&use_tload_end,TBOUNDS_USE,TimeBoundCB);
PANEL_time2c = glui_bounds->add_panel_to_panel(PANEL_time2,"",false);
SPINNER_tload_skip=glui_bounds->add_spinner_to_panel(PANEL_time2c,_("frame skip"),GLUI_SPINNER_INT,&tload_skip,TBOUNDS,TimeBoundCB);
glui_bounds->add_column_to_panel(PANEL_time2c,false);
CHECKBOX_use_tload_skip=glui_bounds->add_checkbox_to_panel(PANEL_time2c,"",&use_tload_skip,TBOUNDS_USE,TimeBoundCB);
SPINNER_tload_skip->set_int_limits(0,1000);
glui_bounds->add_button_to_panel(PANEL_time2,_("Reload all data"), RELOAD_ALL_DATA,TimeBoundCB);
glui_bounds->add_button_to_panel(PANEL_time2, _("Reload new data"), RELOAD_INCREMENTAL_DATA, TimeBoundCB);
TimeBoundCB(TBOUNDS_USE);
// ----------------------------------- Memory check ----------------------------------------
#ifdef pp_MEMDEBUG
ROLLOUT_memcheck = glui_bounds->add_rollout(_("Memory check"),false,MEMCHECK_ROLLOUT,FileRolloutCB);
INSERT_ROLLOUT(ROLLOUT_memcheck, glui_bounds);
ADDPROCINFO(fileprocinfo, nfileprocinfo, ROLLOUT_memcheck, MEMCHECK_ROLLOUT, glui_bounds);
list_memcheck_index = 0;
RADIO_memcheck = glui_bounds->add_radiogroup_to_panel(ROLLOUT_memcheck,&list_memcheck_index,MEMCHECK, MemcheckCB);
glui_bounds->add_radiobutton_to_group(RADIO_memcheck,_("Unlimited"));
glui_bounds->add_radiobutton_to_group(RADIO_memcheck,"1 GB");
glui_bounds->add_radiobutton_to_group(RADIO_memcheck,"2 GB");
glui_bounds->add_radiobutton_to_group(RADIO_memcheck,"4 GB");
glui_bounds->add_radiobutton_to_group(RADIO_memcheck,"8 GB");
#endif
glui_bounds->add_button(_("Save settings"), SAVE_SETTINGS_BOUNDS, BoundsDlgCB);
glui_bounds->add_button(_("Close"), CLOSE_BOUNDS, BoundsDlgCB);
glui_bounds->set_main_gfx_window( main_window );
}
/* ------------------ CompressOnOff ------------------------ */
extern "C" void CompressOnOff(int flag){
switch(flag){
case OFF:
if(BUTTON_compress!=NULL)BUTTON_compress->disable();
if(CHECKBOX_overwrite_all!=NULL)CHECKBOX_overwrite_all->disable();
if(CHECKBOX_erase_all!=NULL)CHECKBOX_erase_all->disable();
if(CHECKBOX_multi_task!=NULL)CHECKBOX_multi_task->disable();
break;
case ON:
if(BUTTON_compress!=NULL)BUTTON_compress->enable();
if(CHECKBOX_overwrite_all!=NULL)CHECKBOX_overwrite_all->enable();
if(CHECKBOX_erase_all!=NULL)CHECKBOX_erase_all->enable();
if(CHECKBOX_multi_task!=NULL)CHECKBOX_multi_task->enable();
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ Plot3DBoundCB ------------------------ */
extern "C" void Plot3DBoundCB(int var){
int i;
switch(var){
case UNLOAD_QDATA:
if(cache_qdata==0){
ROLLOUT_isosurface->disable();
}
else{
int enable_isosurface;
enable_isosurface=1;
for(i=0;i<nmeshes;i++){
meshdata *meshi;
plot3ddata *plot3di;
meshi = meshinfo + i;
if(meshi->plot3dfilenum==-1)continue;
plot3di = plot3dinfo + meshi->plot3dfilenum;
if(plot3di->loaded==0||plot3di->display==0)continue;
if(meshi->qdata==NULL){
enable_isosurface=0;
break;
}
}
if(enable_isosurface==1)ROLLOUT_isosurface->enable();
if(enable_isosurface==0)ROLLOUT_isosurface->disable();
}
break;
case PLOT3D_VECTORSKIP:
if(SPINNER_slicevectorskip!=NULL)SPINNER_slicevectorskip->set_int_val(vectorskip);
break;
case UPDATE_VECTOR_FROM_SMV:
if(SPINNER_vectorpointsize!=NULL&&SPINNER_vectorlinewidth!=NULL&&SPINNER_vectorlinelength!=NULL){
SPINNER_vectorpointsize->set_float_val(vectorpointsize);
SPINNER_vectorlinewidth->set_float_val(vectorlinewidth);
SPINNER_vectorlinelength->set_float_val(vecfactor);
}
Plot3DBoundCB(UPDATE_VECTOR);
break;
case UPDATE_VECTOR:
UpdatePlotSlice(XDIR);
UpdatePlotSlice(YDIR);
UpdatePlotSlice(ZDIR);
break;
case CHOPUPDATE:
UpdateChopColors();
break;
case SETCHOPMINVAL:
UpdateChopColors();
switch(setp3chopmin_temp){
case DISABLE:
EDIT_p3_chopmin->disable();
break;
case ENABLE:
EDIT_p3_chopmin->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case SETCHOPMAXVAL:
UpdateChopColors();
switch(setp3chopmax_temp){
case DISABLE:
EDIT_p3_chopmax->disable();
break;
case ENABLE:
EDIT_p3_chopmax->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case CHOPVALMIN:
p3chopmin[list_p3_index]=p3chopmin_temp;
setp3chopmin[list_p3_index]=setp3chopmin_temp;
UpdateChopColors();
break;
case CHOPVALMAX:
p3chopmax[list_p3_index]=p3chopmax_temp;
setp3chopmax[list_p3_index]=setp3chopmax_temp;
UpdateChopColors();
break;
case PLOTISO:
visiso = 1 - visiso;
HandleIso();
glutPostRedisplay();
break;
case PLOTISOTYPE:
updatemenu=1;
break;
case UPDATEPLOT:
UpdateRGBColors(COLORBAR_INDEX_NONE);
updatemenu=1;
glutPostRedisplay();
break;
case FILETYPEINDEX:
p3min[list_p3_index_old]=p3min_temp;
p3max[list_p3_index_old]=p3max_temp;
setp3min[list_p3_index_old]=setp3min_temp;
setp3max[list_p3_index_old]=setp3max_temp;
p3chopmin[list_p3_index_old]=p3chopmin_temp;
p3chopmax[list_p3_index_old]=p3chopmax_temp;
setp3chopmin[list_p3_index_old]=setp3chopmin_temp;
setp3chopmax[list_p3_index_old]=setp3chopmax_temp;
p3min_temp=p3min[list_p3_index];
p3max_temp=p3max[list_p3_index];
setp3min_temp=setp3min[list_p3_index];
setp3max_temp=setp3max[list_p3_index];
p3chopmin_temp=p3chopmin[list_p3_index];
p3chopmax_temp=p3chopmax[list_p3_index];
setp3chopmin_temp=setp3chopmin[list_p3_index];
setp3chopmax_temp=setp3chopmax[list_p3_index];
if(plot3dinfo!=NULL){
plot3dmin_unit = (unsigned char *)plot3dinfo->label[list_p3_index].unit;
plot3dmax_unit = plot3dmin_unit;
UpdateGluiPlot3D_units();
}
EDIT_p3_min->set_float_val(p3min_temp);
EDIT_p3_max->set_float_val(p3max_temp);
EDIT_p3_chopmin->set_float_val(p3chopmin_temp);
EDIT_p3_chopmax->set_float_val(p3chopmax_temp);
list_p3_index_old=list_p3_index;
RADIO_p3_setmin->set_int_val(setp3min_temp);
RADIO_p3_setmax->set_int_val(setp3max_temp);
CHECKBOX_p3_setchopmin->set_int_val(setp3chopmin_temp);
CHECKBOX_p3_setchopmax->set_int_val(setp3chopmax_temp);
Plot3DBoundCB(SETCHOPMINVAL);
Plot3DBoundCB(SETCHOPMAXVAL);
Plot3DBoundCB(SETVALMIN);
Plot3DBoundCB(SETVALMAX);
break;
case SETVALMIN:
switch(setp3min_temp){
case PERCENTILE_MIN:
case GLOBAL_MIN:
EDIT_p3_min->disable();
break;
case SET_MIN:
case CHOP_MIN:
EDIT_p3_min->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case SETVALMAX:
switch(setp3max_temp){
case PERCENTILE_MIN:
case GLOBAL_MIN:
EDIT_p3_max->disable();
break;
case SET_MIN:
case CHOP_MIN:
EDIT_p3_max->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case FILEUPDATE:
p3min[list_p3_index] = p3min_temp;
p3max[list_p3_index] = p3max_temp;
setp3min[list_p3_index] = setp3min_temp;
setp3max[list_p3_index] = setp3max_temp;
break;
case FILERELOAD:
Plot3DBoundCB(FILEUPDATE);
for(i=0;i<nplot3dinfo;i++){
if(plot3dinfo[i].loaded==0)continue;
LoadPlot3dMenu(i);
}
UpdateGlui();
break;
case VALMIN:
case VALMAX:
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ UpdateTracers ------------------------ */
extern "C" void UpdateTracers(void){
if(CHECKBOX_showtracer==NULL)return;
CHECKBOX_showtracer->set_int_val(show_tracers_always);
}
/* ------------------ UpdateGluiIsotype ------------------------ */
extern "C" void UpdateGluiIsotype(void){
CHECKBOX_show_iso_shaded->set_int_val(visAIso&1);
CHECKBOX_show_iso_outline->set_int_val((visAIso&2)/2);
CHECKBOX_show_iso_points->set_int_val((visAIso&4)/4);
}
/* ------------------ UpdateGluiPlot3Dtype ------------------------ */
extern "C" void UpdateGluiPlot3Dtype(void){
RADIO_plot3d_isotype->set_int_val(p3dsurfacetype);
}
/* ------------------ UpdateChar ------------------------ */
extern "C" void UpdateChar(void){
if(CHECKBOX_showchar==NULL)return;
if(canshow_threshold==1){
CHECKBOX_showchar->enable();
}
else{
CHECKBOX_showchar->disable();
}
CHECKBOX_showchar->set_int_val(vis_threshold);
BoundBoundCB(SHOWCHAR);
}
/* ------------------ UpdatePlot3dListIndex ------------------------ */
extern "C" void UpdatePlot3dListIndex(void){
int i;
if(RADIO_p3==NULL)return;
i = RADIO_p3->get_int_val();
if(i!=plotn-1){
p3min[i]=p3min_temp;
p3max[i]=p3max_temp;
setp3min[i]=setp3min_temp;
setp3max[i]=setp3max_temp;
p3chopmin[i]=p3chopmin_temp;
p3chopmax[i]=p3chopmax_temp;
setp3chopmin[i]=setp3chopmin_temp;
setp3chopmax[i]=setp3chopmax_temp;
}
i=plotn-1;
list_p3_index_old=i;
if(i<0)i=0;
if(i>MAXPLOT3DVARS-1)i= MAXPLOT3DVARS-1;
RADIO_p3->set_int_val(i);
p3min_temp = p3min[i];
p3max_temp = p3max[i];
setp3min_temp = setp3min[i];
setp3max_temp = setp3max[i];
p3chopmin_temp = p3chopmin[i];
p3chopmax_temp = p3chopmax[i];
setp3chopmin_temp = setp3chopmin[i];
setp3chopmax_temp = setp3chopmax[i];
if(nplot3dinfo>0){
Plot3DBoundCB(SETVALMIN);
Plot3DBoundCB(SETVALMAX);
Plot3DBoundCB(SETCHOPMINVAL);
Plot3DBoundCB(SETCHOPMAXVAL);
}
UpdateChopColors();
UpdateGlui();
}
/* ------------------ GetColorTableIndex ------------------------ */
int GetColorTableIndex(int *color){
int i;
if(colortableinfo==NULL)return -1;
for(i=0;i<ncolortableinfo;i++){
colortabledata *cti;
cti = colortableinfo + i;
if(color[0]==cti->color[0]&&color[1]==cti->color[1]&&color[2]==cti->color[2])return i;
}
return -1;
}
/* ------------------ GetColorTable ------------------------ */
colortabledata *GetColorTable(char *label){
int i;
if(label==NULL||strlen(label)==0)return NULL;
for(i=0;i<ncolortableinfo;i++){
colortabledata *cti;
cti = colortableinfo + i;
if(strcmp(label,cti->label)==0)return cti;
}
return NULL;
}
/* ------------------ IsoBoundCB ------------------------ */
extern "C" void IsoBoundCB(int var){
int i;
float *iso_color;
switch(var){
case ISO_OUTLINE_IOFFSET:
iso_outline_offset = (float)iso_outline_ioffset/1000.0;
break;
case ISO_COLORBAR_LIST:
iso_colorbar = colorbarinfo + iso_colorbar_index;
ColorbarMenu(iso_colorbar_index);
updatemenu = 1;
update_texturebar = 1;
break;
case ISO_TRANSPARENCY_OPTION:
switch(iso_transparency_option){
case ISO_TRANSPARENT_CONSTANT:
use_transparency_data=1;
iso_opacity_change=0;
break;
case ISO_TRANSPARENT_VARYING:
use_transparency_data=1;
iso_opacity_change=1;
break;
case ISO_OPAQUE:
use_transparency_data=0;
iso_opacity_change=1;
break;
}
SliceBoundCB(DATA_transparent);
break;
case COLORTABLE_LIST:
if(i_colortable_list>=0){
colortabledata *cti;
cti = colortableinfo+i_colortable_list;
glui_iso_colors[0] = cti->color[0];
glui_iso_colors[1] = cti->color[1];
glui_iso_colors[2] = cti->color[2];
glui_iso_colors[3] = cti->color[3];
IsoBoundCB(ISO_COLORS);
if(SPINNER_iso_colors[0]!=NULL)SPINNER_iso_colors[0]->set_int_val(glui_iso_colors[0]);
if(SPINNER_iso_colors[1]!=NULL)SPINNER_iso_colors[1]->set_int_val(glui_iso_colors[1]);
if(SPINNER_iso_colors[2]!=NULL)SPINNER_iso_colors[2]->set_int_val(glui_iso_colors[2]);
if(SPINNER_iso_colors[3]!=NULL)SPINNER_iso_colors[3]->set_int_val(glui_iso_colors[3]);
}
break;
case ISO_LEVEL:
iso_color = iso_colors+4*(glui_iso_level-1);
glui_iso_colors[0] = CLAMP(255*iso_color[0]+0.1, 0, 255);
glui_iso_colors[1] = CLAMP(255*iso_color[1]+0.1, 0, 255);
glui_iso_colors[2] = CLAMP(255*iso_color[2]+0.1, 0, 255);
glui_iso_colors[3] = CLAMP(255*iso_color[3]+0.1, 1, 255);
if(SPINNER_iso_colors[0]!=NULL)SPINNER_iso_colors[0]->set_int_val(glui_iso_colors[0]);
if(SPINNER_iso_colors[1]!=NULL)SPINNER_iso_colors[1]->set_int_val(glui_iso_colors[1]);
if(SPINNER_iso_colors[2]!=NULL)SPINNER_iso_colors[2]->set_int_val(glui_iso_colors[2]);
if(SPINNER_iso_colors[3]!=NULL)SPINNER_iso_colors[3]->set_int_val(glui_iso_colors[3]);
if(LIST_colortable != NULL){
i_colortable_list = CLAMP(GetColorTableIndex(glui_iso_colors), -1, ncolortableinfo - 1);
LIST_colortable->set_int_val(i_colortable_list);
}
break;
case GLOBAL_ALPHA:
for(i = 0; i < MAX_ISO_COLORS; i++){
iso_colors[4 * i + 3] = iso_transparency;
}
if(SPINNER_iso_colors[3]!=NULL)SPINNER_iso_colors[3]->set_int_val(glui_iso_transparency);
IsoBoundCB(ISO_COLORS);
break;
case ISO_TRANSPARENCY:
iso_transparency = CLAMP(((float)glui_iso_transparency + 0.1) / 255.0,0.0,1.0);
break;
case ISO_COLORS:
iso_color = iso_colors+4*(glui_iso_level-1);
iso_color[0] = ((float)glui_iso_colors[0]+0.1)/255.0;
iso_color[1] = ((float)glui_iso_colors[1]+0.1)/255.0;
iso_color[2] = ((float)glui_iso_colors[2]+0.1)/255.0;
iso_color[3] = ((float)glui_iso_colors[3]+0.1)/255.0;
for(i = 0; i < MAX_ISO_COLORS; i++){
float graylevel;
graylevel = TOBW(iso_colors+4*i);
iso_colorsbw[4 * i + 0] = graylevel;
iso_colorsbw[4 * i + 1] = graylevel;
iso_colorsbw[4 * i + 2] = graylevel;
iso_colorsbw[4 * i + 3] = iso_colors[4 * i + 3];
}
UpdateIsoColors();
if(LIST_colortable!=NULL){
i_colortable_list = CLAMP(GetColorTableIndex(glui_iso_colors), -1, ncolortableinfo-1);
LIST_colortable->set_int_val(i_colortable_list);
}
break;
case FRAMELOADING:
isoframestep_global=isoframeskip_global+1;
isozipstep=isozipskip+1;
updatemenu=1;
break;
case ISO_SURFACE:
case ISO_OUTLINE:
case ISO_POINTS:
visAIso= 1*show_iso_shaded + 2*show_iso_outline + 4*show_iso_points;
updatemenu=1;
break;
case ISO_SETVALMIN:
switch (setisomin){
case SET_MIN:
iso_valmin=glui_iso_valmin;
EDIT_iso_valmin->enable();
break;
case PERCENTILE_MIN:
iso_valmin = iso_percentile_min;
EDIT_iso_valmin->disable();
break;
case GLOBAL_MIN:
iso_valmin = iso_global_min;
EDIT_iso_valmin->disable();
break;
default:
ASSERT(FFALSE);
break;
}
glui_iso_valmin=iso_valmin;
EDIT_iso_valmin->set_float_val(glui_iso_valmin);
glutPostRedisplay();
break;
case ISO_SETVALMAX:
switch (setisomax){
case SET_MAX:
iso_valmax=glui_iso_valmax;
EDIT_iso_valmax->enable();
break;
case PERCENTILE_MAX:
iso_valmax = iso_percentile_max;
EDIT_iso_valmax->disable();
break;
case GLOBAL_MAX:
iso_valmax = iso_global_max;
EDIT_iso_valmax->disable();
break;
default:
ASSERT(FFALSE);
break;
}
glui_iso_valmax = iso_valmax;
EDIT_iso_valmax->set_float_val(glui_iso_valmax);
glutPostRedisplay();
break;
case ISO_VALMIN:
iso_valmin=glui_iso_valmin;
glutPostRedisplay();
break;
case ISO_VALMAX:
iso_valmax=glui_iso_valmax;
glutPostRedisplay();
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ AddScriptList ------------------------ */
extern "C" void AddScriptList(char *file, int id){
if(file!=NULL&&strlen(file)>0&&LIST_scriptlist!=NULL){
LIST_scriptlist->add_item(id,file);
}
}
/* ------------------ GluiScriptEnable ------------------------ */
extern "C" void GluiScriptEnable(void){
BUTTON_script_start->enable();
BUTTON_script_stop->enable();
BUTTON_script_runscript->enable();
LIST_scriptlist->enable();
BUTTON_script_saveini->enable();
BUTTON_script_setsuffix->enable();
EDIT_ini->enable();
}
/* ------------------ GluiScriptDisable ------------------------ */
extern "C" void GluiScriptDisable(void){
BUTTON_script_start->disable();
BUTTON_script_stop->disable();
BUTTON_script_runscript->disable();
LIST_scriptlist->disable();
BUTTON_script_saveini->disable();
BUTTON_script_setsuffix->disable();
EDIT_ini->disable();
}
/* ------------------ UpdateBoundaryListIndex ------------------------ */
extern "C" void UpdateBoundaryListIndex(int patchfilenum){
int i;
if(RADIO_bf==NULL)return;
for(i=0;i<npatch2;i++){
patchdata *patchi;
patchi = patchinfo + patchfilenum;
if(strcmp(patchlabellist[i],patchi->label.shortlabel)==0){
if(RADIO_bf == NULL){
list_patch_index = i;
}
else {
RADIO_bf->set_int_val(i);
}
list_patch_index_old=list_patch_index;
Global2LocalBoundaryBounds(patchlabellist[i]);
RADIO_patch_setmin->set_int_val(setpatchmin);
RADIO_patch_setmax->set_int_val(setpatchmax);
EDIT_patch_min->set_float_val(patchmin);
EDIT_patch_max->set_float_val(patchmax);
CHECKBOX_patch_setchopmin->set_int_val(setpatchchopmin);
CHECKBOX_patch_setchopmax->set_int_val(setpatchchopmax);
EDIT_patch_chopmin->set_float_val(patchchopmin);
EDIT_patch_chopmax->set_float_val(patchchopmax);
if(setpatchmin==SET_MIN){
EDIT_patch_min->enable();
}
else{
EDIT_patch_min->disable();
}
if(setpatchmax==SET_MAX){
EDIT_patch_max->enable();
}
else{
EDIT_patch_max->disable();
}
if(setpatchchopmin==SET_MIN){
EDIT_patch_chopmin->enable();
}
else{
EDIT_patch_chopmin->disable();
}
if(setpatchchopmax==SET_MAX){
EDIT_patch_chopmax->enable();
}
else{
EDIT_patch_chopmax->disable();
}
return;
}
}
}
/* ------------------ UpdateBoundaryListIndex2 ------------------------ */
extern "C" void UpdateBoundaryListIndex2(char *label){
int i;
for(i=0;i<npatch2;i++){
if(strcmp(patchlabellist[i],label)==0){
UpdateBoundaryListIndex(patchlabellist_index[i]);
break;
}
}
}
/* ------------------ UpdateGluiStreakValue ------------------------ */
extern "C" void UpdateGluiStreakValue(float rvalue){
float_streak5value=rvalue;
if(SPINNER_partstreaklength!=NULL){
SPINNER_partstreaklength->set_float_val(rvalue);
SPINNER_partstreaklength->set_float_limits(0.0,tmax_part);
}
}
/* ------------------ PartBoundCB ------------------------ */
void PartBoundCB(int var){
partpropdata *prop_new, *prop_old;
prop_new = part5propinfo + ipart5prop;
prop_old = part5propinfo + ipart5prop_old;
switch(var){
case VALMIN:
if(setpartmin==SET_MIN)prop_new->user_min=partmin;
break;
case VALMAX:
if(setpartmax==SET_MAX)prop_new->user_max = partmax;
break;
case FILETYPEINDEX:
// save data from controls
prop_old->setvalmin=setpartmin;
prop_old->setvalmax=setpartmax;
if(setpartmin==SET_MIN){
prop_old->user_min=partmin;
}
if(setpartmax==SET_MAX){
prop_old->user_max=partmax;
}
prop_old->setchopmin=setpartchopmin;
prop_old->setchopmax=setpartchopmax;
prop_old->chopmin=partchopmin;
prop_old->chopmax=partchopmax;
// copy data to controls
setpartmin=prop_new->setvalmin;
if(setpartmin==PERCENTILE_MIN)setpartmin = GLOBAL_MIN;
setpartmax = prop_new->setvalmax;
if(setpartmax==PERCENTILE_MAX)setpartmax = GLOBAL_MAX;
PartBoundCB(SETVALMIN);
PartBoundCB(SETVALMAX);
setpartchopmin=prop_new->setchopmin;
setpartchopmax=prop_new->setchopmax;
partchopmin=prop_new->chopmin;
partchopmax=prop_new->chopmax;
partmin_unit = (unsigned char *)prop_new->label->unit;
partmax_unit = partmin_unit;
UpdateGluiPartUnits();
// update controls
if(RADIO_part_setmin!=NULL)RADIO_part_setmin->set_int_val(setpartmin);
if(RADIO_part_setmax!=NULL)RADIO_part_setmax->set_int_val(setpartmax);
if(EDIT_part_chopmin!=NULL)EDIT_part_chopmin->set_float_val(partchopmin);
if(EDIT_part_chopmax!=NULL)EDIT_part_chopmax->set_float_val(partchopmax);
if(CHECKBOX_part_setchopmin!=NULL)CHECKBOX_part_setchopmin->set_int_val(setpartchopmin);
if(CHECKBOX_part_setchopmax!=NULL)CHECKBOX_part_setchopmax->set_int_val(setpartchopmax);
ipart5prop_old = ipart5prop;
if(CHECKBOX_part_setchopmin!=NULL)PartBoundCB(SETCHOPMINVAL);
if(CHECKBOX_part_setchopmax!=NULL)PartBoundCB(SETCHOPMAXVAL);
break;
case STREAKLENGTH:
UpdateStreakValue(float_streak5value-0.001);
if(float_streak5value==0.0){
streak5show=0;
}
else{
streak5show=1;
}
updatemenu=1;
break;
case TRACERS:
case PARTFAST:
if(partfast==0||npartinfo<=1){
CHECKBOX_part_multithread->disable();
SPINNER_npartthread_ids->disable();
}
else{
CHECKBOX_part_multithread->enable();
SPINNER_npartthread_ids->enable();
}
CHECKBOX_part_multithread->set_int_val(part_multithread);
updatemenu=1;
break;
case FRAMELOADING:
partframestep=partframeskip+1;
evacframestep=evacframeskip+1;
evacframestep=evacframeskip+1;
updatemenu=1;
break;
case CHOPUPDATE:
UpdateChopColors();
break;
case SETCHOPMINVAL:
prop_new->setchopmin=setpartchopmin;
prop_new->chopmin=partchopmin;
UpdateChopColors();
switch(setpartchopmin){
case DISABLE:
EDIT_part_chopmin->disable();
break;
case ENABLE:
EDIT_part_chopmin->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case SETCHOPMAXVAL:
prop_new->setchopmax=setpartchopmax;
prop_new->chopmax=partchopmax;
UpdateChopColors();
switch(setpartchopmax){
case DISABLE:
EDIT_part_chopmax->disable();
break;
case ENABLE:
EDIT_part_chopmax->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case CHOPVALMIN:
prop_new->setchopmin=setpartchopmin;
prop_new->chopmin=partchopmin;
if(EDIT_part_chopmin!=NULL)EDIT_part_chopmin->set_float_val(partchopmin);
UpdateChopColors();
break;
case CHOPVALMAX:
prop_new->setchopmax=setpartchopmax;
prop_new->chopmax=partchopmax;
if(EDIT_part_chopmax!=NULL)EDIT_part_chopmax->set_float_val(partchopmax);
UpdateChopColors();
break;
case SETVALMIN:
if(setpartmin_old==SET_MIN){
if(prop_old!=NULL)prop_old->user_min=partmin;
}
setpartmin_old=setpartmin;
if(prop_new!=NULL)prop_new->setvalmin = setpartmin;
switch(setpartmin){
case PERCENTILE_MIN:
if(prop_new!=NULL)partmin=prop_new->percentile_min;
if(EDIT_part_min!=NULL)EDIT_part_min->disable();
break;
case GLOBAL_MIN:
if(prop_new!=NULL)partmin=prop_new->global_min;
if(EDIT_part_min!=NULL)EDIT_part_min->disable();
break;
case SET_MIN:
if(prop_new!=NULL)partmin=prop_new->user_min;
if(EDIT_part_min!=NULL)EDIT_part_min->enable();
break;
default:
ASSERT(FFALSE);
break;
}
if(prop_new!=NULL)prop_new->valmin=partmin;
if(EDIT_part_min!=NULL)EDIT_part_min->set_float_val(partmin);
break;
case SETVALMAX:
if(setpartmax_old==SET_MAX){
if(prop_old!=NULL)prop_old->user_max=partmax;
}
setpartmax_old=setpartmax;
if(prop_new!=NULL)prop_new->setvalmax = setpartmax;
switch(setpartmax){
case PERCENTILE_MAX:
if(prop_new!=NULL)partmax=prop_new->percentile_max;
if(EDIT_part_max!=NULL)EDIT_part_max->disable();
break;
case GLOBAL_MAX:
if(prop_new!=NULL)partmax=prop_new->global_max;
if(EDIT_part_max!=NULL)EDIT_part_max->disable();
break;
case SET_MAX:
if(prop_new!=NULL)partmax=prop_new->user_max;
if(EDIT_part_max!=NULL)EDIT_part_max->enable();
break;
default:
ASSERT(FFALSE);
break;
}
if(prop_new!=NULL)prop_new->valmax=partmax;
if(EDIT_part_max!=NULL)EDIT_part_max->set_float_val(partmax);
break;
case FILERELOAD:
{
int prop_index_SAVE;
prop_index_SAVE= global_prop_index;
PartBoundCB(FILETYPEINDEX);
if(EDIT_part_min!=NULL&&setpartmin==SET_MIN)PartBoundCB(SETVALMIN);
if(EDIT_part_max!=NULL&&setpartmax==SET_MAX)PartBoundCB(SETVALMAX);
LoadParticleMenu(PARTFILE_RELOADALL);
LoadEvacMenu(EVACFILE_RELOADALL);
UpdateGlui();
ParticlePropShowMenu(prop_index_SAVE);
}
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ UpdateZoneTempBounds ------------------------ */
#ifdef pp_NEWBOUND_DIALOG
void UpdateZoneTempBounds(float valmin, float valmax){
#else
void UpdateZoneTempBounds(int setvalmin, float valmin, int setvalmax, float valmax){
#endif
int slice_index;
if(nzoneinfo>0&&RADIO_slice!=NULL){
slice_index = RADIO_slice->get_int_val();
if(strcmp(slicebounds[slice_index].shortlabel, "TEMP")==0){
#ifdef pp_NEWBOUND_DIALOG
setzonemin = SET_MIN;
setzonemax = SET_MAX;
#else
setzonemin = setvalmin;
setzonemax = setvalmax;
#endif
zonemin = valmin;
zonemax = valmax;
if(EDIT_zone_min!=NULL)EDIT_zone_min->set_float_val(valmin);
if(EDIT_zone_max!=NULL)EDIT_zone_max->set_float_val(valmax);
#ifndef pp_NEWBOUND_DIALOG
if(RADIO_zone_setmin!=NULL)RADIO_zone_setmin->set_int_val(setvalmin);
if(RADIO_zone_setmax!=NULL)RADIO_zone_setmax->set_int_val(setvalmax);
#endif
SliceBoundCB(FILEUPDATE);
}
}
}
/* ------------------ UpdateSliceTempBounds ------------------------ */
#ifdef pp_NEWBOUND_DIALOG
void UpdateSliceTempBounds(float valmin, float valmax){
#else
void UpdateSliceTempBounds(int setvalmin, float valmin, int setvalmax, float valmax){
#endif
int temp_index;
if(slicebounds_temp==NULL||RADIO_slice==NULL)return;
temp_index = slicebounds_temp-slicebounds;
#ifdef pp_NEWBOUND_DIALOG
slicebounds_temp->dlg_valmin = valmin;
slicebounds_temp->dlg_valmax = valmax;
#else
if(setvalmin==SET_MIN){
slicebounds_temp->dlg_valmin = valmin;
}
else{
slicebounds_temp->global_valmin = valmin;
}
if(setvalmax==SET_MAX){
slicebounds_temp->dlg_valmax = valmax;
}
else{
slicebounds_temp->global_valmax = valmax;
}
slicebounds_temp->dlg_setvalmin = setvalmin;
slicebounds_temp->dlg_setvalmax = setvalmax;
#endif
if(RADIO_slice==NULL)return;
RADIO_slice->set_int_val(temp_index);
EDIT_slice_min->set_float_val(valmin);
EDIT_slice_max->set_float_val(valmax);
#ifndef pp_NEWBOUND_DIALOG
RADIO_slice_setmin->set_int_val(setvalmin);
RADIO_slice_setmax->set_int_val(setvalmax);
#endif
SliceBounds2Glui(temp_index);
}
#ifdef pp_NEWBOUND_DIALOG
/* ------------------ Glui2SliceBounds ------------------------ */
void Glui2SliceBounds(void){
if(slicebounds==NULL)return;
slicebounds[list_slice_index].dlg_valmin = glui_slicemin;
slicebounds[list_slice_index].setchopmin = glui_setslicechopmin;
slicebounds[list_slice_index].chopmin = glui_slicechopmin;
slicebounds[list_slice_index].dlg_valmax = glui_slicemax;
slicebounds[list_slice_index].setchopmax = glui_setslicechopmax;
slicebounds[list_slice_index].chopmax = glui_slicechopmax;
}
#else
/* ------------------ SetSliceMin ------------------------ */
void SetSliceMin(int setslicemin_local, float slicemin_local, int setslicechopmin_local, float slicechopmin_local){
if(slicebounds == NULL)return;
#ifndef pp_NEWBOUND_DIALOG
slicebounds[list_slice_index].dlg_setvalmin = setslicemin_local;
#endif
slicebounds[list_slice_index].dlg_valmin = slicemin_local;
slicebounds[list_slice_index].setchopmin = setslicechopmin_local;
slicebounds[list_slice_index].chopmin = slicechopmin_local;
}
/* ------------------ SetSliceMax ------------------------ */
void SetSliceMax(int setslicemax_local, float slicemax_local, int setslicechopmax_local, float slicechopmax_local){
if(slicebounds==NULL)return;
#ifndef pp_NEWBOUND_DIALOG
slicebounds[list_slice_index].dlg_setvalmax = setslicemax_local;
#endif
slicebounds[list_slice_index].dlg_valmax = slicemax_local;
slicebounds[list_slice_index].setchopmax = setslicechopmax_local;
slicebounds[list_slice_index].chopmax = slicechopmax_local;
}
#endif
/* ------------------ SliceBoundCB ------------------------ */
extern "C" void SliceBoundCB(int var){
int error,i;
int ii;
slicedata *sd;
int last_slice;
updatemenu=1;
#ifdef pp_NEWBOUND_DIALOG
if(var==SLICE_LOADED_ONLY){
if(slice_loaded_only==1){
BUTTON_slice_percentile_bounds->enable();
}
else{
BUTTON_slice_percentile_bounds->disable();
}
return;
}
if(var==PERCENTILE_BOUNDS_LOADED){
float per_min, per_max;
SliceBoundCB(GLOBAL_BOUNDS);
GetSlicePercentileBounds(slicebounds[list_slice_index].label->shortlabel, glui_slicemin, glui_slicemax, &per_min, &per_max);
if(per_min<=per_max){
slicebounds[list_slice_index].percentile_valmin = per_min;
slicebounds[list_slice_index].percentile_valmax = per_max;
slicebounds[list_slice_index].dlg_valmin = per_min;
slicebounds[list_slice_index].dlg_valmax = per_max;
EDIT_slice_min->set_float_val(per_min);
EDIT_slice_max->set_float_val(per_max);
}
return;
}
if(var==GLOBAL_BOUNDS_MIN){
slicebounds[list_slice_index].dlg_valmin = slicebounds[list_slice_index].global_valmin;
EDIT_slice_min->set_float_val(slicebounds[list_slice_index].dlg_valmin);
return;
}
if(var==GLOBAL_BOUNDS_MAX){
slicebounds[list_slice_index].dlg_valmax = slicebounds[list_slice_index].global_valmax;
EDIT_slice_max->set_float_val(slicebounds[list_slice_index].dlg_valmax);
return;
}
if(var==GLOBAL_BOUNDS){
if(slice_loaded_only==0){
SliceBoundCB(GLOBAL_BOUNDS_MIN);
SliceBoundCB(GLOBAL_BOUNDS_MAX);
}
else{
float slice_min, slice_max;
int slice_loaded=0;
slice_min = 1.0;
slice_max = 0.0;
for(i = 0; i<nsliceinfo; i++){
slicedata *slicei;
slicei = sliceinfo+i;
if(slicei->loaded==0||strcmp(slicei->label.shortlabel, slicebounds[list_slice_index].shortlabel)!=0)continue;
slice_loaded = 1;
if(slicei->file_min>slicei->file_max)continue;
if(slice_min>slice_max){
slice_min = slicei->file_min;
slice_max = slicei->file_max;
}
else{
slice_min = MIN(slice_min, slicei->file_min);
slice_max = MAX(slice_max, slicei->file_max);
}
}
if(slice_loaded==0)printf("no slices of type %s are loaded - minimum slice bound not updated\n",slicebounds[list_slice_index].shortlabel);
if(slice_min<=slice_max){
slicebounds[list_slice_index].dlg_valmin = slice_min;
EDIT_slice_min->set_float_val(slice_min);
slicebounds[list_slice_index].dlg_valmax = slice_max;
EDIT_slice_max->set_float_val(slice_max);
}
}
return;
}
if(var==GLOBAL_BOUNDS_MAX_LOADED){
float slice_min, slice_max;
int slice_loaded=0;
slice_min = 1.0;
slice_max = 0.0;
for(i = 0; i<nsliceinfo; i++){
slicedata *slicei;
slicei = sliceinfo+i;
if(slicei->loaded==0||strcmp(slicei->label.shortlabel, slicebounds[list_slice_index].shortlabel)!=0)continue;
slice_loaded=1;
if(slicei->file_min>slicei->file_max)continue;
if(slice_min>slice_max){
slice_min = slicei->file_min;
slice_max = slicei->file_max;
}
else{
slice_min = MIN(slice_min, slicei->file_min);
slice_max = MAX(slice_max, slicei->file_max);
}
}
if(slice_loaded==0)printf("no slices of type %s are loaded - maximum slice bound not updated\n",slicebounds[list_slice_index].shortlabel);
if(slice_min<=slice_max){
slicebounds[list_slice_index].dlg_valmax = slice_max;
EDIT_slice_max->set_float_val(slice_max);
}
return;
}
if(var==GLOBAL_BOUNDS_LOADED){
SliceBoundCB(GLOBAL_BOUNDS_MIN_LOADED);
SliceBoundCB(GLOBAL_BOUNDS_MAX_LOADED);
return;
}
#endif
if(var==UPDATE_HISTOGRAM){
update_slice_hists = 1;
histograms_defined = 0;
return;
}
if(var == INIT_HISTOGRAM){
if(histogram_show_graph == 1 || histogram_show_numbers == 1){
update_slice_hists = 1;
visColorbarVertical = 1;
}
return;
}
if(var==SLICE_IN_OBST){
if(show_slice_in_obst!=show_slice_in_obst_old){
SliceBoundCB(FILEUPDATE);
show_slice_in_obst_old = show_slice_in_obst;
}
return;
}
if(var==DATA_transparent){
UpdateTransparency();
UpdateChopColors();
UpdateIsoControls();
return;
}
if(var==COLORBAR_EXTREME2){
UpdateExtreme();
return;
}
if(var==COLORBAR_LIST2){
selectedcolorbar_index= GetColorbarListIndex();
UpdateColorbarList();
ColorbarMenu(selectedcolorbar_index);
ColorbarGlobal2Local();
}
if(var==COLORBAR_SMOOTH){
updatemenu=1;
return;
}
switch(var){
case UPDATE_SLICEDUPS:
updatemenu = 1;
break;
case SLICE_VECTORSKIP:
if(SPINNER_plot3dvectorskip!=NULL)SPINNER_plot3dvectorskip->set_int_val(vectorskip);
break;
case ZONEVALMINMAX:
GetZoneColors(zonetu, nzonetotal, izonetu,zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
GetZoneColors(zonetl, nzonetotal, izonetl, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
if(have_zonefl==1)GetZoneColors(zonefl, nzonetotal, izonefl, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
if(have_zonelw==1)GetZoneColors(zonelw, nzonetotal, izonelw, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
if(have_zoneuw==1)GetZoneColors(zoneuw, nzonetotal, izoneuw, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
if(have_zonecl==1)GetZoneColors(zonecl, nzonetotal, izonecl, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
if(have_target_data==1)GetZoneColors(zonetargets, nzonetotal_targets, izonetargets, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
#ifdef pp_NEWBOUND_DIALOG
UpdateSliceTempBounds(zonemin, zonemax);
#else
UpdateSliceTempBounds(setzonemin, zonemin, setzonemax, zonemax);
#endif
zoneusermin=zonemin;
zoneusermax=zonemax;
break;
case SETZONEVALMINMAX:
if(setzonemin==SET_MIN){
EDIT_zone_min->enable();
if(EDIT_slice_min!=NULL)EDIT_slice_min->enable();
zonemin=zoneusermin;
EDIT_zone_min->set_float_val(zonemin);
}
else{
EDIT_zone_min->disable();
if(EDIT_slice_min!=NULL)EDIT_slice_min->disable();
EDIT_zone_min->set_float_val(zoneglobalmin);
}
if(setzonemax==SET_MAX){
EDIT_zone_max->enable();
if(EDIT_slice_max!=NULL)EDIT_slice_max->enable();
zonemax = zoneusermax;
EDIT_zone_max->set_float_val(zonemax);
}
else{
EDIT_zone_max->disable();
if(EDIT_slice_max!=NULL)EDIT_slice_max->disable();
EDIT_zone_max->set_float_val(zoneglobalmax);
}
GetZoneColors(zonetu, nzonetotal, izonetu,zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
GetZoneColors(zonetl, nzonetotal, izonetl, zonemin, zonemax, nrgb, nrgb_full, colorlabelzone, colorvalueszone, zonescale, zonelevels256);
#ifdef pp_NEWBOUND_DIALOG
UpdateSliceTempBounds(zonemin, zonemax);
#else
UpdateSliceTempBounds(setzonemin, zonemin, setzonemax, zonemax);
#endif
break;
case COLORBAR_LIST2:
if(selectedcolorbar_index2 == bw_colorbar_index){
setbwdata = 1;
ColorbarMenu(bw_colorbar_index);
}
else{
setbwdata = 0;
}
IsoBoundCB(ISO_COLORS);
SetLabelControls();
break;
case RESEARCH_MODE:
for(i=0;i<nsliceinfo;i++){
slicedata *slicei;
slicei = sliceinfo + i;
if(slicei->loaded==0||slicei->display==0)continue;
UpdateSliceList(GetSliceBoundsIndex(slicei));
break;
}
if(research_mode==1){
axislabels_smooth=0;
visColorbarVertical_save=visColorbarVertical;
visColorbarVertical=1;
// slice files
if(nsliceloaded > 0){
#ifndef pp_NEWBOUND_DIALOG
glui_setslicemin_save = glui_setslicemin;
glui_setslicemin = GLOBAL_MIN;
glui_setslicemax_save = glui_setslicemax;
glui_setslicemax = GLOBAL_MAX;
#endif
#ifndef pp_NEWBOUND_DIALOG
glui_setslicemin_save = glui_setslicemin;
#endif
glui_slicemin_save = glui_slicemin;
SliceBoundCB(SETVALMIN);
#ifndef pp_NEWBOUND_DIALOG
glui_setslicemax_save = glui_setslicemax;
#endif
glui_slicemax_save = glui_slicemax;
SliceBoundCB(SETVALMAX);
}
// boundary files
if(npatchloaded > 0){
setpatchmin_save = setpatchmin;
patchmin_save = patchmin;
setpatchmin = GLOBAL_MIN;
BoundBoundCB(SETVALMIN);
setpatchmax_save = setpatchmax;
patchmax_save = patchmax;
setpatchmax = GLOBAL_MAX;
BoundBoundCB(SETVALMAX);
BoundBoundCB(FILERELOAD);
}
// particle files
if(npartloaded>0){
setpartmin_save = setpartmin;
partmin_save = partmin;
setpartmin = GLOBAL_MIN;
PartBoundCB(SETVALMIN);
setpartmax_save = setpartmax;
partmax_save = partmax;
setpartmax = GLOBAL_MAX;
PartBoundCB(SETVALMAX);
PartBoundCB(FILERELOAD);
}
// plot3d files
if(nplot3dloaded>0){
for(i = 0; i < MAXPLOT3DVARS; i++){
setp3min_save[i] = setp3min[i];
p3min_save[i] = p3min[i];
setp3min[i] = GLOBAL_MIN;
setp3max_save[i] = setp3max[i];
p3max_save[i] = p3max[i];
setp3max[i] = GLOBAL_MAX;
}
Plot3DBoundCB(SETVALMIN);
Plot3DBoundCB(SETVALMAX);
Plot3DBoundCB(FILERELOAD);
}
PRINTF("research mode on\n");
}
else{
visColorbarVertical=visColorbarVertical_save;
// slice files
if(nsliceloaded > 0){
SliceBoundCB(SETVALMIN);
SliceBoundCB(VALMIN);
SliceBoundCB(SETVALMAX);
SliceBoundCB(VALMAX);
}
// boundary files
if(npatchloaded > 0){
setpatchmin = setpatchmin_save;
BoundBoundCB(SETVALMIN);
patchmin = patchmin_save;
BoundBoundCB(VALMIN);
setpatchmax = setpatchmax_save;
BoundBoundCB(SETVALMAX);
patchmax = patchmax_save;
BoundBoundCB(VALMAX);
BoundBoundCB(FILERELOAD);
}
// particle files
if(npartloaded > 0){
setpartmin = setpartmin_save;
PartBoundCB(SETVALMIN);
partmin = partmin_save;
PartBoundCB(VALMIN);
setpartmax = setpartmax_save;
PartBoundCB(SETVALMAX);
partmax = partmax_save;
PartBoundCB(VALMAX);
PartBoundCB(FILERELOAD);
}
// Plot3D files
if(nplot3dloaded > 0){
for(i = 0; i < MAXPLOT3DVARS; i++){
setp3min[i] = setp3min_save[i];
p3min[i] = p3min_save[i];
setp3max[i] = setp3max_save[i];
p3max[i] = p3max_save[i];
}
Plot3DBoundCB(SETVALMIN);
Plot3DBoundCB(VALMIN);
Plot3DBoundCB(SETVALMAX);
Plot3DBoundCB(VALMAX);
Plot3DBoundCB(FILERELOAD);
}
PRINTF("research mode off\n");
}
UpdateAxisLabelsSmooth();
SliceBoundCB(FILEUPDATE);
break;
case SMOOTH_SURFACES:
CHECKBOX_smooth2->set_int_val(smooth_iso_normal);
break;
case SORT_SURFACES:
sort_geometry=sort_iso_triangles;
for(i=nsurfinfo;i<nsurfinfo+MAX_ISO_COLORS+1;i++){
surfdata *surfi;
surfi = surfinfo + i;
surfi->transparent_level=transparent_level;
}
CHECKBOX_sort2->set_int_val(sort_iso_triangles);
IsoBoundCB(GLOBAL_ALPHA);
break;
case SHOW_EVAC_SLICES:
data_evac_coloring = 1-constant_evac_coloring;
UpdateSliceMenuShow();
if(CHECKBOX_data_coloring!=NULL)CHECKBOX_data_coloring->set_int_val(data_evac_coloring);
break;
case DATA_EVAC_COLORING:
constant_evac_coloring = 1-data_evac_coloring;
UpdateSliceMenuShow();
if(CHECKBOX_constant_coloring!=NULL)CHECKBOX_constant_coloring->set_int_val(constant_evac_coloring);
break;
case COLORBAND:
UpdateRGBColors(colorbar_select_index);
break;
case TRANSPARENTLEVEL:
for(i=nsurfinfo;i<nsurfinfo+MAX_ISO_COLORS+1;i++){
surfdata *surfi;
surfi = surfinfo + i;
surfi->transparent_level=transparent_level;
}
UpdateRGBColors(COLORBAR_INDEX_NONE);
if(SPINNER_transparent_level!=NULL)SPINNER_transparent_level->set_float_val(transparent_level);
break;
case LINE_CONTOUR_VALUE:
if(slice_line_contour_num<1){
slice_line_contour_num=1;
SPINNER_line_contour_num->set_int_val(slice_line_contour_num);
}
if(slice_line_contour_num==1&&slice_line_contour_min!=slice_line_contour_max){
slice_line_contour_max=slice_line_contour_min;
SPINNER_line_contour_max->set_float_val(slice_line_contour_max);
}
slicebounds[list_slice_index].line_contour_min=slice_line_contour_min;
slicebounds[list_slice_index].line_contour_max=slice_line_contour_max;
slicebounds[list_slice_index].line_contour_num=slice_line_contour_num;
break;
case UPDATE_LINE_CONTOUR_VALUE:
UpdateSliceContours(list_slice_index,slice_line_contour_min, slice_line_contour_max,slice_line_contour_num);
break;
case UPDATE_VECTOR_FROM_SMV:
if(SPINNER_plot3d_vectorpointsize!=NULL&&SPINNER_plot3d_vectorlinewidth!=NULL&&SPINNER_plot3d_vectorlinelength!=NULL){
SPINNER_plot3d_vectorpointsize->set_float_val(vectorpointsize);
SPINNER_plot3d_vectorlinewidth->set_float_val(vectorlinewidth);
SPINNER_plot3d_vectorlinelength->set_float_val(vecfactor);
}
SliceBoundCB(UPDATE_VECTOR);
break;
case UPDATE_VECTOR:
break;
case FRAMELOADING:
sliceframestep=sliceframeskip+1;
slicezipstep=slicezipskip+1;
updatemenu=1;
break;
case CHOPUPDATE:
UpdateChopColors();
break;
case SETCHOPMINVAL:
UpdateChopColors();
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
#else
SetSliceMin(glui_setslicemin, glui_slicemin, glui_setslicechopmin, glui_slicechopmin);
#endif
switch(glui_setslicechopmin){
case DISABLE:
EDIT_slice_chopmin->disable();
break;
case ENABLE:
EDIT_slice_chopmin->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case SETCHOPMAXVAL:
UpdateChopColors();
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
#else
SetSliceMax(glui_setslicemax, glui_slicemax, glui_setslicechopmax, glui_slicechopmax);
#endif
switch(glui_setslicechopmax){
case DISABLE:
EDIT_slice_chopmax->disable();
break;
case ENABLE:
EDIT_slice_chopmax->enable();
break;
default:
ASSERT(FFALSE);
break;
}
break;
case CHOPVALMIN:
if(EDIT_slice_min!=NULL)EDIT_slice_min->set_float_val(glui_slicemin);
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
#else
SetSliceMin(glui_setslicemin, glui_slicemin, glui_setslicechopmin, glui_slicechopmin);
#endif
UpdateChopColors();
break;
case CHOPVALMAX:
if(EDIT_slice_max!=NULL)EDIT_slice_max->set_float_val(glui_slicemax);
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
#else
SetSliceMax(glui_setslicemax,glui_slicemax,glui_setslicechopmax,glui_slicechopmax);
#endif
UpdateChopColors();
break;
case SETVALMIN:
#ifndef pp_NEWBOUND_DIALOG
switch(glui_setslicemin){
case PERCENTILE_MIN:
case GLOBAL_MIN:
if(EDIT_slice_min!=NULL)EDIT_slice_min->disable();
if(EDIT_zone_min!=NULL)EDIT_zone_min->disable();
break;
case SET_MIN:
if(EDIT_slice_min!=NULL)EDIT_slice_min->enable();
if(EDIT_zone_min!=NULL)EDIT_zone_min->enable();
break;
default:
ASSERT(FFALSE);
break;
}
if(RADIO_slice_setmin!=NULL)RADIO_slice_setmin->set_int_val(glui_setslicemin);
#endif
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
UpdateZoneTempBounds(glui_slicemin, glui_slicemax);
#else
SetSliceMin(glui_setslicemin, glui_slicemin, glui_setslicechopmin, glui_slicechopmin);
UpdateZoneTempBounds(glui_setslicemin, glui_slicemin, glui_setslicemax, glui_slicemax);
#endif
break;
case SETVALMAX:
#ifndef pp_NEWBOUND_DIALOG
switch(glui_setslicemax){
case PERCENTILE_MAX:
case GLOBAL_MAX:
if(EDIT_slice_max!=NULL)EDIT_slice_max->disable();
if(EDIT_zone_max!=NULL)EDIT_zone_max->disable();
break;
case SET_MAX:
if(EDIT_slice_max!=NULL)EDIT_slice_max->enable();
if(EDIT_zone_max!=NULL)EDIT_zone_max->enable();
break;
default:
ASSERT(FFALSE);
break;
}
if(RADIO_slice_setmax!=NULL)RADIO_slice_setmax->set_int_val(glui_setslicemax);
#endif
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
UpdateZoneTempBounds(glui_slicemin, glui_slicemax);
#else
SetSliceMax(glui_setslicemax, glui_slicemax, glui_setslicechopmax, glui_slicechopmax);
UpdateZoneTempBounds(glui_setslicemin, glui_slicemin, glui_setslicemax, glui_slicemax);
#endif
break;
case VALMIN:
#ifdef pp_NEWBOUND_DIALOG
if(is_fed_colorbar==1&&ABS(glui_slicemin)>0.001){
#else
if(is_fed_colorbar==1&&glui_setslicemin==1&&ABS(glui_slicemin)>0.001){
#endif
printf("***warning: min/max bounds for the FED colorbar are set to 0.0 and 3.0 respectively.\n");
printf(" To use different min/max bounds, change the colorbar.\n");
glui_slicemin = 0.0;
}
if(EDIT_slice_min!=NULL)EDIT_slice_min->set_float_val(glui_slicemin);
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
UpdateZoneTempBounds(glui_slicemin, glui_slicemax);
#else
SetSliceMin(glui_setslicemin, glui_slicemin, glui_setslicechopmin, glui_slicechopmin);
UpdateZoneTempBounds(glui_setslicemin, glui_slicemin, glui_setslicemax, glui_slicemax);
#endif
break;
case VALMAX:
#ifdef pp_NEWBOUND_DIALOG
if(is_fed_colorbar==1&&ABS(glui_slicemax-3.0)>0.001){
#else
if(is_fed_colorbar==1&&glui_setslicemax==1&&ABS(glui_slicemax-3.0)>0.001){
#endif
printf("***warning: min/max bounds for the FED colorbar are set to 0.0 and 3.0 respectively.\n");
printf(" To use different min/max bounds, change the colorbar.\n");
glui_slicemax = 3.0;
}
if(EDIT_slice_max!=NULL)EDIT_slice_max->set_float_val(glui_slicemax);
#ifdef pp_NEWBOUND_DIALOG
Glui2SliceBounds();
UpdateZoneTempBounds(glui_slicemin, glui_slicemax);
#else
SetSliceMax(glui_setslicemax,glui_slicemax,glui_setslicechopmax,glui_slicechopmax);
UpdateZoneTempBounds(glui_setslicemin, glui_slicemin, glui_setslicemax, glui_slicemax);
#endif
break;
case FILETYPEINDEX:
if(slice_bounds_dialog==1&&list_slice_index==fire_line_index){
slice_bounds_dialog=0;
if(ROLLOUT_slice_bound!=NULL){
ROLLOUT_slice_bound->close();
ROLLOUT_slice_bound->disable();
}
if(ROLLOUT_slice_chop!=NULL){
ROLLOUT_slice_chop->close();
ROLLOUT_slice_chop->disable();
}
}
if(slice_bounds_dialog==0&&list_slice_index!=fire_line_index){
slice_bounds_dialog=1;
if(ROLLOUT_slice_bound!=NULL){
ROLLOUT_slice_bound->enable();
}
if(ROLLOUT_slice_chop!=NULL){
ROLLOUT_slice_chop->enable();
}
}
SliceBounds2Glui(list_slice_index);
if(EDIT_slice_min!=NULL)EDIT_slice_min->set_float_val(glui_slicemin);
if(EDIT_slice_max!=NULL)EDIT_slice_max->set_float_val(glui_slicemax);
#ifndef pp_NEWBOUND_DIALOG
RADIO_slice_setmin->set_int_val(glui_setslicemin);
RADIO_slice_setmax->set_int_val(glui_setslicemax);
#endif
EDIT_slice_chopmin->set_float_val(glui_slicechopmin);
EDIT_slice_chopmax->set_float_val(glui_slicechopmax);
CHECKBOX_slice_setchopmin->set_int_val(glui_setslicechopmin);
CHECKBOX_slice_setchopmax->set_int_val(glui_setslicechopmax);
if(glui_setslicechopmin==1){
EDIT_slice_chopmin->enable();
}
else{
EDIT_slice_chopmin->disable();
}
if(glui_setslicechopmax==1){
EDIT_slice_chopmax->enable();
}
else{
EDIT_slice_chopmax->disable();
}
SPINNER_line_contour_min->set_float_val(slice_line_contour_min);
SPINNER_line_contour_max->set_float_val(slice_line_contour_max);
SPINNER_line_contour_num->set_int_val(slice_line_contour_num);
if(ROLLOUT_zone_bound!=NULL){
int slice_index;
slice_index = RADIO_slice->get_int_val();
if(strcmp(slicebounds[slice_index].shortlabel, "TEMP")==0){
BoundRolloutCB(ZONE_ROLLOUT);
if(ROLLOUT_slice_bound!=NULL)ROLLOUT_slice_bound->disable();
}
else{
if(ROLLOUT_slice_bound!=NULL)ROLLOUT_slice_bound->enable();
}
}
#ifndef pp_NEWBOUND_DIALOG
switch(glui_setslicemin){
case PERCENTILE_MIN:
case GLOBAL_MIN:
if(EDIT_slice_min!=NULL)EDIT_slice_min->disable();
break;
case SET_MIN:
if(EDIT_slice_min!=NULL)EDIT_slice_min->enable();
break;
default:
ASSERT(FFALSE);
break;
}
switch(glui_setslicemax){
case PERCENTILE_MIN:
case GLOBAL_MAX:
if(EDIT_slice_max!=NULL)EDIT_slice_max->disable();
break;
case SET_MAX:
if(EDIT_slice_max!=NULL)EDIT_slice_max->enable();
break;
default:
ASSERT(FFALSE);
break;
}
#endif
break;
case FILEUPDATE:
use_slice_glui_bounds = 1;
#ifndef pp_NEWBOUND_DIALOG
glui_setslicemin_save = glui_setslicemin;
glui_setslicemax_save = glui_setslicemax;
#endif
slice_fileupdate++;
if(slice_fileupdate>1){
slice_fileupdate--;
break;
}
for(ii = nslice_loaded - 1; ii >= 0; ii--){
i = slice_loaded_list[ii];
sd = sliceinfo + i;
if(sd->slicefile_labelindex == slicefile_labelindex){
last_slice = i;
break;
}
}
for(ii = 0; ii < nslice_loaded; ii++){
i = slice_loaded_list[ii];
sd = sliceinfo + i;
if(sd->slicefile_labelindex == slicefile_labelindex){
int set_slicecolor;
set_slicecolor = DEFER_SLICECOLOR;
if(i == last_slice)set_slicecolor = SET_SLICECOLOR;
ReadSlice("", i, RESETBOUNDS, set_slicecolor, &error);
}
}
slice_fileupdate--;
use_slice_glui_bounds = 0;
#ifndef pp_NEWBOUND_DIALOG
glui_setslicemin = glui_setslicemin_save;
glui_setslicemax = glui_setslicemax_save;
#endif
break;
case FILERELOAD:
SliceBoundCB(FILEUPDATE);
if(slicefilenum>=0&&slicefilenum<nsliceinfo){
LoadSliceMenu(slicefilenum);
}
else{
LoadSliceMenu(0);
}
UpdateGlui();
break;
case ALLFILERELOAD:
ReloadAllSliceFiles();
break;
default:
ASSERT(FFALSE);
break;
}
}
/* ------------------ UpdateSliceList ------------------------ */
extern "C" void UpdateSliceList(int index){
if(glui_defined==0)return;
RADIO_slice->set_int_val(index);
}
/* ------------------ UpdateSliceListIndex ------------------------ */
extern "C" void UpdateSliceListIndex(int sfn){
int i;
int slice_filetype;
slicedata *sd;
if(glui_defined==0)return;
if(sfn<0){
UpdateSliceFilenum();
sfn=slicefilenum;
}
if(sfn < 0)return;
sd = sliceinfo+sfn;
slice_filetype = GetSliceBoundsIndex(sd);
if(slice_filetype>=0&&slice_filetype<nslicebounds){
i = slice_filetype;
RADIO_slice->set_int_val(i);
SliceBounds2Glui(i);
list_slice_index=i;
SliceBoundCB(SETVALMIN);
SliceBoundCB(SETVALMAX);
SliceBoundCB(VALMIN);
SliceBoundCB(VALMAX);
SliceBoundCB(SETCHOPMINVAL);
SliceBoundCB(SETCHOPMAXVAL);
SliceBoundCB(CHOPVALMIN);
SliceBoundCB(CHOPVALMAX);
if(nzoneinfo>0){
if(strcmp(slicebounds[i].shortlabel, "TEMP")==0){
BoundRolloutCB(ZONE_ROLLOUT);
if(ROLLOUT_slice_bound!=NULL)ROLLOUT_slice_bound->disable();
}
else{
if(ROLLOUT_slice_bound!=NULL)ROLLOUT_slice_bound->enable();
}
}
}
}
/* ------------------ UpdateGlui ------------------------ */
extern "C" void UpdateGlui(void){
GLUI_Master.sync_live_all();
}
/* ------------------ ShowGluiBounds ------------------------ */
extern "C" void ShowGluiBounds(int menu_id){
if(menu_id==DIALOG_BOUNDS){
if(nsliceinfo>0){
int islice;
islice=RADIO_slice->get_int_val();
SliceBounds2Glui(islice);
SliceBoundCB(SETVALMIN);
SliceBoundCB(SETVALMAX);
SliceBoundCB(VALMIN);
SliceBoundCB(VALMAX);
}
if(npatchinfo>0){
int ipatch;
if(RADIO_bf == NULL){
ipatch = list_patch_index;
}
else {
ipatch = RADIO_bf->get_int_val();
}
Global2LocalBoundaryBounds(patchlabellist[ipatch]);
BoundBoundCB(SETVALMIN);
BoundBoundCB(SETVALMAX);
}
if(npartinfo>0&&npartinfo!=nevac){
PartBoundCB(SETVALMIN);
PartBoundCB(SETVALMAX);
}
if(nplot3dinfo>0){
Plot3DBoundCB(SETVALMIN);
Plot3DBoundCB(SETVALMAX);
}
if(nsliceinfo>0||npatchinfo>0)UpdateGlui();
UpdateChar();
FileRolloutCB(FILEBOUNDS_ROLLOUT);
}
else if(menu_id == DIALOG_SHOWFILES){
FileRolloutCB(SHOWHIDE_ROLLOUT);
}
else if(menu_id==DIALOG_CONFIG){
FileRolloutCB(CONFIG_ROLLOUT);
}
else if(menu_id==DIALOG_AUTOLOAD){
FileRolloutCB(LOAD_ROLLOUT);
}
else if(menu_id==DIALOG_TIME){
FileRolloutCB(TIME_ROLLOUT);
}
else if(menu_id==DIALOG_SCRIPT){
FileRolloutCB(SCRIPT_ROLLOUT);
}
else if(menu_id == DIALOG_SMOKEZIP){
FileRolloutCB(COMPRESS_ROLLOUT);
}
else if(menu_id == DIALOG_3DSMOKE){
FileRolloutCB(FILEBOUNDS_ROLLOUT);
BoundRolloutCB(SMOKE3D_ROLLOUT);
}
glui_bounds->show();
}
/* ------------------ ShowBoundsDialog ------------------------ */
extern "C" void ShowBoundsDialog(int type){
ShowGluiBounds(DIALOG_3DSMOKE);
switch (type){
case DLG_3DSMOKE:
if(ROLLOUT_smoke3d!=NULL)ROLLOUT_smoke3d->open();
break;
case DLG_BOUNDARY:
if(ROLLOUT_bound!=NULL)ROLLOUT_bound->open();
break;
case DLG_SLICE:
if(ROLLOUT_slice != NULL)ROLLOUT_slice->open();
break;
case DLG_PART:
if(ROLLOUT_part!=NULL)ROLLOUT_part->open();
break;
case DLG_PLOT3D:
if(ROLLOUT_plot3d!=NULL)ROLLOUT_plot3d->open();
break;
case DLG_ISO:
if(ROLLOUT_iso!=NULL)ROLLOUT_iso->open();
break;
}
}
/* ------------------ EnableBoundaryGlui ------------------------ */
extern "C" void EnableBoundaryGlui(void){
ROLLOUT_boundary_bound->enable();
}
/* ------------------ DisableBoundaryGlui ------------------------ */
extern "C" void DisableBoundaryGlui(void){
ROLLOUT_boundary_bound->disable();
}
/* ------------------ UpdateOverwrite ------------------------ */
extern "C" void UpdateOverwrite(void){
if(CHECKBOX_overwrite_all!=NULL)CHECKBOX_overwrite_all->set_int_val(overwrite_all);
if(CHECKBOX_compress_autoloaded!=NULL)CHECKBOX_compress_autoloaded->set_int_val(compress_autoloaded);
}
/* ------------------ HideGluiBounds ------------------------ */
extern "C" void HideGluiBounds(void){
CloseRollouts(glui_bounds);
}
/* ------------------ UpdateVectorWidgets ------------------------ */
extern "C" void UpdateVectorWidgets(void){
Plot3DBoundCB(UPDATE_VECTOR_FROM_SMV);
SliceBoundCB(UPDATE_VECTOR_FROM_SMV);
}
/* ------------------ UpdatePlot3dDisplay ------------------------ */
extern "C" void UpdatePlot3dDisplay(void){
if(RADIO_plot3d_display!=NULL)RADIO_plot3d_display->set_int_val(contour_type);
}
/* ------------------ UpdateGluiTimeBounds ------------------------ */
extern "C" void UpdateGluiTimeBounds(float time_min, float time_max){
if(SPINNER_timebounds!=NULL){
SPINNER_timebounds->set_float_limits(time_min,time_max);
}
}
/* ------------------ UpdateTBounds ------------------------ */
extern "C" void UpdateTBounds(void){
settmin_p=use_tload_begin;
settmax_p=use_tload_end;
tmin_p=tload_begin;
tmax_p=tload_end;
settmin_s=use_tload_begin;
settmax_s=use_tload_end;
tmin_s=tload_begin;
tmax_s=tload_end;
settmin_i=use_tload_begin;
settmax_i=use_tload_end;
tmin_i=tload_begin;
tmax_i=tload_end;
settmin_s=use_tload_begin;
settmax_s=use_tload_end;
tmin_s=tload_begin;
tmax_s=tload_end;
settmin_b=use_tload_begin;
settmax_b=use_tload_end;
tmin_b=tload_begin;
tmax_b=tload_end;
if(use_tload_skip==1){
smoke3dframeskip=tload_skip;
boundframeskip=tload_skip;
isoframeskip_global=tload_skip;
partframeskip=tload_skip;
evacframeskip=tload_skip;
sliceframeskip=tload_skip;
}
else{
smoke3dframeskip=0;
boundframeskip=0;
isoframeskip_global=0;
partframeskip=0;
evacframeskip=0;
sliceframeskip=0;
}
Smoke3dBoundCB(FRAMELOADING);
BoundBoundCB(FRAMELOADING);
IsoBoundCB(FRAMELOADING);
PartBoundCB(FRAMELOADING);
SliceBoundCB(FRAMELOADING);
}
/* ------------------ UpdateShowHideButtons ------------------------ */
extern "C" void UpdateShowHideButtons(void){
// if(CHECKBOX_label_3 != NULL){
// CHECKBOX_label_3->set_int_val(hide_overlaps);
// }
if(BUTTON_PART != NULL){
if(npartloaded == 0){
BUTTON_PART->disable();
}
else{
BUTTON_PART->enable();
}
}
if(BUTTON_SLICE != NULL){
if(nsliceloaded == 0){
BUTTON_SLICE->disable();
}
else{
BUTTON_SLICE->enable();
}
}
if(BUTTON_VSLICE != NULL){
if(nvsliceloaded == 0){
BUTTON_VSLICE->disable();
}
else{
BUTTON_VSLICE->enable();
}
}
if(BUTTON_ISO != NULL){
if(nisoloaded == 0){
BUTTON_ISO->disable();
}
else{
BUTTON_ISO->enable();
}
}
if(BUTTON_BOUNDARY != NULL){
if(npatchloaded == 0){
BUTTON_BOUNDARY->disable();
}
else{
BUTTON_BOUNDARY->enable();
}
}
if(BUTTON_3DSMOKE != NULL){
if(nsmoke3dloaded == 0){
BUTTON_3DSMOKE->disable();
}
else{
BUTTON_3DSMOKE->enable();
}
}
if(BUTTON_PLOT3D != NULL){
if(nplot3dloaded == 0){
BUTTON_PLOT3D->disable();
}
else{
BUTTON_PLOT3D->enable();
}
}
if(nplot3dloaded == 0 && nsmoke3dloaded == 0 && nisoloaded == 0 && nsliceloaded == 0 && npartloaded == 0 && npatchloaded == 0){
if(RADIO_showhide != NULL)RADIO_showhide->disable();
}
else{
if(RADIO_showhide != NULL)RADIO_showhide->enable();
}
}
| [
"gforney@gmail.com"
] | gforney@gmail.com |
0a8d0c5f43de3e158b8b30a11f0481d08555c1c6 | cf7ca00bb9f94f2056694a8e3705298ccf6932be | /BullsCar/BullsCar.h | 6982bf0c7da4337d709b90c4b4ace97b1b3b87e1 | [] | no_license | bullseye73/BullsCar | fd6c908dcf4311d65c51c58bef0738322bd766cf | ae6ef030c05e0dbf6e2730b39ea835376a9f0ee7 | refs/heads/master | 2021-01-13T01:44:58.453058 | 2012-07-12T04:21:53 | 2012-07-12T04:21:53 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 574 | h | // BullsCar.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다.
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다."
#endif
#include "resource.h" // 주 기호입니다.
// CBullsCarApp:
// 이 클래스의 구현에 대해서는 BullsCar.cpp을 참조하십시오.
//
class CBullsCarApp : public CWinApp
{
public:
CBullsCarApp();
// 재정의입니다.
public:
virtual BOOL InitInstance();
// 구현입니다.
DECLARE_MESSAGE_MAP()
};
extern CBullsCarApp theApp; | [
"bullseye73@gmail.com"
] | bullseye73@gmail.com |
14eb291d9292b611bfa31ff40cf404015b45f3fe | 90ee7e3223f1a57442c41326e5b6a4f54bf8908f | /original_content/myutil/log.cpp | 1368bb36dee748e489f512f4a1c3b91d0a46cb8f | [] | no_license | ThomasPf/Tor-Bandwidth-Fingerprinting | 7e08c51fbc6dbafa9e68600e5e5a3f433cb9a4e2 | 05344b27ec21d5c6864bd89a0a318360b82b7eb0 | refs/heads/master | 2020-04-11T08:07:49.945181 | 2019-01-31T17:09:34 | 2019-01-31T17:09:34 | 161,632,839 | 1 | 0 | null | 2018-12-13T11:59:59 | 2018-12-13T11:59:59 | null | UTF-8 | C++ | false | false | 162 | cpp | #include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include "log.h"
using namespace std;
void LOG(FILE* fp, char* msg)
{
fprintf(fp, "%s\n", msg);
}
| [
"nikita@illinois.edu"
] | nikita@illinois.edu |
4c42b874c87dddc3453d03b11192363bb94ea4f2 | 5908c584b22d8f152deeb4082ff6003d841deaa9 | /Physics_RT/Havok/Source/Physics2012/Collide/Agent3/Machine/1n/hkpCpuDoubleContainerIterator.h | 50205542816ad2b758c581dcb66ee75bf38ee5ae | [] | no_license | imengyu/Physics_RT | 1e7b71912e54b14679e799e7327b7d65531811f5 | b8411b4bc483d6ce5c240ae4c004f3872c64d073 | refs/heads/main | 2023-07-17T20:55:39.303641 | 2021-08-28T18:25:01 | 2021-08-28T18:25:01 | 399,414,182 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,869 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_DEFAULT_DOUBLE_BATCH_ITERATOR
#define HK_DEFAULT_DOUBLE_BATCH_ITERATOR
#include <Physics2012/Collide/Shape/hkpShape.h>
#include <Physics2012/Collide/Shape/hkpShapeContainer.h>
#include <Physics2012/Collide/Filter/hkpCollisionFilter.h>
class hkpCpuDoubleContainerIterator
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpCpuDoubleContainerIterator );
HK_FORCE_INLINE hkpCpuDoubleContainerIterator( const HK_SHAPE_CONTAINER* containerA, const HK_SHAPE_CONTAINER* containerB, const hkpShapeKeyPair* shapeKeys );
/// prepare iterator for being queried for getShapes and getShapeKeys
HK_FORCE_INLINE void update();
/// Return the current shape key.
HK_FORCE_INLINE hkpShapeKeyPair getShapeKeyPair();
/// Get the collision filter infos for the two child shapes.
HK_FORCE_INLINE hkBool isCollisionEnabled( const hkpProcessCollisionInput* input, const hkpCdBody* collectionBodyA, const hkpCdBody* collectionBodyB );
/// Set the body to have the current shape and shape key.
HK_FORCE_INLINE void setShapes( hkpCdBody& bodyA, hkpCdBody& bodyB );
/// Next time the update is called it should advance.
HK_FORCE_INLINE void advance();
public:
hkpShapeBuffer m_shapeBufferA;
hkpShapeBuffer m_shapeBufferB;
const HK_SHAPE_CONTAINER* m_containerA;
const HK_SHAPE_CONTAINER* m_containerB;
const hkpShapeKeyPair* m_shapeKeys;
hkpShapeKeyPair m_lastShapeKeyPair;
hkpShapeKey m_extractedShapeKeyA;
hkpShapeKey m_extractedShapeKeyB;
const hkpShape* m_extractedShapeA;
const hkpShape* m_extractedShapeB;
};
#include<Physics2012/Collide/Agent3/Machine/1n/hkpCpuDoubleContainerIterator.inl>
#endif // HK_DEFAULT_DOUBLE_BATCH_ITERATOR
/*
* Havok SDK - Base file, BUILD(#20131218)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
| [
"1501076885@qq.com"
] | 1501076885@qq.com |
54a7e3dbe590d3e3ba17c2d7ae8683a2990024c7 | f83af3ef220fc8dc7af0ab296a2cad8c8a92281f | /kody w cpp/sort_buble.cpp | dc0e733a70131d31ee850cefcf1570a602a8b2d7 | [] | no_license | mateusz0407/gitrepo | 57633ab9fe727c918ee92745f4f810729b4431e6 | 63acc31b8819adcb3e646bb42ba7b4389449ec16 | refs/heads/master | 2021-07-01T16:40:12.032709 | 2019-02-22T12:14:31 | 2019-02-22T12:14:31 | 103,923,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | cpp | #include <iostream>
#include <time.h>
using namespace std;
void wypelnij(int t[], int n, int max)
{
srand(time(NULL)); // pobieranie czasu od 1970 do teraz
for ( int i = 0; i < n; i++)
{
t[i] = rand()% max+1; // funkcja losująca liczbę
}
}
void drukuj(int t[], int n)
{
for ( int i = 0; i < n; i++)
{
cout << t[i] << " ";
}
cout << endl;
}
void zamien(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
void sort_bab(int tab[], int n)
{
// bubble sort
cout << " ------------- Sortowanie przez bąbelkowanie ---------------" << endl;
int i, j;
for(i = 0; i < n; i++)
{
for ( j = 0; j < n - 1 - i; j++)
{
if(tab[j] > tab[j + 1])
zamien(tab[j], tab[j + 1]);
}
}
}
int main(int argc, char **argv)
{
int ile = 10;
int tab[ile];
wypelnij(tab, ile, 20);
drukuj(tab, ile);
sort_bab(tab, ile);
drukuj(tab, ile);
return 0;
}
| [
"jackowskim2000@wp.pl"
] | jackowskim2000@wp.pl |
90cb2ca19c1f1b4513ab94cb390580e7dc5dad4c | d3bffcd475d0222184055752f278f49806e4f568 | /Sensor_calibration_w_Motor/Sensor_calibration_w_Motor.ino | 3addc0b514a8e72fe788b819d9e112d773958a2c | [] | no_license | derrickpehjh/CZ3004-Multidisciplinary-Design-Project | 806845c7853f0ff941d4815307efa9309106dbcd | 4c01bc4541f148c7a50ce20cf08088fcb48f8134 | refs/heads/master | 2021-09-09T19:12:34.448457 | 2018-03-19T04:49:47 | 2018-03-19T04:49:47 | 121,524,617 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,921 | ino | //import the library in the sketch
#include <DualVNH5019MotorShield.h>
#include <RunningMedian.h>
#include <EnableInterrupt.h>
DualVNH5019MotorShield md;
#define motor_encoder_left 3 //left motor
#define motor_encoder_right 11 //right motor
//the model of the short range sensor is "GP2Y0A21YK0F"
//The model of the long range sensor is "GP2Y0A20YK0F"
#define front_right_sensor_pin 0 //MDP BOARD PIN PS1
#define front_middle_sensor_pin 1 //MDP BOARD PIN PS2
#define front_left_sensor_pin 2 //MDP BOARD PIN PS3
#define left_front_sensor_pin 3 //MDP BOARD PIN PS4
#define left_back_sensor_pin 4 //MDP BOARD PIN PS5
#define right_front_long_range_sensor_pin 5 //MDP BOARD PIN PS6
#define motor_encoder_left 3 //left motor
#define motor_encoder_right 11 //right motor
#define small_delay_between_moves 30
#define small_delay_before_reading_sensor 30
#define small_delay_after_reading_sensor 20
#define small_delay_after_align 30
//---------------Declare variables--------------------------
String stringToSend, command;
char character;
volatile int encoder_R_value = 0 , encoder_L_value = 0 ;
int stringIndex, tickError, error, grids = 0;
bool explorationEnabled, fastestPathEnabled, rotateCheck = false;
void setup()
{
pinMode(motor_encoder_right, INPUT);
pinMode(motor_encoder_left, INPUT);
enableInterrupt(motor_encoder_left, LeftEncoderInc, CHANGE);
enableInterrupt(motor_encoder_right, RightEncoderInc, CHANGE);
Serial.begin(115200); //Enable the serial comunication
md.init();
}
/*----------------------------------------------
Commands from ALGO/RPI to Arduino:
F -> Move Forward
L -> Rotate Left
R -> Rotate Right
C -> Calibrate Robot before start(exploration/fastest path)
X -> Starts Fastest Path
Z -> Starts Exploration
A -> Checklists evaluation
----------------------------------------------*/
void loop()
{
while (Serial.available())
{
character = Serial.read();
if (character == '\n' || character == '\0') //Meaning end of line / no new line and indicates no further input received
break;
else {
command += character;
delay(4);//Else read in new commands received.
}
}
while (command.length() > stringIndex) //If there are any valid comments, perform/execute- operations on it.
{
while (command[stringIndex] != '\n' && command[stringIndex] != '\0') //While not end of string
{
switch (command[stringIndex]) //Switch-case multiple scenarios, handle diff poss scenario inputs.
{
case 'F': //Command to move forward 1 grid
{
// delay(small_delay_between_moves);
// gotWallThenAlign();
while (command[stringIndex] == 'F')
{
stringIndex++;
grids++;
}
stringIndex--;
moveForward(grids);
// delay(small_delay_before_reading_sensor);
gotWallThenAlign();
grids = 0;
break;
}
case 'L': //Command to move rotate left 90 degrees
{
//delay(small_delay_between_moves);
rotateCheck = true;
gotWallThenAlign();
delay(small_delay_before_reading_sensor);
rotateLeft();
delay(2000);
rotateCheck = false;
break;
}
case 'R': //Command to move rotate right 90 degrees //turns right when Front = 1 + Left=1 (LF=1 & LB =1), so cannot turn left as is default action, can only turn right. In this case, then yes, go Left wall that can check, so check alignment to front & left first before turning. Then aft turning depending on how much/deg of adjustment, align to wall again if not correct/accurate.
{
//delay(small_delay_between_moves);
rotateCheck = true;
gotWallThenAlign();
delay(small_delay_before_reading_sensor);
rotateRight();
delay(2000);
gotWallThenAlign();
rotateCheck = false;
break;
}
case 'C': //Command to callibrate robot before/after
{
calibrate();
break;
}
case 'A': //Read Sensors
{
// Serial.println(getMedianDistance(0, 1080));
// Serial.println(getMedianDistance(1, 1080));
// Serial.println(getMedianDistance(2, 1080));
// Serial.println(getMedianDistance(3, 1080));
// Serial.println(getMedianDistance(4, 1080));
// Serial.println(getMedianDistance(5, 20150));
readAllSensors();
break;
}
default:
{
break;
}
}
stringIndex++;
}
stringIndex++;
grids = 0;
}
stringIndex = 0;
command = "";
}
void moveForward(int gridss)
{
forward(25, 100);
forward(425 + 600 * (gridss - 1), 380);
md.setBrakes(400, 400);
forwardCorrection(535 + 600 * (gridss - 1)); //510 original
// Serial.print(encoder_L_value);
// Serial.print(" : ");
// Serial.println(encoder_R_value);
}
void forward(int value, int Speed)
{
resetEncoderValues();
if (Speed <= 100) {
while ( encoder_R_value < value || encoder_L_value < value ) {
tickError = 1 * tuneWithPID2();
md.setSpeeds(-(Speed - tickError), Speed + tickError); //lower the right motor speed
}
}
else {
while ( encoder_L_value < value || encoder_R_value < value ) {
// tickError = 3 * tuneWithPID(); // ORIGINAL
tickError = 5 * tuneWithPID();
md.setSpeeds(-(390 + tickError ), 360 - tickError ); //lower the right motor speed 397
}
}
}
void backward(int value, int Speed) {
resetEncoderValues();
while ( encoder_R_value < value || encoder_L_value < value ) {
tickError = 2 * tuneWithPID();
md.setSpeeds(Speed + tickError, -(Speed - tickError));
}
}
void forwardCorrection(int practicalValue) {
int Speed = 80;
while ( encoder_R_value < practicalValue && encoder_L_value < practicalValue ) {
tickError = 1 * tuneWithPID2();
md.setSpeeds(-(Speed - tickError), Speed + tickError);
delay(10);
md.setBrakes(400, 400);
delay(5);
}
md.setBrakes(400, 400);
while (encoder_L_value < practicalValue ) {
md.setSpeeds(-Speed, 0);
delay(10);
md.setBrakes(400, 400);
delay(5);
}
md.setBrakes(400, 400);
while (encoder_R_value < practicalValue) {
md.setSpeeds(0, Speed);
delay(10);
md.setBrakes(400, 400);
delay(5);
}
}
void rotateLeft()
{
left(722, 380); //620 380 ORIGINAL
md.setBrakes(400, 400);
// turnLeftCorrection(735); //741 ORIGINAL
// delay(small_delay_between_moves);
// forward(10, 80);
md.setBrakes(400, 400);
}
void rotateRight() //for exploration
{
right(726, 380); //647 380 ORIGINAL
md.setBrakes(400, 400);
// turnRightCorrection(739); //736 ORIGINAL
// delay(small_delay_between_moves);
// forward(10, 80);
md.setBrakes(400, 400);
}
void left(int encoderValue, int Speed) {
resetEncoderValues();
while (encoder_R_value < encoderValue || encoder_L_value < encoderValue) {
tickError = 5 * tuneWithPID();
md.setSpeeds((Speed + tickError), (Speed - tickError));
}
}
void turnLeftCorrection(int practicalValue) {
int Speed = 80;
while ( encoder_R_value < practicalValue && encoder_L_value < practicalValue ) {
tickError = 3 * tuneWithPID();
md.setSpeeds(Speed + tickError, (Speed - tickError) );
md.setBrakes(400, 400);
}
while (encoder_L_value < practicalValue ) {
md.setSpeeds(Speed, 0);
md.setBrakes(400, 400);
}
while (encoder_R_value < practicalValue) {
md.setSpeeds(0, Speed);
md.setBrakes(400, 400);
}
}
void right(int encoderValue, int Speed) {
resetEncoderValues();
while (encoder_R_value < encoderValue || encoder_L_value < encoderValue) {
tickError = 5 * tuneWithPID();
md.setSpeeds(-(Speed + tickError), -(Speed - tickError));
}
}
void turnRightCorrection(int practicalValue) {
int Speed = 80;
while ( encoder_R_value < practicalValue && encoder_L_value < practicalValue ) {
tickError = 3 * tuneWithPID();
md.setSpeeds(-(Speed + tickError), -(Speed - tickError) );
md.setBrakes(400, 400);
}
while (encoder_L_value < practicalValue ) {
md.setSpeeds(-Speed, 0);
md.setBrakes(400, 400);
}
while (encoder_R_value < practicalValue) {
md.setSpeeds(0, -Speed);
md.setBrakes(400, 400);
}
}
double tuneWithPID() {
error = encoder_R_value - encoder_L_value;
return error;
}
double tuneWithPID2() {
error = encoder_L_value - encoder_R_value;
return error;
}
void LeftEncoderInc() {
encoder_L_value++;
}
void RightEncoderInc() {
encoder_R_value++;
}
void resetEncoderValues() {
encoder_R_value = 0;
encoder_L_value = 0;
}
float readSensor(int IRpin, int model)
{
float sensorValue = analogRead(IRpin);
float distance;
if (model == 1080) //for 10-80cm sensor
distance = 4468.9 * pow(sensorValue, -0.959); // 10-80cm ~ formula
if (model == 20150) //for 20-150cm sensor
distance = 105812 * pow(sensorValue, -1.39275766016713); //20-150cm
return distance;
}
float getMedianDistance(int IRpin, int model)
{
RunningMedian samples = RunningMedian(21); //take 20 samples of sensor reading
for (int i = 0; i < 20; i ++)
samples.add(readSensor(IRpin, model)); //samples call readSensor() to read in sensor value
int median = samples.getMedian();
if (IRpin == front_right_sensor_pin)
{
median = median - 5;
if (median <= 14) return median - 1;
else if (median <= 23) return median;
else if (median <= 33) return median + 3;
}
if (IRpin == front_middle_sensor_pin)
{
median = median - 5;
if (median <= 14) return median - 1;
else if (median <= 23) return median - 1;
else if (median <= 33) return median ;
}
if (IRpin == front_left_sensor_pin)
{
median = median - 5;
if (median <= 14) return median - 1;
else if (median <= 23) return median;
else if (median <= 33) return median + 3;
}
if (IRpin == left_front_sensor_pin)
{
median = median - 5;
if (median <= 14) return median - 2;
else if (median <= 23) return median + 1;
else if (median <= 33) return median;
}
if (IRpin == left_back_sensor_pin)
{
median = median - 5;
if (median <= 14) return median - 1;
else if (median <= 23) return median - 1;
else if (median <= 33) return median + 2;
}
if (IRpin == right_front_long_range_sensor_pin)
{
median = median - 9;
if (median <= 16) return median + 4; //20
else if (median <= 27) return median + 4; //30
else if (median <= 35) return median + 6; //40
else if (median <= 38) return median + 13; //50
else if (median <= 45) return median + 18; //60
}
return median;
}
int getObstacleGridsAway(int pin, int type)
{
int distance = getMedianDistance(pin, type);
if (type == 1080)
{
if (distance < 12) return 1;
else if (distance < 23) return 2;
else if (distance < 33) return 3;
else return 0;
}
else
{
if (distance < 15) return 1;
else if (distance < 25) return 2;
else if (distance < 35) return 3;
else if (distance < 45) return 4;
else if (distance < 55) return 5;
else if (distance < 65) return 6;
else return 0;
}
}
//FR:FM:FL:LF:LB:R
void readAllSensors()
{
delay(small_delay_before_reading_sensor);
stringToSend += getObstacleGridsAway(front_right_sensor_pin, 1080);
stringToSend += ":";
stringToSend += getObstacleGridsAway(front_middle_sensor_pin, 1080);
stringToSend += ":";
stringToSend += getObstacleGridsAway(front_left_sensor_pin, 1080);
stringToSend += ":";
stringToSend += getObstacleGridsAway(left_front_sensor_pin, 1080);
stringToSend += ":";
stringToSend += getObstacleGridsAway(left_back_sensor_pin, 1080);
stringToSend += ":";
stringToSend += getObstacleGridsAway(right_front_long_range_sensor_pin, 20150);
Serial.println(stringToSend);
stringToSend = "";
}
void calibrate() {
gotWallThenAlign();
md.setBrakes(400, 400);
}
boolean frontCanAlign() {
if ( (getObstacleGridsAway(front_left_sensor_pin, 1080) == 1) && (getObstacleGridsAway(front_right_sensor_pin, 1080) == 1) )
return true;
else
return false;
}
boolean sideCanAlign() {
if ( (getObstacleGridsAway(left_front_sensor_pin, 1080) == 1) && (getObstacleGridsAway(left_back_sensor_pin, 1080) == 1) )
return true;
else
{
return false;
}
}
void gotWallThenAlign() { //function returns true if can align front or side, false if cannot align
if (sideCanAlign() || frontCanAlign()) {
delay(small_delay_before_reading_sensor);
if (sideCanAlign()) {
alignSideAngle();
}
if (frontCanAlign()) {
alignFrontAngle();
}
delay(small_delay_after_align);
}
}
void alignSideAngle() { //align left using motor
int Speed = 80; //speed that you want it to move left / right while adjusting
int sensorError;
int sensorErrorAllowance = 1;
resetEncoderValues();
while ( ( (sensorError = getMedianDistance(left_front_sensor_pin, 1080) - getMedianDistance(left_back_sensor_pin, 1080) ) <= -sensorErrorAllowance)) { //robot tilted left, turn right until acceptable error angle
tickError = 2 * tuneWithPID();
md.setSpeeds(-(Speed + tickError), -(Speed - tickError)); //turn right
}
md.setBrakes(400, 400);
delay(small_delay_between_moves);
resetEncoderValues();
while ( ( sensorError = getMedianDistance(left_front_sensor_pin, 1080) - getMedianDistance(left_back_sensor_pin, 1080) ) >= sensorErrorAllowance ) { //robot tilted right, turn left until acceptable error angle
tickError = 2 * tuneWithPID();
md.setSpeeds( Speed + tickError, (Speed - tickError)); //turn left
}
md.setBrakes(400, 400);
delay(small_delay_between_moves);
if ( rotateCheck == false) {
if ((getMedianDistance(left_front_sensor_pin, 1080) < 5 && getMedianDistance(left_back_sensor_pin, 1080) < 5) ||
((getMedianDistance(left_front_sensor_pin, 1080) > 6 && getMedianDistance(left_back_sensor_pin, 1080) > 6) && getMedianDistance(left_front_sensor_pin, 1080) < 10 && getMedianDistance(left_back_sensor_pin, 1080) < 10))
{
rotateLeft();
delay(small_delay_before_reading_sensor);
alignFrontAngle();
delay(small_delay_after_align);
rotateRight();
delay(small_delay_between_moves);
backward(10, 80);
}
}
md.setBrakes(400, 400);
}
void alignFrontAngle() {
int Speed = 80;
int sensorError;
int sensorErrorAllowance = 0;
resetEncoderValues();
while (sensorError = getMedianDistance(front_left_sensor_pin, 1080) - getMedianDistance(front_right_sensor_pin, 1080) > sensorErrorAllowance)
{
tickError = 2 * tuneWithPID();
md.setSpeeds(-(Speed + tickError), -(Speed - tickError));
}
md.setBrakes(400, 400);
delay(small_delay_between_moves);
resetEncoderValues();
while ( sensorError = getMedianDistance(front_left_sensor_pin, 1080) - getMedianDistance(front_right_sensor_pin, 1080 ) < sensorErrorAllowance ) { //robot tilted right, turn left until acceptable error angle
tickError = 2 * tuneWithPID();
md.setSpeeds( Speed + tickError, (Speed - tickError)); //turn left
}
md.setBrakes(400, 400);
delay(small_delay_between_moves);
while (getMedianDistance(front_middle_sensor_pin, 1080) < 6)
{
backward(1, 80);
}
md.setBrakes(400, 400);
delay(small_delay_between_moves);
while (getMedianDistance(front_middle_sensor_pin, 1080) > 6 && getMedianDistance(front_middle_sensor_pin, 1080) < 12)
{
forward(1, 80);
}
md.setBrakes(400, 400);
}
| [
"derrickpehjh@gmail.com"
] | derrickpehjh@gmail.com |
b05c5e0599481856ad5a3745b00819c245896c62 | 56f3588e16e4d0c85611cae296897b1a11dc61ad | /backjoon/stepbystep/32.dp3/1086.cpp | 34d17a6b88da7c441398ff968d7f1c8c348744a6 | [] | no_license | cjswoduddn/algorithm-master | 24739f7481d4b51c03778181173a60faef09654a | 1be36ca27e2481fae905cb887dac7f9f373f0c7f | refs/heads/main | 2023-04-01T04:15:25.669272 | 2021-04-04T05:09:21 | 2021-04-04T05:09:21 | 336,210,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | cpp | #include<iostream>
#include<string>
#include<vector>
using namespace std;
typedef long long ll;
ll dp[100][1<<15];
vector<string> g;
vector<int> tenMOD(51);
vector<int> gMOD;
int N, MOD;
int mod(string& str){
int ret = 0;
int j = 0;
for(int i = str.size()-1; i >= 0; i--){
ret += ((str[j++]-'0')*tenMOD[i])%MOD;
ret %= MOD;
}
return ret;
}
ll recur(int m, int state){
if(state == (1<<N)-1){
if(m == 0) return 1;
return 0;
}
ll& ret = dp[m][state];
if(ret != -1) return ret;
ret = 0;
for(int i = 0; i < N; i++){
int bit = 1<<i;
if((state&bit) != 0) continue;
int nm = ((m*tenMOD[g[i].size()])%MOD+gMOD[i])%MOD;
ret += recur(nm, state|bit);
}
return ret;
}
ll GCD(ll a, ll b){
if(b == 0) return a;
return GCD(b, a%b);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
g.resize(N);
gMOD.resize(N);
for(int i = 0; i < N; i++){
cin >> g[i];
}
cin >> MOD;
tenMOD[0] = 1;
for(int i = 0; i < 100; i++){
for(int j = 0; j < (1<<N); j++)
dp[i][j] = -1;
}
for(int i = 1; i < 51; i++)
tenMOD[i] = (tenMOD[i-1]*10)%MOD;
for(int i = 0; i < N; i++)
gMOD[i] = mod(g[i]);
ll child = recur(0, 0);
ll parent = 1;
for(int i = 1; i <= N; i++)
parent *= i;
ll gcd = GCD(child, parent);
child /= gcd;
parent /= gcd;
printf("%lld/%lld\n", child, parent);
return 0;
}
| [
"cjswoudddn@naver.com"
] | cjswoudddn@naver.com |
db296cacdcc83000e8b02bc67d29f3818c4ba3dd | 903ce2f7bf92b605b986b74fc1a8d8c2b0052e62 | /utilsJsonFS.h | eb0f9cb64597227c901cd73f4e8e282fc4210352 | [] | no_license | juanpc13/ESP32_Reloj | a242a83e74c723dea2f82386a68c157b34844e02 | 6e45ede2668a4c1a25d459194dfa7f927843e7de | refs/heads/master | 2020-04-09T06:42:08.926499 | 2018-12-14T20:37:17 | 2018-12-14T20:37:17 | 160,123,767 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,214 | h | #include <ArduinoJson.h>
class utilsJsonFS {
private:
utilsSPIFFS _uFS;
String _dataFilePath;
public:
void begin(utilsSPIFFS u) {
_uFS = u;
}
void dataFileTarget(String f) {
_dataFilePath = f;
if (!_uFS.fileExits(_dataFilePath)) {
Serial.print("No File ");
Serial.print(_dataFilePath);
} else {
Serial.print("File ");
Serial.print(_dataFilePath);
Serial.print(" Found...Using File");
}
Serial.println();
}
String getJsonDataFileNamed(String name) {
if (_uFS.fileExits(_dataFilePath)) {
String json = _uFS.readFile(_dataFilePath);
DynamicJsonDocument doc;
deserializeJson(doc, json);
JsonObject object = doc.as<JsonObject>();
JsonVariant property = object.get(name);
return property.as<String>();
} else {
Serial.println("File not Exits");
return "";
}
}
void editJsonDataFileNamed(String name, String value) {
if (_uFS.fileExits(_dataFilePath)) {
String json = _uFS.readFile(_dataFilePath);
DynamicJsonDocument doc;
deserializeJson(doc, json);
JsonObject root = doc.as<JsonObject>();
JsonVariant property = root.get(name);
if (!property.isNull()) {
property.set(value);
json = "";
serializeJson(root, json);
//serializeJsonPretty(root, json);
if (_uFS.writeFile(_dataFilePath, json)) {
Serial.print("done");
}
}else{
Serial.print("property to edit not found");
}
} else {
Serial.print("File not Exits");
}
Serial.println();
}
String getPasswordFromJsonFile(String wifiName) {
if (_uFS.fileExits(_dataFilePath)) {
String json = getJsonDataFileNamed("wifiList");
DynamicJsonDocument doc;
deserializeJson(doc, json);
// extract the values
JsonArray array = doc.as<JsonArray>();
for (JsonVariant v : array) {
String wifiJson = v.as<String>();
StaticJsonDocument<64> w;
deserializeJson(w, wifiJson);
JsonObject wifi = w.as<JsonObject>();
JsonVariant ssid = wifi.get("ssid");
JsonVariant password = wifi.get("password");
if (!ssid.isNull() && !password.isNull()) {
if (ssid.as<String>() == wifiName) {
return password.as<String>();
}
}
}
} else {
Serial.println("File not Exits");
}
return "";
}
void addWifiJsonFile(String ssid, String password){
if (_uFS.fileExits(_dataFilePath)) {
String json = getJsonDataFileNamed("wifiList");
DynamicJsonDocument doc;
deserializeJson(doc, json);
// extract the values
JsonArray wifiList = doc.as<JsonArray>();
JsonObject wifi = wifiList.createNestedObject();
wifi["ssid"] = ssid;
wifi["password"] = password;
json = "";
serializeJson(wifiList, json);
editJsonDataFileNamed("wifiList",json);
}else{
Serial.println("File not Exits");
}
}
};
| [
"juanpc13lolol@gmail.com"
] | juanpc13lolol@gmail.com |
7873fe4f92febef606db421d738298c22d8993bd | afa9fcd0f2443515ba89e96ed4eb9416e9d11847 | /include/GafferBindings/CompoundDataPlugBinding.h | 38833a511049ab339d779bf140557740bc0ca0fe | [
"BSD-3-Clause"
] | permissive | dneg/gaffer | 6eb12b3ab3cde00afdf170c456969a38f5968237 | e87cb50f55a048cd7f6d5dcdfe6f95e38db2c5b6 | refs/heads/master | 2021-01-16T18:13:33.456876 | 2013-09-24T17:23:58 | 2013-09-24T17:23:58 | 13,094,917 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | h | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef GAFFERBINDINGS_COMPOUNDDATAPLUGBINDING_H
#define GAFFERBINDINGS_COMPOUNDDATAPLUGBINDING_H
namespace GafferBindings
{
void bindCompoundDataPlug();
} // namespace GafferBindings
#endif // GAFFERBINDINGS_COMPOUNDDATAPLUGBINDING_H
| [
"thehaddonyoof@gmail.com"
] | thehaddonyoof@gmail.com |
4ca71b179e6dea04489456f18219861347794043 | bc4e54400d03b2adb57b683d3141e39c7a4dbe2b | /RayTracing/Project1/ReadInput.h | 44aaa6ee86bb5c780d9182cd41ad7d61db331020 | [] | no_license | mephistia/RayTracingCGA | 43192709de3881f2f962fdd5bd741ab30f10177b | 2e7cc0fb2c6ba1b33a9c3533d064865457254f70 | refs/heads/master | 2022-06-13T17:58:20.709568 | 2020-05-06T18:04:24 | 2020-05-06T18:04:24 | 255,691,499 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,200 | h |
#ifndef READINPUT_H
#define READINPUT_H
#include "Utilities.h"
#include "Camera.h"
#include "Metal.h"
#include "Lambertian.h"
#include "Dielectric.h"
#include "Sphere.h"
#include "HittableList.h"
class ReadInput
{
public:
ReadInput() {}
~ReadInput() {}
ReadInput(std::string filename) {
// abrir arquivo
inputFile = std::ifstream(filename);
if (inputFile.is_open()) {
// Pré-requisito: as configs estão em formato correto
// Largura e altura da imagem, antialiasing
inputFile >> imgWidth >> imgHeight >> antialiasing;
std::cerr << imgWidth << " " << imgHeight << " " << antialiasing << "\n";
// Calcular Aspect Ratio
aspectRatio = float(imgWidth) / imgHeight;
// vetor lookfrom
char X[100], Y[100], Z[100];
inputFile >> X >> Y >> Z;
std::cerr << (float)atof(X) << " " << (float)atof(Y) << " " << (float)atof(Z) << "\n";
lookfrom = glm::vec3((float)atof(X), (float)atof(Y), (float)atof(Z));
// vetor lookat
inputFile >> X >> Y >> Z;
std::cerr << (float)atof(X) << " " << " " << (float)atof(Y) << " " << (float)atof(Z) << "\n";
lookat = glm::vec3((float)atof(X), (float)atof(Y), (float)atof(Z));
// outras configs da câmera
char data[100];
inputFile >> data;
distFocus = (float)atof(data);
inputFile >> data;
aperture = (float)atof(data);
inputFile >> data;
fov = (float)atof(data);
std::cerr << distFocus << " " << aperture << " " << fov << "\n";
// É Ray Tracing? (0 ou 1)
inputFile >> rayTracing;
std::cerr << rayTracing << "\n";
// para Ray Tracing, existe um valor de max depth no arquivo
if (rayTracing)
inputFile >> maxDepth;
else
maxDepth = 2;
std::cerr << maxDepth << "\n";
// Qtd de esferas para ler
inputFile >> spheresCount;
std::cerr << spheresCount << "\n";
for (int i = 0; i < spheresCount; i++) {
// posição da esfera, raio e material
inputFile >> X >> Y >> Z;
inputFile >> data;
r = (float)atof(data);
inputFile >> material;
position = glm::vec3((float)atof(X), (float)atof(Y), (float)atof(Z));
std::cerr << X << " " << Y << " " << Z << " " << r << " " << "\n";
// se possuir albedo
if (material != 'D') {
inputFile >> X >> Y >> Z;
albedo = glm::vec3((float)atof(X), (float)atof(Y), (float)atof(Z));
std::cerr << X << " " << Y << " " << Z;
// metal possui fuzz
if (material == 'M') {
inputFile >> data;
fuzz = (float)atof(data);
std::cerr << " " << fuzz << "\n";
// Se for Ray Casting, ignora e faz Lambert
if (!rayTracing) {
world.add(make_shared<Sphere>(position, r, make_shared<Lambertian>(albedo)));
}
else {
// adicionar Metal ao mundo
world.add(make_shared<Sphere>(position, r, make_shared<Metal>(albedo, fuzz)));
}
std::cerr << "Sphere " << i << " done!\n";
}
else {
// adicionar Lambert ao mundo
world.add(make_shared<Sphere>(position, r, make_shared<Lambertian>(albedo)));
std::cerr << "Sphere " << i << " done!\n";
}
}
else {
// Se for vidro (dielétrico)
inputFile >> data; // Lê índice de refração
ref = (float)atof(data);
std::cerr << " " << ref << "\n";
// se for Ray Casting, ignora o D
if (!rayTracing) {
material = 'L';
albedo = glm::vec3(0.5f, 0.5f, 0.5f);
world.add(make_shared<Sphere>(position, r, make_shared<Lambertian>(albedo)));
std::cerr << "Sphere " << i << " done!\n";
}
else
world.add(make_shared<Sphere>(position, r, make_shared<Dielectric>(ref)));
std::cerr << "Sphere " << i << " done!\n";
}
}
// Criar esferas lambert random?
inputFile >> createRandomSpheres;
std::cerr << createRandomSpheres << "\n";
if (createRandomSpheres) {
inputFile >> randomSpheres;
std::cerr << randomSpheres << "\n";
for (int i = 0; i < randomSpheres; i++) {
glm::vec3 center;
do {
center = glm::vec3(random_float(-5,5), 0.2, random_float(-5,5));
} while (!((center - glm::vec3(2.0, 0.2, 0)).length() > 1));
albedo = randomVec() * randomVec();
// Adiciona apenas Lambertian se for Ray Casting
if (!rayTracing) {
world.add(
make_shared<Sphere>(center, 0.2, make_shared<Lambertian>(albedo)));
}
// Se não, sorteia material
else {
std::vector<int> randomMat = { 0,1,2 };
int mat = *Choose(randomMat.begin(), randomMat.end());
if (mat == 0) {
world.add(
make_shared<Sphere>(center, 0.2, make_shared<Lambertian>(albedo)));
}
else if (mat == 1) {
fuzz = random_float(0, .5f);
world.add(make_shared<Sphere>(center, 0.2, make_shared<Metal>(albedo, fuzz)));
}
else {
world.add(make_shared<Sphere>(center, 0.2, make_shared<Dielectric>(1.5)));
}
}
std::cerr << "Random Sphere " << i << " done!\n";
}
}
inputFile.close();
}
// Depois de ler o arquivo, world pode ser chamado
std::cerr << "Done reading file.\n";
}
template<typename Iter, typename RandomGenerator>
Iter Choose(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(g));
return start;
}
template<typename Iter>
Iter Choose(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return Choose(start, end, gen);
}
HittableList getWorld(){
return world;
}
Camera getCam(){
vup = glm::vec3(0.f, 1.f, 0.f);
Camera cam(lookfrom, lookat, vup, fov, aspectRatio, aperture, distFocus);
return cam;
}
int getWidth(){
return imgWidth;
}
int getHeight(){
return imgHeight;
}
int getMaxDepth(){
return maxDepth;
}
int getSamples(){
return antialiasing;
}
private:
int imgWidth, imgHeight, antialiasing, maxDepth, spheresCount, randomSpheres, fov, r;
bool createRandomSpheres;
bool rayTracing;
float distFocus, aperture, aspectRatio, fuzz, ref;
HittableList world;
glm::vec3 lookfrom;
glm::vec3 lookat;
glm::vec3 vup;
glm::vec3 position;
glm::vec3 albedo;
std::ifstream inputFile;
char material;
};
#endif | [
"39158254+mephistia@users.noreply.github.com"
] | 39158254+mephistia@users.noreply.github.com |
1adebe1ab5d02cb560655240ea21cc9a05848368 | 799e4351abb801105f1b3c86cfa97a944b6117b4 | /Classes/DataManage/MoneyManager.h | d13e2fe06ad8ce7c3453dc29610e44a60bd7b450 | [] | no_license | wu736139669/SmallGame_Cocos2dx | e53d5315718a111c1944b6a2d28ba9c9b60b8268 | bfe1a8fbd10eec78830e01d1dbcc4ca8f470e667 | refs/heads/master | 2021-01-19T16:51:22.475515 | 2015-07-01T03:34:15 | 2015-07-01T03:34:15 | 23,140,682 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | h |
#ifndef MONEY_MANAGER_H
#define MONEY_MANAGER_H
#include "cocos2d.h"
#include <string>
#include "Singleton.h"
#include "JsonHelper.h"
#include "ComData.h"
enum e_ExchangeId {
DiamondToGold_1 = 1,
DiamondToGold_2,
DiamondToGold_3,
DiamondToGold_4,
DiamondToGold_5,
GoldToRice_1,
GoldToRice_2,
GoldToRice_3,
GoldToRice_4,
GoldToRice_5,
RMBToDiamond_1,
RMBToDiamond_2,
RMBToDiamond_3,
RMBToDiamond_4,
RMBToDiamond_5,
};
class CBasePacket;
struct SMoneySysChgTempData
{
int ExchangeId;
std::string ExchangeName;
int ExchangeFromID;
int ExchangeFromValue;
int ExchangeToID;
int ExchangeToValue;
};
typedef std::vector<SMoneySysChgTempData> VEC_MEONEYSYSCHGTEMPDATA;
class CMoneyMan :public CSingleton<CMoneyMan>,public ILoadTempData
{
public:
CMoneyMan();
~CMoneyMan();
public:
VEC_MEONEYSYSCHGTEMPDATA& getMoneyChgTmpData(){return mVecMoneyChgTempData;};
void parseNetData(CBasePacket* pBasePacket);
SMoneySysChgTempData* getChgTempData(int nId);
virtual void reset();
//////////////////////////////////////////////////////////////////////////
//网络请求
void RequestGetMoneyTmpInfo();//请求货币兑换模板数据
//////////////////////////////////////////////////////////////////////////
virtual void updataTemplateData(const char* p);
protected:
VEC_MEONEYSYSCHGTEMPDATA mVecMoneyChgTempData;
};
#endif
| [
"736139669@qq.com"
] | 736139669@qq.com |
b6a05b1f9ae91129d695c41483359374f7981068 | 04fde8a09465f91bb95c407192a8ac6efe1ddf6a | /lab_01/density_distr/threads_stop_indicator.cpp | f8a0273a3658a7cb9eb05f702d4e4b3ffeaf4bc9 | [] | no_license | adv-dev-22/mm_ii | 235f11598385cfa72a491b09af6ab2141e6c607a | 1b36f027e86cd6f36417898740d6d8bdc4101cae | refs/heads/master | 2021-03-01T11:18:32.021677 | 2020-03-23T05:45:54 | 2020-03-23T05:45:54 | 245,780,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | cpp | #include "threads_stop_indicator.h"
#include <QMutex>
#include <QDebug>
ThreadsStopIndicator::ThreadsStopIndicator(QObject *parent):
QObject(parent),
total_number_(0),
current_number_(0) {
}
void ThreadsStopIndicator::set_number(size_t number) {
total_number_ = number;
}
void ThreadsStopIndicator::drop_counter() noexcept {
current_number_ = 0;
}
void ThreadsStopIndicator::checkout() {
qDebug() << " checkout worked ";
QMutex mutex;
mutex.lock();
++current_number_;
if (total_number_ == current_number_) {
qDebug() << "emit signal threads are done with id = " << current_number_;
emit all_threads_are_done();
}
mutex.unlock();
}
// End of the file
| [
"a2nced.c0mputin9.lms.17551@yandex.ru"
] | a2nced.c0mputin9.lms.17551@yandex.ru |
6acab46274304c7213c15585c598822531e27f4a | 279c6c16e999c2b30afa8277d24c14964d695297 | /tests/tests/precision_loss_experiment.cc | e0c43bf1a8fbe25bb338d76ac055c793629b4a40 | [
"Apache-2.0"
] | permissive | maxim-masterov/qx-simulator | 39647a729c526a0b3f34a0a314fec22a0bac7c3c | 87c289427e2d1c9573d1164ada8ad05a261ccefb | refs/heads/develop | 2023-04-23T11:12:33.251832 | 2021-01-26T15:11:04 | 2021-01-26T15:11:04 | 345,998,757 | 0 | 2 | NOASSERTION | 2021-05-04T08:37:37 | 2021-03-09T12:29:58 | null | UTF-8 | C++ | false | false | 1,636 | cc | /**
* @file
* @author Nader KHAMMASSI - nader.khammassi@gmail.com
* @date 10-12-15
* @brief
*/
{
uint32_t n=4;
qx::qu_register reg(n);
println("[T]======== Precision Loss Experiment =========[T]");
println("[+] performance :");
n=8;
qx::qu_register r(n);
qx::qu_register ref(n);
qx::circuit p(n,"precision_loss_experiment");
uint32_t ng = 2048*64;
/*
for (uint32_t i=0; i<ng; i++)
{
//p.add(new qx::rx(0,0.12345));
//p.add(new qx::rz(0,0.12345));
//p.add(new qx::rz(0,-0.12345));
//p.add(new qx::rx(0,-0.12345));
//p.add(new qx::phase_shift(i%n)); // fidelity 1
//p.add(new qx::pauli_x(i%n)); // fidelity 1
//p.add(new qx::pauli_y(i%n)); // fidelity 1
p.add(new qx::hadamard(0)); // fidelity f(n_gates)
//p.add(new qx::hadamard(i%n)); // fidelity f(n_gates)
}
// for (uint32_t j=0; j<n; j++)
// p.add(new qx::hadamard(j));
*/
for (uint32_t i=0; i<200; i++)
{
for (uint32_t j=0; j<5000; j++)
{
p.add(new qx::hadamard(0)); // fidelity f(n_gates)
p.add(new qx::pauli_x(0)); // fidelity 1
//p.add(new qx::pauli_y(i%n)); // fidelity 1
}
//double predicted_fidelity = 1-0.000035*(ng/2048);
//println("[+] predicted fidelity : " << predicted_fidelity);
println("[+] circuit depth (gates) : " << (i*5000));
p.execute(r);
println("[>] fidelity : " << qx::fidelity(r,ref));
println("-------------------------------------------");
}
println("[T]============================================[T]");
}
| [
"nader.khammassi@gmail.com"
] | nader.khammassi@gmail.com |
a31feb041ea8ee15a34420a31c17d513192e345a | 39eb39e0794827f24ddb54df398a1353ef8d8d4c | /算法/3n_1/main.cpp | 3e7f21a9d8514a27e458aee6be6ca0ead8361b5b | [] | no_license | XiaoYunZi1001/ACM | c0acc02d7e2978113acfb69240f382a0f4bb3237 | 7e73a77202cede0044bf957372a123fb882e34fe | refs/heads/master | 2021-05-26T05:10:33.304180 | 2018-10-06T13:20:50 | 2018-10-06T13:20:50 | 127,531,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int a,b;
int run(int x)
{
if(x==1) return 1;
if(x&1) return run(x*3+1)+1;
else return run(x/2)+1;
}
int main()
{
while(scanf("%d%d",&a,&b)!=EOF)
{
int ans=0;
for(int x=min(a,b);x<=max(a,b);x++)
{
ans=max(ans,run(x));
}
cout<<a<<" "<<b<<" "<<ans<<endl;
}
return 0;
}
| [
"claire_hrz@qq.com"
] | claire_hrz@qq.com |
9ba9dc361b606534b8d58a611241a9353c10e7dd | fbf1762846a7b779b38740eabeeb7805ba79289e | /app/libs/ogre/OgreMain/include/OgreTagPoint.h | f8041d057d67a085621ac5fd941ed62a7987bb71 | [
"MIT"
] | permissive | litao1009/AndroidOgreTest | 8b591202515cfcc22d741d1c35da3ae9bf4a7bf4 | a339100e46631d45523c0a185a7e2ceaba89cc78 | refs/heads/master | 2020-06-14T18:04:32.390217 | 2019-04-17T07:03:52 | 2019-04-17T07:03:52 | 75,349,260 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,827 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __TagPoint_H_
#define __TagPoint_H_
#include "OgrePrerequisites.h"
#include "OgreOldBone.h"
#include "OgreMatrix4.h"
namespace Ogre {
/** \addtogroup Core
* @{
*/
/** \addtogroup Animation
* @{
*/
/** A tagged point on a skeleton, which can be used to attach entities to on specific
other entities.
@remarks
A Skeleton, like a Mesh, is shared between Entity objects and simply updated as required
when it comes to rendering. However there are times when you want to attach another object
to an animated entity, and make sure that attachment follows the parent entity's animation
(for example, a character holding a gun in his / her hand). This class simply identifies
attachment points on a skeleton which can be used to attach child objects.
@par
The child objects themselves are not physically attached to this class; as it's name suggests
this class just 'tags' the area. The actual child objects are attached to the Entity using the
skeleton which has this tag point. Use the Entity::attachMovableObjectToBone method to attach
the objects, which creates a new TagPoint on demand.
*/
class _OgreExport TagPoint : public OldBone
{
public:
TagPoint(unsigned short handle, Skeleton* creator);
virtual ~TagPoint();
Entity *getParentEntity(void) const;
MovableObject* getChildObject(void) const;
void setParentEntity(Entity *pEntity);
void setChildObject(MovableObject *pObject);
/** Tells the TagPoint whether it should inherit orientation from it's parent entity.
@param inherit If true, this TagPoint's orientation will be affected by
its parent entity's orientation. If false, it will not be affected.
*/
void setInheritParentEntityOrientation(bool inherit);
/** Returns true if this TagPoint is affected by orientation applied to the parent entity.
*/
bool getInheritParentEntityOrientation(void) const;
/** Tells the TagPoint whether it should inherit scaling factors from it's parent entity.
@param inherit If true, this TagPoint's scaling factors will be affected by
its parent entity's scaling factors. If false, it will not be affected.
*/
void setInheritParentEntityScale(bool inherit);
/** Returns true if this TagPoint is affected by scaling factors applied to the parent entity.
*/
bool getInheritParentEntityScale(void) const;
/** Gets the transform of parent entity. */
const Matrix4& getParentEntityTransform(void) const;
/** Gets the transform of this node just for the skeleton (not entity) */
const Matrix4& _getFullLocalTransform(void) const;
/** @copydoc Node::needUpdate */
void needUpdate(bool forceParentUpdate = false);
/** Overridden from Node in order to include parent Entity transform. */
void updateFromParentImpl(void) const;
/** @copydoc Renderable::getLights */
const LightList& getLights(void) const;
private:
Entity *mParentEntity;
MovableObject *mChildObject;
mutable Matrix4 mFullLocalTransform;
bool mInheritParentEntityOrientation;
bool mInheritParentEntityScale;
};
/** @} */
/** @} */
} //namespace
#endif//__TagPoint_H_
| [
"lee@lee.com"
] | lee@lee.com |
990b903fe2a22aaf300e96dce521b47a1248c5ce | eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86 | /Grade 10-12/2018 summer/二中集训/8.6 contest/t3/t3.cpp | d3a01e249d476a09a99078dd76894c517a9c7311 | [] | no_license | Orion545/OI-Record | 0071ecde8f766c6db1f67b9c2adf07d98fd4634f | fa7d3a36c4a184fde889123d0a66d896232ef14c | refs/heads/master | 2022-01-13T19:39:22.590840 | 2019-05-26T07:50:17 | 2019-05-26T07:50:17 | 188,645,194 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cassert>
#include<cmath>
#define ll long long
using namespace std;
inline int read(){
int re=0,flag=1;char ch=getchar();
while(ch>'9'||ch<'0'){
if(ch=='-') flag=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') re=(re<<1)+(re<<3)+ch-'0',ch=getchar();
return re*flag;
}
int n,a[110],now[110];
int main(){
n=read();int i,maxn=0,cnt=0;
for(i=1;i<=n;i++) a[i]=read(),maxn=max(maxn,a[i]),now[a[i]]++;
if(maxn%2){
for(i=maxn/2+1;i<=maxn;i++){
if(now[i]<2){
puts("Impossible");return 0;
}
}
now[maxn/2+1]-=2;
for(i=0;i<=maxn/2+1;i++){
if(now[i]){
puts("Impossible");return 0;
}
}
puts("Possible");
}
else{
if(!now[maxn/2]){
puts("Impossible");return 0;
}
now[maxn/2]--;
for(i=maxn/2+1;i<=maxn;i++){
if(now[i]<2){
puts("Impossible");return 0;
}
}
for(i=0;i<=maxn/2;i++){
if(now[i]){
puts("Impossible");return 0;
}
}
puts("Possible");
}
}
| [
"orion545@qq.com"
] | orion545@qq.com |
8c14bec138bfafa8ae46713f0d3a23f366b62e37 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/renderer/modules/xr/xr_reference_space_options.h | f579eb8b7c70fc2bf82e5e5e1dc53515604e46ac | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,866 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_REFERENCE_SPACE_OPTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_REFERENCE_SPACE_OPTIONS_H_
#include "third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
class MODULES_EXPORT XRReferenceSpaceOptions : public IDLDictionaryBase {
public:
static XRReferenceSpaceOptions* Create() { return MakeGarbageCollected<XRReferenceSpaceOptions>(); }
XRReferenceSpaceOptions();
virtual ~XRReferenceSpaceOptions();
bool hasSubtype() const { return !subtype_.IsNull(); }
const String& subtype() const {
return subtype_;
}
inline void setSubtype(const String&);
bool hasType() const { return !type_.IsNull(); }
const String& type() const {
return type_;
}
inline void setType(const String&);
v8::Local<v8::Value> ToV8Impl(v8::Local<v8::Object>, v8::Isolate*) const override;
void Trace(blink::Visitor*) override;
private:
String subtype_;
String type_;
friend class V8XRReferenceSpaceOptions;
};
void XRReferenceSpaceOptions::setSubtype(const String& value) {
subtype_ = value;
}
void XRReferenceSpaceOptions::setType(const String& value) {
type_ = value;
}
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_REFERENCE_SPACE_OPTIONS_H_
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
2511509414c10707a966ee855dc4a33f30f14a7b | 67c69c0b366a0335aceea2098ac09142c7ed5c3c | /libraries/RC/InputChannelToInputPipe.h | 1d774d247d1b0eb90fd65f0e12ad566094134c5e | [] | no_license | cooliscool/t5x | 593e72d9849d67cdd3d612bb5faf5f77ed3c4634 | 28c0aa13823c805ecd3d5cbfd7dd1451b199d8cb | refs/heads/master | 2020-05-16T09:04:40.172051 | 2015-04-01T06:23:10 | 2015-04-01T06:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,443 | h | #ifndef INC_RC_INPUTCHANNELTOINPUTPIPE_H
#define INC_RC_INPUTCHANNELTOINPUTPIPE_H
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** InputChannelToInputPipe.h
** Class copying from input channel buffer directly to input buffer
**
** Author: Daniel van den Ouden
** Project: ArduinoRCLib
** Website: http://sourceforge.net/p/arduinorclib/
** -------------------------------------------------------------------------*/
#include <inttypes.h>
#include <InputChannelProcessor.h>
#include <InputSource.h>
namespace rc
{
/*!
* \brief Class for copying from input channel directly to input
* \details Fetches input channel and puts it in input.
* \author Daniel van den Ouden
* \date Nov-2012
* \copyright Public Domain.
*/
class InputChannelToInputPipe : public InputChannelProcessor, public InputSource
{
public:
/*! \brief Constructs an InputChannelToInputPipe object
\param p_source Index to use as input channel source.
\param p_destination Index to use as input destination.*/
InputChannelToInputPipe(InputChannel p_source, Input p_destination);
/*! \brief Fetches input channel and writes input.*/
void apply() const;
};
} // namespace end
#endif // INC_RC_INPUTCHANNELTOINPUTPIPE_H
| [
"christian.konecny+GitHub@gmail.com"
] | christian.konecny+GitHub@gmail.com |
7e426d9aceebc767e917c798a7913d810af96cc5 | 0521201a036d74e54ca066c82ab8a5122359afb7 | /file_mng/file_managing.cpp | e7a592990ae8c7836c0c6a349091f53baabdad81 | [
"MIT"
] | permissive | quantumBytes/AED_classes | 6a643419b8b2be1c1d96511e6ba14a51f1195e53 | 8723db36f2524dccac34ec715028fdd02d72b1b2 | refs/heads/master | 2020-06-08T04:20:31.981127 | 2013-10-28T08:33:14 | 2013-10-28T08:33:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | cpp | #include "file_managing.h"
Word::Word() :
begin(0),
end(0)
{}
Word::Word(string &w, ifstream *f, p_seek _beg, p_seek _end) :
word(w),
file(f),
begin(_beg),
end(_end)
{}
void Word::setWord(string &_word) {
word = _word;
}
void Word::setBeginSeeker(p_seek _ini) {
begin = _ini;
}
void Word::setEndSeeker(p_seek _end) {
end = _end;
}
void Word::setSeekers(p_seek _ini, p_seek _end) {
begin = _ini;
end = _end;
}
string& Word::getWord() {
return word;
}
string Word::getDefinition() {
string a = "Definition";
return a;
}
| [
"elpumitaelias@gmail.com"
] | elpumitaelias@gmail.com |
761fdfeed59f0db8126075dd47b3a51a136b6ce9 | d4c720f93631097ee048940d669e0859e85eabcf | /third_party/blink/renderer/core/paint/ng/ng_text_painter_base.cc | afecde701ac16a533ffb638f29707bd4074163a6 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 3b920d87437d9293f654de1f22d3ea341e7a8b55 | refs/heads/webnn | 2023-03-21T03:20:15.377034 | 2023-01-25T21:19:44 | 2023-01-25T21:19:44 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 7,398 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/ng/ng_text_painter_base.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/layout/text_decoration_offset_base.h"
#include "third_party/blink/renderer/core/paint/applied_decoration_painter.h"
#include "third_party/blink/renderer/core/paint/box_painter_base.h"
#include "third_party/blink/renderer/core/paint/highlight_painting_utils.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/text_decoration_info.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/text_run_paint_info.h"
#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
namespace blink {
// We have two functions to paint text decorations, because we should paint
// text and decorations in following order:
// 1. Paint underline or overline text decorations
// 2. Paint text
// 3. Paint line through
void NGTextPainterBase::PaintUnderOrOverLineDecorations(
const NGTextFragmentPaintInfo& fragment_paint_info,
const TextDecorationOffsetBase& decoration_offset,
TextDecorationInfo& decoration_info,
TextDecorationLine lines_to_paint,
const PaintInfo& paint_info,
const TextPaintStyle& text_style,
const cc::PaintFlags* flags) {
// Updating the graphics context and looping through applied decorations is
// expensive, so avoid doing it if there are no decorations of the given
// |lines_to_paint|, or the only decoration was a ‘line-through’.
if (!decoration_info.HasAnyLine(lines_to_paint &
~TextDecorationLine::kLineThrough))
return;
GraphicsContext& context = paint_info.context;
GraphicsContextStateSaver state_saver(context);
// Updating Graphics Context for text only (kTextProperOnly),
// instead of the default text and shadows (kBothShadowsAndTextProper),
// because shadows will be painted by
// NGTextPainterBase::PaintUnderOrOverLineDecorationShadows.
UpdateGraphicsContext(context, text_style, state_saver,
ShadowMode::kTextProperOnly);
PaintUnderOrOverLineDecorationShadows(fragment_paint_info, decoration_offset,
decoration_info, lines_to_paint, flags,
text_style, context);
PaintUnderOrOverLineDecorations(fragment_paint_info, decoration_offset,
decoration_info, lines_to_paint, flags,
context);
}
void NGTextPainterBase::PaintUnderOrOverLineDecorationShadows(
const NGTextFragmentPaintInfo& fragment_paint_info,
const TextDecorationOffsetBase& decoration_offset,
TextDecorationInfo& decoration_info,
TextDecorationLine lines_to_paint,
const cc::PaintFlags* flags,
const TextPaintStyle& text_style,
GraphicsContext& context) {
if (text_style.shadow == nullptr)
return;
const ShadowList* shadow_list = text_style.shadow.get();
if (shadow_list == nullptr)
return;
for (const auto& shadow : shadow_list->Shadows()) {
const Color& color = shadow.GetColor().Resolve(text_style.current_color,
text_style.color_scheme);
// Detect when there's no effective shadow.
if (color.IsTransparent())
continue;
const gfx::Vector2dF& offset = shadow.Location().OffsetFromOrigin();
float blur = shadow.Blur();
DCHECK_GE(blur, 0);
const auto sigma = BlurRadiusToStdDev(blur);
context.BeginLayer(
1.0f, SkBlendMode::kSrcOver, nullptr, kColorFilterNone,
sk_make_sp<DropShadowPaintFilter>(
offset.x(), offset.y(), sigma, sigma, color.toSkColor4f(),
DropShadowPaintFilter::ShadowMode::kDrawShadowOnly, nullptr));
PaintUnderOrOverLineDecorations(fragment_paint_info, decoration_offset,
decoration_info, lines_to_paint, flags,
context);
context.EndLayer();
}
}
void NGTextPainterBase::PaintUnderOrOverLineDecorations(
const NGTextFragmentPaintInfo& fragment_paint_info,
const TextDecorationOffsetBase& decoration_offset,
TextDecorationInfo& decoration_info,
TextDecorationLine lines_to_paint,
const cc::PaintFlags* flags,
GraphicsContext& context) {
for (wtf_size_t i = 0; i < decoration_info.AppliedDecorationCount(); i++) {
decoration_info.SetDecorationIndex(i);
context.SetStrokeThickness(decoration_info.ResolvedThickness());
if (decoration_info.HasSpellingOrGrammerError() &&
EnumHasFlags(lines_to_paint, TextDecorationLine::kSpellingError |
TextDecorationLine::kGrammarError)) {
decoration_info.SetSpellingOrGrammarErrorLineData(decoration_offset);
// We ignore "text-decoration-skip-ink: auto" for spelling and grammar
// error markers.
AppliedDecorationPainter decoration_painter(context, decoration_info);
decoration_painter.Paint(flags);
continue;
}
if (decoration_info.HasUnderline() && decoration_info.FontData() &&
EnumHasFlags(lines_to_paint, TextDecorationLine::kUnderline)) {
decoration_info.SetUnderlineLineData(decoration_offset);
PaintDecorationUnderOrOverLine(fragment_paint_info, context,
decoration_info,
TextDecorationLine::kUnderline, flags);
}
if (decoration_info.HasOverline() && decoration_info.FontData() &&
EnumHasFlags(lines_to_paint, TextDecorationLine::kOverline)) {
decoration_info.SetOverlineLineData(decoration_offset);
PaintDecorationUnderOrOverLine(fragment_paint_info, context,
decoration_info,
TextDecorationLine::kOverline, flags);
}
}
}
void NGTextPainterBase::PaintDecorationUnderOrOverLine(
const NGTextFragmentPaintInfo& fragment_paint_info,
GraphicsContext& context,
TextDecorationInfo& decoration_info,
TextDecorationLine line,
const cc::PaintFlags* flags) {
AppliedDecorationPainter decoration_painter(context, decoration_info);
if (decoration_info.TargetStyle().TextDecorationSkipInk() ==
ETextDecorationSkipInk::kAuto) {
// In order to ignore intersects less than 0.5px, inflate by -0.5.
gfx::RectF decoration_bounds = decoration_info.Bounds();
decoration_bounds.Inset(gfx::InsetsF::VH(0.5, 0));
ClipDecorationsStripe(
fragment_paint_info,
decoration_info.InkSkipClipUpper(decoration_bounds.y()),
decoration_bounds.height(),
std::min(decoration_info.ResolvedThickness(),
kDecorationClipMaxDilation));
}
decoration_painter.Paint(flags);
}
} // namespace blink
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
df96359820991acbb50b6512a10da3b3a7735b43 | 85bcac5d7883f439fd040b10b8d3ce258dd7ade4 | /Mikudayo/SkinningPass.h | 24c364035387d56edd6d3ab9f937780a1e206514 | [
"MIT"
] | permissive | newpolaris/Mikudayo | f9effd73467065f98c20efce398ed0782901bb7f | f989697848bee0f2a45636758050620b2421e77a | refs/heads/master | 2023-02-03T10:59:39.513123 | 2020-12-23T08:36:04 | 2020-12-23T08:36:04 | 104,229,577 | 18 | 1 | MIT | 2019-02-18T16:20:26 | 2017-09-20T14:55:50 | C | UTF-8 | C++ | false | false | 194 | h | #pragma once
#include "RenderPass.h"
class SkinningPass : public RenderPass
{
public:
SkinningPass();
// Inherited from Visitor
virtual bool Visit( SceneNode& node ) override;
};
| [
"newpolaris@gmail.com"
] | newpolaris@gmail.com |
f1437c1af02637b67ea7afc694df782f70f02b60 | 3a5a3de780e8db9cc204088c6cd022355acf577e | /Platform/tests/os_tests.h | 3b0dab96cb0a505b3174f8b28f50d019701aa6a5 | [] | no_license | concubicycle/StuffSim | d849502df65056c1c6c3166fdfee3cb436bf876f | 2ece619a41c178429d234ced4897206b4d9d93fa | refs/heads/master | 2021-01-02T09:33:36.413360 | 2014-07-25T05:44:59 | 2014-07-25T05:44:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | h | #include <iostream>
#include <chrono>
#include <thread>
#include "ss_os.h"
void run_os_tests(StuffSim::StuffSimOS& os);
| [
"concubicyclestuffsim@gmail.com"
] | concubicyclestuffsim@gmail.com |
bd86f6abbc5bffb40af5a241f31832315ed9c06e | 710bd1abc201ac06a28b4e8c9385215a94be3440 | /src/backends/reference/workloads/RefSpaceToBatchNdWorkload.cpp | fb9811853666b7c98b5c650aef35f2760e105633 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mcharleb/armnn | 27caa0f28bc02d70ac4a88c0b74badbbf73db341 | afa4e3a489df01d7f3b4d0c3f0a89a5251976bd5 | refs/heads/master | 2020-05-04T16:47:05.575512 | 2019-04-02T10:41:45 | 2019-04-02T10:48:03 | 179,287,902 | 0 | 0 | null | 2019-04-03T12:43:12 | 2019-04-03T12:43:12 | null | UTF-8 | C++ | false | false | 948 | cpp | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "RefSpaceToBatchNdWorkload.hpp"
#include "SpaceToBatchNd.hpp"
#include "RefWorkloadUtils.hpp"
#include "TypeUtils.hpp"
namespace armnn
{
template<armnn::DataType DataType>
void RefSpaceToBatchNdWorkload<DataType>::Execute() const
{
using T = ResolveType<DataType>;
ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, GetName() + "_Execute");
const TensorInfo& inputInfo = GetTensorInfo(m_Data.m_Inputs[0]);
const TensorInfo& outputInfo = GetTensorInfo(m_Data.m_Outputs[0]);
const T* inputData = GetInputTensorData<T>(0, m_Data);
T* outputData = GetOutputTensorData<T>(0, m_Data);
SpaceToBatchNd(inputInfo, outputInfo, m_Data.m_Parameters, inputData, outputData);
}
template class RefSpaceToBatchNdWorkload<DataType::Float32>;
template class RefSpaceToBatchNdWorkload<DataType::QuantisedAsymm8>;
} //namespace armnn
| [
"nattapat.chaimanowong@arm.com"
] | nattapat.chaimanowong@arm.com |
e733c98f254e1ae12a762353e569c22f9961a06c | 7f2a1d62ff56a55e8b0ea1cf93ff2be0e629494b | /Chapter18/exercises/18.16/ex_1816.cpp | a01d506cf299e22a6d937f87ebac379b19a7e747 | [] | no_license | yousirong/Cpp-How-To-Program-9E-master | ffad7f164358dbc30a2298a377dfd46351299e9b | aab924f56281d61d62dab804b0ae3ac7ab07f515 | refs/heads/main | 2023-08-22T22:42:23.976286 | 2021-03-09T11:57:37 | 2021-03-09T11:57:37 | 346,019,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,506 | cpp | /*
* =====================================================================================
*
* Filename: ex_1816.cpp
*
* Description: Exercise 18.16 - Counting Palindromes
*
* Version: 1.0
* Created: 20/02/17 10:38:24
* Revision: none
* Compiler: g++
*
* Author: Siidney Watson - siidney.watson.work@gmail.com
* Organization: LolaDog Studio
*
* =====================================================================================
*/
#include <iostream>
#include <sstream>
#include <string>
int totalPalindromes(const std::string&);
bool isPalindrome(std::string&);
int main(int argc, const char* argv[]) {
std::cout << "Enter a sentence: ";
std::string base;
std::getline(std::cin, base);
std::cout << "\nYour sentence contains " << totalPalindromes(base)
<< " Palindromes." << std::endl;
return 0;
}
// count and return total palindromes in given sentence
int totalPalindromes(const std::string& base) {
std::stringstream ss(base);
std::string word;
int total = 0;
while (std::getline(ss, word, ' ')) {
total += ((isPalindrome(word)) ? 1 : 0);
}
return total;
}
// test if word is palindrome
bool isPalindrome(std::string& word) {
std::string test = "";
if (word.length() != 1) {
std::string::reverse_iterator rit = word.rbegin();
while (rit != word.rend()) {
test += *(rit++);
}
}
return (word == test);
}
| [
"80014277+yousirong@users.noreply.github.com"
] | 80014277+yousirong@users.noreply.github.com |
9f9c4caeac6d89ee2cbba41ecdd52803a672d2a6 | e9bc173922ad17c1748abcea9134609319832e13 | /c++/objects/simpleio/watchdog-libsimpleio.cpp | 63307b0415332fab32627e51f1e5e10fa1c60532 | [] | no_license | pmunts/libsimpleio | 35c0deda95d8afef2817701a89bee63a5771086d | cd62ceddfc4a54f6c4714ca1c15a73867f492cda | refs/heads/master | 2023-08-28T15:15:08.177754 | 2023-08-15T02:11:24 | 2023-08-15T02:11:24 | 163,849,784 | 18 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,597 | cpp | // Watchdog timer device services using libsimpleio
// Copyright (C)2017-2020, Philip Munts, President, Munts AM Corp.
//
// 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.
//
// 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.
#include <exception-raisers.h>
#include <watchdog-libsimpleio.h>
#include <libsimpleio/libwatchdog.h>
using namespace libsimpleio::Watchdog;
// Constructor
Timer_Class::Timer_Class(const char *devname, unsigned timeout)
{
int32_t fd;
int32_t error;
// Validate parameters
if (devname == nullptr)
THROW_MSG("The devname parameter is NULL");
// Open the watchdog timer device
WATCHDOG_open(devname, &fd, &error);
if (error) THROW_MSG_ERR("WATCHDOG_open() failed", error);
// Change the watchdog timeout period, if requested
if (timeout != DefaultTimeout)
{
int32_t newtimeout;
WATCHDOG_set_timeout(fd, timeout, &newtimeout, &error);
if (error) THROW_MSG_ERR("WATCHDOG_set_timeout() failed", error);
}
this->fd = fd;
}
// Methods
unsigned Timer_Class::GetTimeout(void)
{
int32_t timeout;
int32_t error;
WATCHDOG_get_timeout(this->fd, &timeout, &error);
if (error) THROW_MSG_ERR("WATCHDOG_get_timeout() failed", error);
return timeout;
}
unsigned Timer_Class::SetTimeout(unsigned timeout)
{
int32_t newtimeout;
int32_t error;
WATCHDOG_set_timeout(this->fd, timeout, &newtimeout, &error);
if (error) THROW_MSG_ERR("WATCHDOG_set_timeout() failed", error);
return timeout;
}
void Timer_Class::Kick(void)
{
int32_t error;
WATCHDOG_kick(this->fd, &error);
if (error) THROW_MSG_ERR("WATCHDOG_kick() failed", error);
}
| [
"svn@06ee2f96-5407-11de-8bab-f3d7589a4122"
] | svn@06ee2f96-5407-11de-8bab-f3d7589a4122 |
198668c7e6e6b645f3c338b500b897720bd67a8d | aaac23e7fa85785f43bf1d8037708ee77ef640ef | /src/Meta_User.cpp | c266129cf9e880a7bed92eeb913bf181821d27bc | [
"MIT",
"OML",
"BSD-3-Clause",
"Zlib"
] | permissive | anto0ine/ciyam | ee2b057a9cd11008ae0d477dac111c0a8d2f60b3 | 7127d528c37584e7d562732274fa2ed6025daeaa | refs/heads/master | 2020-12-07T13:43:24.528962 | 2014-11-20T07:22:08 | 2014-11-20T07:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,808 | cpp | // Copyright (c) 2008-2012 CIYAM Pty. Ltd. ACN 093 704 539
// Copyright (c) 2012-2014 CIYAM Developers
//
// Distributed under the MIT/X11 software license, please refer to the file license.txt
// in the root project directory or http://www.opensource.org/licenses/mit-license.php.
#ifdef PRECOMPILE_H
# include "precompile.h"
#endif
#pragma hdrstop
#ifndef HAS_PRECOMPILED_STD_HEADERS
# include <cstring>
# include <fstream>
# include <iostream>
# include <algorithm>
# include <stdexcept>
#endif
#define CIYAM_BASE_LIB
#define MODULE_META_IMPL
// [<start macros>]
// [<finish macros>]
#include "Meta_User.h"
#include "Meta_Workgroup.h"
#include "ciyam_base.h"
#include "ciyam_common.h"
#include "class_domains.h"
#include "module_strings.h"
#include "ciyam_constants.h"
#include "class_utilities.h"
#include "command_handler.h"
#include "module_interface.h"
// [<start includes>]
// [<finish includes>]
using namespace std;
// [<start namespaces>]
// [<finish namespaces>]
template< > inline string to_string( const Meta_Workgroup& c )
{
return ::to_string( static_cast< const class_base& >( c ) );
}
inline void from_string( Meta_Workgroup& c, const string& s )
{
::from_string( static_cast< class_base& >( c ), s );
}
inline int system( const string& cmd ) { return exec_system( cmd ); }
namespace
{
#include "Meta_User.cmh"
const int32_t c_version = 1;
const char* const c_okay = "okay";
const char* const c_field_id_Active = "100102";
const char* const c_field_id_Description = "100104";
const char* const c_field_id_Email = "100105";
const char* const c_field_id_Password = "100103";
const char* const c_field_id_Password_Hash = "100108";
const char* const c_field_id_Permissions = "100106";
const char* const c_field_id_User_Hash = "100107";
const char* const c_field_id_User_Id = "100101";
const char* const c_field_id_Workgroup = "300100";
const char* const c_field_name_Active = "Active";
const char* const c_field_name_Description = "Description";
const char* const c_field_name_Email = "Email";
const char* const c_field_name_Password = "Password";
const char* const c_field_name_Password_Hash = "Password_Hash";
const char* const c_field_name_Permissions = "Permissions";
const char* const c_field_name_User_Hash = "User_Hash";
const char* const c_field_name_User_Id = "User_Id";
const char* const c_field_name_Workgroup = "Workgroup";
const char* const c_field_display_name_Active = "field_user_active";
const char* const c_field_display_name_Description = "field_user_description";
const char* const c_field_display_name_Email = "field_user_email";
const char* const c_field_display_name_Password = "field_user_password";
const char* const c_field_display_name_Password_Hash = "field_user_password_hash";
const char* const c_field_display_name_Permissions = "field_user_permissions";
const char* const c_field_display_name_User_Hash = "field_user_user_hash";
const char* const c_field_display_name_User_Id = "field_user_user_id";
const char* const c_field_display_name_Workgroup = "field_user_workgroup";
const int c_num_fields = 9;
const char* const c_all_sorted_field_ids[ ] =
{
"100101",
"100102",
"100103",
"100104",
"100105",
"100106",
"100107",
"100108",
"300100"
};
const char* const c_all_sorted_field_names[ ] =
{
"Active",
"Description",
"Email",
"Password",
"Password_Hash",
"Permissions",
"User_Hash",
"User_Id",
"Workgroup"
};
inline bool compare( const char* p_s1, const char* p_s2 ) { return strcmp( p_s1, p_s2 ) < 0; }
inline bool has_field( const string& field )
{
return binary_search( c_all_sorted_field_ids, c_all_sorted_field_ids + c_num_fields, field.c_str( ), compare )
|| binary_search( c_all_sorted_field_names, c_all_sorted_field_names + c_num_fields, field.c_str( ), compare );
}
const int c_num_transient_fields = 1;
const char* const c_transient_sorted_field_ids[ ] =
{
"100108"
};
const char* const c_transient_sorted_field_names[ ] =
{
"Password_Hash"
};
inline bool transient_compare( const char* p_s1, const char* p_s2 ) { return strcmp( p_s1, p_s2 ) < 0; }
inline bool is_transient_field( const string& field )
{
return binary_search( c_transient_sorted_field_ids,
c_transient_sorted_field_ids + c_num_transient_fields, field.c_str( ), transient_compare )
|| binary_search( c_transient_sorted_field_names,
c_transient_sorted_field_names + c_num_transient_fields, field.c_str( ), transient_compare );
}
domain_string_max_size< 100 > g_Description_domain;
domain_string_max_size< 200 > g_Password_domain;
domain_string_max_size< 30 > g_User_Id_domain;
string g_order_field_name;
string g_owner_field_name;
set< string > g_derivations;
set< string > g_file_field_names;
typedef map< string, Meta_User* > external_aliases_container;
typedef external_aliases_container::const_iterator external_aliases_const_iterator;
typedef external_aliases_container::value_type external_aliases_value_type;
typedef map< size_t, Meta_User* > external_aliases_lookup_container;
typedef external_aliases_lookup_container::const_iterator external_aliases_lookup_const_iterator;
external_aliases_container g_external_aliases;
external_aliases_lookup_container g_external_aliases_lookup;
bool g_default_Active = bool( 1 );
string g_default_Description = string( );
string g_default_Email = string( );
string g_default_Password = string( );
string g_default_Password_Hash = string( );
string g_default_Permissions = string( );
string g_default_User_Hash = string( );
string g_default_User_Id = string( );
string g_default_Workgroup = string( );
// [<start anonymous>]
// [<finish anonymous>]
}
registration< Meta_User > User_registration( get_class_registry( ), "100100" );
class Meta_User_command_functor;
class Meta_User_command_handler : public command_handler
{
friend class Meta_User_command_functor;
public:
Meta_User_command_handler( ) : p_Meta_User( 0 ) { }
void set_Meta_User( Meta_User* p_new_Meta_User ) { p_Meta_User = p_new_Meta_User; }
void handle_unknown_command( const string& command )
{
throw runtime_error( "unknown command '" + command + "'" );
}
void handle_invalid_command( const command_parser& parser, const string& cmd_and_args )
{
throw runtime_error( "invalid command usage '" + cmd_and_args + "'" );
}
private:
Meta_User* p_Meta_User;
protected:
string retval;
};
class Meta_User_command_functor : public command_functor
{
public:
Meta_User_command_functor( Meta_User_command_handler& handler )
: command_functor( handler ),
cmd_handler( handler )
{
}
void operator ( )( const string& command, const parameter_info& parameters );
private:
Meta_User_command_handler& cmd_handler;
};
command_functor* Meta_User_command_functor_factory( const string& /*name*/, command_handler& handler )
{
return new Meta_User_command_functor( dynamic_cast< Meta_User_command_handler& >( handler ) );
}
void Meta_User_command_functor::operator ( )( const string& command, const parameter_info& parameters )
{
if( command == c_cmd_Meta_User_key )
{
bool want_fixed( has_parm_val( parameters, c_cmd_parm_Meta_User_key_fixed ) );
if( !want_fixed )
cmd_handler.retval = cmd_handler.p_Meta_User->get_key( );
else
cmd_handler.retval = cmd_handler.p_Meta_User->get_fixed_key( );
}
else if( command == c_cmd_Meta_User_ver )
{
string ver_rev( to_string( cmd_handler.p_Meta_User->get_version( ) ) );
ver_rev += "." + to_string( cmd_handler.p_Meta_User->get_revision( ) );
cmd_handler.retval = ver_rev;
}
else if( command == c_cmd_Meta_User_get )
{
string field_name( get_parm_val( parameters, c_cmd_parm_Meta_User_get_field_name ) );
bool handled = false;
if( field_name.empty( ) )
throw runtime_error( "field name must not be empty for getter call" );
if( !handled && field_name == c_field_id_Active || field_name == c_field_name_Active )
{
handled = true;
string_getter< bool >( cmd_handler.p_Meta_User->Active( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Description || field_name == c_field_name_Description )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->Description( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Email || field_name == c_field_name_Email )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->Email( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Password || field_name == c_field_name_Password )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->Password( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Password_Hash || field_name == c_field_name_Password_Hash )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->Password_Hash( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Permissions || field_name == c_field_name_Permissions )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->Permissions( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_User_Hash || field_name == c_field_name_User_Hash )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->User_Hash( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_User_Id || field_name == c_field_name_User_Id )
{
handled = true;
string_getter< string >( cmd_handler.p_Meta_User->User_Id( ), cmd_handler.retval );
}
if( !handled && field_name == c_field_id_Workgroup || field_name == c_field_name_Workgroup )
{
handled = true;
string_getter< Meta_Workgroup >( cmd_handler.p_Meta_User->Workgroup( ), cmd_handler.retval );
}
if( !handled )
throw runtime_error( "unknown field name '" + field_name + "' for getter call" );
}
else if( command == c_cmd_Meta_User_set )
{
string field_name( get_parm_val( parameters, c_cmd_parm_Meta_User_set_field_name ) );
string field_value( get_parm_val( parameters, c_cmd_parm_Meta_User_set_field_value ) );
bool handled = false;
if( field_name.empty( ) )
throw runtime_error( "field name must not be empty for setter call" );
if( !handled && field_name == c_field_id_Active || field_name == c_field_name_Active )
{
handled = true;
func_string_setter< Meta_User, bool >(
*cmd_handler.p_Meta_User, &Meta_User::Active, field_value );
}
if( !handled && field_name == c_field_id_Description || field_name == c_field_name_Description )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::Description, field_value );
}
if( !handled && field_name == c_field_id_Email || field_name == c_field_name_Email )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::Email, field_value );
}
if( !handled && field_name == c_field_id_Password || field_name == c_field_name_Password )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::Password, field_value );
}
if( !handled && field_name == c_field_id_Password_Hash || field_name == c_field_name_Password_Hash )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::Password_Hash, field_value );
}
if( !handled && field_name == c_field_id_Permissions || field_name == c_field_name_Permissions )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::Permissions, field_value );
}
if( !handled && field_name == c_field_id_User_Hash || field_name == c_field_name_User_Hash )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::User_Hash, field_value );
}
if( !handled && field_name == c_field_id_User_Id || field_name == c_field_name_User_Id )
{
handled = true;
func_string_setter< Meta_User, string >(
*cmd_handler.p_Meta_User, &Meta_User::User_Id, field_value );
}
if( !handled && field_name == c_field_id_Workgroup || field_name == c_field_name_Workgroup )
{
handled = true;
func_string_setter< Meta_User, Meta_Workgroup >(
*cmd_handler.p_Meta_User, &Meta_User::Workgroup, field_value );
}
if( !handled )
throw runtime_error( "unknown field name '" + field_name + "' for setter call" );
cmd_handler.retval = c_okay;
}
else if( command == c_cmd_Meta_User_cmd )
{
string field_name( get_parm_val( parameters, c_cmd_parm_Meta_User_cmd_field_name ) );
string cmd_and_args( get_parm_val( parameters, c_cmd_parm_Meta_User_cmd_cmd_and_args ) );
cmd_handler.retval.erase( );
if( field_name.empty( ) )
throw runtime_error( "field name must not be empty for command call" );
else if( field_name == c_field_id_Workgroup || field_name == c_field_name_Workgroup )
cmd_handler.retval = cmd_handler.p_Meta_User->Workgroup( ).execute( cmd_and_args );
else
throw runtime_error( "unknown field name '" + field_name + "' for command call" );
}
}
struct Meta_User::impl : public Meta_User_command_handler
{
impl( Meta_User& o )
:
cp_obj( &o ),
total_child_relationships( 0 )
{
p_obj = &o;
set_Meta_User( &o );
add_commands( 0, Meta_User_command_functor_factory,
ARRAY_PTR_AND_SIZE( Meta_User_command_definitions ) );
}
Meta_User& get_obj( ) const
{
return *cp_obj;
}
bool impl_Active( ) const { return lazy_fetch( p_obj ), v_Active; }
void impl_Active( bool Active ) { v_Active = Active; }
const string& impl_Description( ) const { return lazy_fetch( p_obj ), v_Description; }
void impl_Description( const string& Description ) { v_Description = Description; }
const string& impl_Email( ) const { return lazy_fetch( p_obj ), v_Email; }
void impl_Email( const string& Email ) { v_Email = Email; }
const string& impl_Password( ) const { return lazy_fetch( p_obj ), v_Password; }
void impl_Password( const string& Password ) { v_Password = Password; }
const string& impl_Password_Hash( ) const { return lazy_fetch( p_obj ), v_Password_Hash; }
void impl_Password_Hash( const string& Password_Hash ) { v_Password_Hash = Password_Hash; }
const string& impl_Permissions( ) const { return lazy_fetch( p_obj ), v_Permissions; }
void impl_Permissions( const string& Permissions ) { v_Permissions = Permissions; }
const string& impl_User_Hash( ) const { return lazy_fetch( p_obj ), v_User_Hash; }
void impl_User_Hash( const string& User_Hash ) { v_User_Hash = User_Hash; }
const string& impl_User_Id( ) const { return lazy_fetch( p_obj ), v_User_Id; }
void impl_User_Id( const string& User_Id ) { v_User_Id = User_Id; }
Meta_Workgroup& impl_Workgroup( )
{
if( !cp_Workgroup )
{
cp_Workgroup.init( );
p_obj->setup_graph_parent( *cp_Workgroup, c_field_id_Workgroup, v_Workgroup );
}
return *cp_Workgroup;
}
const Meta_Workgroup& impl_Workgroup( ) const
{
lazy_fetch( p_obj );
if( !cp_Workgroup )
{
cp_Workgroup.init( );
p_obj->setup_graph_parent( *cp_Workgroup, c_field_id_Workgroup, v_Workgroup );
}
return *cp_Workgroup;
}
void impl_Workgroup( const string& key )
{
class_base_accessor cba( impl_Workgroup( ) );
cba.set_key( key );
}
string get_field_value( int field ) const;
void set_field_value( int field, const string& value );
bool is_field_default( int field ) const;
uint64_t get_state( ) const;
const string& execute( const string& cmd_and_args );
void clear_foreign_key( const string& field );
void set_foreign_key_value( const string& field, const string& value );
const string& get_foreign_key_value( const string& field );
void get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const;
void add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const;
void add_extra_paging_info( vector< pair< string, string > >& paging_info ) const;
void clear( );
bool value_will_be_provided( const string& field_name );
void validate( unsigned state, bool is_internal, validation_error_container* p_validation_errors );
void validate_set_fields( set< string >& fields_set, validation_error_container* p_validation_errors );
void after_fetch( );
void finalise_fetch( );
void at_create( );
void post_init( );
void to_store( bool is_create, bool is_internal );
void for_store( bool is_create, bool is_internal );
void after_store( bool is_create, bool is_internal );
bool can_destroy( bool is_internal );
void for_destroy( bool is_internal );
void after_destroy( bool is_internal );
void set_default_values( );
bool is_filtered( ) const;
void get_required_transients( ) const;
Meta_User* p_obj;
class_pointer< Meta_User > cp_obj;
mutable set< string > required_transients;
// [<start members>]
// [<finish members>]
size_t total_child_relationships;
bool v_Active;
string v_Description;
string v_Email;
string v_Password;
string v_Password_Hash;
string v_Permissions;
string v_User_Hash;
string v_User_Id;
string v_Workgroup;
mutable class_pointer< Meta_Workgroup > cp_Workgroup;
};
string Meta_User::impl::get_field_value( int field ) const
{
string retval;
switch( field )
{
case 0:
retval = to_string( impl_Active( ) );
break;
case 1:
retval = to_string( impl_Description( ) );
break;
case 2:
retval = to_string( impl_Email( ) );
break;
case 3:
retval = to_string( impl_Password( ) );
break;
case 4:
retval = to_string( impl_Password_Hash( ) );
break;
case 5:
retval = to_string( impl_Permissions( ) );
break;
case 6:
retval = to_string( impl_User_Hash( ) );
break;
case 7:
retval = to_string( impl_User_Id( ) );
break;
case 8:
retval = to_string( impl_Workgroup( ) );
break;
default:
throw runtime_error( "field #" + to_string( field ) + " is out of range in get field value" );
}
return retval;
}
void Meta_User::impl::set_field_value( int field, const string& value )
{
switch( field )
{
case 0:
func_string_setter< Meta_User::impl, bool >( *this, &Meta_User::impl::impl_Active, value );
break;
case 1:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_Description, value );
break;
case 2:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_Email, value );
break;
case 3:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_Password, value );
break;
case 4:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_Password_Hash, value );
break;
case 5:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_Permissions, value );
break;
case 6:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_User_Hash, value );
break;
case 7:
func_string_setter< Meta_User::impl, string >( *this, &Meta_User::impl::impl_User_Id, value );
break;
case 8:
func_string_setter< Meta_User::impl, Meta_Workgroup >( *this, &Meta_User::impl::impl_Workgroup, value );
break;
default:
throw runtime_error( "field #" + to_string( field ) + " is out of range in set field value" );
}
}
bool Meta_User::impl::is_field_default( int field ) const
{
bool retval = false;
switch( field )
{
case 0:
retval = ( v_Active == g_default_Active );
break;
case 1:
retval = ( v_Description == g_default_Description );
break;
case 2:
retval = ( v_Email == g_default_Email );
break;
case 3:
retval = ( v_Password == g_default_Password );
break;
case 4:
retval = ( v_Password_Hash == g_default_Password_Hash );
break;
case 5:
retval = ( v_Permissions == g_default_Permissions );
break;
case 6:
retval = ( v_User_Hash == g_default_User_Hash );
break;
case 7:
retval = ( v_User_Id == g_default_User_Id );
break;
case 8:
retval = ( v_Workgroup == g_default_Workgroup );
break;
default:
throw runtime_error( "field #" + to_string( field ) + " is out of range in is_field_default" );
}
return retval;
}
uint64_t Meta_User::impl::get_state( ) const
{
uint64_t state = 0;
// [<start get_state>]
// [<finish get_state>]
return state;
}
const string& Meta_User::impl::execute( const string& cmd_and_args )
{
execute_command( cmd_and_args );
return retval;
}
void Meta_User::impl::clear_foreign_key( const string& field )
{
if( field.empty( ) )
throw runtime_error( "unexpected empty field name/id" );
else if( field == c_field_id_Workgroup || field == c_field_name_Workgroup )
impl_Workgroup( "" );
else
throw runtime_error( "unknown foreign key field '" + field + "'" );
}
void Meta_User::impl::set_foreign_key_value( const string& field, const string& value )
{
if( field.empty( ) )
throw runtime_error( "unexpected empty field name/id for value: " + value );
else if( field == c_field_id_Workgroup || field == c_field_name_Workgroup )
v_Workgroup = value;
else
throw runtime_error( "unknown foreign key field '" + field + "'" );
}
const string& Meta_User::impl::get_foreign_key_value( const string& field )
{
if( field.empty( ) )
throw runtime_error( "unexpected empty field name/id" );
else if( field == c_field_id_Workgroup || field == c_field_name_Workgroup )
return v_Workgroup;
else
throw runtime_error( "unknown foreign key field '" + field + "'" );
}
void Meta_User::impl::get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const
{
foreign_key_values.insert( foreign_key_data_value_type( c_field_id_Workgroup, v_Workgroup ) );
}
void Meta_User::impl::add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const
{
( void )fixed_info;
// [<start add_extra_fixed_info>]
// [<finish add_extra_fixed_info>]
}
void Meta_User::impl::add_extra_paging_info( vector< pair< string, string > >& paging_info ) const
{
( void )paging_info;
// [<start add_extra_paging_info>]
// [<finish add_extra_paging_info>]
}
void Meta_User::impl::clear( )
{
v_Active = g_default_Active;
v_Description = g_default_Description;
v_Email = g_default_Email;
v_Password = g_default_Password;
v_Password_Hash = g_default_Password_Hash;
v_Permissions = g_default_Permissions;
v_User_Hash = g_default_User_Hash;
v_User_Id = g_default_User_Id;
v_Workgroup = string( );
if( cp_Workgroup )
p_obj->setup_foreign_key( *cp_Workgroup, v_Workgroup );
}
bool Meta_User::impl::value_will_be_provided( const string& field_name )
{
( void )field_name;
// [<start value_will_be_provided>]
// [<finish value_will_be_provided>]
return false;
}
void Meta_User::impl::validate( unsigned state, bool is_internal, validation_error_container* p_validation_errors )
{
( void )state;
( void )is_internal;
if( !p_validation_errors )
throw runtime_error( "unexpected null validation_errors container" );
if( is_null( v_Description ) && !value_will_be_provided( c_field_name_Description ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Description,
get_string_message( GS( c_str_field_must_not_be_empty ), make_pair(
c_str_parm_field_must_not_be_empty_field, get_module_string( c_field_display_name_Description ) ) ) ) );
if( is_null( v_Password ) && !value_will_be_provided( c_field_name_Password ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Password,
get_string_message( GS( c_str_field_must_not_be_empty ), make_pair(
c_str_parm_field_must_not_be_empty_field, get_module_string( c_field_display_name_Password ) ) ) ) );
if( is_null( v_User_Id ) && !value_will_be_provided( c_field_name_User_Id ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_User_Id,
get_string_message( GS( c_str_field_must_not_be_empty ), make_pair(
c_str_parm_field_must_not_be_empty_field, get_module_string( c_field_display_name_User_Id ) ) ) ) );
string error_message;
if( !is_null( v_Description )
&& ( v_Description != g_default_Description
|| !value_will_be_provided( c_field_name_Description ) )
&& !g_Description_domain.is_valid( v_Description, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Description,
get_module_string( c_field_display_name_Description ) + " " + error_message ) );
if( !is_null( v_Password )
&& ( v_Password != g_default_Password
|| !value_will_be_provided( c_field_name_Password ) )
&& !g_Password_domain.is_valid( v_Password, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Password,
get_module_string( c_field_display_name_Password ) + " " + error_message ) );
if( !is_null( v_User_Id )
&& ( v_User_Id != g_default_User_Id
|| !value_will_be_provided( c_field_name_User_Id ) )
&& !g_User_Id_domain.is_valid( v_User_Id, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_User_Id,
get_module_string( c_field_display_name_User_Id ) + " " + error_message ) );
// [<start validate>]
// [<finish validate>]
}
void Meta_User::impl::validate_set_fields( set< string >& fields_set, validation_error_container* p_validation_errors )
{
( void )fields_set;
if( !p_validation_errors )
throw runtime_error( "unexpected null validation_errors container" );
string error_message;
if( !is_null( v_Description )
&& ( fields_set.count( c_field_id_Description ) || fields_set.count( c_field_name_Description ) )
&& !g_Description_domain.is_valid( v_Description, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Description,
get_module_string( c_field_display_name_Description ) + " " + error_message ) );
if( !is_null( v_Password )
&& ( fields_set.count( c_field_id_Password ) || fields_set.count( c_field_name_Password ) )
&& !g_Password_domain.is_valid( v_Password, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_Password,
get_module_string( c_field_display_name_Password ) + " " + error_message ) );
if( !is_null( v_User_Id )
&& ( fields_set.count( c_field_id_User_Id ) || fields_set.count( c_field_name_User_Id ) )
&& !g_User_Id_domain.is_valid( v_User_Id, error_message = "" ) )
p_validation_errors->insert( validation_error_value_type( c_field_name_User_Id,
get_module_string( c_field_display_name_User_Id ) + " " + error_message ) );
}
void Meta_User::impl::after_fetch( )
{
if( !get_obj( ).get_is_iterating( ) || get_obj( ).get_is_starting_iteration( ) )
get_required_transients( );
if( cp_Workgroup )
p_obj->setup_foreign_key( *cp_Workgroup, v_Workgroup );
post_init( );
uint64_t state = p_obj->get_state( );
( void )state;
// [<start after_fetch>]
// [<finish after_fetch>]
}
void Meta_User::impl::finalise_fetch( )
{
// [<start finalise_fetch>]
// [<finish finalise_fetch>]
}
void Meta_User::impl::at_create( )
{
// [<start at_create>]
// [<finish at_create>]
}
void Meta_User::impl::post_init( )
{
// [<start post_init>]
// [<finish post_init>]
}
void Meta_User::impl::to_store( bool is_create, bool is_internal )
{
( void )is_create;
( void )is_internal;
if( !get_obj( ).get_is_preparing( ) )
post_init( );
uint64_t state = p_obj->get_state( );
( void )state;
// [(start field_clear)] 600001
get_obj( ).Permissions( string( ) );
// [(finish field_clear)] 600001
// [<start to_store>]
// [<finish to_store>]
}
void Meta_User::impl::for_store( bool is_create, bool is_internal )
{
( void )is_create;
( void )is_internal;
uint64_t state = p_obj->get_state( );
( void )state;
// [<start for_store>]
//nyi
get_obj( ).Password_Hash( decrypt( get_obj( ).Password( ) ) );
get_obj( ).User_Hash( hash_sha256( get_obj( ).User_Id( ) + get_obj( ).Password_Hash( ) ) );
// [<finish for_store>]
}
void Meta_User::impl::after_store( bool is_create, bool is_internal )
{
( void )is_create;
( void )is_internal;
uint64_t state = p_obj->get_state( );
( void )state;
// [<start after_store>]
// [<finish after_store>]
}
bool Meta_User::impl::can_destroy( bool is_internal )
{
uint64_t state = p_obj->get_state( );
bool retval = is_internal || !( state & c_state_undeletable );
// [<start can_destroy>]
// [<finish can_destroy>]
return retval;
}
void Meta_User::impl::for_destroy( bool is_internal )
{
( void )is_internal;
uint64_t state = p_obj->get_state( );
( void )state;
// [<start for_destroy>]
// [<finish for_destroy>]
}
void Meta_User::impl::after_destroy( bool is_internal )
{
( void )is_internal;
uint64_t state = p_obj->get_state( );
( void )state;
// [<start after_destroy>]
// [<finish after_destroy>]
}
void Meta_User::impl::set_default_values( )
{
clear( );
}
bool Meta_User::impl::is_filtered( ) const
{
uint64_t state = p_obj->get_state( );
( void )state;
// [<start is_filtered>]
// [<finish is_filtered>]
return false;
}
void Meta_User::impl::get_required_transients( ) const
{
required_transients.clear( );
get_obj( ).add_required_transients( required_transients );
set< string > dependents( required_transients.begin( ), required_transients.end( ) );
p_obj->get_required_field_names( required_transients, true, &dependents );
int iterations = 0;
// NOTE: It is possible that due to "interdependent" required fields
// some required fields may not have been added in the first or even
// later calls to "get_required_field_names" so continue calling the
// function until no further field names have been added.
size_t num_required = required_transients.size( );
while( num_required )
{
p_obj->get_required_field_names( required_transients, true, &dependents );
if( required_transients.size( ) == num_required )
break;
if( ++iterations > 100 )
throw runtime_error( "unexpected excessive get_required_field_names( ) iterations in get_required_transients( )" );
num_required = required_transients.size( );
}
}
#undef MODULE_TRACE
#define MODULE_TRACE( x ) trace( x )
Meta_User::Meta_User( )
{
set_version( c_version );
p_impl = new impl( *this );
}
Meta_User::~Meta_User( )
{
cleanup( );
delete p_impl;
}
bool Meta_User::Active( ) const
{
return p_impl->impl_Active( );
}
void Meta_User::Active( bool Active )
{
p_impl->impl_Active( Active );
}
const string& Meta_User::Description( ) const
{
return p_impl->impl_Description( );
}
void Meta_User::Description( const string& Description )
{
p_impl->impl_Description( Description );
}
const string& Meta_User::Email( ) const
{
return p_impl->impl_Email( );
}
void Meta_User::Email( const string& Email )
{
p_impl->impl_Email( Email );
}
const string& Meta_User::Password( ) const
{
return p_impl->impl_Password( );
}
void Meta_User::Password( const string& Password )
{
p_impl->impl_Password( Password );
}
const string& Meta_User::Password_Hash( ) const
{
return p_impl->impl_Password_Hash( );
}
void Meta_User::Password_Hash( const string& Password_Hash )
{
p_impl->impl_Password_Hash( Password_Hash );
}
const string& Meta_User::Permissions( ) const
{
return p_impl->impl_Permissions( );
}
void Meta_User::Permissions( const string& Permissions )
{
p_impl->impl_Permissions( Permissions );
}
const string& Meta_User::User_Hash( ) const
{
return p_impl->impl_User_Hash( );
}
void Meta_User::User_Hash( const string& User_Hash )
{
p_impl->impl_User_Hash( User_Hash );
}
const string& Meta_User::User_Id( ) const
{
return p_impl->impl_User_Id( );
}
void Meta_User::User_Id( const string& User_Id )
{
p_impl->impl_User_Id( User_Id );
}
Meta_Workgroup& Meta_User::Workgroup( )
{
return p_impl->impl_Workgroup( );
}
const Meta_Workgroup& Meta_User::Workgroup( ) const
{
return p_impl->impl_Workgroup( );
}
void Meta_User::Workgroup( const string& key )
{
p_impl->impl_Workgroup( key );
}
string Meta_User::get_field_value( int field ) const
{
return p_impl->get_field_value( field );
}
void Meta_User::set_field_value( int field, const string& value )
{
p_impl->set_field_value( field, value );
}
bool Meta_User::is_field_default( int field ) const
{
return is_field_default( ( field_id )( field + 1 ) );
}
bool Meta_User::is_field_default( field_id id ) const
{
return p_impl->is_field_default( ( int )id - 1 );
}
bool Meta_User::is_field_default( const string& field ) const
{
return p_impl->is_field_default( get_field_num( field ) );
}
bool Meta_User::is_field_transient( int field ) const
{
return static_is_field_transient( ( field_id )( field + 1 ) );
}
string Meta_User::get_field_name( int field ) const
{
return static_get_field_name( ( field_id )( field + 1 ) );
}
int Meta_User::get_field_num( const string& field ) const
{
int rc = static_get_field_num( field );
if( rc < 0 )
throw runtime_error( "unknown field name/id '" + field + "' in get_field_num( )" );
return rc;
}
bool Meta_User::has_field_changed( const string& field ) const
{
return class_base::has_field_changed( get_field_num( field ) );
}
uint64_t Meta_User::get_state( ) const
{
uint64_t state = 0;
state |= p_impl->get_state( );
return state;
}
const string& Meta_User::execute( const string& cmd_and_args )
{
return p_impl->execute( cmd_and_args );
}
void Meta_User::clear( )
{
p_impl->clear( );
}
void Meta_User::validate( unsigned state, bool is_internal )
{
p_impl->validate( state, is_internal, &validation_errors );
}
void Meta_User::validate_set_fields( set< string >& fields_set )
{
p_impl->validate_set_fields( fields_set, &validation_errors );
}
void Meta_User::after_fetch( )
{
p_impl->after_fetch( );
}
void Meta_User::finalise_fetch( )
{
p_impl->finalise_fetch( );
}
void Meta_User::at_create( )
{
p_impl->at_create( );
}
void Meta_User::post_init( )
{
p_impl->post_init( );
}
void Meta_User::to_store( bool is_create, bool is_internal )
{
p_impl->to_store( is_create, is_internal );
}
void Meta_User::for_store( bool is_create, bool is_internal )
{
p_impl->for_store( is_create, is_internal );
}
void Meta_User::after_store( bool is_create, bool is_internal )
{
p_impl->after_store( is_create, is_internal );
}
bool Meta_User::can_destroy( bool is_internal )
{
return p_impl->can_destroy( is_internal );
}
void Meta_User::for_destroy( bool is_internal )
{
p_impl->for_destroy( is_internal );
}
void Meta_User::after_destroy( bool is_internal )
{
p_impl->after_destroy( is_internal );
}
void Meta_User::set_default_values( )
{
p_impl->set_default_values( );
}
bool Meta_User::is_filtered( ) const
{
return p_impl->is_filtered( );
}
const char* Meta_User::get_field_id(
const string& name, bool* p_sql_numeric, string* p_type_name ) const
{
const char* p_id( 0 );
if( name.empty( ) )
throw runtime_error( "unexpected empty field name for get_field_id" );
else if( name == c_field_name_Active )
{
p_id = c_field_id_Active;
if( p_type_name )
*p_type_name = "bool";
if( p_sql_numeric )
*p_sql_numeric = true;
}
else if( name == c_field_name_Description )
{
p_id = c_field_id_Description;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_Email )
{
p_id = c_field_id_Email;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_Password )
{
p_id = c_field_id_Password;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_Password_Hash )
{
p_id = c_field_id_Password_Hash;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_Permissions )
{
p_id = c_field_id_Permissions;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_User_Hash )
{
p_id = c_field_id_User_Hash;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_User_Id )
{
p_id = c_field_id_User_Id;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( name == c_field_name_Workgroup )
{
p_id = c_field_id_Workgroup;
if( p_type_name )
*p_type_name = "Meta_Workgroup";
if( p_sql_numeric )
*p_sql_numeric = false;
}
return p_id;
}
const char* Meta_User::get_field_name(
const string& id, bool* p_sql_numeric, string* p_type_name ) const
{
const char* p_name( 0 );
if( id.empty( ) )
throw runtime_error( "unexpected empty field id for get_field_name" );
else if( id == c_field_id_Active )
{
p_name = c_field_name_Active;
if( p_type_name )
*p_type_name = "bool";
if( p_sql_numeric )
*p_sql_numeric = true;
}
else if( id == c_field_id_Description )
{
p_name = c_field_name_Description;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_Email )
{
p_name = c_field_name_Email;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_Password )
{
p_name = c_field_name_Password;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_Password_Hash )
{
p_name = c_field_name_Password_Hash;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_Permissions )
{
p_name = c_field_name_Permissions;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_User_Hash )
{
p_name = c_field_name_User_Hash;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_User_Id )
{
p_name = c_field_name_User_Id;
if( p_type_name )
*p_type_name = "string";
if( p_sql_numeric )
*p_sql_numeric = false;
}
else if( id == c_field_id_Workgroup )
{
p_name = c_field_name_Workgroup;
if( p_type_name )
*p_type_name = "Meta_Workgroup";
if( p_sql_numeric )
*p_sql_numeric = false;
}
return p_name;
}
string& Meta_User::get_order_field_name( ) const
{
return g_order_field_name;
}
string& Meta_User::get_owner_field_name( ) const
{
return g_owner_field_name;
}
bool Meta_User::is_file_field_name( const string& name ) const
{
return g_file_field_names.count( name );
}
void Meta_User::get_file_field_names( vector< string >& file_field_names ) const
{
for( set< string >::const_iterator ci = g_file_field_names.begin( ); ci != g_file_field_names.end( ); ++ci )
file_field_names.push_back( *ci );
}
string Meta_User::get_field_uom_symbol( const string& id_or_name ) const
{
string uom_symbol;
string name;
pair< string, string > next;
if( id_or_name.empty( ) )
throw runtime_error( "unexpected empty field id_or_name for get_field_uom_symbol" );
else if( id_or_name == c_field_id_Active || id_or_name == c_field_name_Active )
{
name = string( c_field_display_name_Active );
get_module_string( c_field_display_name_Active, &next );
}
else if( id_or_name == c_field_id_Description || id_or_name == c_field_name_Description )
{
name = string( c_field_display_name_Description );
get_module_string( c_field_display_name_Description, &next );
}
else if( id_or_name == c_field_id_Email || id_or_name == c_field_name_Email )
{
name = string( c_field_display_name_Email );
get_module_string( c_field_display_name_Email, &next );
}
else if( id_or_name == c_field_id_Password || id_or_name == c_field_name_Password )
{
name = string( c_field_display_name_Password );
get_module_string( c_field_display_name_Password, &next );
}
else if( id_or_name == c_field_id_Password_Hash || id_or_name == c_field_name_Password_Hash )
{
name = string( c_field_display_name_Password_Hash );
get_module_string( c_field_display_name_Password_Hash, &next );
}
else if( id_or_name == c_field_id_Permissions || id_or_name == c_field_name_Permissions )
{
name = string( c_field_display_name_Permissions );
get_module_string( c_field_display_name_Permissions, &next );
}
else if( id_or_name == c_field_id_User_Hash || id_or_name == c_field_name_User_Hash )
{
name = string( c_field_display_name_User_Hash );
get_module_string( c_field_display_name_User_Hash, &next );
}
else if( id_or_name == c_field_id_User_Id || id_or_name == c_field_name_User_Id )
{
name = string( c_field_display_name_User_Id );
get_module_string( c_field_display_name_User_Id, &next );
}
else if( id_or_name == c_field_id_Workgroup || id_or_name == c_field_name_Workgroup )
{
name = string( c_field_display_name_Workgroup );
get_module_string( c_field_display_name_Workgroup, &next );
}
// NOTE: It is being assumed here that the customised UOM symbol for a field (if it
// has one) will be in the module string that immediately follows that of its name.
if( next.first.find( name + "_(" ) == 0 )
uom_symbol = next.second;
return uom_symbol;
}
string Meta_User::get_field_display_name( const string& id_or_name ) const
{
string display_name;
if( id_or_name.empty( ) )
throw runtime_error( "unexpected empty field id_or_name for get_field_display_name" );
else if( id_or_name == c_field_id_Active || id_or_name == c_field_name_Active )
display_name = get_module_string( c_field_display_name_Active );
else if( id_or_name == c_field_id_Description || id_or_name == c_field_name_Description )
display_name = get_module_string( c_field_display_name_Description );
else if( id_or_name == c_field_id_Email || id_or_name == c_field_name_Email )
display_name = get_module_string( c_field_display_name_Email );
else if( id_or_name == c_field_id_Password || id_or_name == c_field_name_Password )
display_name = get_module_string( c_field_display_name_Password );
else if( id_or_name == c_field_id_Password_Hash || id_or_name == c_field_name_Password_Hash )
display_name = get_module_string( c_field_display_name_Password_Hash );
else if( id_or_name == c_field_id_Permissions || id_or_name == c_field_name_Permissions )
display_name = get_module_string( c_field_display_name_Permissions );
else if( id_or_name == c_field_id_User_Hash || id_or_name == c_field_name_User_Hash )
display_name = get_module_string( c_field_display_name_User_Hash );
else if( id_or_name == c_field_id_User_Id || id_or_name == c_field_name_User_Id )
display_name = get_module_string( c_field_display_name_User_Id );
else if( id_or_name == c_field_id_Workgroup || id_or_name == c_field_name_Workgroup )
display_name = get_module_string( c_field_display_name_Workgroup );
return display_name;
}
void Meta_User::clear_foreign_key( const string& field )
{
p_impl->clear_foreign_key( field );
}
void Meta_User::set_foreign_key_value( const string& field, const string& value )
{
p_impl->set_foreign_key_value( field, value );
}
const string& Meta_User::get_foreign_key_value( const string& field )
{
return p_impl->get_foreign_key_value( field );
}
void Meta_User::get_foreign_key_values( foreign_key_data_container& foreign_key_values ) const
{
p_impl->get_foreign_key_values( foreign_key_values );
}
void Meta_User::setup_foreign_key( Meta_Workgroup& o, const string& value )
{
static_cast< Meta_Workgroup& >( o ).set_key( value );
}
void Meta_User::setup_graph_parent(
Meta_Workgroup& o, const string& foreign_key_field, const string& init_value )
{
static_cast< Meta_Workgroup& >( o ).set_graph_parent( this, foreign_key_field, true );
static_cast< Meta_Workgroup& >( o ).set_key( init_value );
}
size_t Meta_User::get_total_child_relationships( ) const
{
return p_impl->total_child_relationships;
}
void Meta_User::set_total_child_relationships( size_t new_total_child_relationships ) const
{
p_impl->total_child_relationships = new_total_child_relationships;
}
size_t Meta_User::get_num_foreign_key_children( bool is_internal ) const
{
size_t rc = 0;
if( !is_internal )
{
g_external_aliases_lookup.clear( );
for( external_aliases_const_iterator
eaci = g_external_aliases.begin( ), end = g_external_aliases.end( ); eaci != end; ++eaci )
{
size_t num_extra = eaci->second->get_num_foreign_key_children( true );
if( num_extra )
{
eaci->second->set_key( get_key( ) );
eaci->second->copy_all_field_values( *this );
g_external_aliases_lookup.insert( make_pair( rc, eaci->second ) );
rc += num_extra;
}
}
}
set_total_child_relationships( rc );
return rc;
}
class_base* Meta_User::get_next_foreign_key_child(
size_t child_num, string& next_child_field, cascade_op op, bool is_internal )
{
class_base* p_class_base = 0;
( void )child_num;
( void )next_child_field;
( void )op;
return p_class_base;
}
void Meta_User::add_extra_fixed_info( vector< pair< string, string > >& fixed_info ) const
{
p_impl->add_extra_fixed_info( fixed_info );
}
void Meta_User::add_extra_paging_info( vector< pair< string, string > >& paging_info ) const
{
p_impl->add_extra_paging_info( paging_info );
}
string Meta_User::get_class_id( ) const
{
return static_class_id( );
}
string Meta_User::get_class_name( ) const
{
return static_class_name( );
}
string Meta_User::get_plural_name( ) const
{
return static_plural_name( );
}
string Meta_User::get_module_id( ) const
{
return static_module_id( );
}
string Meta_User::get_module_name( ) const
{
return static_module_name( );
}
string Meta_User::get_display_name( bool plural ) const
{
string key( plural ? "plural_" : "class_" );
key += "user";
return get_module_string( key );
}
string Meta_User::get_create_instance_info( ) const
{
return "";
}
string Meta_User::get_update_instance_info( ) const
{
return "";
}
string Meta_User::get_destroy_instance_info( ) const
{
return "";
}
string Meta_User::get_execute_procedure_info( const string& procedure_id ) const
{
string retval;
if( procedure_id.empty( ) )
throw runtime_error( "unexpected empty procedure_id for get_execute_procedure_info" );
return retval;
}
bool Meta_User::get_is_alias( ) const
{
return false;
}
void Meta_User::get_alias_base_info( pair< string, string >& alias_base_info ) const
{
( void )alias_base_info;
}
void Meta_User::get_base_class_info( vector< pair< string, string > >& base_class_info ) const
{
( void )base_class_info;
}
class_base& Meta_User::get_or_create_graph_child( const string& context )
{
class_base* p_class_base( 0 );
string::size_type pos = context.find( '.' );
string sub_context( context.substr( 0, pos ) );
if( sub_context.empty( ) )
throw runtime_error( "unexpected empty sub-context" );
else if( sub_context == c_field_id_Workgroup || sub_context == c_field_name_Workgroup )
p_class_base = &Workgroup( );
if( !p_class_base )
throw runtime_error( "unknown sub-context '" + sub_context + "'" );
if( pos != string::npos )
p_class_base = &p_class_base->get_or_create_graph_child( context.substr( pos + 1 ) );
return *p_class_base;
}
void Meta_User::get_sql_column_names(
vector< string >& names, bool* p_done, const string* p_class_name ) const
{
if( p_done && *p_done )
return;
names.push_back( "C_Active" );
names.push_back( "C_Description" );
names.push_back( "C_Email" );
names.push_back( "C_Password" );
names.push_back( "C_Permissions" );
names.push_back( "C_User_Hash" );
names.push_back( "C_User_Id" );
names.push_back( "C_Workgroup" );
if( p_done && p_class_name && *p_class_name == static_class_name( ) )
*p_done = true;
}
void Meta_User::get_sql_column_values(
vector< string >& values, bool* p_done, const string* p_class_name ) const
{
if( p_done && *p_done )
return;
values.push_back( to_string( Active( ) ) );
values.push_back( sql_quote( to_string( Description( ) ) ) );
values.push_back( sql_quote( to_string( Email( ) ) ) );
values.push_back( sql_quote( to_string( Password( ) ) ) );
values.push_back( sql_quote( to_string( Permissions( ) ) ) );
values.push_back( sql_quote( to_string( User_Hash( ) ) ) );
values.push_back( sql_quote( to_string( User_Id( ) ) ) );
values.push_back( sql_quote( to_string( Workgroup( ) ) ) );
if( p_done && p_class_name && *p_class_name == static_class_name( ) )
*p_done = true;
}
void Meta_User::get_required_field_names(
set< string >& names, bool use_transients, set< string >* p_dependents ) const
{
set< string > local_dependents;
set< string >& dependents( p_dependents ? *p_dependents : local_dependents );
get_always_required_field_names( names, use_transients, dependents );
// [<start get_required_field_names>]
// [<finish get_required_field_names>]
}
void Meta_User::get_always_required_field_names(
set< string >& names, bool use_transients, set< string >& dependents ) const
{
( void )names;
( void )dependents;
( void )use_transients;
// [<start get_always_required_field_names>]
// [<finish get_always_required_field_names>]
}
void Meta_User::get_transient_replacement_field_names( const string& name, vector< string >& names ) const
{
( void )name;
( void )names;
// [<start get_transient_replacement_field_names>]
// [<finish get_transient_replacement_field_names>]
}
void Meta_User::do_generate_sql(
generate_sql_type type, vector< string >& sql_stmts, set< string >& tx_key_info ) const
{
generate_sql( static_class_name( ), type, sql_stmts, tx_key_info );
}
const char* Meta_User::static_resolved_module_id( )
{
return static_module_id( );
}
const char* Meta_User::static_resolved_module_name( )
{
return static_module_name( );
}
const char* Meta_User::static_lock_class_id( )
{
return "100100";
}
const char* Meta_User::static_check_class_name( )
{
return "User";
}
bool Meta_User::static_has_derivations( )
{
return !g_derivations.empty( );
}
void Meta_User::static_get_class_info( class_info_container& class_info )
{
class_info.push_back( "100.100100" );
}
void Meta_User::static_get_field_info( field_info_container& all_field_info )
{
all_field_info.push_back( field_info( "100102", "Active", "bool", false, "", "" ) );
all_field_info.push_back( field_info( "100104", "Description", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100105", "Email", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100103", "Password", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100108", "Password_Hash", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100106", "Permissions", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100107", "User_Hash", "string", false, "", "" ) );
all_field_info.push_back( field_info( "100101", "User_Id", "string", false, "", "" ) );
all_field_info.push_back( field_info( "300100", "Workgroup", "Meta_Workgroup", false, "", "" ) );
}
void Meta_User::static_get_foreign_key_info( foreign_key_info_container& foreign_key_info )
{
( void )foreign_key_info;
foreign_key_info.insert( foreign_key_info_value_type( c_field_id_Workgroup, make_pair( "Meta.100100", "Meta_Workgroup" ) ) );
}
int Meta_User::static_get_num_fields( bool* p_done, const string* p_class_name )
{
if( p_done && p_class_name && *p_class_name == static_class_name( ) )
*p_done = true;
return c_num_fields;
}
bool Meta_User::static_is_field_transient( field_id id )
{
return is_transient_field( static_get_field_id( id ) );
}
const char* Meta_User::static_get_field_id( field_id id )
{
const char* p_id = 0;
switch( id )
{
case 1:
p_id = "100102";
break;
case 2:
p_id = "100104";
break;
case 3:
p_id = "100105";
break;
case 4:
p_id = "100103";
break;
case 5:
p_id = "100108";
break;
case 6:
p_id = "100106";
break;
case 7:
p_id = "100107";
break;
case 8:
p_id = "100101";
break;
case 9:
p_id = "300100";
break;
}
if( !p_id )
throw runtime_error( "unknown field id #" + to_string( id ) + " for class User" );
return p_id;
}
const char* Meta_User::static_get_field_name( field_id id )
{
const char* p_id = 0;
switch( id )
{
case 1:
p_id = "Active";
break;
case 2:
p_id = "Description";
break;
case 3:
p_id = "Email";
break;
case 4:
p_id = "Password";
break;
case 5:
p_id = "Password_Hash";
break;
case 6:
p_id = "Permissions";
break;
case 7:
p_id = "User_Hash";
break;
case 8:
p_id = "User_Id";
break;
case 9:
p_id = "Workgroup";
break;
}
if( !p_id )
throw runtime_error( "unknown field id #" + to_string( id ) + " for class User" );
return p_id;
}
int Meta_User::static_get_field_num( const string& field )
{
int rc = 0;
if( field.empty( ) )
throw runtime_error( "unexpected empty field name/id for static_get_field_num( )" );
else if( field == c_field_id_Active || field == c_field_name_Active )
rc += 1;
else if( field == c_field_id_Description || field == c_field_name_Description )
rc += 2;
else if( field == c_field_id_Email || field == c_field_name_Email )
rc += 3;
else if( field == c_field_id_Password || field == c_field_name_Password )
rc += 4;
else if( field == c_field_id_Password_Hash || field == c_field_name_Password_Hash )
rc += 5;
else if( field == c_field_id_Permissions || field == c_field_name_Permissions )
rc += 6;
else if( field == c_field_id_User_Hash || field == c_field_name_User_Hash )
rc += 7;
else if( field == c_field_id_User_Id || field == c_field_name_User_Id )
rc += 8;
else if( field == c_field_id_Workgroup || field == c_field_name_Workgroup )
rc += 9;
return rc - 1;
}
procedure_info_container& Meta_User::static_get_procedure_info( )
{
static procedure_info_container procedures;
return procedures;
}
string Meta_User::static_get_sql_columns( )
{
string sql_columns;
sql_columns +=
"C_Key_ VARCHAR(75),"
"C_Ver_ INTEGER NOT NULL,"
"C_Rev_ INTEGER NOT NULL,"
"C_Typ_ VARCHAR(24) NOT NULL,"
"C_Active INTEGER NOT NULL,"
"C_Description VARCHAR(200) NOT NULL,"
"C_Email VARCHAR(200) NOT NULL,"
"C_Password VARCHAR(200) NOT NULL,"
"C_Permissions VARCHAR(200) NOT NULL,"
"C_User_Hash VARCHAR(200) NOT NULL,"
"C_User_Id VARCHAR(200) NOT NULL,"
"C_Workgroup VARCHAR(75) NOT NULL,"
"PRIMARY KEY(C_Key_)";
return sql_columns;
}
void Meta_User::static_get_text_search_fields( vector< string >& fields )
{
( void )fields;
}
void Meta_User::static_get_all_enum_pairs( vector< pair< string, string > >& pairs )
{
( void )pairs;
}
void Meta_User::static_get_sql_indexes( vector< string >& indexes )
{
indexes.push_back( "C_Active,C_Description,C_Key_" );
indexes.push_back( "C_Active,C_User_Id" );
indexes.push_back( "C_Description,C_Key_" );
indexes.push_back( "C_User_Hash" );
indexes.push_back( "C_User_Id" );
indexes.push_back( "C_Workgroup,C_Active,C_Description,C_Key_" );
indexes.push_back( "C_Workgroup,C_Active,C_User_Id" );
indexes.push_back( "C_Workgroup,C_Description,C_Key_" );
indexes.push_back( "C_Workgroup,C_User_Id" );
}
void Meta_User::static_get_sql_unique_indexes( vector< string >& indexes )
{
indexes.push_back( "C_Active,C_User_Id" );
indexes.push_back( "C_User_Hash" );
indexes.push_back( "C_User_Id" );
indexes.push_back( "C_Workgroup,C_Active,C_User_Id" );
indexes.push_back( "C_Workgroup,C_User_Id" );
}
void Meta_User::static_insert_derivation( const string& module_and_class_id )
{
g_derivations.insert( module_and_class_id );
}
void Meta_User::static_remove_derivation( const string& module_and_class_id )
{
if( g_derivations.count( module_and_class_id ) )
g_derivations.erase( module_and_class_id );
}
void Meta_User::static_insert_external_alias( const string& module_and_class_id, Meta_User* p_instance )
{
g_external_aliases.insert( external_aliases_value_type( module_and_class_id, p_instance ) );
}
void Meta_User::static_remove_external_alias( const string& module_and_class_id )
{
if( g_external_aliases.count( module_and_class_id ) )
{
delete g_external_aliases[ module_and_class_id ];
g_external_aliases.erase( module_and_class_id );
}
}
void Meta_User::static_class_init( const char* p_module_name )
{
if( !p_module_name )
throw runtime_error( "unexpected null module name pointer for init" );
// [<start static_class_init>]
// [<finish static_class_init>]
}
void Meta_User::static_class_term( const char* p_module_name )
{
if( !p_module_name )
throw runtime_error( "unexpected null module name pointer for term" );
// [<start static_class_term>]
// [<finish static_class_term>]
}
| [
"ian@ciyam.com"
] | ian@ciyam.com |
4247d072ec902f878760f31053b852fab97a8554 | a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286 | /build/iOS/Preview/include/Fuse.Scripting.DoubleChangedArgs.h | ac09d636ecb5d4baf61cee89483c5cfce471caf5 | [] | no_license | epireve/hikr-tute | df0af11d1cfbdf6e874372b019d30ab0541c09b7 | 545501fba7044b4cc927baea2edec0674769e22c | refs/heads/master | 2021-09-02T13:54:05.359975 | 2018-01-03T01:21:31 | 2018-01-03T01:21:31 | 115,536,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,050 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Scripting/1.4.2/IScriptEvent.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Scripting.IScriptEvent.h>
#include <Uno.Double.h>
#include <Uno.UX.ValueChangedArgs-1.h>
namespace g{namespace Fuse{namespace Scripting{struct DoubleChangedArgs;}}}
namespace g{
namespace Fuse{
namespace Scripting{
// public sealed class DoubleChangedArgs :52
// {
struct DoubleChangedArgs_type : uType
{
::g::Fuse::Scripting::IScriptEvent interface0;
};
DoubleChangedArgs_type* DoubleChangedArgs_typeof();
void DoubleChangedArgs__ctor_2_fn(DoubleChangedArgs* __this, double* value);
void DoubleChangedArgs__FuseScriptingIScriptEventSerialize_fn(DoubleChangedArgs* __this, uObject* s);
void DoubleChangedArgs__New3_fn(double* value, DoubleChangedArgs** __retval);
struct DoubleChangedArgs : ::g::Uno::UX::ValueChangedArgs
{
void ctor_2(double value);
static DoubleChangedArgs* New3(double value);
};
// }
}}} // ::g::Fuse::Scripting
| [
"i@firdaus.my"
] | i@firdaus.my |
4be16777fe0da20ea3bade06312b39ff91e93412 | 19a4fffd52c60cc83132e6bb622b1c2ed85bc67c | /No482_LicenseKeyFormatting.cpp | 446fc289bbb3b087ba2df3e0d2cda89ba3ac761d | [] | no_license | XingwenZhang/Leetcode | 2562d8f475b381a44b891105e29f23844b6bf4a4 | 3ce14802a0494988e5372565ccac709ac2489f7a | refs/heads/master | 2021-04-26T07:29:05.063883 | 2018-01-01T08:16:29 | 2018-01-01T08:16:29 | 65,857,071 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,814 | cpp | // 482. License Key Formatting
// Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.
// We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.
// So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.
// Example 1:
// Input: S = "2-4A0r7-4k", K = 4
// Output: "24A0-R74K"
// Explanation: The string S has been split into two parts, each part has 4 characters.
// Example 2:
// Input: S = "2-4A0r7-4k", K = 3
// Output: "24-A0R-74K"
// Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said above.
// Note:
// The length of string S will not exceed 12,000, and K is a positive integer.
// String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
// String S is non-empty.
// Python Solution
// class Solution(object):
// def licenseKeyFormatting(self, S, K):
// """
// :type S: str
// :type K: int
// :rtype: str
// """
// # S =''.join(S.split('-')).upper()[::-1]
// # size = len(S)
// # S = iter(S)
// # items = [S] * K
// # res = '-'.join(''.join(item) for item in zip(*items))
// # c=''
// # if(len(res) < size//K-1 + size):
// # res += '-'
// # c = next(S)
// # try:
// # while(c):
// # res += c
// # c = next(S)
// # res = res[::-1]
// # return res
// S = ''.join(S.split('-')).upper()[::-1]
// res = '-'.join(S[i:i+K] for i in range(0,len(S),K))[::-1]
// return res
// C++ Solution
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res = "";
if(S.empty())
return res;
for(int i=S.size()-1; i>=0; i--){
if(S[i] != '-'){
res.append(res.size() % (K+1) == K ? "-" : "").push_back(S[i]);
}
}
reverse(res.begin(), res.end());
transform(res.begin(), res.end(), res.begin(), ::toupper);
return res;
}
};
| [
"xingwenz@usc.edu"
] | xingwenz@usc.edu |
24b6761bb64ebe9397a620b63bd5e9107ea7ba27 | 9e330ca8c015e8c9247159102aa4c20b6966edb2 | /contracts/fscio.system/delegate_bandwidth.cpp | f162df1ee5ba42ecf6d17b9f08dc7ce230e7de37 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | w1r2p1/fsc | 40cc7c92c1d9ac37ff31d7ccdba3e8cbe6a242f6 | 5070b49e7007d50f95f28463f167a440eea612a8 | refs/heads/master | 2022-03-24T14:42:48.998615 | 2019-10-29T10:03:33 | 2019-12-06T04:10:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,503 | cpp | /**
* @file
* @copyright defined in fsc/LICENSE
*/
#include "fscio.system.hpp"
#include <fsciolib/fscio.hpp>
#include <fsciolib/print.hpp>
#include <fsciolib/datastream.hpp>
#include <fsciolib/serialize.hpp>
#include <fsciolib/multi_index.hpp>
#include <fsciolib/privileged.h>
#include <fsciolib/transaction.hpp>
#include <fscio.token/fscio.token.hpp>
#include <cmath>
#include <map>
namespace fsciosystem {
using fscio::asset;
using fscio::indexed_by;
using fscio::const_mem_fun;
using fscio::bytes;
using fscio::print;
using fscio::permission_level;
using std::map;
using std::pair;
static constexpr time refund_delay = 3*24*3600;
static constexpr time refund_expiration_time = 3600;
struct user_resources {
account_name owner;
asset net_weight;
asset cpu_weight;
int64_t ram_bytes = 0;
uint64_t primary_key()const { return owner; }
// explicit serialization macro is not necessary, used here only to improve compilation time
FSCLIB_SERIALIZE( user_resources, (owner)(net_weight)(cpu_weight)(ram_bytes) )
};
/**
* Every user 'from' has a scope/table that uses every receipient 'to' as the primary key.
*/
struct delegated_bandwidth {
account_name from;
account_name to;
asset net_weight;
asset cpu_weight;
uint64_t primary_key()const { return to; }
// explicit serialization macro is not necessary, used here only to improve compilation time
FSCLIB_SERIALIZE( delegated_bandwidth, (from)(to)(net_weight)(cpu_weight) )
};
struct refund_request {
account_name owner;
time request_time;
fscio::asset net_amount;
fscio::asset cpu_amount;
uint64_t primary_key()const { return owner; }
// explicit serialization macro is not necessary, used here only to improve compilation time
FSCLIB_SERIALIZE( refund_request, (owner)(request_time)(net_amount)(cpu_amount) )
};
/**
* These tables are designed to be constructed in the scope of the relevant user, this
* facilitates simpler API for per-user queries
*/
typedef fscio::multi_index< N(userres), user_resources> user_resources_table;
typedef fscio::multi_index< N(delband), delegated_bandwidth> del_bandwidth_table;
typedef fscio::multi_index< N(refunds), refund_request> refunds_table;
/**
* This action will buy an exact amount of ram and bill the payer the current market price.
*/
void system_contract::buyrambytes( account_name payer, account_name receiver, uint32_t bytes ) {
auto itr = _rammarket.find(S(4,RAMCORE));
auto tmp = *itr;
auto fscout = tmp.convert( asset(bytes,S(0,RAM)), CORE_SYMBOL );
buyram( payer, receiver, fscout );
}
/**
* When buying ram the payer irreversiblly transfers quant to system contract and only
* the receiver may reclaim the tokens via the sellram action. The receiver pays for the
* storage of all database records associated with this action.
*
* RAM is a scarce resource whose supply is defined by global properties max_ram_size. RAM is
* priced using the bancor algorithm such that price-per-byte with a constant reserve ratio of 100:1.
*/
void system_contract::buyram( account_name payer, account_name receiver, asset quant )
{
require_auth( payer );
fscio_assert( quant.amount > 0, "must purchase a positive amount" );
auto fee = quant;
fee.amount = ( fee.amount + 199 ) / 200; /// .5% fee (round up)
// fee.amount cannot be 0 since that is only possible if quant.amount is 0 which is not allowed by the assert above.
// If quant.amount == 1, then fee.amount == 1,
// otherwise if quant.amount > 1, then 0 < fee.amount < quant.amount.
auto quant_after_fee = quant;
quant_after_fee.amount -= fee.amount;
// quant_after_fee.amount should be > 0 if quant.amount > 1.
// If quant.amount == 1, then quant_after_fee.amount == 0 and the next inline transfer will fail causing the buyram action to fail.
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {payer,N(active)},
{ payer, N(fscio.ram), quant_after_fee, std::string("buy ram") } );
if( fee.amount > 0 ) {
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {payer,N(active)},
{ payer, N(fscio.ramfee), fee, std::string("ram fee") } );
}
int64_t bytes_out;
const auto& market = _rammarket.get(S(4,RAMCORE), "ram market does not exist");
_rammarket.modify( market, 0, [&]( auto& es ) {
bytes_out = es.convert( quant_after_fee, S(0,RAM) ).amount;
});
fscio_assert( bytes_out > 0, "must reserve a positive amount" );
_gstate.total_ram_bytes_reserved += uint64_t(bytes_out);
_gstate.total_ram_stake += quant_after_fee.amount;
user_resources_table userres( _self, receiver );
auto res_itr = userres.find( receiver );
if( res_itr == userres.end() ) {
res_itr = userres.emplace( receiver, [&]( auto& res ) {
res.owner = receiver;
res.ram_bytes = bytes_out;
});
} else {
userres.modify( res_itr, receiver, [&]( auto& res ) {
res.ram_bytes += bytes_out;
});
}
set_resource_limits( res_itr->owner, res_itr->ram_bytes, res_itr->net_weight.amount, res_itr->cpu_weight.amount );
}
/**
* The system contract now buys and sells RAM allocations at prevailing market prices.
* This may result in traders buying RAM today in anticipation of potential shortages
* tomorrow. Overall this will result in the market balancing the supply and demand
* for RAM over time.
*/
void system_contract::sellram( account_name account, int64_t bytes ) {
require_auth( account );
fscio_assert( bytes > 0, "cannot sell negative byte" );
user_resources_table userres( _self, account );
auto res_itr = userres.find( account );
fscio_assert( res_itr != userres.end(), "no resource row" );
fscio_assert( res_itr->ram_bytes >= bytes, "insufficient quota" );
asset tokens_out;
auto itr = _rammarket.find(S(4,RAMCORE));
_rammarket.modify( itr, 0, [&]( auto& es ) {
/// the cast to int64_t of bytes is safe because we certify bytes is <= quota which is limited by prior purchases
tokens_out = es.convert( asset(bytes,S(0,RAM)), CORE_SYMBOL);
});
fscio_assert( tokens_out.amount > 1, "token amount received from selling ram is too low" );
_gstate.total_ram_bytes_reserved -= static_cast<decltype(_gstate.total_ram_bytes_reserved)>(bytes); // bytes > 0 is asserted above
_gstate.total_ram_stake -= tokens_out.amount;
//// this shouldn't happen, but just in case it does we should prevent it
fscio_assert( _gstate.total_ram_stake >= 0, "error, attempt to unstake more tokens than previously staked" );
userres.modify( res_itr, account, [&]( auto& res ) {
res.ram_bytes -= bytes;
});
set_resource_limits( res_itr->owner, res_itr->ram_bytes, res_itr->net_weight.amount, res_itr->cpu_weight.amount );
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {N(fscio.ram),N(active)},
{ N(fscio.ram), account, asset(tokens_out), std::string("sell ram") } );
auto fee = ( tokens_out.amount + 199 ) / 200; /// .5% fee (round up)
// since tokens_out.amount was asserted to be at least 2 earlier, fee.amount < tokens_out.amount
if( fee > 0 ) {
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {account,N(active)},
{ account, N(fscio.ramfee), asset(fee), std::string("sell ram fee") } );
}
}
void validate_b1_vesting( int64_t stake ) {
const int64_t base_time = 1527811200; /// 2018-06-01
const int64_t max_claimable = 100'000'000'0000ll;
const int64_t claimable = int64_t(max_claimable * double(now()-base_time) / (10*seconds_per_year) );
fscio_assert( max_claimable - claimable <= stake, "b1 can only claim their tokens over 10 years" );
}
void system_contract::changebw( account_name from, account_name receiver,
const asset stake_net_delta, const asset stake_cpu_delta, bool transfer )
{
require_auth( from );
fscio_assert( stake_net_delta != asset(0) || stake_cpu_delta != asset(0), "should stake non-zero amount" );
fscio_assert( std::abs( (stake_net_delta + stake_cpu_delta).amount )
>= std::max( std::abs( stake_net_delta.amount ), std::abs( stake_cpu_delta.amount ) ),
"net and cpu deltas cannot be opposite signs" );
account_name source_stake_from = from;
if ( transfer ) {
from = receiver;
}
// update stake delegated from "from" to "receiver"
{
del_bandwidth_table del_tbl( _self, from);
auto itr = del_tbl.find( receiver );
if( itr == del_tbl.end() ) {
itr = del_tbl.emplace( from, [&]( auto& dbo ){
dbo.from = from;
dbo.to = receiver;
dbo.net_weight = stake_net_delta;
dbo.cpu_weight = stake_cpu_delta;
});
}
else {
del_tbl.modify( itr, 0, [&]( auto& dbo ){
dbo.net_weight += stake_net_delta;
dbo.cpu_weight += stake_cpu_delta;
});
}
fscio_assert( asset(0) <= itr->net_weight, "insufficient staked net bandwidth" );
fscio_assert( asset(0) <= itr->cpu_weight, "insufficient staked cpu bandwidth" );
if ( itr->net_weight == asset(0) && itr->cpu_weight == asset(0) ) {
del_tbl.erase( itr );
}
} // itr can be invalid, should go out of scope
// update totals of "receiver"
{
user_resources_table totals_tbl( _self, receiver );
auto tot_itr = totals_tbl.find( receiver );
if( tot_itr == totals_tbl.end() ) {
tot_itr = totals_tbl.emplace( from, [&]( auto& tot ) {
tot.owner = receiver;
tot.net_weight = stake_net_delta;
tot.cpu_weight = stake_cpu_delta;
});
} else {
totals_tbl.modify( tot_itr, from == receiver ? from : 0, [&]( auto& tot ) {
tot.net_weight += stake_net_delta;
tot.cpu_weight += stake_cpu_delta;
});
}
fscio_assert( asset(0) <= tot_itr->net_weight, "insufficient staked total net bandwidth" );
fscio_assert( asset(0) <= tot_itr->cpu_weight, "insufficient staked total cpu bandwidth" );
set_resource_limits( receiver, tot_itr->ram_bytes, tot_itr->net_weight.amount, tot_itr->cpu_weight.amount );
if ( tot_itr->net_weight == asset(0) && tot_itr->cpu_weight == asset(0) && tot_itr->ram_bytes == 0 ) {
totals_tbl.erase( tot_itr );
}
} // tot_itr can be invalid, should go out of scope
// create refund or update from existing refund
if ( N(fscio.stake) != source_stake_from ) { //for fscio both transfer and refund make no sense
refunds_table refunds_tbl( _self, from );
auto req = refunds_tbl.find( from );
//create/update/delete refund
auto net_balance = stake_net_delta;
auto cpu_balance = stake_cpu_delta;
bool need_deferred_trx = false;
// net and cpu are same sign by assertions in delegatebw and undelegatebw
// redundant assertion also at start of changebw to protect against misuse of changebw
bool is_undelegating = (net_balance.amount + cpu_balance.amount ) < 0;
bool is_delegating_to_self = (!transfer && from == receiver);
if( is_delegating_to_self || is_undelegating ) {
if ( req != refunds_tbl.end() ) { //need to update refund
refunds_tbl.modify( req, 0, [&]( refund_request& r ) {
if ( net_balance < asset(0) || cpu_balance < asset(0) ) {
r.request_time = now();
}
r.net_amount -= net_balance;
if ( r.net_amount < asset(0) ) {
net_balance = -r.net_amount;
r.net_amount = asset(0);
} else {
net_balance = asset(0);
}
r.cpu_amount -= cpu_balance;
if ( r.cpu_amount < asset(0) ){
cpu_balance = -r.cpu_amount;
r.cpu_amount = asset(0);
} else {
cpu_balance = asset(0);
}
});
fscio_assert( asset(0) <= req->net_amount, "negative net refund amount" ); //should never happen
fscio_assert( asset(0) <= req->cpu_amount, "negative cpu refund amount" ); //should never happen
if ( req->net_amount == asset(0) && req->cpu_amount == asset(0) ) {
refunds_tbl.erase( req );
need_deferred_trx = false;
} else {
need_deferred_trx = true;
}
} else if ( net_balance < asset(0) || cpu_balance < asset(0) ) { //need to create refund
refunds_tbl.emplace( from, [&]( refund_request& r ) {
r.owner = from;
if ( net_balance < asset(0) ) {
r.net_amount = -net_balance;
net_balance = asset(0);
} // else r.net_amount = 0 by default constructor
if ( cpu_balance < asset(0) ) {
r.cpu_amount = -cpu_balance;
cpu_balance = asset(0);
} // else r.cpu_amount = 0 by default constructor
r.request_time = now();
});
need_deferred_trx = true;
} // else stake increase requested with no existing row in refunds_tbl -> nothing to do with refunds_tbl
} /// end if is_delegating_to_self || is_undelegating
if ( need_deferred_trx ) {
fscio::transaction out;
out.actions.emplace_back( permission_level{ from, N(active) }, _self, N(refund), from );
out.delay_sec = refund_delay;
cancel_deferred( from ); // TODO: Remove this line when replacing deferred trxs is fixed
out.send( from, from, true );
} else {
cancel_deferred( from );
}
auto transfer_amount = net_balance + cpu_balance;
if ( asset(0) < transfer_amount ) {
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {source_stake_from, N(active)},
{ source_stake_from, N(fscio.stake), asset(transfer_amount), std::string("stake bandwidth") } );
}
}
// update voting power
{
asset total_update = stake_net_delta + stake_cpu_delta;
auto from_voter = _voters.find(from);
if( from_voter == _voters.end() ) {
from_voter = _voters.emplace( from, [&]( auto& v ) {
v.owner = from;
v.staked = total_update.amount;
});
} else {
_voters.modify( from_voter, 0, [&]( auto& v ) {
v.staked += total_update.amount;
});
}
fscio_assert( 0 <= from_voter->staked, "stake for voting cannot be negative");
if( from == N(b1) ) {
validate_b1_vesting( from_voter->staked );
}
if( from_voter->producers.size() || from_voter->proxy ) {
update_votes( from, from_voter->proxy, from_voter->producers, false );
}
}
}
void system_contract::delegatebw( account_name from, account_name receiver,
asset stake_net_quantity,
asset stake_cpu_quantity, bool transfer )
{
fscio_assert( stake_cpu_quantity >= asset(0), "must stake a positive amount" );
fscio_assert( stake_net_quantity >= asset(0), "must stake a positive amount" );
fscio_assert( stake_net_quantity + stake_cpu_quantity > asset(0), "must stake a positive amount" );
fscio_assert( !transfer || from != receiver, "cannot use transfer flag if delegating to self" );
changebw( from, receiver, stake_net_quantity, stake_cpu_quantity, transfer);
} // delegatebw
void system_contract::undelegatebw( account_name from, account_name receiver,
asset unstake_net_quantity, asset unstake_cpu_quantity )
{
fscio_assert( asset() <= unstake_cpu_quantity, "must unstake a positive amount" );
fscio_assert( asset() <= unstake_net_quantity, "must unstake a positive amount" );
fscio_assert( asset() < unstake_cpu_quantity + unstake_net_quantity, "must unstake a positive amount" );
fscio_assert( _gstate.total_activated_stake >= min_activated_stake,
"cannot undelegate bandwidth until the chain is activated (at least 15% of all tokens participate in voting)" );
changebw( from, receiver, -unstake_net_quantity, -unstake_cpu_quantity, false);
} // undelegatebw
void system_contract::refund( const account_name owner ) {
require_auth( owner );
refunds_table refunds_tbl( _self, owner );
auto req = refunds_tbl.find( owner );
fscio_assert( req != refunds_tbl.end(), "refund request not found" );
fscio_assert( req->request_time + refund_delay <= now(), "refund is not available yet" );
// Until now() becomes NOW, the fact that now() is the timestamp of the previous block could in theory
// allow people to get their tokens earlier than the 3 day delay if the unstake happened immediately after many
// consecutive missed blocks.
INLINE_ACTION_SENDER(fscio::token, transfer)( N(fscio.token), {N(fscio.stake),N(active)},
{ N(fscio.stake), req->owner, req->net_amount + req->cpu_amount, std::string("unstake") } );
refunds_tbl.erase( req );
}
} //namespace fsciosystem
| [
"jason@valicn.com"
] | jason@valicn.com |
085108255dabc6ea26e01a793f45b9a6ad9f2ae3 | 46f53e9a564192eed2f40dc927af6448f8608d13 | /components/cdm/renderer/widevine_key_systems.h | 15c55daf85e8784c65b00a0b37fdd5e41bc4dcff | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_CDM_RENDERER_WIDEVINE_KEY_SYSTEMS_H_
#define COMPONENTS_CDM_RENDERER_WIDEVINE_KEY_SYSTEMS_H_
#include <vector>
#include "build/build_config.h"
#include "media/base/key_system_info.h"
namespace cdm {
enum WidevineCdmType {
WIDEVINE,
#if defined(OS_ANDROID)
WIDEVINE_HR_NON_COMPOSITING,
#endif // defined(OS_ANDROID)
};
void AddWidevineWithCodecs(
WidevineCdmType widevine_cdm_type,
media::SupportedCodecs supported_codecs,
media::EmeSessionTypeSupport persistent_license_support,
media::EmeSessionTypeSupport persistent_release_message_support,
media::EmeFeatureSupport persistent_state_support,
media::EmeFeatureSupport distinctive_identifier_support,
std::vector<media::KeySystemInfo>* concrete_key_systems);
} // namespace cdm
#endif // COMPONENTS_CDM_RENDERER_WIDEVINE_KEY_SYSTEMS_H_
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
7093d90229b0bd9768a69248443227cd3ceb5760 | 78aa3bf3253370629766770cb00b523f1d406bcd | /src/editor/PointEntRenderer.h | 86180e24eff5aae576d28b4869e3dffb85eac81a | [
"Unlicense"
] | permissive | huidaoyuandian123/bspguy | 5b0517afe0a1b13de0957a129ea8ed8936612930 | 7d72ce7df394a90248b45a9c7f1667193826fba6 | refs/heads/master | 2023-07-04T21:14:32.619222 | 2021-04-04T05:59:32 | 2021-04-04T05:59:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 694 | h | #pragma once
#include "util.h"
#include "Fgd.h"
#include "VertexBuffer.h"
struct EntCube {
vec3 mins;
vec3 maxs;
COLOR4 color;
VertexBuffer* buffer;
VertexBuffer* selectBuffer; // red coloring for selected ents
VertexBuffer* wireframeBuffer; // yellow outline for selected ents
};
class PointEntRenderer {
public:
Fgd* fgd;
PointEntRenderer(Fgd* fgd, ShaderProgram* colorShader);
~PointEntRenderer();
EntCube* getEntCube(Entity* ent);
private:
ShaderProgram* colorShader;
map<string, EntCube*> cubeMap;
vector<EntCube*> entCubes;
void genPointEntCubes();
EntCube* getCubeMatchingProps(EntCube* cube);
void genCubeBuffers(EntCube* cube);
}; | [
"drake.rhunter@gmail.com"
] | drake.rhunter@gmail.com |
43ac23a328ec64bd6bebc3a5e37002c0eb28c8b4 | 524e30074edb03424218e937d92b2a89592a4373 | /src/config/Http_config.cpp | fc2f5d54b0f44093e6b93bb8acd42823bcfb7238 | [] | no_license | mnaji42/Webserv | 677fe158ea575fab8a82cd8679d7e98d11aed920 | 817e52ee3d7e21d3b910e181d5c0531c79cfc39c | refs/heads/master | 2023-02-09T03:45:12.341385 | 2021-01-04T11:37:39 | 2021-01-04T11:37:39 | 326,664,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,213 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Http_config.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skybt <skybt@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/10 21:32:33 by dnicolas #+# #+# */
/* Updated: 2020/05/08 02:01:37 by skybt ### ########.fr */
/* */
/* ************************************************************************** */
#include "parsing.hpp"
#include "Location_config.hpp"
#include "Server_config.hpp"
#include "Http_config.hpp"
Http_config::Http_config(void)
{
}
Http_config::Http_config(std::pair<std::string const&, size_t&> file)
{
std::string tmp;
this->pass_http_start(file);
while (file.second < file.first.size() && get_next_word(file) != "}")
{
tmp = pass_next_word(file);
if (tmp == "server")
this->add_new_server(file);
else
this->keyword_get_arg(file, tmp);
pass_spaces(file);
}
if (pass_next_word(file) != "}")
throw syntax_error(file, "block not end");
pass_spaces(file);
}
Http_config::Http_config(const Http_config ©)
{
(void)copy;
}
Http_config::~Http_config(void)
{
}
Http_config const &Http_config::operator=(const Http_config ©)
{
this->server = copy.server;
for (size_t i = 0; i < NB_KEYWORD; ++i)
this->arg[i] = copy.arg[i];
return (*this);
}
void Http_config::pass_http_start(std::pair<std::string const&, size_t&> file)
{
if (pass_spaces(file) == 0)
throw syntax_error(file, "not a valid syntax to start a block");
if (pass_next_word(file) != "{")
throw syntax_error(file, "not a valid syntax to start a block");
pass_spaces(file);
}
void Http_config::keyword_get_arg(
std::pair<std::string const&, size_t&>file, std::string const &keyword)
{
size_t i = 0;
std::vector<std::string> tmp;
while (i < NB_KEYWORD)
{
if (this->keyword[i] == keyword)
break ;
++i;
}
if (i >= NB_KEYWORD)
throw syntax_error(file, "not a valid keyword for http block");
pass_spaces(file);
tmp = pass_arg_value(file);
if (flag_keyword[i][MULTIPLE] == 0 || this->arg[i].empty())
this->arg[i] = tmp;
else
{
this->arg[i].push_back(";");
for (size_t j = 0; j < tmp.size(); ++j)
this->arg[i].push_back(tmp[j]);
}
if (tmp.size() < flag_keyword[i][MIN] || tmp.size() > flag_keyword[i][MAX])
throw syntax_error(file, "not good number of arguments");
if (!argument_error(i))
throw syntax_error(file, "wrong arguments");
}
void Http_config::add_new_server(std::pair<std::string const&, size_t&>file)
{
this->server.push_back(file);
}
void Http_config::set_argument(unsigned int keyword,
std::vector<std::string> new_arg)
{
if (keyword >= NB_KEYWORD)
return ;
this->arg[keyword] = new_arg;
}
void Http_config::set_recursively_argument(unsigned int keyword,
std::vector<std::string> new_arg)
{
if (keyword >= NB_KEYWORD || !this->arg[keyword].empty())
return ;
this->arg[keyword] = new_arg;
set_all_recursively_argument(keyword, new_arg);
}
void Http_config::set_recursively_argument(std::string const &str,
std::vector<std::string> new_arg)
{
unsigned int i = 0;
while (i < NB_KEYWORD)
{
if (this->keyword[i] == str)
{
std::cout << "| " <<this->keyword[i] << " " << str << std::endl;
if (!this->arg[i].empty())
return ;
this->arg[i] = new_arg;
set_all_recursively_argument(i, new_arg);
return ;
}
++i;
}
}
void Http_config::set_all_recursively_argument(unsigned int keyword,
std::vector<std::string> new_arg)
{
std::vector<Server_config>::iterator it = this->server.begin();
std::vector<Server_config>::iterator end = this->server.end();
if (keyword >= NB_KEYWORD)
return ;
for (; it != end; ++it)
(*it).set_recursively_argument(
static_cast<std::string>(this->keyword[keyword]), new_arg);
}
const char *Http_config::get_keyword(unsigned int nb) const
{
if (nb >= NB_KEYWORD)
throw error_exception("out of range");
return (this->keyword[nb]);
}
std::vector<std::string> const &Http_config::get_arg(unsigned int nb) const
{
if (nb >= NB_KEYWORD)
throw error_exception("out of range");
return (this->arg[nb]);
}
Server_config const &Http_config::get_server(size_t nb) const
{
if (nb >= this->server.size())
throw error_exception("out of range");
return (this->server[nb]);
}
size_t Http_config::nb_server(void) const
{
return (this->server.size());
}
bool Http_config::argument_error(size_t index)
{
if (index == ERROR_PAGE)
return (check_error_page_argument(this->arg[index]));
if (index == ROOT)
return (check_root_argument(this->arg[index]));
return (false);
}
const char *Http_config::keyword[NB_KEYWORD] = {
"error_page", "root"};
const unsigned int Http_config::flag_keyword[NB_KEYWORD][NB_FLAG_KEYWORD] =
{
{2, (unsigned int)-1, 1}, //ERROR_PAGE
{1, 1, 0}, //ROOT
};
| [
"mehdi.n.1993@gmail.com"
] | mehdi.n.1993@gmail.com |
b82695dbef31e4e55de52f29c81bc2e3e6308dd6 | 7cce0635a50e8d2db92b7b1bf4ad49fc218fb0b8 | /硬件仿真测试环境合集版27_优化_变量/MatrixTestSoft/MatrixTestSoft/MatrixTestSoft.h | 5d206409031b32fb064f281dac492d677b0d4455 | [] | no_license | liquanhai/cxm-hitech-matrix428 | dcebcacea58123aabcd9541704b42b3491444220 | d06042a3de79379a77b0e4e276de42de3c1c6d23 | refs/heads/master | 2021-01-20T12:06:23.622153 | 2013-01-24T01:05:10 | 2013-01-24T01:05:10 | 54,619,320 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | // MatrixTestSoft.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CMatrixTestSoftApp:
// See MatrixTestSoft.cpp for the implementation of this class
//
class CMatrixTestSoftApp : public CWinApp
{
public:
CMatrixTestSoftApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CMatrixTestSoftApp theApp; | [
"chengxianming1981@gmail.com"
] | chengxianming1981@gmail.com |
ddbf3645697b9cdd7ce3e1cadac2335f4610eab7 | 597995f8465ef515b58985386688d0e05b2f73d6 | /Project/DXRDemo/Source/Private/main.cpp | 41868d60e2460ca81fd31e59dbac6a8b44a8f49e | [] | no_license | Shuusui/DXRDemo | cb41347b5a4dc2d87eeea82b9d5c7802b8b01a4b | 23a085a67b3d0cccb334d1bd4f128a476ddbb79e | refs/heads/master | 2020-04-20T21:59:27.070077 | 2019-10-26T13:52:54 | 2019-10-26T13:52:54 | 169,125,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | #pragma region Includes
#include <windows.h>
#include "DX12.h"
#include "SharedMacros.h"
#include "WindowManager.h"
#include "SharedStructs.h"
#include "AssetManager.h"
#pragma endregion
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
UtilRen::SWindowCreationParams wndCreationParams = { UtilRen::EResolution::FULL_HD };
wndCreationParams.HInstance = hInstance;
wndCreationParams.NCmdShow = nShowCmd;
UtilRen::SWindowClassParams wndClassParams = {};
wndClassParams.ClassName = "DXRDemo";
const UtilRen::SAdjustWindowRectParams adjWndRectParams = {};
UtilRen::SWindowHandleParams wndHandleParams = {};
wndHandleParams.ClassName = "DXRDemo";
wndHandleParams.WindowName = "DXRDemo-MainWindow";
UtilRen::SWindowParams wndParams = { UtilRen::EResolution::FULL_HD };
wndParams.WndHandle = Rendering::Window::WindowManager::CreateNewWindow(wndCreationParams, wndClassParams, adjWndRectParams, wndHandleParams);
Rendering::DX12* dx12 = new Rendering::DX12(wndParams);
dx12->Init();
UtAI::AssetManager::Create();
UtAI::AssetManager* assetManager = UtAI::AssetManager::GetHandle();
assetManager->Init();
std::vector<Util::Util::SMesh> meshes = assetManager->GetMeshes();
std::vector<UtilRen::SVector4> positions = {};
for (const Util::Util::SMesh& mesh : meshes)
{
for (const Util::Util::SVertex& vertex : mesh.Vertices.Vertices)
{
UtilRen::SVector4 vector = { vertex.X, vertex.Y, vertex.Z, vertex.W };
positions.push_back(vector);
}
}
dx12->LoadAssets(positions);
dx12->LoadShader(assetManager->GetShaderPaths());
MSG msg = {};
while (msg.message != WM_QUIT)
{
Rendering::Window::WindowManager::RunWindow(wndParams.WndHandle, msg);
dx12->OnRender();
}
dx12->OnDestroy();
delete(dx12);
return static_cast<int>(msg.wParam);
} | [
"K.schaefer92@gmx.de"
] | K.schaefer92@gmx.de |
2a8fa0f4570f46b6c495ded58333458ce86d9d2f | db8be521b8e2eab424f594a50886275d68dd5a1b | /Competitive Programming/TEST/webcam/CPPfile.cpp | 6e67b32c36d18002222a58e7d51840597766f71b | [] | no_license | purnimamehta/Articles-n-Algorithms | 7f2aa8046c8eef0e510689771a493f84707e9297 | aaea50bf1627585b935f8e43465360866b3b4eac | refs/heads/master | 2021-01-11T01:01:53.382696 | 2017-01-15T04:12:44 | 2017-01-15T04:12:44 | 70,463,305 | 10 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 6,736 | cpp | #include "VideoCapture.h"
//VIDEODEVICE
//public
VideoDevice::VideoDevice()
{
friendlyname = (char*) calloc(1, MAX_DEVICE_NAME * sizeof(char));
filtername = (WCHAR*) calloc(1, MAX_DEVICE_NAME * sizeof(WCHAR));
filter = 0;
}
VideoDevice::~VideoDevice()
{
free(friendlyname);
free(filtername);
}
const char* VideoDevice::GetFriendlyName()
{
return friendlyname;
}
//VIDEOCAPTURE
//public
VideoCapture::VideoCapture(VideoCaptureCallback cb)
{
CoInitialize(NULL);
playing = false;
current = 0;
callbackhandler = new CallbackHandler(cb);
devices = new VideoDevice[MAX_DEVICES];
InitializeGraph();
SetSourceFilters();
SetSampleGrabber();
SetNullRenderer();
}
VideoCapture::~VideoCapture()
{
delete callbackhandler;
delete[] devices;
}
VideoDevice* VideoCapture::GetDevices()
{
return devices;
}
int VideoCapture::NumDevices()
{
return num_devices;
}
void VideoCapture::Select(VideoDevice* dev)
{
HRESULT hr;
LONGLONG start=MAXLONGLONG, stop=MAXLONGLONG;
bool was_playing = playing;
if (!dev->filter) throw E_INVALIDARG;
//temporary stop
if (playing) Stop();
if (current)
{
//remove and add the filters to force disconnect of pins
graph->RemoveFilter(current->filter);
graph->RemoveFilter(samplegrabberfilter);
graph->AddFilter(samplegrabberfilter,L"Sample Grabber");
graph->AddFilter(current->filter, current->filtername);
}
start = 0;
current = dev;
//connect graph with current source filter
#ifdef SHOW_DEBUG_RENDERER
hr = capture->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, current->filter, samplegrabberfilter, NULL);
#else
hr = capture->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, current->filter, samplegrabberfilter, nullrenderer);
#endif
if (hr != S_OK) throw hr;
//start streaming
hr = capture->ControlStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, current->filter, &start, &stop, 1,2);
if (hr < 0) throw hr;
//restart
if (was_playing) Start();
}
void VideoCapture::Start()
{
HRESULT hr;
hr = control->Run();
if (hr < 0) throw hr;
playing = true;
}
void VideoCapture::Stop()
{
HRESULT hr;
hr = control->StopWhenReady();
if (hr < 0) throw hr;
playing = false;
}
//protected
void VideoCapture::InitializeGraph()
{
HRESULT hr;
//create the FilterGraph
hr = CoCreateInstance(CLSID_FilterGraph,NULL,CLSCTX_INPROC_SERVER,IID_IFilterGraph2,(void**) &graph);
if (hr < 0) throw hr;
//create the CaptureGraphBuilder
hr = CoCreateInstance(CLSID_CaptureGraphBuilder2,NULL,CLSCTX_INPROC_SERVER,IID_ICaptureGraphBuilder2,(void**) &capture);
if (hr < 0) throw hr;
//get the controller for the graph
hr = graph->QueryInterface(IID_IMediaControl, (void**) &control);
if (hr < 0) throw hr;
capture->SetFiltergraph(graph);
}
void VideoCapture::SetSourceFilters()
{
HRESULT hr;
VARIANT name;
LONGLONG start=MAXLONGLONG, stop=MAXLONGLONG;
unsigned long dev_count;
ICreateDevEnum* dev_enum;
IEnumMoniker* enum_moniker;
IMoniker* moniker;
IPropertyBag* pbag;
//create an enumerator for video input devices
hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,CLSCTX_INPROC_SERVER,IID_ICreateDevEnum,(void**) &dev_enum);
if (hr < 0) throw hr;
hr = dev_enum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&enum_moniker,NULL);
if (hr < 0) throw hr;
if (hr == S_FALSE) return; //no devices found
//get devices (max 8)
num_devices = 0;
enum_moniker->Next(MAX_DEVICES, &moniker, &dev_count);
for (unsigned int i=0; i<dev_count; i++)
{
//get properties
hr = moniker[i].BindToStorage(0, 0, IID_IPropertyBag, (void**) &pbag);
if (hr >= 0)
{
VariantInit(&name);
//get the description
hr = pbag->Read(L"Description", &name, 0);
if (hr < 0) hr = pbag->Read(L"FriendlyName", &name, 0);
if (hr >= 0)
{
//Initialize the VideoDevice struct
VideoDevice* dev = devices+num_devices++;
BSTR ptr = name.bstrVal;
for (int c = 0; *ptr; c++, ptr++)
{
//bit hacky, but i don't like to include ATL
dev->filtername[c] = *ptr;
dev->friendlyname[c] = *ptr & 0xFF;
}
//add a filter for the device
hr = graph->AddSourceFilterForMoniker(moniker+i, 0, dev->filtername, &dev->filter);
if (hr != S_OK) num_devices--;
}
VariantClear(&name);
pbag->Release();
}
moniker[i].Release();
}
}
void VideoCapture::SetSampleGrabber()
{
HRESULT hr;
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,IID_IBaseFilter,(void**)&samplegrabberfilter);
if (hr < 0) throw hr;
hr = graph->AddFilter(samplegrabberfilter, L"Sample Grabber");
if (hr != S_OK) throw hr;
hr = samplegrabberfilter->QueryInterface(IID_ISampleGrabber, (void**)&samplegrabber);
if (hr != S_OK) throw hr;
//set the media type
AM_MEDIA_TYPE mt;
memset(&mt, 0, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video;
mt.subtype = MEDIASUBTYPE_RGB24;
// setting the above to 32 bits fails consecutive Select for some reason
// and only sends one single callback (flush from previous one ???)
// must be deeper problem. 24 bpp seems to work fine for now.
callbackhandler->SetMediaType(&mt);
hr = samplegrabber->SetMediaType(&mt);
if (hr != S_OK) throw hr;
samplegrabber->SetCallback(callbackhandler,0);
}
void VideoCapture::SetNullRenderer()
{
HRESULT hr;
hr = CoCreateInstance(CLSID_NullRenderer,NULL,CLSCTX_INPROC_SERVER,IID_IBaseFilter,(void**) &nullrenderer);
if (hr < 0) throw hr;
graph->AddFilter(nullrenderer, L"Null Renderer");
}
//CALLBACKHANDLER
//public
VideoCapture::CallbackHandler::CallbackHandler(VideoCaptureCallback cb)
{
callback = cb;
}
VideoCapture::CallbackHandler::~CallbackHandler()
{
}
void VideoCapture::CallbackHandler::SetMediaType(AM_MEDIA_TYPE* am)
{
if (am->subtype == MEDIASUBTYPE_RGB555) bitpixel = 16;
else if (am->subtype == MEDIASUBTYPE_RGB24) bitpixel = 24;
else if (am->subtype == MEDIASUBTYPE_RGB32) bitpixel = 32;
}
HRESULT VideoCapture::CallbackHandler::SampleCB(double time, IMediaSample *sample)
{
HRESULT hr;
AM_MEDIA_TYPE* mt;
unsigned char* buffer;
hr = sample->GetPointer((BYTE**)&buffer);
if (hr != S_OK) return S_OK;
hr = sample->GetMediaType(&mt);
if (hr < 0) return S_OK;
if (hr == S_OK) SetMediaType(mt);
callback(buffer, sample->GetActualDataLength(), bitpixel);
return S_OK;
}
HRESULT VideoCapture::CallbackHandler::BufferCB(double time, BYTE *buffer, long len)
{
return S_OK;
}
HRESULT VideoCapture::CallbackHandler::QueryInterface(const IID &iid, LPVOID *ppv)
{
if( iid == IID_ISampleGrabberCB || iid == IID_IUnknown )
{
*ppv = (void *) static_cast<ISampleGrabberCB*>( this );
return S_OK;
}
return E_NOINTERFACE;
}
ULONG VideoCapture::CallbackHandler::AddRef()
{
return 1;
}
ULONG VideoCapture::CallbackHandler::Release()
{
return 2;
}
| [
"me@lefeeza.com"
] | me@lefeeza.com |
295aa08d21f7930b4a79701f7b110840f2e41422 | 900a70be484cb96ce5f19d785c4fac5f6f5b74cc | /2015.cpp | 715f4d35af22ae0c9cdbd6b243f9aa5976fcab13 | [] | no_license | HaochenLiu/My-POJ | ff15731b8a6a8fb691a36d45f676cb05f09dec35 | 2f60b5eeee10c2a3ffe104456edfc55aff600e18 | refs/heads/master | 2021-01-10T17:44:35.789596 | 2016-09-16T06:22:17 | 2016-09-16T06:22:17 | 43,051,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | cpp | #include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <stack>
#include <sstream>
#include <string.h>
#include <utility>
#include <vector>
using namespace std;
/*
以d为切入点。C[d] = S[i]推出M[d] = P[i]
然后向前推进M[d-1],...
*/
int get(string s, char c) {
for(int i = 0; i < s.length(); i++) {
if(s[i] == c) {
return i;
}
}
return -1;
}
int main() {
int x;
string S, P, C, M;
while(cin>>x) {
if(x == 0) {
break;
}
cin>>S>>P>>C;
M = C;//先将长度设定
int n = M.length();
int d = (int)(sqrt(double(n * n * n)) + x) % n;
M[d] = P[get(S, C[d])];
for(int i = d; i != (n + d + 1)%n; i = (n + i - 1) % n) {
int num1 = get(S, M[i]);
int num2 = get(S, C[(n + i - 1) % n]);
int num = num1 ^ num2;
M[(n + i - 1) % n] = P[num];
}
cout<<M<<endl;
}
return 0;
}
| [
"liuhaochen1221@hotmail.com"
] | liuhaochen1221@hotmail.com |
c97ec0a9ac50becf9d3a81b7cad210dd848e7b16 | d2566520060aa4e0dc9ee53cca3cfe8b0bc09cb9 | /src/Control/UnitTest/CmdLine/Grammar.hpp | 36df89f24cc780bc4e3c01939e9b62b83c5f0b76 | [
"BSD-2-Clause"
] | permissive | supermangithu/quinoa | f4a452de8ff1011a89dec1365a32730299ceecc1 | 2dd7ead9592b43a06fa25fec2f7fa7687f6169bf | refs/heads/master | 2023-04-13T14:42:02.394865 | 2020-09-12T13:35:33 | 2020-09-12T13:35:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | hpp | // *****************************************************************************
/*!
\file src/Control/UnitTest/CmdLine/Grammar.hpp
\copyright 2012-2015 J. Bakosi,
2016-2018 Los Alamos National Security, LLC.,
2019-2020 Triad National Security, LLC.
All rights reserved. See the LICENSE file for details.
\brief UnitTest's command line grammar definition
\details Grammar definition for parsing the command line. We use the Parsing
Expression Grammar Template Library (PEGTL) to create the grammar and the
associated parser. Word of advice: read from the bottom up.
*/
// *****************************************************************************
#ifndef UnitTestCmdLineGrammar_h
#define UnitTestCmdLineGrammar_h
#include "CommonGrammar.hpp"
#include "Keywords.hpp"
namespace unittest {
//! UnitTest command line grammar definition
namespace cmd {
using namespace tao;
//! \brief Specialization of tk::grm::use for UnitTest's command line parser
template< typename keyword >
using use = tk::grm::use< keyword, ctr::CmdLine::keywords::set >;
// UnitTest's CmdLine state
// UnitTest's CmdLine grammar
//! \brief Match and set verbose switch (i.e., verbose or quiet output)
struct verbose :
tk::grm::process_cmd_switch< use, kw::verbose,
tag::verbose > {};
//! Match and set chare state switch
struct charestate :
tk::grm::process_cmd_switch< use, kw::charestate,
tag::chare > {};
//! \brief Match help on command-line parameters
struct help :
tk::grm::process_cmd_switch< use, kw::help,
tag::help > {};
//! \brief Match help on a command-line keyword
struct helpkw :
tk::grm::process_cmd< use, kw::helpkw,
tk::grm::helpkw,
pegtl::alnum,
tag::discr /* = unused */ > {};
//! \brief Match test group name(s) and only run those
struct group :
tk::grm::process_cmd< use, kw::group,
tk::grm::Store< tag::group >,
pegtl::any,
tag::group > {};
//! Match switch on quiescence
struct quiescence :
tk::grm::process_cmd_switch< use, kw::quiescence,
tag::quiescence > {};
//! Match switch on trace output
struct trace :
tk::grm::process_cmd_switch< use, kw::trace,
tag::trace > {};
//! Match switch on version output
struct version :
tk::grm::process_cmd_switch< use, kw::version,
tag::version > {};
//! Match switch on license output
struct license :
tk::grm::process_cmd_switch< use, kw::license,
tag::license > {};
//! \brief Match and set io parameter
template< typename keyword, typename io_tag >
struct io :
tk::grm::process_cmd< use, keyword,
tk::grm::Store< tag::io, io_tag >,
pegtl::any,
tag::io, io_tag > {};
//! \brief Match all command line keywords
struct keywords :
pegtl::sor< verbose, charestate, help, helpkw, group,
quiescence, trace, version, license,
io< kw::screen, tag::screen > > {};
//! \brief Grammar entry point: parse keywords until end of string
struct read_string :
tk::grm::read_string< keywords > {};
} // cmd::
} // unittest::
#endif // UnitTestCmdLineGrammar_h
| [
"jbakosi@lanl.gov"
] | jbakosi@lanl.gov |
a54f45df779208b0e0a9139f5be9f5030f2f5efb | 7a831a6bd4fa7a401f0b015d8c73d0290e03ec8b | /124.intersection_between_two_files.cpp | 6076187e63e2434f16156974e7a9c1c3f9dca4f8 | [] | no_license | CawaAlreadyTaken/UniTN_exercises | 63f9826c41e07e24cd6924a56eb93962573d3fa3 | 784969a7c472cc03afc79378fbd2cfa83be1ba22 | refs/heads/master | 2023-02-10T04:41:05.475086 | 2020-12-27T13:22:06 | 2020-12-27T13:22:06 | 300,202,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,857 | cpp | #include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
bool find(char words1[], char words2[][100], int it2);
void removeDuplicates(char array[][100], int size);
int main(int argc, char * argv[]) {
if (argc != 4) {
cout << "Usage: " << argv[0] << " <inputFile1> <inputFile2> <outputFile>" << endl;
exit(0);
}
fstream in1, in2, out;
in1.open(argv[1], ios::in);
char words1[1000][100];
char words2[1000][100];
int it1 = 1;
in1 >> words1[0];
if (in1.fail()) {
cout << "Failed to read '" << argv[1] << "'." << endl;
in1.close();
exit(0);
}
while (!in1.eof()) {
in1>>words1[it1];
it1++;
}
in1.close();
in2.open(argv[2], ios::in);
int it2 = 1;
in2 >> words2[0];
if (in2.fail()) {
cout << "Failed to read '" << argv[2] << "'." << endl;
in2.close();
exit(0);
}
while (!in2.eof()) {
in2>>words2[it2];
it2++;
}
in2.close();
cout << "Into the file '" << argv[3] << "', you will find the list of the words that are both in '" << argv[1] << "' and in '" << argv[2] << "'." << endl;
out.open(argv[3], ios::out);
int it3 = 0;
char output[1000][100];
for (int i = 0; i < it1; i++) {
if (find(words1[i], words2, it2)) {
strcpy(output[it3], words1[i]);
it3++;
}
}
removeDuplicates(output, it3);
for (int i = 0; i < it3; i++) {
char check[100] = {0};
if (strcmp(output[i], check) != 0)
out << output[i] << endl;
}
out.close();
return 0;
}
bool find(char words1[], char words2[][100], int it2) {
bool return_ = false;
for (int i = 0; i < it2 && !return_; i++) {
if (strcmp(words1, words2[i]) == 0) return_ = true;
}
return return_;
}
void removeDuplicates(char array[][100], int size) {
char trash[100] = {0};
for (int i = 0; i < size-1; i++) {
for (int j = i+1; j < size; j++) {
if (strcmp(array[i], array[j]) == 0) strcpy(array[j], trash);
}
}
}
| [
"daniele.cabassi01@gmail.com"
] | daniele.cabassi01@gmail.com |
544bc3c6bfa7ec9c2e8091c6b12a6275b58b5619 | 521e578f9d7c5297224343876ed74a04d0825102 | /leetcode top 100/0169多数元素.cpp | 192c5527cb2ef7b62e5d431e63fc2ace504f5862 | [] | no_license | caitouwww/probable-octo-doodle | 2b165b15c8dda57a0106ed5a967d6682262630cc | 19050c5fb72722633735ae53261761b950c3f21f | refs/heads/master | 2021-11-28T13:49:47.578791 | 2021-08-26T09:58:33 | 2021-08-26T09:58:33 | 242,519,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,190 | cpp | class Solution {
public:
int majorityElement(vector<int>& nums) {
//排序
/*sort(nums.begin(),nums.end());
return nums[nums.size()/2];*/
//Boyer-Moore投票算法
/*int candidate=nums[0];
int count=1;
for(int i=1;i<nums.size();i++)
{
if(nums[i]==candidate)
count++;
else
{
count--;
if(count==0)
{
candidate=nums[i];
count=1;
}
}
}
return candidate;*/
//随机化
/*while(true)
{
int candidate=nums[rand()%nums.size()];
int cnt=0;
for(int i=0;i<nums.size();i++)
{
if(candidate==nums[i])
{
cnt++;
}
if(cnt>nums.size()/2)
{
return candidate;
}
}
}
return -1;*/
//分治
//return majorityElementRec(nums,0,nums.size()-1);
//哈希表
unordered_map<int,int> counts;
int majority=0,cnt=0;
for(int val:nums)
{
++counts[val];
if(counts[val]>cnt)
{
cnt=counts[val];
majority=val;
}
}
return majority;
}
/*int majorityElementRec(vector<int>& nums,int start,int end)
{
if(start==end)
return nums[start];
int mid=(start+end)/2;
int leftMajority=majorityElementRec(nums,start,mid);
int rightMajority=majorityElementRec(nums,mid+1,end);
if(countInRange(nums,leftMajority,start,end)>(end-start+1)/2)
return leftMajority;
if(countInRange(nums,rightMajority,start,end)>(end-start+1)/2)
return rightMajority;
return -1;
}
int countInRange(vector<int>& nums,int target,int start,int end)
{
int cnt=0;
for(int i=start;i<=end;i++)
{
if(nums[i]==target)
cnt++;
}
return cnt;
}*/
};
| [
"wangwetro@gmail.com"
] | wangwetro@gmail.com |
c4d5063b528c0eb1397f65defb8f434424c62a7a | abdfad0a4c83c80050749e3010c5099bd3a35d81 | /src/ST7789display.h | a1c57441622d7b2931a36c4e642d9348bfdfc5ea | [
"MIT"
] | permissive | narfg/gbemulator | ddd3a5e59fa366ebe055fadeee67de527d7c4590 | 4f911e50df966a79177b458f6f618f02d940e88c | refs/heads/master | 2020-09-12T19:55:56.345832 | 2020-05-02T13:13:10 | 2020-05-02T13:13:10 | 222,533,488 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,119 | h | #pragma once
#include <cstdint>
#include <array>
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include "display.h"
// Display Settings
const int TFT_CS = 5;
const int TFT_RST = 19;
const int TFT_DC = 2;
// HW SPI will use those pins
// const int TFT_MOSI = 23
// const int TFT_SCLK = 18
class ST7789Display : public Display {
public:
ST7789Display() : tft_(Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST)) {
}
void init(uint16_t /* width */, uint16_t /* height */) override {
tft_.init(240, 320);
tft_.fillScreen(ST77XX_BLACK);
}
void close() override {}
void update() override {}
void drawPixel(uint16_t x, uint16_t y, uint8_t color) override {
// tft_.drawPixel(x, y, colors_[color]);
// Landscape mode
if (y < 240)
tft_.drawPixel(y, tft_.height() - ((320-256)/2+x), colors_[color]);
}
private:
Adafruit_ST7789 tft_;
// Green shades in 16bit RGB565 format
std::array<uint16_t, 4> colors_{{0xE7DA, 0x8E0E, 0x334A, 0x08C4}};
};
| [
"timhabigt@gmail.com"
] | timhabigt@gmail.com |
77d35ae9e7df066988a41c8660f27f78581c1b67 | ba718273739277573faade9be1f5e891aea7e99a | /cnc/internal/dist/communicator.h | 9a8e4ede11a227c4b575a31cb3a3f575716b329d | [
"BSD-3-Clause"
] | permissive | kod3r/icnc | e2f3f329161b4ebbf45a7fadbe372fec39600064 | 3f6b7c7dab7ae37d86d40d375f51ed5181ef05f4 | refs/heads/master | 2021-01-17T21:57:59.408194 | 2015-01-16T10:30:39 | 2015-01-16T10:30:39 | 31,246,584 | 1 | 0 | null | 2015-02-24T05:45:41 | 2015-02-24T05:45:40 | null | UTF-8 | C++ | false | false | 5,089 | h | /* *******************************************************************************
* Copyright (c) 2007-2014, Intel Corporation
*
* 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 Intel Corporation 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 OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
#ifndef _CnC_COMMUNICATOR_H_
#define _CnC_COMMUNICATOR_H_
#include <cnc/internal/cnc_api.h>
#include <cnc/internal/traceable.h>
#include <cnc/internal/tbbcompat.h>
#include <tbb/scalable_allocator.h>
//#include <cnc/serializer.h>
#include <cnc/internal/scalable_vector.h>
namespace CnC {
class serializer;
namespace Internal {
class CNC_API msg_callback;
typedef void (*communicator_loader_type)(msg_callback &, bool);
/// There might be several communication systems.
/// Each one must derive from this and implement its interface.
/// Communicators are supposed to reside in an extra library.
/// The communicator library get dynamically loaded, it must provide
/// a function extern "C" load_communicator_( msg_callback & d, bool dist_env )
/// in which the communicator must get registered with the msg_callback
/// by calling msg_callback.set_communicator(c).
/// \see CnC::Internal::dist_cnc
class communicator
{
public:
virtual ~communicator() {}
/// initialize communication infrastructure
/// start up communication system to accept incoming messages
/// incoming messages are handed over to the msg_callback
/// sender/rcvr ids in this network start with min_id
/// created processes will be identified with ids in the range [min_id, (min_id+N)]
/// currently there is only one communicator supported
/// \return number of sender/rcvrs in this network (N)
virtual int init( int min_id, long flag = 0 ) = 0;
/// shut down communication network
virtual void fini() = 0;
/// distributors call this to send messages
/// send_msg must not block - message must be sent asynchroneously;
/// hence the given serializer must be deleted by the communicator
virtual void send_msg( serializer *, int rcver ) = 0;
/// distributors call this to send the same message to all other processes.
/// bcast_msg must not block - message must be sent asynchroneously;
/// hence the given serializer must be deleted by the communicator
virtual void bcast_msg( serializer * ) = 0;
/// distributors call this to send the same message to all given processes.
/// bcast_msg must not block - message must be sent asynchroneously;
/// hence the given serializer must be deleted by the communicator
/// \return whether calling process was in the list of receivers
virtual bool bcast_msg( serializer * ser, const int * rcvers, int nrecvrs ) = 0;
/// return process id of calling thread/process
virtual int myPid() = 0;
/// return number of processes (#clients + host)
virtual int numProcs() = 0;
/// return true if calling thread is on a remote process
virtual bool remote() = 0;
/// \return true if at least one message is pending (waiting for being sent)
virtual bool has_pending_messages() = 0;
};
} // namespace Internal
} // namespace CnC
#endif // _CnC_COMMUNICATOR_H_
| [
"frank.schlimbach@intel.com"
] | frank.schlimbach@intel.com |
f0516989c4808ce2184a35c318b84e59659d6246 | b45255c4ee39791de879422cbe06485de56148fb | /程序设计II_c++/12428 [STL] map and pair _from lecture 8/Latest Submission/EX8_7.cpp | 8facfe3441ed935b9fed0405bad09f7b5b515cf0 | [] | no_license | yoyo-hu/Programming-exercises | 4e60f50f63ec102ae5d1333d393349f156167e87 | cda87dcc477839e096500710eed470a94ae19200 | refs/heads/master | 2023-06-20T00:15:58.746894 | 2021-07-15T05:28:28 | 2021-07-15T05:28:28 | 386,024,430 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | #include <iostream>
#include <map>
using namespace std;
int main() {
map <char, int>m;
int i;
//put pairs into map
m.insert(pair<char, int>('A',65));
char ch;
cout <<"enter key:";
cin >>ch;
map<char, int>::iterator p;
//find value given key ch
p=m.find('A');
if (p!=m.end())
cout <<"Its ASCII value is " <<p->second;
else
cout <<"Key not in map." ;
return 0;
} | [
"1417193568@qq.com"
] | 1417193568@qq.com |
0c7d667dcd95f24edd4e8d20477b05fc36d4fe4e | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /gpdb/src/model/DescribeWaitingSQLInfoRequest.cc | 5e5f4a45ed81d6477de1ce78827eb22bbab410fb | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,051 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/gpdb/model/DescribeWaitingSQLInfoRequest.h>
using AlibabaCloud::Gpdb::Model::DescribeWaitingSQLInfoRequest;
DescribeWaitingSQLInfoRequest::DescribeWaitingSQLInfoRequest()
: RpcServiceRequest("gpdb", "2016-05-03", "DescribeWaitingSQLInfo") {
setMethod(HttpRequest::Method::Post);
}
DescribeWaitingSQLInfoRequest::~DescribeWaitingSQLInfoRequest() {}
std::string DescribeWaitingSQLInfoRequest::getPID() const {
return pID_;
}
void DescribeWaitingSQLInfoRequest::setPID(const std::string &pID) {
pID_ = pID;
setParameter(std::string("PID"), pID);
}
std::string DescribeWaitingSQLInfoRequest::getAccessKeyId() const {
return accessKeyId_;
}
void DescribeWaitingSQLInfoRequest::setAccessKeyId(const std::string &accessKeyId) {
accessKeyId_ = accessKeyId;
setParameter(std::string("AccessKeyId"), accessKeyId);
}
std::string DescribeWaitingSQLInfoRequest::getDatabase() const {
return database_;
}
void DescribeWaitingSQLInfoRequest::setDatabase(const std::string &database) {
database_ = database;
setParameter(std::string("Database"), database);
}
std::string DescribeWaitingSQLInfoRequest::getDBInstanceId() const {
return dBInstanceId_;
}
void DescribeWaitingSQLInfoRequest::setDBInstanceId(const std::string &dBInstanceId) {
dBInstanceId_ = dBInstanceId;
setParameter(std::string("DBInstanceId"), dBInstanceId);
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
899917c0637702a6271028df72fa361659b31856 | 308f3cb8a30fcacd8851cc2ed979949b643cf1d9 | /bzoj__orzliyicheng/p1015.cpp | 19038ba5c2e68115c6c6b1595a6dda8eb39d301f | [] | no_license | szh-bash/ACM | 9a49859644d077bcb40f90dbac33d88649e7b0f3 | 3ddab1ab8f9b8a066f012f2978ee9519d00aec54 | refs/heads/master | 2022-08-08T19:20:09.912359 | 2022-07-20T10:43:57 | 2022-07-20T10:43:57 | 98,170,219 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
int n, m, cnt, p, ans, f[200010], l[200010], an[200010], next[1000100], nu[1000100], fa[200010], a[200010];
void add(int u, int v){
next[++cnt]=next[u];next[u]=cnt;nu[cnt]=v;
}
int father(int x){
if (fa[x]==x) return x;
fa[x]=father(fa[x]);
return fa[x];
}
int main(){
scanf("%d%d", &n, &m);
cnt=n-1;
int u, v;
for (int i=1;i<=m;i++){
scanf("%d%d", &u, &v);
add(u, v);
add(v, u);
}
scanf("%d", &p);
for (int i=1;i<=p;i++){
scanf("%d", &a[i]);
f[a[i]]=1;
}
int le=1, ri=0;
for (int i=0;i<n;i++){
if (!f[i]) l[++ri]=i;
fa[i]=i;
}
int tp=p;
while (p!=-1){
ans+=ri-le+1;
for (int i=le;i<=ri;i++){
u=l[i];
int j=next[u];
while (j){
v=nu[j];
if (!f[v] && father(u)!=father(v)){
fa[fa[u]]=fa[v];
ans--;
}
j=next[j];
}
}
le=ri+1;
if (p){
l[++ri]=a[p];
f[a[p]]=0;
}
an[p]=ans;
p--;
}
for (int i=0;i<=tp;i++) printf("%d\n", an[i]);
return 0;
}
| [
"342333349@qq.com"
] | 342333349@qq.com |
a0f372d4cb197028ec80f82a8f8a1d60c2534620 | f061d1ec69b8c26e827d581f56cfd0b1fd7ae5b6 | /src/qt/tradingdialog.cpp | b6ea1f678e6ca0c7a965c5917d66f23af25266a7 | [
"MIT"
] | permissive | seatrips/XUVCoin-WORKING | 5f9d1b3056386284610f846f92d0dfc16715bee9 | 585dea87c75804a41fa67b3d242501701722c89e | refs/heads/master | 2021-05-06T12:05:11.702975 | 2017-12-08T08:51:48 | 2017-12-08T08:51:48 | 113,038,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,999 | cpp | #include "tradingdialog.h"
#include "ui_tradingdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include <qmessagebox.h>
#include <qtimer.h>
#include <rpcserver.h>
#include <QClipboard>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QVariant>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>
#include <QTime>
#include <openssl/hmac.h>
#include <stdlib.h>
using namespace std;
tradingDialog::tradingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::tradingDialog),
model(0)
{
ui->setupUi(this);
timerid = 0;
qDebug() << "Expected this";
ui->BtcAvailableLabel->setTextFormat(Qt::RichText);
ui->XUVAvailableLabel->setTextFormat(Qt::RichText);
ui->BuyCostLabel->setTextFormat(Qt::RichText);
ui->SellCostLabel->setTextFormat(Qt::RichText);
ui->BittrexBTCLabel->setTextFormat(Qt::RichText);
ui->BittrexXUVLabel->setTextFormat(Qt::RichText);
ui->CSDumpLabel->setTextFormat(Qt::RichText);
ui->CSTotalLabel->setTextFormat(Qt::RichText);
ui->CSReceiveLabel->setTextFormat(Qt::RichText);
//Set tabs to inactive
ui->TradingTabWidget->setTabEnabled(0,false);
ui->TradingTabWidget->setTabEnabled(1,false);
ui->TradingTabWidget->setTabEnabled(3,false);
ui->TradingTabWidget->setTabEnabled(4,false);
ui->TradingTabWidget->setTabEnabled(5,false);
// Listen for keypress
connect(ui->PasswordInput, SIGNAL(returnPressed()),ui->LoadKeys,SIGNAL(clicked()));
/*OrderBook Table Init*/
CreateOrderBookTables(*ui->BidsTable,QStringList() << "SUM(BTC)" << "TOTAL(BTC)" << "XUV(SIZE)" << "BID(BTC)");
CreateOrderBookTables(*ui->AsksTable,QStringList() << "ASK(BTC)" << "XUV(SIZE)" << "TOTAL(BTC)" << "SUM(BTC)");
/*OrderBook Table Init*/
/*Market History Table Init*/
ui->MarketHistoryTable->setColumnCount(5);
ui->MarketHistoryTable->verticalHeader()->setVisible(false);
ui->MarketHistoryTable->setHorizontalHeaderLabels(QStringList()<<"DATE"<<"BUY/SELL"<<"BID/ASK"<<"TOTAL UNITS(XUV)"<<"TOTAL COST(BTC");
ui->MarketHistoryTable->setRowCount(0);
int Cellwidth = ui->MarketHistoryTable->width() / 5;
ui->MarketHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->MarketHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*Market History Table Init*/
/*Account History Table Init*/
ui->TradeHistoryTable->setColumnCount(9);
ui->TradeHistoryTable->verticalHeader()->setVisible(false);
ui->TradeHistoryTable->setHorizontalHeaderLabels(QStringList() << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Closed");
ui->TradeHistoryTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->TradeHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->TradeHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*Account History Table Init*/
/*Open Orders Table*/
ui->OpenOrdersTable->setColumnCount(10);
ui->OpenOrdersTable->verticalHeader()->setVisible(false);
ui->OpenOrdersTable->setHorizontalHeaderLabels(QStringList() << "OrderId" << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Cancel Order");
ui->OpenOrdersTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->OpenOrdersTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->OpenOrdersTable->setColumnHidden(0,true);
ui->OpenOrdersTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->OpenOrdersTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
connect (ui->OpenOrdersTable, SIGNAL(cellClicked(int,int)), this, SLOT(CancelOrderSlot(int, int)));
/*Open Orders Table*/
}
void tradingDialog::InitTrading()
{ //todo - add internet connection/socket error checking.
//Get default exchange info for the qlabels
UpdaterFunction();
qDebug() << "Updater called";
if(this->timerid == 0)
{
//Timer is not set,lets create one.
this->timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(UpdaterFunction()));
this->timer->start(5000);
this->timerid = this->timer->timerId();
}
}
void tradingDialog::UpdaterFunction(){
//XUVst get the main exchange info in order to populate qLabels in maindialog. then get data
//required for the current tab.
int Retval = SetExchangeInfoTextLabels();
if (Retval == 0){
ActionsOnSwitch(-1);
}
}
QString tradingDialog::GetMarketSummary(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/GetMarketSummary?market=btc-XUV");
return Response;
}
QString tradingDialog::GetOrderBook(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-XUV&type=both&depth=50");
return Response;
}
QString tradingDialog::GetMarketHistory(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-XUV&count=100");
return Response;
}
QString tradingDialog::CancelOrder(QString OrderId){
QString URL = "https://bittrex.com/api/v1.1/market/cancel?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&uuid=";
URL += OrderId;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::BuyXUV(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-XUV&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::SellXUV(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-XUV&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::Withdraw(double Amount, QString Address, QString Coin){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/account/withdraw?apikey=";
URL += this->ApiKey;
URL += "¤cy=";
URL += Coin;
URL += "&quantity=";
URL += str.number(Amount,'i',8);
URL += "&address=";
URL += Address;
URL += "&nonce=12345434";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetOpenOrders(){
QString URL = "https://bittrex.com/api/v1.1/market/getopenorders?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-XUV";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetBalance(QString Currency){
QString URL = "https://bittrex.com/api/v1.1/account/getbalance?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=";
URL += Currency;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetDepositAddress(){
QString URL = "https://bittrex.com/api/v1.1/account/getdepositaddress?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=XUV";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetAccountHistory(){
QString URL = "https://bittrex.com/api/v1.1/account/getorderhistory?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-XUV&count=10";
QString Response = sendRequest(URL);
return Response;
}
int tradingDialog::SetExchangeInfoTextLabels(){
//Get the current exchange information + information for the current open tab if required.
QString str = "";
QString Response = GetMarketSummary();
//Set the labels, parse the json result to get values.
QJsonObject obj = GetResultObjectFromJSONArray(Response);
//set labels to richtext to use css.
ui->Bid->setTextFormat(Qt::RichText);
ui->Ask->setTextFormat(Qt::RichText);
ui->volumet->setTextFormat(Qt::RichText);
ui->volumebtc->setTextFormat(Qt::RichText);
ui->Ask->setText("<b>Ask:</b> <span style='font-weight:bold; font-size:12px; color:Red'>" + str.number(obj["Ask"].toDouble(),'i',8) + "</span> BTC");
ui->Bid->setText("<b>Bid:</b> <span style='font-weight:bold; font-size:12px; color:Green;'>" + str.number(obj["Bid"].toDouble(),'i',8) + "</span> BTC");
ui->volumet->setText("<b>XUV Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["Volume"].toDouble(),'i',8) + "</span> XUV");
ui->volumebtc->setText("<b>BTC Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["BaseVolume"].toDouble(),'i',8) + "</span> BTC");
obj.empty();
return 0;
}
void tradingDialog::CreateOrderBookTables(QTableWidget& Table,QStringList TableHeader){
Table.setColumnCount(4);
Table.verticalHeader()->setVisible(false);
Table.setHorizontalHeaderLabels(TableHeader);
int Cellwidth = Table.width() / 4;
Table.horizontalHeader()->resizeSection(1,Cellwidth); // column 1, width 50
Table.horizontalHeader()->resizeSection(2,Cellwidth);
Table.horizontalHeader()->resizeSection(3,Cellwidth);
Table.horizontalHeader()->resizeSection(4,Cellwidth);
Table.setRowCount(0);
Table.horizontalHeader()->setResizeMode(QHeaderView::Stretch);
Table.horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
Table.horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * { font-weight :bold;}");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel,QLabel &Available, QLabel &Pending, QString Currency,QString Response){
QString str;
BalanceLabel.setTextFormat(Qt::RichText);
Available.setTextFormat(Qt::RichText);
Pending.setTextFormat(Qt::RichText);
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Balance"].toDouble(),'i',8) + "</span> " + Currency);
Available.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Available"].toDouble(),'i',8) + "</span> " +Currency);
Pending.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Pending"].toDouble(),'i',8) + "</span> " +Currency);
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QString Response){
QString str;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QLabel &BalanceLabel2, QString Response, QString Response2){
QString str;
QString str2;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
QJsonObject ResultObject2 = GetResultObjectFromJSONObject(Response2);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
BalanceLabel2.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str2.number(ResultObject2["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::ParseAndPopulateOpenOrdersTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->OpenOrdersTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->OpenOrdersTable->rowCount();
ui->OpenOrdersTable->insertRow(RowCount);
ui->OpenOrdersTable->setItem(itteration, 0, new QTableWidgetItem(obj["OrderUuid"].toString()));
ui->OpenOrdersTable->setItem(itteration, 1, new QTableWidgetItem(BittrexTimeStampToReadable(obj["Opened"].toString())));
ui->OpenOrdersTable->setItem(itteration, 2, new QTableWidgetItem(obj["Exchange"].toString()));
ui->OpenOrdersTable->setItem(itteration, 3, new QTableWidgetItem(obj["OrderType"].toString()));
ui->OpenOrdersTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 8, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 9, new QTableWidgetItem(tr("Cancel Order")));
//Handle the cancel link in open orders table
QTableWidgetItem* CancelCell;
CancelCell= ui->OpenOrdersTable->item(itteration, 9); //Set the wtablewidget item to the cancel cell item.
CancelCell->setForeground(QColor::fromRgb(255,0,0)); //make this item red.
CancelCell->setTextAlignment(Qt::AlignCenter);
itteration++;
}
obj.empty();
}
void tradingDialog::CancelOrderSlot(int row, int col){
QString OrderId = ui->OpenOrdersTable->model()->data(ui->OpenOrdersTable->model()->index(row,0)).toString();
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Cancel Order","Are you sure you want to cancel the order?",QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = CancelOrder(OrderId);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8());
QJsonObject ResponseObject = jsonResponse.object();
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed To Cancel Order",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
ui->OpenOrdersTable->model()->removeRow(row);
QMessageBox::information(this,"Success","You're order was cancelled.");
}
} else {
qDebug() << "Do Nothing";
}
}
void tradingDialog::ParseAndPopulateAccountHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->TradeHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->TradeHistoryTable->rowCount();
ui->TradeHistoryTable->insertRow(RowCount);
ui->TradeHistoryTable->setItem(itteration, 0, new QTableWidgetItem(BittrexTimeStampToReadable(obj["TimeStamp"].toString())));
ui->TradeHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["Exchange"].toString()));
ui->TradeHistoryTable->setItem(itteration, 2, new QTableWidgetItem(obj["OrderType"].toString()));
ui->TradeHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 8, new QTableWidgetItem(obj["Closed"].toString()));
itteration++;
}
obj.empty();
}
void tradingDialog::ParseAndPopulateOrderBookTables(QString OrderBook){
QString str;
QJsonObject obj;
QJsonObject ResultObject = GetResultObjectFromJSONObject(OrderBook);
int BuyItteration = 0,SellItteration = 0, BidRows = 0, AskRows = 0;
QJsonArray BuyArray = ResultObject.value("buy").toArray(); //get buy/sell object from result object
QJsonArray SellArray = ResultObject.value("sell").toArray(); //get buy/sell object from result object
double XUVSupply = 0;
double XUVDemand = 0;
double BtcSupply = 0;
double BtcDemand = 0;
ui->AsksTable->setRowCount(0);
foreach (const QJsonValue & value, SellArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
XUVSupply += y;
BtcSupply += a;
AskRows = ui->AsksTable->rowCount();
ui->AsksTable->insertRow(AskRows);
ui->AsksTable->setItem(SellItteration, 0, new QTableWidgetItem(str.number(x,'i',8)));
ui->AsksTable->setItem(SellItteration, 1, new QTableWidgetItem(str.number(y,'i',8)));
ui->AsksTable->setItem(SellItteration, 2, new QTableWidgetItem(str.number(a,'i',8)));
ui->AsksTable->setItem(SellItteration, 3, new QTableWidgetItem(str.number(BtcSupply,'i',8)));
SellItteration++;
}
ui->BidsTable->setRowCount(0);
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
XUVDemand += y;
BtcDemand += a;
BidRows = ui->BidsTable->rowCount();
ui->BidsTable->insertRow(BidRows);
ui->BidsTable->setItem(BuyItteration, 0, new QTableWidgetItem(str.number(BtcDemand,'i',8)));
ui->BidsTable->setItem(BuyItteration, 1, new QTableWidgetItem(str.number(a,'i',8)));
ui->BidsTable->setItem(BuyItteration, 2, new QTableWidgetItem(str.number(y,'i',8)));
ui->BidsTable->setItem(BuyItteration, 3, new QTableWidgetItem(str.number(x,'i',8)));
BuyItteration++;
}
ui->XUVSupply->setText("<b>Supply:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(XUVSupply,'i',8) + "</span><b> XUV</b>");
ui->BtcSupply->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcSupply,'i',8) + "</span><b> BTC</b>");
ui->AsksCount->setText("<b>Ask's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->AsksTable->rowCount()) + "</span>");
ui->XUVDemand->setText("<b>Demand:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(XUVDemand,'i',8) + "</span><b> XUV</b>");
ui->BtcDemand->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcDemand,'i',8) + "</span><b> BTC</b>");
ui->BidsCount->setText("<b>Bid's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->BidsTable->rowCount()) + "</span>");
obj.empty();
}
void tradingDialog::ParseAndPopulateMarketHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->MarketHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->MarketHistoryTable->rowCount();
ui->MarketHistoryTable->insertRow(RowCount);
ui->MarketHistoryTable->setItem(itteration, 0, new QTableWidgetItem(BittrexTimeStampToReadable(obj["TimeStamp"].toString())));
ui->MarketHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["OrderType"].toString()));
ui->MarketHistoryTable->setItem(itteration, 2, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Total"].toDouble(),'i',8)));
ui->MarketHistoryTable->item(itteration,1)->setBackgroundColor((obj["OrderType"] == QStringLiteral("BUY")) ? (QColor (150, 191, 70,255)) : ( QColor (201, 119, 153,255)));
itteration++;
}
obj.empty();
}
void tradingDialog::ActionsOnSwitch(int index = -1){
QString Response = "";
QString Response2 = "";
QString Response3 = "";
if(index == -1){
index = ui->TradingTabWidget->currentIndex();
}
switch (index){
case 0: //buy tab is active
Response = GetBalance("BTC");
Response2 = GetBalance("XUV");
Response3 = GetOrderBook();
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->BtcAvailableLabel, *ui->XUVAvailableLabel, Response, Response2);
}
if ((Response3.size() > 0 && Response3 != "Error")) {
ParseAndPopulateOrderBookTables(Response3);
}
break;
case 1: //Cross send tab active
Response = GetBalance("XUV");
Response2 = GetBalance("BTC");
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->BittrexXUVLabel, *ui->BittrexBTCLabel, Response, Response2);
}
break;
case 2://market history tab
Response = GetMarketHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateMarketHistoryTable(Response);
}
break;
case 3: //open orders tab
Response = GetOpenOrders();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateOpenOrdersTable(Response);
}
break;
case 4://account history tab
Response = GetAccountHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateAccountHistoryTable(Response);
}
break;
case 5://show balance tab
Response = GetBalance("BTC");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->BitcoinBalanceLabel,*ui->BitcoinAvailableLabel,*ui->BitcoinPendingLabel, QString::fromUtf8("BTC"),Response);
}
Response = GetBalance("XUV");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->XUVBalanceLabel,*ui->XUVAvailableLabel_2,*ui->XUVPendingLabel, QString::fromUtf8("XUV"),Response);
}
break;
case 6:
break;
}
}
void tradingDialog::on_TradingTabWidget_tabBarClicked(int index)
{
//tab was clicked, interrupt the timer and restart after action completed.
this->timer->stop();
ActionsOnSwitch(index);
this->timer->start();
}
QString tradingDialog::sendRequest(QString url){
QString Response = "";
QString Secret = this->SecretKey;
// create custom temporary event loop on stack
QEventLoop eventLoop;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// the HTTP request
QNetworkRequest req = QNetworkRequest(QUrl(url));
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//make this conditional,depending if we are using private api call
req.setRawHeader("apisign",HMAC_SHA512_SIGNER(url,Secret).toStdString().c_str()); //set header for bittrex
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
//success
Response = reply->readAll();
delete reply;
}
else{
//failure
qDebug() << "Failure" <<reply->errorString();
Response = "Error";
//QMessageBox::information(this,"Error",reply->errorString());
delete reply;
}
return Response;
}
QString tradingDialog::BittrexTimeStampToReadable(QString DateTime){
//Seperate Time and date.
int TPos = DateTime.indexOf("T");
int sPos = DateTime.indexOf(".");
QDateTime Date = QDateTime::fromString(DateTime.left(TPos),"yyyy-MM-dd"); //format to convert from
DateTime.remove(sPos,sizeof(DateTime));
DateTime.remove(0,TPos+1);
QDateTime Time = QDateTime::fromString(DateTime.right(TPos),"hh:mm:ss");
//Reconstruct time and date in our own format, one that QDateTime will recognise.
QString DisplayDate = Date.toString("dd/MM/yyyy") + " " + Time.toString("hh:mm:ss A"); //formats to convert to
return DisplayDate;
}
void tradingDialog::CalculateBuyCostLabel(){
double price = ui->BuyBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInput->text().toDouble();
double cost = ((price * Quantity) + ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->BuyCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateSellCostLabel(){
double price = ui->SellBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInputXUV->text().toDouble();
double cost = ((price * Quantity) - ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->SellCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateCSReceiveLabel(){
//calculate amount of currency than can be transferred to bitcoin
QString balance = GetBalance("XUV");
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject BalanceObject = GetResultObjectFromJSONObject(balance);
QJsonObject obj;
double AvailableXUV = BalanceObject["Available"].toDouble();
double Quantity = ui->CSUnitsInput->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( ((Quantity / x) - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= ((Price * y) - ((Price * y / 100) * 0.25));
} else {
Price = x;
Received += ((Price * (Quantity / x)) - ((Price * (Quantity / x) / 100) * 0.25));
Qty += (Quantity / x);
Quantity -= 0;
break;
}
}
QString ReceiveStr = "";
QString DumpStr = "";
QString TotalStr = "";
if ( Qty < AvailableXUV )
{
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + ReceiveStr.number((ui->CSUnitsInput->text().toDouble() - 0.0002),'i',8) + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr.number(Price,'i',8) + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr.number(Qty,'i',8) + "</span>");
} else {
ReceiveStr = "N/A";
TotalStr = "N/A";
DumpStr = "N/A";
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + ReceiveStr + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr + "</span>");
}
}
void tradingDialog::on_UpdateKeys_clicked(bool Save, bool Load)
{
this->ApiKey = ui->ApiKeyInput->text();
this->SecretKey = ui->SecretKeyInput->text();
QJsonDocument jsonResponse = QJsonDocument::fromJson(GetAccountHistory().toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if ( ResponseObject.value("success").toBool() == false){
QMessageBox::information(this,"API Configuration Failed","Api configuration was unsuccesful.");
}else if ( ResponseObject.value("success").toBool() == true && Load){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been loaded and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else if ( ResponseObject.value("success").toBool() == true && Save){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been saved and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else{
QMessageBox::information(this,"API Configuration Complete","Api connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}
}
string tradingDialog::encryptDecrypt(string toEncrypt, string password) {
char * key = new char [password.size()+1];
std::strcpy (key, password.c_str());
key[password.size()] = '\0'; // don't forget the terminating 0
string output = toEncrypt;
for (unsigned int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
void tradingDialog::on_SaveKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ofstream stream (pathConfigFile.string(), ios::out | ios::trunc);
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
// qstrings to utf8, add to byteArray and convert to const char for stream
string Secret = ui->SecretKeyInput->text().toUtf8().constData();
string Key = ui->ApiKeyInput->text().toUtf8().constData();
string ESecret = "";
string EKey = "";
if (stream.is_open() && fSuccess)
{
ESecret = encryptDecrypt(Secret, password);
EKey = encryptDecrypt(Key, password);
stream << ESecret << '\n';
stream << EKey;
stream.close();
}
if (fSuccess) {
bool Save = true;
on_UpdateKeys_clicked(Save);
}
}
void tradingDialog::on_LoadKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ifstream stream (pathConfigFile.string());
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
QString DSecret = "";
QString DKey = "";
if (stream.is_open() && fSuccess)
{
int i =0;
for ( std::string line; std::getline(stream,line); )
{
if (i == 0 ){
DSecret = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->SecretKeyInput->setText(DSecret);
} else if (i == 1){
DKey = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->ApiKeyInput->setText(DKey);
}
i++;
}
stream.close();
}
if (fSuccess) {
bool Save = false;
bool Load = true;
on_UpdateKeys_clicked(Save, Load);
}
}
void tradingDialog::on_GenDepositBTN_clicked()
{
QString response = GetDepositAddress();
QJsonObject ResultObject = GetResultObjectFromJSONObject(response);
ui->DepositAddressLabel->setText(ResultObject["Address"].toString());
}
void tradingDialog::on_Sell_Max_Amount_clicked()
{
//calculate amount of BTC that can be gained from selling XUV available balance
QString responseA = GetBalance("XUV");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
double AvailableXUV = ResultObject["Available"].toDouble();
ui->UnitsInputXUV->setText(str.number(AvailableXUV,'i',8));
}
void tradingDialog::on_Buy_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("BTC");
QString responseB = GetMarketSummary();
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
QJsonObject ResultObj = GetResultObjectFromJSONArray(responseB);
//Get the Bid ask or last value from combo
QString value = ui->BuyBidcomboBox->currentText();
double AvailableBTC = ResultObject["Available"].toDouble();
double CurrentASK = ResultObj[value].toDouble();
double Result = (AvailableBTC / CurrentASK);
double percentofnumber = (Result * 0.0025);
Result = Result - percentofnumber;
ui->UnitsInput->setText(str.number(Result,'i',8));
}
void tradingDialog::on_CS_Max_Amount_clicked()
{
double Quantity = ui->BittrexXUVLabel->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject obj;
QString str;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( (Quantity - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= y;
} else {
Price = x;
Received += ((Price * Quantity) - ((Price * Quantity / 100) * 0.25));
Qty += Quantity;
if ((Quantity * x) < 0.00055){
Quantity = (0.00055 / x);
}
break;
}
}
ui->CSUnitsInput->setText(str.number(Received,'i',8));
}
void tradingDialog::on_Withdraw_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("XUV");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
double AvailableXUV = ResultObject["Available"].toDouble();
ui->WithdrawUnitsInput->setText(str.number(AvailableXUV,'i',8));
}
QJsonObject tradingDialog::GetResultObjectFromJSONObject(QString response){
QJsonDocument jsonResponse = QJsonDocument::fromJson(response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
QJsonObject ResultObject = ResponseObject.value(QString("result")).toObject(); //get result object
return ResultObject;
}
QJsonObject tradingDialog::GetResultObjectFromJSONArray(QString response){
QJsonDocument jsonResponsea = QJsonDocument::fromJson(response.toUtf8());
QJsonObject jsonObjecta = jsonResponsea.object();
QJsonArray jsonArraya = jsonObjecta["result"].toArray();
QJsonObject obj;
foreach (const QJsonValue & value, jsonArraya)
{
obj = value.toObject();
}
return obj;
}
QJsonArray tradingDialog::GetResultArrayFromJSONObject(QString response){
QJsonDocument jsonResponse = QJsonDocument::fromJson(response.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["result"].toArray();
return jsonArray;
}
QString tradingDialog::HMAC_SHA512_SIGNER(QString UrlToSign, QString Secret){
QString retval = "";
QByteArray byteArray = UrlToSign.toUtf8();
const char* URL = byteArray.constData();
QByteArray byteArrayB = Secret.toUtf8();
const char* Secretkey = byteArrayB.constData();
const EVP_MD *md = EVP_sha512();
unsigned char* digest = NULL;
// Using sha512 hash engine here.
digest = HMAC(md, Secretkey, strlen( Secretkey), (unsigned char*) URL, strlen( URL), NULL, NULL);
// Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.
// Change the length accordingly with your choosen hash engine
char mdString[129] = { 0 };
for(int i = 0; i < 64; i++){
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
}
retval = mdString;
//qDebug() << "HMAC digest:"<< retval;
return retval;
}
void tradingDialog::on_SellBidcomboBox_currentIndexChanged(const QString &arg1)
{
QString response = GetMarketSummary();
QJsonObject ResultObject = GetResultObjectFromJSONArray(response);
QString Str;
//Get the Bid ask or last value from combo
ui->SellBidPriceEdit->setText(Str.number(ResultObject[arg1].toDouble(),'i',8));
CalculateSellCostLabel(); //update cost
}
void tradingDialog::on_BuyBidcomboBox_currentIndexChanged(const QString &arg1)
{
QString response = GetMarketSummary();
QJsonObject ResultObject = GetResultObjectFromJSONArray(response);
QString Str;
//Get the Bid ask or last value from combo
ui->BuyBidPriceEdit->setText(Str.number(ResultObject[arg1].toDouble(),'i',8));
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_BuyXUV_clicked()
{
double Rate;
double Quantity;
Rate = ui->BuyBidPriceEdit->text().toDouble();
Quantity = ui->UnitsInput->text().toDouble();
QString OrderType = "Limit";
QString Order;
if(OrderType == "Limit"){Order = "buylimit";}else if (OrderType == "Market"){ Order = "buymarket";}
QString Msg = "Are you sure you want to buy ";
Msg += ui->UnitsInput->text();
Msg += "XUV @ ";
Msg += ui->BuyBidPriceEdit->text();
Msg += " BTC Each";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Buy Order",Msg,QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = BuyXUV(Order,Quantity,Rate);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Buy Order Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Buy Order Initiated","You Placed an order");
}
}else{
//do nothing
}
}
void tradingDialog::on_SellXUVBTN_clicked()
{
double Rate;
double Quantity;
Rate = ui->SellBidPriceEdit->text().toDouble();
Quantity = ui->UnitsInputXUV->text().toDouble();
QString OrderType = "Limit";
QString Order;
if(OrderType == "Limit"){Order = "selllimit";}else if (OrderType == "Market"){ Order = "sellmarket";}
QString Msg = "Are you sure you want to Sell ";
Msg += ui->UnitsInputXUV->text();
Msg += " XUV @ ";
Msg += ui->SellBidPriceEdit->text();
Msg += " BTC Each";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Sell Order",Msg,QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = SellXUV(Order,Quantity,Rate);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Sell Order Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Sell Order Initiated","You Placed an order");
}
}else{
//do nothing
}
}
void tradingDialog::on_CSUnitsBtn_clicked()
{
double Quantity = ui->CSUnitsInput->text().toDouble();
double Rate = ui->CSDumpLabel->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
double Add = 0;
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject obj;
QString Astr;
QString Qstr;
QString Rstr;
QString Coin = "BTC";
QString Msg = "Are you sure you want to Send ";
Msg += Qstr.number((Quantity - 0.0002),'i',8);
Msg += " BTC to ";
Msg += ui->CSUnitsAddress->text();
Msg += ", DUMPING your coins at ";
Msg += Rstr.number(Rate,'i',8);
Msg += " satoshis ?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Cross-Send",Msg,QMessageBox::Yes|QMessageBox::No);
if(reply != QMessageBox::Yes)
{
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return;
}
QString Order = "selllimit";
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( ((Quantity / x) - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= ((Price * y) - ((Price * y / 100) * 0.25));
QString SellResponse = SellXUV(Order,y,x);
QJsonDocument SelljsonResponse = QJsonDocument::fromJson(SellResponse.toUtf8()); //get json from str.
QJsonObject SellResponseObject = SelljsonResponse.object(); //get json obj
if (SellResponseObject["success"].toBool() == false){
if (SellResponseObject["message"].toString() == "DUST_TRADE_DISALLOWED_MIN_VALUE_50K_SAT"){
Add += y;
continue;
}
QMessageBox::information(this,"sFailed",SellResponse);
break;
}
MilliSleep(100);
} else {
Price = x;
Received += ((Price * (Quantity / x)) - ((Price * (Quantity / x) / 100) * 0.25));
Qty += (Quantity / x);
if (Add > 0)
Quantity += (Add * x);
if (Quantity < 0.00051){
Quantity = 0.00051;
}
QString SellResponse = SellXUV(Order,(Quantity / x),x);
QJsonDocument SelljsonResponse = QJsonDocument::fromJson(SellResponse.toUtf8()); //get json from str.
QJsonObject SellResponseObject = SelljsonResponse.object(); //get json obj
if (SellResponseObject["success"].toBool() == false){
QMessageBox::information(this,"sFailed",SellResponse);
} else if (SellResponseObject["success"].toBool() == true){
MilliSleep(5000);
QString Response = Withdraw(ui->CSUnitsInput->text().toDouble(),ui->CSUnitsAddress->text(),Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
MilliSleep(5000);
QString Response = Withdraw(ui->CSUnitsInput->text().toDouble(),ui->CSUnitsAddress->text(),Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object();
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed",ResponseObject["message"].toString());
} else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","<center>Cross-Send Successful</center>\n Sold "+Astr.number(Qty,'i',4)+" XUV for "+Qstr.number((ui->CSUnitsInput->text().toDouble()-0.0002),'i',8)+" BTC");
}
} else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","<center>Cross-Send Successful</center>\n Sold "+Astr.number(Qty,'i',4)+" XUV for "+Qstr.number((ui->CSUnitsInput->text().toDouble()-0.0002),'i',8)+" BTC");
}
}
break;
}
}
}
void tradingDialog::on_WithdrawUnitsBtn_clicked()
{
double Quantity = ui->WithdrawUnitsInput->text().toDouble();
QString Qstr;
QString Coin = "XUV";
QString Msg = "Are you sure you want to Withdraw ";
Msg += Qstr.number((Quantity - 0.02),'i',8);
Msg += " XUV to ";
Msg += ui->WithdrawAddress->text();
Msg += " ?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Withdraw",Msg,QMessageBox::Yes|QMessageBox::No);
if(reply != QMessageBox::Yes)
{
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return;
}
QString Response = Withdraw(Quantity, ui->WithdrawAddress->text(), Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","Withdrawal Successful !");
}
}
void tradingDialog::on_UnitsInputXUV_textChanged(const QString &arg1)
{
CalculateSellCostLabel(); //update cost
}
void tradingDialog::on_UnitsInput_textChanged(const QString &arg1)
{
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_BuyBidPriceEdit_textChanged(const QString &arg1)
{
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_SellBidPriceEdit_textChanged(const QString &arg1)
{
CalculateSellCostLabel();
}
void tradingDialog::on_CSUnitsInput_textChanged(const QString &arg1)
{
CalculateCSReceiveLabel(); //update cost
}
void tradingDialog::on_CSPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->CSUnitsAddress->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_WithdrawPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->WithdrawAddress->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_SecretPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->SecretKeyInput->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_KeyPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->ApiKeyInput->setText(QApplication::clipboard()->text());
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
void tradingDialog::on_DepositCopyButton_clicked()
{
setClipboard(ui->DepositAddressLabel->text());
}
void tradingDialog::setModel(WalletModel *model)
{
this->model = model;
}
tradingDialog::~tradingDialog()
{
delete ui;
}
| [
"33975900+XUVCoin@users.noreply.github.com"
] | 33975900+XUVCoin@users.noreply.github.com |
90aa8fd36b3644baae475bab41cce5434b9dfee0 | 20aaa0f98403712526b5080043968f946c3906f7 | /SGUI/Src/Platform/OpenGl/OpenGlTexture.cpp | 147633caaf1c8346f96d2c80fd07d2c9e303ae82 | [
"Apache-2.0"
] | permissive | saimankhatiwada/SGUI | 61a72c5ce8d18633ce4cd28c83284e25866dbec2 | 5f3d023c9309e9d34a9d80888ac221c799aa92e0 | refs/heads/main | 2023-04-10T17:19:09.503419 | 2021-04-14T16:35:40 | 2021-04-14T16:35:40 | 298,014,341 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,618 | cpp | #include "hzpch.h"
#include "Platform/OpenGL/OpenGLTexture.h"
#include <stb_image.h>
namespace SGUI {
OpenGLTexture2D::OpenGLTexture2D(uint32_t width, uint32_t height)
: m_Width(width), m_Height(height)
{
SG_PROFILE_FUNCTION();
m_InternalFormat = GL_RGBA8;
m_DataFormat = GL_RGBA;
glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);
glTextureStorage2D(m_RendererID, 1, m_InternalFormat, m_Width, m_Height);
glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
OpenGLTexture2D::OpenGLTexture2D(const std::string& path)
: m_Path(path)
{
SG_PROFILE_FUNCTION();
int width, height, channels;
stbi_set_flip_vertically_on_load(1);
stbi_uc* data = nullptr;
{
SG_PROFILE_SCOPE("stbi_load - OpenGLTexture2D::OpenGLTexture2D(const std::string&)");
data = stbi_load(path.c_str(), &width, &height, &channels, 0);
}
SG_CORE_ASSERT(data, "Failed to load image!");
m_Width = width;
m_Height = height;
GLenum internalFormat = 0, dataFormat = 0;
if (channels == 4)
{
internalFormat = GL_RGBA8;
dataFormat = GL_RGBA;
}
else if (channels == 3)
{
internalFormat = GL_RGB8;
dataFormat = GL_RGB;
}
m_InternalFormat = internalFormat;
m_DataFormat = dataFormat;
SG_CORE_ASSERT(internalFormat & dataFormat, "Format not supported!");
glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);
glTextureStorage2D(m_RendererID, 1, internalFormat, m_Width, m_Height);
glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, dataFormat, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
OpenGLTexture2D::~OpenGLTexture2D()
{
SG_PROFILE_FUNCTION();
glDeleteTextures(1, &m_RendererID);
}
void OpenGLTexture2D::SetData(void* data, uint32_t size)
{
SG_PROFILE_FUNCTION();
uint32_t bpp = m_DataFormat == GL_RGBA ? 4 : 3;
SG_CORE_ASSERT(size == m_Width * m_Height * bpp, "Data must be entire texture!");
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);
}
void OpenGLTexture2D::Bind(uint32_t slot) const
{
SG_PROFILE_FUNCTION();
glBindTextureUnit(slot, m_RendererID);
}
}
| [
"saimankhatiwada9611@gmail.com"
] | saimankhatiwada9611@gmail.com |
697d4cb6e3afe49deaab173c0952e55c43878987 | 7b0ad6eb7781119997b8dc51822b5bca1bcaf2c7 | /src/ui/wizard/BudgetSourceWizard.hpp | 975f77c810a7013f5ee3eea82735beb866303f9d | [
"Apache-2.0"
] | permissive | vimofthevine/UnderBudget | 7fce75d9cada97e566afecde9aa4c3980fe1238f | 0df01460d28f82f65af64a060e792d1551d60001 | refs/heads/master | 2021-01-01T10:13:58.770184 | 2015-05-27T09:57:44 | 2015-05-27T09:57:44 | 1,743,072 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,232 | hpp | /*
* Copyright 2013 Kyle Treubig
*
* 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 BUDGETSOURCEWIZARD_HPP
#define BUDGETSOURCEWIZARD_HPP
// Qt include(s)
#include <QSharedPointer>
// UnderBudget include(s)
#include "budget/storage/BudgetSource.hpp"
// Forward declaration(s)
class QWidget;
namespace ub {
/**
* Budget source selection wizard.
*
* @ingroup ui_wizard
*/
class BudgetSourceWizard {
public:
/**
* Prompts the user for all information necessary to re-open a budget
* from the specified location. If the described budget source could
* not be determined, the returned pointer will be null.
*
* @param[in] parent parent widget
* @param[in] location budget location description
* @return budget source from which to retrieve an existing budget
*/
static QSharedPointer<BudgetSource> promptToReOpen(QWidget* parent,
const QString& location);
/**
* Prompts the user for all information necessary to open a budget
* from the user-specified source. If the user cancels the operation or
* the selected source is invalid, the returned pointer will be null.
*
* @param[in] parent parent widget
* @return budget source from which to retrieve an existing budget
*/
static QSharedPointer<BudgetSource> promptForBudgetToOpen(QWidget* parent);
/**
* Prompts the user for all information necessary to save a budget
* to the user-specified source. If the user cancels the operation or
* the selected source is invalid, the returned pointer will be null.
*
* @param[in] parent parent widget
* @param[in] existing original budget source, can be a null pointer
* @return budget source to which to save a budget
*/
static QSharedPointer<BudgetSource> promptForBudgetToSave(QWidget* parent,
QSharedPointer<BudgetSource> existing);
private:
// Last-used budget file directory settings key
static const QString LAST_USED_BUDGET_DIR;
/**
* Records the directory containing the specified file as the last-used
* budget file directory. This allows the next open operation to begin
* in the same directory.
*
* @param[in] fileName name of a budget file
*/
static void recordLastUsedPath(const QString& fileName);
/**
* Creates a budget source for the specified file name. The type of the
* budget source created depends on the extension of the file name. If
* the file extension is unrecognized, a null pointer is returned.
*
* @param[in] fileName name of a budget file
* @return budget source for the specified budget file, or a null pointer
* if the specified file name contains an unrecognized extension
*/
static BudgetSource* createForFile(const QString& fileName);
};
}
#endif //BUDGETSOURCEWIZARD_HPP
| [
"kyle@vimofthevine.com"
] | kyle@vimofthevine.com |
da2d94acd25cfcc358106f71aaf5994e97248d85 | 9b4f6fa69ec833198d5e27bef0453ffce21da316 | /08-28_queue/radix_practice.cpp | f2e7c6cfd9319e5ff25159e5654e4e5bc625f3d7 | [] | no_license | nattee/data2019 | cec667fc90d35689815557a9f4c546fa11f35a63 | 3f9373bf6fbaac4ec83bd4e7beba160e5f63eb42 | refs/heads/master | 2020-07-04T15:37:10.427297 | 2019-10-16T04:04:14 | 2019-10-16T04:04:14 | 202,326,521 | 2 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | #include <iostream>
#include <vector>
using namespace std;
int getDigit(int v, int k,base) { // return the kth digit of v
int i;
for (i=0; i<k; i++) v /= base;
return v % base;
}
void radixSort(vector<int> &data, int d) { // d = #digits
int base = 10;
//declare queue as a vector
for (int k=0; k<d; k++) {
for (int i=0; i < xxxx ; i++) // <<- maybe do something here
q[getDigit(data[i],k),base].push(data[i]);
for (int i=0,j=0; i<base; i++)
while(!q[i].empty()) {
data[j++] = q[i].front(); q[i].pop();
}
}
}
int main() {
}
| [
"nattee@gmail.com"
] | nattee@gmail.com |
0dae44a1fbeffd5428db66d70b9130b742410351 | d19d5f5f2f7e44884932aa087c63a549f53f0907 | /SwingEngine/SEGeometricTools/Distance/SEDistSegment2Segment2.cpp | 8c92471b55e4ef256a986e89d21f223187cebea5 | [] | no_license | jazzboysc/SwingEngine2 | d26c60f4cbf89f0d7207e5152cae69677a4d7b18 | d7dbd09a5e7748def0bd3fa6a547b1c734529f61 | refs/heads/master | 2021-03-27T11:05:20.543758 | 2018-07-13T09:42:22 | 2018-07-13T09:42:22 | 44,491,987 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,465 | cpp | // Swing Engine Version 2 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 and 5 open-source game engine. The author of Swing Engine
// learned a lot from Eberly's experience of architecture and algorithm.
// Several subsystems are totally new, and others are reorganized or
// reimplimented based on Wild Magic's subsystems.
// Copyright (c) 2007-2011
//
// David Eberly's permission:
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
#include "SEGeometricToolsPCH.h"
#include "SEDistSegment2Segment2.h"
using namespace Swing;
//----------------------------------------------------------------------------
SEDistSegment2Segment2f::SEDistSegment2Segment2f(const SESegment2f& rSegment0,
const SESegment2f& rSegment1)
:
m_pSegment0(&rSegment0),
m_pSegment1(&rSegment1)
{
}
//----------------------------------------------------------------------------
const SESegment2f& SEDistSegment2Segment2f::GetSegment0() const
{
return *m_pSegment0;
}
//----------------------------------------------------------------------------
const SESegment2f& SEDistSegment2Segment2f::GetSegment1() const
{
return *m_pSegment1;
}
//----------------------------------------------------------------------------
float SEDistSegment2Segment2f::Get()
{
float fSqrDist = GetSquared();
return SEMath<float>::Sqrt(fSqrDist);
}
//----------------------------------------------------------------------------
float SEDistSegment2Segment2f::GetSquared()
{
SEVector2f vec2fDiff = m_pSegment0->Origin - m_pSegment1->Origin;
float fA01 = -m_pSegment0->Direction.Dot(m_pSegment1->Direction);
float fB0 = vec2fDiff.Dot(m_pSegment0->Direction);
float fB1 = -vec2fDiff.Dot(m_pSegment1->Direction);
float fC = vec2fDiff.GetSquaredLength();
float fDet = SEMath<float>::FAbs(1.0f - fA01*fA01);
float fS0, fS1, fSqrDist, fExtDet0, fExtDet1, fTmpS0, fTmpS1;
if( fDet >= SEMath<float>::ZERO_TOLERANCE )
{
// 两线段不平行.
fS0 = fA01*fB1 - fB0;
fS1 = fA01*fB0 - fB1;
fExtDet0 = m_pSegment0->Extent*fDet;
fExtDet1 = m_pSegment1->Extent*fDet;
if( fS0 >= -fExtDet0 )
{
if( fS0 <= fExtDet0 )
{
if( fS1 >= -fExtDet1 )
{
if( fS1 <= fExtDet1 ) // region 0 (interior)
{
// 最近点是两线段线上点.
float fInvDet = 1.0f / fDet;
fS0 *= fInvDet;
fS1 *= fInvDet;
fSqrDist = 0.0f;
}
else // region 3 (side)
{
fS1 = m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 < -m_pSegment0->Extent )
{
fS0 = -m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 <= m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
}
}
else // region 7 (side)
{
fS1 = -m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 < -m_pSegment0->Extent )
{
fS0 = -m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 <= m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
}
}
else
{
if( fS1 >= -fExtDet1 )
{
if( fS1 <= fExtDet1 ) // region 1 (side)
{
fS0 = m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 < -m_pSegment1->Extent )
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 <= m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0) + fC;
}
else
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
else // region 2 (corner)
{
fS1 = m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 < -m_pSegment0->Extent )
{
fS0 = -m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 <= m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 < -m_pSegment1->Extent )
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 <= m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0)
+ fC;
}
else
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
}
}
else // region 8 (corner)
{
fS1 = -m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 < -m_pSegment0->Extent )
{
fS0 = -m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 <= m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 > m_pSegment1->Extent )
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 >= -m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0)
+ fC;
}
else
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
}
}
}
else
{
if( fS1 >= -fExtDet1 )
{
if( fS1 <= fExtDet1 ) // region 5 (side)
{
fS0 = -m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 < -m_pSegment1->Extent )
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 <= m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0) + fC;
}
else
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
else // region 4 (corner)
{
fS1 = m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 > m_pSegment0->Extent )
{
fS0 = m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 >= -m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = -m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 < -m_pSegment1->Extent )
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 <= m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0)
+ fC;
}
else
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
}
}
else // region 6 (corner)
{
fS1 = -m_pSegment1->Extent;
fTmpS0 = -(fA01*fS1 + fB0);
if( fTmpS0 > m_pSegment0->Extent )
{
fS0 = m_pSegment0->Extent;
fSqrDist = fS0*(fS0 - 2.0f*fTmpS0) +
fS1*(fS1 + 2.0f*fB1) + fC;
}
else if( fTmpS0 >= -m_pSegment0->Extent )
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0 + fS1*(fS1 + 2.0f*fB1) + fC;
}
else
{
fS0 = -m_pSegment0->Extent;
fTmpS1 = -(fA01*fS0 + fB1);
if( fTmpS1 < -m_pSegment1->Extent )
{
fS1 = -m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
else if( fTmpS1 <= m_pSegment1->Extent )
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1 + fS0*(fS0 + 2.0f*fB0)
+ fC;
}
else
{
fS1 = m_pSegment1->Extent;
fSqrDist = fS1*(fS1 - 2.0f*fTmpS1) +
fS0*(fS0 + 2.0f*fB0) + fC;
}
}
}
}
}
else
{
// 两线段平行.
float fE0pE1 = m_pSegment0->Extent + m_pSegment1->Extent;
float fSign = (fA01 > 0.0f ? -1.0f : 1.0f);
float fLambda = -fB0;
if( fLambda < -fE0pE1 )
{
fLambda = -fE0pE1;
}
else if( fLambda > fE0pE1 )
{
fLambda = fE0pE1;
}
fS1 = fSign*fB0*m_pSegment1->Extent/fE0pE1;
fS0 = fLambda + fSign*fS1;
fSqrDist = fLambda*(fLambda + 2.0f*fB0) + fC;
}
m_ClosestPoint0 = m_pSegment0->Origin + fS0*m_pSegment0->Direction;
m_ClosestPoint1 = m_pSegment1->Origin + fS1*m_pSegment1->Direction;
return SEMath<float>::FAbs(fSqrDist);
}
//----------------------------------------------------------------------------
float SEDistSegment2Segment2f::Get(float fS1, const SEVector2f& rVelocity0,
const SEVector2f& rVelocity1)
{
SEVector2f vec2fMOrigin0 = m_pSegment0->Origin + fS1*rVelocity0;
SEVector2f vec2fMOrigin1 = m_pSegment1->Origin + fS1*rVelocity1;
SESegment2f tempMSegment0(vec2fMOrigin0, m_pSegment0->Direction,
m_pSegment0->Extent);
SESegment2f tempMSegment1(vec2fMOrigin1, m_pSegment1->Direction,
m_pSegment1->Extent);
return SEDistSegment2Segment2f(tempMSegment0, tempMSegment1).Get();
}
//----------------------------------------------------------------------------
float SEDistSegment2Segment2f::GetSquared(float fS1, const SEVector2f&
rVelocity0, const SEVector2f& rVelocity1)
{
SEVector2f vec2fMOrigin0 = m_pSegment0->Origin + fS1*rVelocity0;
SEVector2f vec2fMOrigin1 = m_pSegment1->Origin + fS1*rVelocity1;
SESegment2f tempMSegment0(vec2fMOrigin0, m_pSegment0->Direction,
m_pSegment0->Extent);
SESegment2f tempMSegment1(vec2fMOrigin1, m_pSegment1->Direction,
m_pSegment1->Extent);
return SEDistSegment2Segment2f(tempMSegment0, tempMSegment1).GetSquared();
}
//----------------------------------------------------------------------------
| [
"S515380c"
] | S515380c |
58c2ff8a9824149bde143e92b4f4e86a34c15d91 | a3f1ad55251bf6fbf3dba25294701e898e79da34 | /树的前中后遍历/test.cpp | 05fb70a336f5cfe1834c5c1ba8936294bfba6305 | [] | no_license | 1299960335/code | 0814ebfaaba3b75acbe20dcbfb4a0f9792c59cf4 | 777fa27ad7c2be33ce82e63e754aea3f8dcd6439 | refs/heads/master | 2023-07-17T05:39:53.706264 | 2021-08-26T14:43:55 | 2021-08-26T14:43:55 | 310,982,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
void first(vector<int> &v,TreeNode*root){
if(root==nullptr){
return;
}
v.push_back(root->val);
first(v,root->left);
first(v,root->right);
}
void mid(vector<int> &v,TreeNode*root){
if(root==nullptr)
return;
mid(v,root->left);
v.push_back(root->val);
mid(v,root->right);
}
void last(vector<int> &v,TreeNode*root){
if(root==nullptr)
return;
last(v,root->left);
last(v,root->right);
v.push_back(root->val);
}
vector<vector<int> > threeOrders(TreeNode* root) {
vector<vector<int>> v1;
v1.resize(3);
first(v1[0],root);
mid(v1[1],root);
last(v1[2],root);
return v1;
}
}; | [
"1299960335@qq.com"
] | 1299960335@qq.com |
0bf5eee47da4a83c0dd56a566ecc9ae21e3ff4c2 | d9956aaa7436a7843603aa547535d9c7fdaa5c2f | /proj-01/proj-01-files/grading/minigl.cpp | c42c448731f044bbd714f71e4d6ab7fc2d688ad2 | [] | no_license | xzhou016/CS130 | 434d7930949e94c67eaebef1693bfb526833708c | 5dae7ee9877672e5080a3257e27eb4cb464a334b | refs/heads/master | 2021-03-27T16:44:27.136745 | 2016-10-25T17:28:42 | 2016-10-25T17:28:42 | 70,532,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,705 | cpp | /**
* minigl.cpp
* -------------------------------
* Implement miniGL here.
*
* You may include minigl.h and any of the standard C++ libraries.
* No other includes are permitted. Other preprocessing directives
* are also not permitted. These requirements are strictly
* enforced. Be sure to run a test grading to make sure your file
* passes the sanity tests.
*/
#include "minigl.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
/**
* Global values for rasterization
*/
struct mglVertices {
MGLfloat vert_x;
MGLfloat vert_y;
MGLfloat vert_z;
MGLfloat vert_w;
MGLpixel pixel_color;
};
vector<mglVertices> vertex_set;
struct mglMatrix {
MGLfloat fMatrix[16];
mglMatrix(){make_zero();}
void make_zero()
{for(size_t i = 0; i < 16; i++) fMatrix[i] = 0;}
void make_id()
{make_zero();for(int i = 0; i < 16; i+=5) fMatrix[i] = 1;}
mglMatrix& operator = (const MGLfloat *matrix){
int other_mat_count = 0;
for (size_t i = 0; i < 16; i++) {
fMatrix[i] = matrix[other_mat_count];
other_mat_count++;
}
return *this;
}
// mglMatrix& operator * (mglMatrix B){
// MGLfloat sum[16];
//
// for (size_t i = 0; i < 4; i++) {
// for (size_t j = 0; j < 4; j++) {
// int index = j*4;
// sum[index + i] = B.fMatrix[index]*fMatrix[i]
// + B.fMatrix[index + 4]*fMatrix[i + 1]
// + B.fMatrix[index + 8]*fMatrix[i + 2]
// + B.fMatrix[index + 12]*fMatrix[i + 3];
// }
// }
// }
};
/*******************
*Global variables
*/
mglMatrix render_matrix; //4x4 matrix for transformation
stack<mglMatrix> render_model_stack; //model view
stack<mglMatrix> render_proj_stack; //projection
MGLbool render_started; //check if render started
MGLint render_poly_mode; //choose between v3 and quad
MGLmatrix_mode render_state = MGL_MODELVIEW; //FSM for choosing modelview and projection
/**
* Standard macro to report errors
*/
inline void MGL_ERROR(const char* description) {
printf("%s\n", description);
exit(1);
}
/**
* Read pixel data starting with the pixel at coordinates
* (0, 0), up to (width, height), into the array
* pointed to by data. The boundaries are lower-inclusive,
* that is, a call with width = height = 1 would just read
* the pixel at (0, 0).
*
* Rasterization and z-buffering should be performed when
* this function is called, so that the data array is filled
* with the actual pixel values that should be displayed on
* the two-dimensional screen.
*/
void mglReadPixels(MGLsize width,
MGLsize height,
MGLpixel *data)
{
// assert(width > 0 && height > 0 ); //make sure w, h are positive
//
// //create 2-D display
// MGLpixel screen[width*height];
// MGLfloat z_buffer[width*height];
//
// for (size_t i = 0; i < width*height; i++) {
// screen[i] = data[i]; //read raw data, should be 0
// z_buffer[i] = -1; //z is at infinity
// }
//
// render_matrix.make_id();
}
/**
* Start specifying the vertices for a group of primitives,
* whose type is specified by the given mode.
*/
void mglBegin(MGLpoly_mode mode)
{
render_started = true;
render_poly_mode = mode;
}
/**
* Stop specifying the vertices for a group of primitives.
*/
void mglEnd()
{
// for (std::vector<mglVertices> itr = vertex_set.begin(); itr != vertex_set.end(); itr++) {
//
// }
}
/**
* Specify a two-dimensional vertex; the x- and y-coordinates
* are explicitly specified, while the z-coordinate is assumed
* to be zero. Must appear between calls to mglBegin() and
* mglEnd().
*/
void mglVertex2(MGLfloat x,
MGLfloat y)
{
mglVertex3(x, y, 0);
}
/**
* Specify a three-dimensional vertex. Must appear between
* calls to mglBegin() and mglEnd().
*/
void mglVertex3(MGLfloat x,
MGLfloat y,
MGLfloat z)
{
mglVertices node; //create a vertex
node = {.vert_x = x, .vert_y = y, .vert_z = x, .vert_w = 1};
mglMatrix r_modelview = render_model_stack.top();
mglMatrix r_projection = render_proj_stack.top();
//do proj*modelview*vertex
vertex_set.push_back(node);
}
/**
* Set the current matrix mode (modelview or projection).
*/
void mglMatrixMode(MGLmatrix_mode mode)
{
switch (mode) {
case MGL_MODELVIEW: {
if(render_state != mode) {
render_state = MGL_PROJECTION;
mglPushMatrix();
}
render_matrix = render_model_stack.top();
render_state = mode;
break;
}
case MGL_PROJECTION: {
if (render_state != mode) {
render_state = MGL_MODELVIEW;
mglPushMatrix();
}
render_matrix = render_proj_stack.top();
render_state = mode;
break;
}
default: MGL_ERROR("Cannot find mode"); break;
}
}
/**
* Push a copy of the current matrix onto the stack for the
* current matrix mode.
*/
void mglPushMatrix()
{
switch (render_state) {
case MGL_MODELVIEW:
render_model_stack.push(render_matrix);break;
case MGL_PROJECTION:
render_proj_stack.push(render_matrix); break;
default:
MGL_ERROR("Cannot push onto stack");
}
}
/**
* Pop the top matrix from the stack for the current matrix
* mode.
*/
void mglPopMatrix()
{
switch (render_state) {
case MGL_MODELVIEW:{
render_matrix = render_model_stack.top();
render_model_stack.pop();
break;
}
case MGL_PROJECTION: {
render_matrix = render_proj_stack.top();
render_proj_stack.pop();
break;
}
default:
MGL_ERROR("Cannot pop stack");
}
}
/**
* Replace the current matrix with the identity.
*/
void mglLoadIdentity()
{
render_matrix.make_id();
}
/**
* Replace the current matrix with an arbitrary 4x4 matrix,
* specified in column-major order. That is, the matrix
* is stored as:
*
* ( a0 a4 a8 a12 )
* ( a1 a5 a9 a13 )
* ( a2 a6 a10 a14 )
* ( a3 a7 a11 a15 )
*
* where ai is the i'th entry of the array.
*/
void mglLoadMatrix(const MGLfloat *matrix)
{
render_matrix.make_zero();
render_matrix = matrix;
}
/**
* Multiply the current matrix by an arbitrary 4x4 matrix,
* specified in column-major order. That is, the matrix
* is stored as:
*
* ( a0 a4 a8 a12 )
* ( a1 a5 a9 a13 )
* ( a2 a6 a10 a14 )
* ( a3 a7 a11 a15 )
*
* where ai is the i'th entry of the array.
*/
void mglMultMatrix(const MGLfloat *matrix)
{
mglMatrix mat_sum;
MGLsize sum_index = 0;
for (size_t i = 0; i < 4; i++) {
for (size_t j = 0; j < 4; j++) {
mat_sum.fMatrix[sum_index] = matrix[j] * render_matrix.fMatrix[i]
+ matrix[j+4] * render_matrix.fMatrix[i + 1]
+ matrix[j+8] * render_matrix.fMatrix[i + 2]
+ matrix[j+12] * render_matrix.fMatrix[i + 3];
sum_index++;
}
}
render_matrix = mat_sum;
}
/**
* Multiply the current matrix by the translation matrix
* for the translation vector given by (x, y, z).
*/
void mglTranslate(MGLfloat x,
MGLfloat y,
MGLfloat z)
{
mglMatrix trans_matrix;
trans_matrix.fMatrix[12] = x;
trans_matrix.fMatrix[13] = y;
trans_matrix.fMatrix[14] = z;
mglMultMatrix(trans_matrix.fMatrix);
}
/**
* Multiply the current matrix by the rotation matrix
* for a rotation of (angle) degrees about the vector
* from the origin to the point (x, y, z).
*/
void mglRotate(MGLfloat angle,
MGLfloat x,
MGLfloat y,
MGLfloat z)
{
}
/**
* Multiply the current matrix by the scale matrix
* for the given scale factors.
*/
void mglScale(MGLfloat x,
MGLfloat y,
MGLfloat z)
{
mglMatrix scale_mat;
scale_mat.fMatrix[0] = x;
scale_mat.fMatrix[5] = y;
scale_mat.fMatrix[10] = z;
mglMultMatrix(scale_mat.fMatrix);
}
/**
* Multiply the current matrix by the perspective matrix
* with the given clipping plane coordinates.
*/
void mglFrustum(MGLfloat left,
MGLfloat right,
MGLfloat bottom,
MGLfloat top,
MGLfloat near,
MGLfloat far)
{
}
/**
* Multiply the current matrix by the orthographic matrix
* with the given clipping plane coordinates.
*/
void mglOrtho(MGLfloat left,
MGLfloat right,
MGLfloat bottom,
MGLfloat top,
MGLfloat near,
MGLfloat far)
{
mglMatrix compute_ortho;
compute_ortho.fMatrix[ 0] = 2 /(right - left);
compute_ortho.fMatrix[ 5] = 2 /(top - bottom);
compute_ortho.fMatrix[10] = -2/(far - near);
compute_ortho.fMatrix[12] = -(right+left)/(right - left);
compute_ortho.fMatrix[13] = -(top+bottom)/(top - bottom);
compute_ortho.fMatrix[14] = -(far+near) /(far - near);
mglMultMatrix(compute_ortho.fMatrix);
}
/**
* Set the current color for drawn shapes.
*/
void mglColor(MGLfloat red,
MGLfloat green,
MGLfloat blue)
{
}
| [
"xzhou016@ucr.edu"
] | xzhou016@ucr.edu |
206aa572a5e7fc3b2863a09516dfcbfb3ebddc53 | 418bfbac7208b9cf6acdb2a347c5d02c91f25304 | /Fruit.cpp | aa7845f69be16155b65d24aab0fc53d368852989 | [] | no_license | aryan-gupta/Snake | 6c71ab5e71dcefd5ea345fc3b9bbc94feec11a38 | 8590147579a5db22aa8ed54e8862c8cba3964adb | refs/heads/master | 2021-03-30T18:07:33.996811 | 2017-05-28T19:39:31 | 2017-05-28T19:39:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 835 | cpp | /*
* Copyright (c) 2017 The Gupta Empire - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* Written by Aryan Gupta <me@theguptaempire.net>
*
* =============================================================================
* @author Aryan Gupta
* @project
* @title
* @date (YYYY-MM-DD)
* @fversion 1.0.0
* @description
* =============================================================================
*/
#include "info.h"
#include <cstdlib>
#include "main.h"
#include "Fruit.h"
#include "Game.h"
Fruit::Fruit() {
loc = { rand() % MAP_W, rand() % MAP_H }; // place the fruit randomly on the map
}
void Fruit::render() {
gSnakeGame->renderBlock(loc); // render the block
}
Coordinate Fruit::getLocation() {
return loc;
} | [
"kuantum.freak@gmail.com"
] | kuantum.freak@gmail.com |
d512545a69b5c4293a4d605e05080b40b9467151 | 0716239a35565af06dde9d3ae7c269d5e1fa83b5 | /src/qt/bitcoinaddressvalidator.cpp | 3d68528146be4923b21dcc21352260ed2ca45484 | [
"MIT"
] | permissive | btc20/bitcoin2.0 | 72feb95af1ba9079f189b858745de3ba17662373 | e7a54b00ebd0e8d20f4d5315cc9a21c77ded25cd | refs/heads/main | 2023-03-19T21:23:18.801815 | 2021-03-18T00:41:09 | 2021-03-18T00:41:09 | 348,489,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,922 | cpp | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The Qtum Core developers
// Copyright (c) 2020 The BITCOIN2Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/bitcoinaddressvalidator.h>
#include <key_io.h>
/* Base58 characters are:
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
This is:
- All numbers except for '0'
- All upper-case letters except for 'I' and 'O'
- All lower-case letters except for 'l'
*/
BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State BitcoinAddressEntryValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos);
// Empty address is "intermediate" input
if (input.isEmpty())
return QValidator::Intermediate;
// Correction
for (int idx = 0; idx < input.size();)
{
bool removeChar = false;
QChar ch = input.at(idx);
// Corrections made are very conservative on purpose, to avoid
// users unexpectedly getting away with typos that would normally
// be detected, and thus sending to the wrong address.
switch(ch.unicode())
{
// Qt categorizes these as "Other_Format" not "Separator_Space"
case 0x200B: // ZERO WIDTH SPACE
case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
removeChar = true;
break;
default:
break;
}
// Remove whitespace
if (ch.isSpace())
removeChar = true;
// To next character
if (removeChar)
input.remove(idx, 1);
else
++idx;
}
// Validation
QValidator::State state = QValidator::Acceptable;
for (int idx = 0; idx < input.size(); ++idx)
{
int ch = input.at(idx).unicode();
if (((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z')) &&
ch != 'I' && ch != 'O') // Characters invalid in both Base58 and Bech32
{
// Alphanumeric and not a 'forbidden' character
}
else
{
state = QValidator::Invalid;
}
}
return state;
}
BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject *parent, bool senderAddress) :
QValidator(parent),
m_senderAddress(senderAddress)
{
}
QValidator::State BitcoinAddressCheckValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos);
if(m_senderAddress &&
!IsValidContractSenderAddressString(input.toStdString()))
{
return QValidator::Invalid;
}
// Validate the passed Bitcoin address
if (IsValidDestinationString(input.toStdString())) {
return QValidator::Acceptable;
}
return QValidator::Invalid;
}
| [
""
] | |
9845334c6feb0408e36bb989f5f96baddf908efc | 636b7777cf328f82f44ae2cebb031eaab52655b3 | /0407-1/Son.hpp | ff4e9fccb7d3171d2d4714a61eca540bd73ae0ba | [] | no_license | luxsv/lab | a04e749ccae7adb6ffeb071246e8cb746c4eb6ea | a06e46dc6e0ac69757a8b9049a157254ed484f7f | refs/heads/master | 2021-01-01T06:48:25.084315 | 2017-07-17T20:46:57 | 2017-07-17T20:46:57 | 97,520,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | hpp | //
// Son.hpp
// 0407-1
//
// Created by Serg on 7/4/17.
// Copyright © 2017 Sergii Kushnir. All rights reserved.
//
#ifndef Son_hpp
#define Son_hpp
#include "Daddy.hpp"
using namespace std;
using namespace grandpa;
using namespace daddy;
namespace son {
class Son : public Daddy {
public:
Son(const string& name) : Daddy(name) {}
virtual void Walk() const ;
virtual void Play() const {
cout<<"Play Son"<<endl;
}
};
}
#endif /* Son_hpp */
| [
"luxsv0@gmail.com"
] | luxsv0@gmail.com |
c47f3cc3e0fde8d1a806ba7582d1a363d4b63c67 | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /chrome/browser/ui/views/login_view.cc | 901494db1bb31d74636bd5871b24a03f00f3b0be | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 4,421 | cc | // Copyright (c) 2012 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/ui/views/login_view.h"
#include "chrome/browser/ui/views/harmony/chrome_layout_provider.h"
#include "chrome/browser/ui/views/harmony/chrome_typography.h"
#include "chrome/browser/ui/views/harmony/textfield_layout.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/border.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
namespace {
constexpr int kHeaderColumnSetId = 0;
constexpr int kFieldsColumnSetId = 1;
// Adds a row to |layout| and puts a Label in it.
void AddHeaderLabel(views::GridLayout* layout,
const base::string16& text,
int text_style) {
views::Label* label =
new views::Label(text, views::style::CONTEXT_LABEL, text_style);
label->SetMultiLine(true);
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
label->SetAllowCharacterBreak(true);
layout->StartRow(views::GridLayout::kFixedSize, kHeaderColumnSetId);
layout->AddView(label);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// LoginView, public:
LoginView::LoginView(const base::string16& authority,
const base::string16& explanation,
LoginHandler::LoginModelData* login_model_data)
: login_model_(login_model_data ? login_model_data->model : nullptr) {
// TODO(tapted): When Harmony is default, this should be removed and left up
// to textfield_layout.h to decide.
constexpr int kMessageWidth = 320;
ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();
SetBorder(views::CreateEmptyBorder(
provider->GetDialogInsetsForContentType(views::TEXT, views::CONTROL)));
// Initialize the Grid Layout Manager used for this dialog box.
views::GridLayout* layout =
SetLayoutManager(std::make_unique<views::GridLayout>(this));
views::ColumnSet* column_set = layout->AddColumnSet(kHeaderColumnSetId);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1.0,
views::GridLayout::FIXED, kMessageWidth, 0);
AddHeaderLabel(layout, authority, views::style::STYLE_PRIMARY);
if (!explanation.empty())
AddHeaderLabel(layout, explanation, STYLE_SECONDARY);
layout->AddPaddingRow(
views::GridLayout::kFixedSize,
provider->GetDistanceMetric(DISTANCE_UNRELATED_CONTROL_VERTICAL_LARGE));
ConfigureTextfieldStack(layout, kFieldsColumnSetId);
username_field_ = AddFirstTextfieldRow(
layout, l10n_util::GetStringUTF16(IDS_LOGIN_DIALOG_USERNAME_FIELD),
kFieldsColumnSetId);
password_field_ = AddTextfieldRow(
layout, l10n_util::GetStringUTF16(IDS_LOGIN_DIALOG_PASSWORD_FIELD),
kFieldsColumnSetId);
password_field_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
if (provider->UseExtraDialogPadding()) {
layout->AddPaddingRow(views::GridLayout::kFixedSize,
provider->GetDistanceMetric(
views::DISTANCE_UNRELATED_CONTROL_VERTICAL));
}
if (login_model_data) {
login_model_->AddObserverAndDeliverCredentials(this,
login_model_data->form);
}
}
LoginView::~LoginView() {
if (login_model_)
login_model_->RemoveObserver(this);
}
const base::string16& LoginView::GetUsername() const {
return username_field_->text();
}
const base::string16& LoginView::GetPassword() const {
return password_field_->text();
}
views::View* LoginView::GetInitiallyFocusedView() {
return username_field_;
}
///////////////////////////////////////////////////////////////////////////////
// LoginView, views::View, password_manager::LoginModelObserver overrides:
void LoginView::OnAutofillDataAvailableInternal(
const base::string16& username,
const base::string16& password) {
if (username_field_->text().empty()) {
username_field_->SetText(username);
password_field_->SetText(password);
username_field_->SelectAll(true);
}
}
void LoginView::OnLoginModelDestroying() {
login_model_->RemoveObserver(this);
login_model_ = NULL;
}
const char* LoginView::GetClassName() const {
return "LoginView";
}
| [
"artem@brave.com"
] | artem@brave.com |
d91bd205a20ed59da668202d894df252b83f59ed | 87c12524efba5a739caa1f8b31b503f4bf1e2979 | /CATHETEN.cpp | 52cfecd4e810f24d44aed03cbb4d49b7815909bd | [] | no_license | Ironman0505/Spoj-1 | fe234ab5f70f239090caece9ca888df3de61c22a | d4e6db21ee1ce6cc5bc65a61ae1aeb0d30d0278d | refs/heads/master | 2022-01-18T22:17:03.575047 | 2014-09-01T18:42:56 | 2014-09-01T18:42:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | cpp | #include<iostream>
#include<cstdio>
#include<climits>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<cmath>
#include<queue>
using namespace std;
#define inp(a) scanf("%lld",&a)
#define line(a) printf("%lld ",a);
#define next() printf("\n");
#define out(a) printf("%lld\n",a)
#define swap(a,b) {a=a+b;a=a-b;b=a-b;}
#define VI vector<int>
#define VLL vector<long long int>
#define PQI priority_queue<int>
#define PQLL priority_queue<long long int>
#define ll long long int
#define mod 1000000007
#define getcx getchar_unlocked
/*inline void fscan(ll *a )
{
ll n=0; int ch = getcx(); int sign = 1;
while(ch < '0' || ch > '9')
{
if(ch == '-') sign=-1; ch = getcx();
}
while(ch >= '0' && ch <= '9')
{
n = (n << 3) + (n << 1) + ch - '0', ch = getcx();
}
*a = n * sign;
}*/
ll a[1000005],i,j,k;
int main()
{
for(i=1;i<=1000;i++)
a[i]=i*i;
for(i=1;i<=100;i++)
{
int c=0;
for(j=1;j<=1000;j++)
{
int flag=0;
for(k=1;k<1000;k++)
{
if(a[k]==a[i]+a[j])
{
flag=1;break;
}
if(a[k]>a[i]+a[j])
break;
}
if(flag)
{
c++;
}
}
printf("%lld ",c);
}
return 0;
}
| [
"piyushagarwal.mnnit@gmail.com"
] | piyushagarwal.mnnit@gmail.com |
89bad466d614d6b3a9f7148b4a2dea58e9c37f57 | cc314b4405828d9ae2ab55768d37d237b1570a40 | /test/sample_out.cpp | 9cf4674afed77663ce27342f0319856d3e84b677 | [] | no_license | stephenchouca/lol2cpp | f7e3188a91c1d0e3ef3e2a29cb10feb149faa814 | f88757d2ec9cc7a8b51975f9ca8440105574f0b4 | refs/heads/master | 2020-12-30T09:59:09.558699 | 2014-05-11T18:17:21 | 2014-05-11T18:17:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,203 | cpp | // g++ -std=c++11 -O2 t.cpp
#include <iostream>
#include <type_traits>
#include <memory>
#include <string>
#include <cstdint>
#include <cstdlib>
#include <unordered_map>
#include <new>
#include <fstream>
struct A;
typedef long int NUMBR;
typedef double NUMBAR;
typedef bool TROOF;
typedef std::string YARN;
typedef std::unordered_map<A, A, A> BUKKIT;
typedef std::shared_ptr<BUKKIT> BUKKIT_PTR;
typedef std::fstream FILEZ;
typedef std::shared_ptr<FILEZ> FILEZ_PTR;
struct A {
public:
enum class T : std::int8_t {
NUMBR, NUMBAR, TROOF, YARN, BUKKIT, FILEZ, NOOB
};
T type;
union {
NUMBR numbr;
NUMBAR numbar;
TROOF troof;
YARN yarn;
BUKKIT_PTR bukkit;
FILEZ_PTR filez;
};
A() : type( T::NOOB ) {}
A(const A &a) : type(a.type) {
switch( type ) {
case T::NUMBR:
numbr = a.numbr;
break;
case T::NUMBAR:
numbar = a.numbar;
break;
case T::TROOF:
troof = a.troof;
break;
case T::YARN:
yarn = a.yarn;
break;
case T::BUKKIT:
bukkit = a.bukkit;
case T::FILEZ:
filez = a.filez;
break;
}
}
~A() {
switch( type ) {
case T::BUKKIT:
bukkit.reset();
break;
case T::FILEZ:
filez.reset();
break;
}
}
A &operator=(const A &a) {
type = a.type;
switch( type ) {
case T::NUMBR:
numbr = a.numbr;
break;
case T::NUMBAR:
numbar = a.numbar;
break;
case T::TROOF:
troof = a.troof;
break;
case T::YARN:
yarn = a.yarn;
break;
case T::BUKKIT:
bukkit = a.bukkit;
case T::FILEZ:
filez = a.filez;
break;
}
return *this;
}
bool operator==(const A &a) const {
if( type != a.type ) {
return false;
}
switch( type ) {
case T::NUMBR:
return numbr == a.numbr;
case T::NUMBAR:
return numbar == a.numbar;
case T::TROOF:
return troof == a.troof;
case T::YARN:
return yarn == a.yarn;
case T::BUKKIT:
return bukkit == a.bukkit;
case T::FILEZ:
return filez == a.filez;
case T::NOOB:
return true;
}
}
std::size_t operator()(const A &a) const {
switch( a.type ) {
case T::NUMBR:
return std::hash<NUMBR>()(a.numbr);
case T::NUMBAR:
return std::hash<NUMBAR>()(a.numbar);
case T::TROOF:
return std::hash<TROOF>()(a.troof);
case T::YARN:
return std::hash<YARN>()(a.yarn);
case T::BUKKIT:
return std::hash<BUKKIT_PTR>()(a.bukkit);
case T::FILEZ:
return std::hash<FILEZ_PTR>()(a.filez);
}
return std::hash<NUMBR>()(0);
}
friend std::ostream &operator <<( std::ostream &out, const A &a ) {
switch( a.type ) {
case A::T::NUMBR:
out << "NUMBR: " << a.numbr;
break;
case A::T::NUMBAR:
out << "NUMBAR: " << a.numbar;
break;
case A::T::TROOF:
out << "TROOF: " << a.troof;
break;
case A::T::YARN:
out << "YARN: " << a.yarn;
break;
case A::T::BUKKIT:
out << "BUKKIT: " << a.bukkit;
break;
case A::T::FILEZ:
out << "FILEZ: " << a.filez;
break;
case A::T::NOOB:
out << "NOOB";
}
return out;
}
};
template<class T>
inline typename std::enable_if<std::is_same<T, NUMBR>::value, T>::type
GetData(const A &var) {
switch( var.type ) {
case A::T::NUMBR:
return var.numbr;
case A::T::NUMBAR:
return (T)(var.numbar);
case A::T::TROOF:
return (T)(var.troof);
}
}
template<class T>
inline typename std::enable_if<std::is_same<T, NUMBAR>::value, T>::type
GetData(const A &var) {
switch( var.type ) {
case A::T::NUMBR:
return (T)(var.numbr);
case A::T::NUMBAR:
return var.numbar;
case A::T::TROOF:
return (T)(var.troof);
}
}
template<class T>
inline typename std::enable_if<std::is_same<T, TROOF>::value, T>::type
GetData(const A &var) {
switch( var.type ) {
case A::T::NUMBR:
return (T)(var.numbr);
case A::T::NUMBAR:
return (T)var.numbar;
case A::T::TROOF:
return var.troof;
}
}
inline void GetNumericDataFromYarn( const YARN *yarn, A::T &type,
NUMBR *numbr, NUMBAR *numbar ) {
char *end;
const char *str = yarn->c_str();
*numbr = std::strtol(str, &end, 10);
if (*end == '\0') {
type = A::T::NUMBR;
return;
}
*numbar = std::strtod(str, &end);
if (*end == '\0') {
type = A::T::NUMBAR;
return;
}
type = A::T::NOOB;
}
inline A sum( const A &lhs, const A &rhs ) {
A ret;
A::T lhs_type = lhs.type;
A::T rhs_type = rhs.type;
bool lhs_from_yarn = (lhs_type == A::T::YARN);
bool rhs_from_yarn = (rhs_type == A::T::YARN);
NUMBR lhs_numbr, rhs_numbr;
NUMBAR lhs_numbar, rhs_numbar;
if( lhs_from_yarn || rhs_from_yarn ) {
if( lhs_from_yarn ) {
GetNumericDataFromYarn( &lhs.yarn, lhs_type, &lhs_numbr, &lhs_numbar );
}
if( rhs_from_yarn ) {
GetNumericDataFromYarn( &rhs.yarn, rhs_type, &rhs_numbr, &rhs_numbar );
}
if( lhs_from_yarn && lhs_type == A::T::NUMBR && rhs_type == A::T::NUMBAR) {
lhs_numbar = (NUMBAR)lhs_numbr;
}
if( rhs_from_yarn && rhs_type == A::T::NUMBR && lhs_type == A::T::NUMBAR) {
rhs_numbar = (NUMBAR)rhs_numbr;
}
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = (lhs_from_yarn ? lhs_numbar : GetData<NUMBAR>(lhs)) + (rhs_from_yarn ? rhs_numbar : GetData<NUMBAR>(rhs));
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = (lhs_from_yarn ? lhs_numbr : GetData<NUMBR>(lhs)) + (rhs_from_yarn ? rhs_numbr : GetData<NUMBR>(rhs));
ret.type = A::T::NUMBR;
return ret;
}
inline A mult( const A &lhs, const A &rhs ) {
A ret;
A::T lhs_type = lhs.type;
A::T rhs_type = rhs.type;
bool lhs_from_yarn = (lhs_type == A::T::YARN);
bool rhs_from_yarn = (rhs_type == A::T::YARN);
NUMBR lhs_numbr, rhs_numbr;
NUMBAR lhs_numbar, rhs_numbar;
if( lhs_from_yarn || rhs_from_yarn ) {
if( lhs_from_yarn ) {
GetNumericDataFromYarn( &lhs.yarn, lhs_type, &lhs_numbr, &lhs_numbar );
}
if( rhs_from_yarn ) {
GetNumericDataFromYarn( &rhs.yarn, rhs_type, &rhs_numbr, &rhs_numbar );
}
if( lhs_from_yarn && lhs_type == A::T::NUMBR && rhs_type == A::T::NUMBAR) {
lhs_numbar = (NUMBAR)lhs_numbr;
}
if( rhs_from_yarn && rhs_type == A::T::NUMBR && lhs_type == A::T::NUMBAR) {
rhs_numbar = (NUMBAR)rhs_numbr;
}
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = (lhs_from_yarn ? lhs_numbar : GetData<NUMBAR>(lhs)) * (rhs_from_yarn ? rhs_numbar : GetData<NUMBAR>(rhs));
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = (lhs_from_yarn ? lhs_numbr : GetData<NUMBR>(lhs)) * (rhs_from_yarn ? rhs_numbr : GetData<NUMBR>(rhs));
ret.type = A::T::NUMBR;
return ret;
}
#if 0
inline A sum( const A &lhs, const A &rhs ) {
A ret;
A::T lhs_type = lhs.type;
A::T rhs_type = rhs.type;
if( lhs_type == A::T::YARN || rhs_type == A::T::YARN ) {
NUMBR lhs_numbr, rhs_numbr;
NUMBAR lhs_numbar, rhs_numbar;
bool lhs_from_yarn, rhs_from_yarn;
lhs_from_yarn = (lhs_type == A::T::YARN);
rhs_from_yarn = (rhs_type == A::T::YARN);
if( lhs_from_yarn ) {
GetNumericDataFromYarn( &lhs.yarn, lhs_type, &lhs_numbr, &lhs_numbar );
}
if( rhs_from_yarn ) {
GetNumericDataFromYarn( &rhs.yarn, rhs_type, &rhs_numbr, &rhs_numbar );
}
if( lhs_from_yarn && lhs_type == A::T::NUMBR && rhs_type == A::T::NUMBAR) {
lhs_numbar = (NUMBAR)lhs_numbr;
}
if( rhs_from_yarn && rhs_type == A::T::NUMBR && lhs_type == A::T::NUMBAR) {
rhs_numbar = (NUMBAR)rhs_numbr;
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = (lhs_from_yarn ? lhs_numbar : GetData<NUMBAR>(lhs)) + (rhs_from_yarn ? rhs_numbar : GetData<NUMBAR>(rhs));
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = (lhs_from_yarn ? lhs_numbr : GetData<NUMBR>(lhs)) + (rhs_from_yarn ? rhs_numbr : GetData<NUMBR>(rhs));
ret.type = A::T::NUMBR;
return ret;
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = GetData<NUMBAR>(lhs) + GetData<NUMBAR>(rhs);
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = GetData<NUMBR>(lhs) + GetData<NUMBR>(rhs);
ret.type = A::T::NUMBR;
return ret;
}
inline A mult( const A &lhs, const A &rhs ) {
A ret;
A::T lhs_type = lhs.type;
A::T rhs_type = rhs.type;
if( lhs_type == A::T::YARN || rhs_type == A::T::YARN ) {
NUMBR lhs_numbr, rhs_numbr;
NUMBAR lhs_numbar, rhs_numbar;
bool lhs_from_yarn, rhs_from_yarn;
lhs_from_yarn = (lhs_type == A::T::YARN);
rhs_from_yarn = (rhs_type == A::T::YARN);
if( lhs_from_yarn ) {
GetNumericDataFromYarn( &lhs.yarn, lhs_type, &lhs_numbr, &lhs_numbar );
}
if( rhs_from_yarn ) {
GetNumericDataFromYarn( &rhs.yarn, rhs_type, &rhs_numbr, &rhs_numbar );
}
if( lhs_from_yarn && rhs_from_yarn ) {
if( lhs_type == A::T::NUMBAR ) {
if( rhs_type == A::T::NUMBR ) {
rhs_numbar = (NUMBAR)rhs_numbr;
}
} else {
if( rhs_type == A::T::NUMBAR ) {
lhs_numbar = (NUMBAR)lhs_numbr;
}
}
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = (lhs_from_yarn ? lhs_numbar : GetData<NUMBAR>(lhs)) * (rhs_from_yarn ? rhs_numbar : GetData<NUMBAR>(rhs));
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = (lhs_from_yarn ? lhs_numbr : GetData<NUMBR>(lhs)) * (rhs_from_yarn ? rhs_numbr : GetData<NUMBR>(rhs));
ret.type = A::T::NUMBR;
return ret;
}
if( lhs_type == A::T::NUMBAR || rhs_type == A::T::NUMBAR ) {
ret.numbar = GetData<NUMBAR>(lhs) * GetData<NUMBAR>(rhs);
ret.type = A::T::NUMBAR;
return ret;
}
ret.numbr = GetData<NUMBR>(lhs) * GetData<NUMBR>(rhs);
ret.type = A::T::NUMBR;
return ret;
}
#endif
NUMBAR a() {
A a, b, c;
a.numbar = 4.1;
a.type = A::T::NUMBAR;
b.numbr = 5;
b.type = A::T::NUMBR;
c.numbr = 3;
c.type = A::T::NUMBR;
return GetData<NUMBAR>( mult(a, sum(b, c) ) );
}
double b() {
double a = 4.2;
NUMBR b = 2;
return a + b;
}
NUMBR c() {
A a, b, c;
a.type = A::T::NUMBR;
a.numbr = 5;
b.type = A::T::NUMBR;
b.numbr = 2;
c.type = A::T::NUMBR;
c.numbr = 3;
return GetData<NUMBR>( mult(a, sum(b, c)) );
}
NUMBR d() {
NUMBR a = 4;
NUMBR b = 2;
NUMBR c = 3;
return a + b + c;
}
bool e() {
A e;
e.type = A::T::NUMBAR;
e.numbar = 42.0;
return GetData<TROOF>( e );
}
NUMBR f(NUMBR x) {
A f;
f.type = A::T::NUMBR;
f.numbr = x;
return GetData<NUMBR>( sum( f, mult( f, f ) ) );
}
NUMBR f2(NUMBR x) {
A f, g;
f.type = A::T::NUMBR;
f.numbr = x;
g.type = A::T::NUMBR;
g.numbr = 2;
for(int i = 0; i < x; ++i ) {
f = sum( f, mult( f, g ) );
}
return GetData<NUMBR>( f );
}
inline A g2(const A &x, const A &y) {
return sum( mult( x, x ), mult( y, y ) );
}
inline A g(const A &x, const A &y) {
return g2(mult(x, y), sum(x, y));
}
NUMBR h() {
A x, y;
x.type = A::T::NUMBR;
x.numbr = 6;
y.type = A::T::NUMBR;
y.numbr = 4;
return GetData<NUMBR>( g( x, y ) );
}
NUMBR m() {
A x, z;
x.type = A::T::NUMBR;
x.numbr = 20;
x.type = A::T::YARN;
new (&x.yarn) std::string("10");
A y = x;
z.type = A::T::NUMBR;
z.numbr = 2;
return GetData<NUMBR>( sum( z, mult( x, y ) ) );
}
NUMBAR n() {
A x, y, z;
x.type = A::T::YARN;
new (&x.yarn) std::string("10");
y.type = A::T::YARN;
new (&y.yarn) std::string("10.1");
z.type = A::T::NUMBR;
z.numbr = 2;
return GetData<NUMBAR>( sum( x, mult( z, y ) ) );
}
NUMBR n2() {
A x, y, z;
x.type = A::T::NUMBAR;
x.numbar = 10.1;
y.type = A::T::NUMBR;
y.numbr = 10;
z.type = A::T::NUMBR;
z.numbr = 2;
// Note cast to NUMBR from NUMBAR
return GetData<NUMBR>( sum( z, mult( x, y ) ) );
}
NUMBAR n3() {
A x, y, z;
x.type = A::T::YARN;
new (&x.yarn) std::string("10");
y.type = A::T::YARN;
new (&y.yarn) std::string("10.1");
z.type = A::T::NUMBR;
z.numbr = 2;
return GetData<NUMBAR>( sum( z, mult( x, y ) ) );
}
void p() {
A b, bb, k, kp;
b.type = A::T::BUKKIT;
new (&b.bukkit) BUKKIT_PTR(new BUKKIT());
bb.type = A::T::BUKKIT;
new (&bb.bukkit) BUKKIT_PTR(new BUKKIT());
k.type = A::T::NUMBR;
k.numbr = 1;
(*bb.bukkit)[k] = b;
(*b.bukkit)[k] = k;
std::cout << "at(k) = " << b.bukkit->at(k) << std::endl;
kp = k;
k.type = A::T::NUMBAR;
k.numbar = 1.5;
(*b.bukkit)[k] = k;
std::cout << "at(k) = " << b.bukkit->at(k) << std::endl;
std::cout << "at(kp) = " << b.bukkit->at(kp) << std::endl;
std::cout << "at(kp)(kp) = " << bb.bukkit->at(kp).bukkit->at(kp) << std::endl;
}
void q() {
A fin, in;
fin.type = A::T::FILEZ;
new (&fin.filez) FILEZ_PTR(new FILEZ("t.out", std::ios::out | std::ios::in));
new (&in.yarn) std::string();
//(*fin.filez) << "R";
(*fin.filez) >> in.yarn;
in.type = A::T::YARN;
std::cout << "in.yarn = " << in.yarn << std::endl;
//std::cout << "in.yarn = " << in.yarn << std::endl;
}
int main() {
std::cout << "sizeof(A) = " << sizeof(A) << std::endl;
std::cout << "a() = " << a() << std::endl;
std::cout << "c() = " << c() << std::endl;
std::cout << "e() = " << e() << std::endl;
std::cout << "h() = " << h() << std::endl;
std::cout << "f(5) = " << f(5) << std::endl;
std::cout << "f2(5) = " << f2(5) << std::endl;
std::cout << "m() = " << m() << std::endl;
std::cout << "n() = " << n() << std::endl;
std::cout << "n2() = " << n2() << std::endl;
std::cout << "n3() = " << n3() << std::endl;
p();
q();
return 0;
} | [
"stephen.chou@outlook.com"
] | stephen.chou@outlook.com |
14c2f8aa4b4d67c7a8fc037b9697615efb6f73b1 | e039dbfd3f94edf3834b061749f1189cc29f28a1 | /MayaExporterForER/MayaExporterForER/include/maya/MAtomic.h | 0e6aec368d48ffa2b17067553a3abe29000b4628 | [] | no_license | yvetterowe/Maya-Plugin-for-Elvish-Render | 401a66d75b87b98168e63083c19aa383cba99f56 | cea337b9f10ab81294c3a9e07d64bdd6c82f634f | refs/heads/master | 2021-05-28T08:53:45.483445 | 2015-02-22T21:49:04 | 2015-02-22T21:49:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,355 | h | #ifndef _MAtomic
#define _MAtomic
//-
// ==========================================================================
// Copyright (C) 1995 - 2008 Autodesk, Inc., and/or its licensors. All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Autodesk, Inc. ("Autodesk") and/or its
// licensors, which is protected by U.S. and Canadian federal copyright law
// and by international treaties.
//
// The Data may not be disclosed or distributed to third parties or be
// copied or duplicated, in whole or in part, without the prior written
// consent of Autodesk.
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the following
// disclaimer, must be included in all copies of the Software, in whole
// or in part, and all derivative works of the Software, unless such copies
// or derivative works are solely in the form of machine-executable object
// code generated by a source language processor.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
// AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
// WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
// NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE,
// OR ARISING FROM A COURSE OF DEALING, USAGE, OR TRADE PRACTICE. IN NO
// EVENT WILL AUTODESK AND/OR ITS LICENSORS BE LIABLE FOR ANY LOST
// REVENUES, DATA, OR PROFITS, OR SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK AND/OR ITS LICENSORS HAS
// BEEN ADVISED OF THE POSSIBILITY OR PROBABILITY OF SUCH DAMAGES.
// ==========================================================================
//+
//
// CLASS: MAtomic
//
// ****************************************************************************
#if defined __cplusplus
// ****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MTypes.h>
// ****************************************************************************
// CLASS DECLARATION (MAtomic)
//! \ingroup OpenMaya
//! \brief Methods for atomic operations.
/*!
The MAtomic class implements several cross-platform atomic
operations which are useful when writing a multithreaded
application. Atomic operations are those that appear to happen as
a single operation when viewed from other threads.
As a usage example, during reference counting in an SMP
environment, it is important to ensure that decrementing and
testing the counter against zero happens atomically. If coded this
way:
if (--counter == 0) {}
then another thread could modify the value of counter between the
decrement and the if test. The above code would therefore get the
wrong value. This class provides a routine to perform the
decrement and return the previous value atomically, so the above
snippet could be written as:
if (MAtomic::preDecrement(&counter) == 0) {}
*/
#if defined(_WIN32)
// Ensure that we get winsock2.h rather than winsock.h
# include <winsock2.h>
# include <windows.h>
# include <winbase.h>
# include <math.h>
# include <intrin.h>
#pragma intrinsic(_InterlockedCompareExchange)
#pragma intrinsic(_InterlockedExchange)
#pragma intrinsic(_InterlockedExchangeAdd)
#pragma intrinsic(_InterlockedIncrement)
#pragma intrinsic(_InterlockedDecrement)
#define FORCE_INLINE __forceinline
#elif defined(__linux__) || defined (__APPLE__)
#define FORCE_INLINE inline __attribute__((always_inline))
// implement inline assembly for Linux 32/64 compatible with gcc and
// icc. gcc has atomic intrinsics but icc does not currently support
// them, so we do it all with assembler.
//
#define MAYA_LINUX_ATOMICS(X) \
static FORCE_INLINE int atomicCmpXChg(volatile int *value, int comparand, int newValue ) \
{ \
int result; \
__asm__ __volatile__("lock\ncmpxchg" X " %2,%1" \
: "=a"(result), "=m"(*value) \
: "q"(newValue), "0"(comparand) \
: "memory"); \
return result; \
} \
static FORCE_INLINE int atomicXAdd(volatile int *value, int addend) \
{ \
int result; \
__asm__ __volatile__("lock\nxadd" X " %0,%1" \
: "=r"(result), "=m"(*value) \
: "0"(addend) \
: "memory"); \
return result; \
} \
static FORCE_INLINE int atomicXChg(volatile int *value, int newValue) \
{ \
int result; \
__asm__ __volatile__("lock\nxchg" X " %0,%1" \
: "=r"(result), "=m"(*value) \
: "0"(newValue) \
: "memory"); \
return result; \
}
#if defined(__i386__) || defined (Bits32_)
// 32 bits
MAYA_LINUX_ATOMICS("l")
#else
MAYA_LINUX_ATOMICS("")
#endif
#else
#error Undefined platform
#endif // __linux__
class OPENMAYA_EXPORT MAtomic
{
public:
/*!
Increment variable, return value after increment
\param[in] variable Value to be modified
\return. Variable value after incrementing
*/
static FORCE_INLINE int preIncrement(volatile int *variable)
{
#if defined(_WIN32)
return (_InterlockedIncrement((long*)variable));
#else
return( atomicXAdd( variable, 1 ) + 1 );
#endif
}
/*!
Increment variable, return value before increment
\param[in] variable Value to be modified
\return. Variable value before incrementing
*/
static FORCE_INLINE int postIncrement(volatile int *variable)
{
#if defined(_WIN32)
return (_InterlockedExchangeAdd((long*)variable,1));
#else
return( atomicXAdd( variable, 1 ) );
#endif
}
/*!
Increment variable by incrementValue, return value before increment.
\param[in] variable Value to be modified
\param[in] incrementValue Value by which to increment variable
\return. Variable value before incrementing
*/
static FORCE_INLINE int increment(volatile int *variable, int incrementValue)
{
#if defined(_WIN32)
return (_InterlockedExchangeAdd((long*)variable, incrementValue));
#else
return( atomicXAdd( variable, incrementValue ) );
#endif
}
/*!
Decrement variable, return value after increment
\param[in] variable Value to be modified
\return. Variable value after decrementing
*/
static FORCE_INLINE int preDecrement(volatile int *variable)
{
#if defined(_WIN32)
return (_InterlockedDecrement((long*)variable));
#else
return( atomicXAdd( variable, -1 ) - 1 );
#endif
}
/*!
Decrement variable, return value before decrement
\param[in] variable Value to be modified
\return. Variable value before decrementing
*/
static FORCE_INLINE int postDecrement(volatile int *variable)
{
#if defined(_WIN32)
return (_InterlockedExchangeAdd((long*)variable, -1));
#else
return( atomicXAdd( variable, -1 ) );
#endif
}
/*!
Decrement variable by decrementValue, return value before decrement.
\param[in] variable Value to be modified
\param[in] decrementValue Value by which to decrement variable
\return. Variable value before decrementing
*/
static FORCE_INLINE int decrement(volatile int *variable,
int decrementValue)
{
#if defined(_WIN32)
return (_InterlockedExchangeAdd((long*)variable, -decrementValue));
#else
return( atomicXAdd( variable, -decrementValue ) );
#endif
}
/*!
Set variable to newValue, return value of variable before set.
\param[in] variable Value to be modified
\param[in] newValue Value to which to set variable
\return. Variable value before set
*/
static FORCE_INLINE int set(volatile int *variable, int newValue)
{
#if defined(_WIN32)
return (_InterlockedExchange((long*)variable, newValue));
#else
return atomicXChg( variable, newValue );
#endif
}
/*!
Compare variable with compareValue and if the values are equal,
sets *variable equal to swapValue. The result of the comparison is
returned, true if the compare was sucessful, false otherwise.
\param[in] variable First value to be compared
\param[in] compareValue Second value to be compared
\param[in] swapValue Value to set *variable to if comparison is successful
\return. True if variable equals compareValue, otherwise false
*/
static FORCE_INLINE int compareAndSwap(volatile int *variable,
int compareValue,
int swapValue)
{
#if defined(_WIN32)
return (_InterlockedCompareExchange((long*)variable, swapValue, compareValue)
== compareValue);
#else
return( atomicCmpXChg( variable, compareValue, swapValue ) == compareValue);
#endif
}
};
#endif /* __cplusplus */
#endif /* _MAtomic */
| [
"yvetterowe1116@gmail.com@f82b52a9-fb2f-50e7-dc0d-a1cbf65dcd3b"
] | yvetterowe1116@gmail.com@f82b52a9-fb2f-50e7-dc0d-a1cbf65dcd3b |
ca8132bb6406d4c55b9c76ff05f52b133274ad3a | d5ddd3c8cfda24ca90a9fe7962d2cf2017f2ea8e | /game/box.h | e58bc35b69f94ae5cc226f60585180238fd7f703 | [] | no_license | yjmantilla/hockey | 56c0553de3b3a9fe0c1b71830c03d1a954a26128 | fb63b1b3274547d2876edefd0cc9c05e16b7f388 | refs/heads/master | 2020-03-13T10:48:27.294589 | 2018-06-12T22:59:24 | 2018-06-12T22:59:24 | 131,090,540 | 0 | 1 | null | 2018-06-11T21:23:40 | 2018-04-26T02:43:41 | C++ | UTF-8 | C++ | false | false | 671 | h | #ifndef BOX_H
#define BOX_H
/* Libraries */
#include <QGraphicsItem>
#include <QPainter>
#include "vectorxy.h"
/*
* Box Class
*
* It represents the random box that which
* upon contact with the puck activates an effect
* an disappears.
*
* It moves with constant velocity around the field
* unaffected by other bodies.
*
*/
class Box: public QGraphicsItem
{
public:
/* Attributes */
VectorXY * velocity;
/* Methods */
/* Constructor */
Box();
/* Appearance */
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
/* Destructor */
~Box();
};
#endif // BOX_H
| [
"yjmantilla@gmail.com"
] | yjmantilla@gmail.com |
c4c0856f0cd8efc42b6b122b498293ad9a162204 | 887f3a72757ff8f691c1481618944b727d4d9ff5 | /third_party/gecko_1.9.2/win32/gecko_sdk/include/nsIToolkitProfile.h | 6f7211c021f6d2328958de00431765524becee2c | [] | 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 | 10,567 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.2-win32-xulrunner/build/toolkit/profile/public/nsIToolkitProfile.idl
*/
#ifndef __gen_nsIToolkitProfile_h__
#define __gen_nsIToolkitProfile_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 nsILocalFile; /* forward declaration */
class nsIToolkitProfile; /* forward declaration */
class nsIProfileUnlocker; /* forward declaration */
/* starting interface: nsIProfileLock */
#define NS_IPROFILELOCK_IID_STR "50e07b0a-f338-4da3-bcdb-f4bb0db94dbe"
#define NS_IPROFILELOCK_IID \
{0x50e07b0a, 0xf338, 0x4da3, \
{ 0xbc, 0xdb, 0xf4, 0xbb, 0x0d, 0xb9, 0x4d, 0xbe }}
/**
* Hold on to a profile lock. Once you release the last reference to this
* interface, the profile lock is released.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIProfileLock : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROFILELOCK_IID)
/**
* The main profile directory.
*/
/* readonly attribute nsILocalFile directory; */
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) = 0;
/**
* A directory corresponding to the main profile directory that exists for
* the purpose of storing data on the local filesystem, including cache
* files or other data files that may not represent critical user data.
* (e.g., this directory may not be included as part of a backup scheme.)
*
* In some cases, this directory may just be the main profile directory.
*/
/* readonly attribute nsILocalFile localDirectory; */
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) = 0;
/**
* Unlock the profile.
*/
/* void unlock (); */
NS_SCRIPTABLE NS_IMETHOD Unlock(void) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIProfileLock, NS_IPROFILELOCK_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIPROFILELOCK \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory); \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory); \
NS_SCRIPTABLE NS_IMETHOD Unlock(void);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIPROFILELOCK(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return _to GetDirectory(aDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return _to GetLocalDirectory(aLocalDirectory); } \
NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return _to Unlock(); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIPROFILELOCK(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDirectory(aDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDirectory(aLocalDirectory); } \
NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Unlock(); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsProfileLock : public nsIProfileLock
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROFILELOCK
nsProfileLock();
private:
~nsProfileLock();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsProfileLock, nsIProfileLock)
nsProfileLock::nsProfileLock()
{
/* member initializers and constructor code */
}
nsProfileLock::~nsProfileLock()
{
/* destructor code */
}
/* readonly attribute nsILocalFile directory; */
NS_IMETHODIMP nsProfileLock::GetDirectory(nsILocalFile * *aDirectory)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsILocalFile localDirectory; */
NS_IMETHODIMP nsProfileLock::GetLocalDirectory(nsILocalFile * *aLocalDirectory)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void unlock (); */
NS_IMETHODIMP nsProfileLock::Unlock()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
/* starting interface: nsIToolkitProfile */
#define NS_ITOOLKITPROFILE_IID_STR "7422b090-4a86-4407-972e-75468a625388"
#define NS_ITOOLKITPROFILE_IID \
{0x7422b090, 0x4a86, 0x4407, \
{ 0x97, 0x2e, 0x75, 0x46, 0x8a, 0x62, 0x53, 0x88 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIToolkitProfile : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ITOOLKITPROFILE_IID)
/**
* A interface representing a profile.
* @note THIS INTERFACE SHOULD BE IMPLEMENTED BY THE TOOLKIT CODE ONLY! DON'T
* EVEN THINK ABOUT IMPLEMENTING THIS IN JAVASCRIPT!
*/
/**
* The location of the profile directory.
*/
/* readonly attribute nsILocalFile rootDir; */
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) = 0;
/**
* The location of the profile local directory, which may be the same as
* the root directory. See nsIProfileLock::localDirectory.
*/
/* readonly attribute nsILocalFile localDir; */
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) = 0;
/**
* The name of the profile.
*/
/* attribute AUTF8String name; */
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) = 0;
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) = 0;
/**
* Removes the profile from the registry of profiles.
*
* @param removeFiles
* Indicates whether or not the profile directory should be
* removed in addition.
*/
/* void remove (in boolean removeFiles); */
NS_SCRIPTABLE NS_IMETHOD Remove(PRBool removeFiles) = 0;
/**
* Lock this profile using platform-specific locking methods.
*
* @param lockFile If locking fails, this may return a lockFile object
* which can be used in platform-specific ways to
* determine which process has the file locked. Null
* may be passed.
* @return An interface which holds a profile lock as long as you reference
* it.
* @throws NS_ERROR_FILE_ACCESS_DENIED if the profile was already locked.
*/
/* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker **aUnlocker NS_OUTPARAM, nsIProfileLock **_retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIToolkitProfile, NS_ITOOLKITPROFILE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSITOOLKITPROFILE \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir); \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir); \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName); \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName); \
NS_SCRIPTABLE NS_IMETHOD Remove(PRBool removeFiles); \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker **aUnlocker NS_OUTPARAM, nsIProfileLock **_retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSITOOLKITPROFILE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return _to GetRootDir(aRootDir); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return _to GetLocalDir(aLocalDir); } \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return _to GetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return _to SetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD Remove(PRBool removeFiles) { return _to Remove(removeFiles); } \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker **aUnlocker NS_OUTPARAM, nsIProfileLock **_retval NS_OUTPARAM) { return _to Lock(aUnlocker, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSITOOLKITPROFILE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRootDir(aRootDir); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDir(aLocalDir); } \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD Remove(PRBool removeFiles) { return !_to ? NS_ERROR_NULL_POINTER : _to->Remove(removeFiles); } \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker **aUnlocker NS_OUTPARAM, nsIProfileLock **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Lock(aUnlocker, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsToolkitProfile : public nsIToolkitProfile
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSITOOLKITPROFILE
nsToolkitProfile();
private:
~nsToolkitProfile();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsToolkitProfile, nsIToolkitProfile)
nsToolkitProfile::nsToolkitProfile()
{
/* member initializers and constructor code */
}
nsToolkitProfile::~nsToolkitProfile()
{
/* destructor code */
}
/* readonly attribute nsILocalFile rootDir; */
NS_IMETHODIMP nsToolkitProfile::GetRootDir(nsILocalFile * *aRootDir)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsILocalFile localDir; */
NS_IMETHODIMP nsToolkitProfile::GetLocalDir(nsILocalFile * *aLocalDir)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String name; */
NS_IMETHODIMP nsToolkitProfile::GetName(nsACString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsToolkitProfile::SetName(const nsACString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void remove (in boolean removeFiles); */
NS_IMETHODIMP nsToolkitProfile::Remove(PRBool removeFiles)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */
NS_IMETHODIMP nsToolkitProfile::Lock(nsIProfileUnlocker **aUnlocker NS_OUTPARAM, nsIProfileLock **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIToolkitProfile_h__ */
| [
"gears.daemon@fe895e04-df30-0410-9975-d76d301b4276"
] | gears.daemon@fe895e04-df30-0410-9975-d76d301b4276 |
bf700ad4861aeda346dc3236d419d2810873e1af | bf4e779d3164ac662be09e30bacd956e58ebc75b | /1107.cpp | c2a412e7e80e1ff2ff777f1c3a3bbbbadf2ff145 | [] | no_license | EdsonYamamoto/URI-Online-Judge-AD-HOC | 8e6552a2d9387abf8f709bfd2179e559ee8187f1 | 9b4626b5fb179d9ba29f39caef39c2edd0c09b44 | refs/heads/master | 2021-01-11T21:54:02.725780 | 2017-01-13T16:24:57 | 2017-01-13T16:24:57 | 78,870,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,602 | cpp | /*
URI Online Judge | 1107
Escultura à Laser
Maratona de Programação da SBC Brasil
Timelimit: 1
Desde a sua invenção, em 1958, os raios laser têm sido utilizados em uma imensa variedade de aplicações, como equipamentos eletrônicos, instrumentos cirúrgicos, armamentos, e muito mais.
A figura acima mostra um diagrama esquemático de um equipamento para esculpir, com laser, um bloco de material maciço. Na figura vemos um emissor laser que se desloca horizontalmente para a direita e para a esquerda com velocidade constante. Quando o emissor é ligado durante o deslocamento, uma camada de espessura constante é removida do bloco, sendo vaporizada pelo laser.
A figura abaixo ilustra o processo de escultura a laser, mostrando um exemplo de (a) um bloco, com 5 mm de altura por 8 mm de comprimento, no início do processo, (b) o formato que se deseja que o bloco esculpido tenha, e (c) a sequência de remoção das camadas do bloco durante o processo, considerando que a cada varredura uma camada de espessura de 1 mm é removida.
Na primeira varredura, o pedaço numerado como 1 é removido; na segunda varredura, o pedaço numerado como 2 é removido, e assim por diante. Durante o processo de remoção, o laser foi ligado um total de 7 vezes, uma vez para cada pedaço de bloco removido.
Escreva um programa que, dados a altura do bloco, o comprimento do bloco, e a forma final que o bloco deve ter, determine o número total vezes de que o laser deve ser ligado para esculpir o bloco.
Entrada
A entrada contém vários casos de teste. Cada caso de teste é composto por duas linhas. A primeira linha de um caso de teste contém dois números inteiros A e C, separados por um espaço em branco, indicando respectivamente a altura (1 ≤ A ≤ 104) e o comprimento (1 ≤ C ≤ 104) do bloco a ser esculpido, em milímetros. A segunda linha contém C números inteiros Xi, cada um indicando a altura final, em milímetros, do bloco entre as posições i e i + 1 ao longo do comprimento (0 ≤ Xi ≤ A, para 0 ≤ i ≤ C - 1). Considere que a cada varredura uma camada de espessura 1 milímetro é removida do bloco ao longo dos pontos onde o laser está ligado.
O final da entrada é indicado por uma linha que contém apenas dois zeros, separados por um espaço em branco.
Saída
Para cada caso de teste da entrada seu programa deve imprimir uma única linha, contendo um número inteiro, indicando o número de vezes que o laser deve ser ligado para esculpir o bloco na forma indicada.
Exemplo de Entrada
Exemplo de Saída
5 8
1 2 3 2 0 3 4 5
3 3
1 0 2
4 3
4 4 1
0 0
7
3
3
*/ | [
"edsonkazyamamoto@gmail.com"
] | edsonkazyamamoto@gmail.com |
cfa90006243927cbaa4778703ae230d5fe5307d8 | 63d3f1240a2813ec83ebddada2cc5d1906b1471b | /BasicCppStudy/PK_Game/monster.cpp | 8354dcd74104e6fb6ea715f08dc0bc7ef2dd300d | [] | no_license | DaleChen0351/basic_cpp_learn_repo | 67298e46d934a478ed439e5dfbca41b19ad491ed | 4898632238907f8b37877490ba3a492bd924187a | refs/heads/master | 2022-05-14T14:13:41.457853 | 2022-04-16T13:08:21 | 2022-04-16T13:08:21 | 226,445,129 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 967 | cpp | #include "monster.h"
Monster::Monster(int monsterId)
{
FileManager fm;
map<string, map<string, string>>m_monster;
fm.loadCSVData("resource/Monster.csv", m_monster);
string tem_id = std::to_string(monsterId);
string Id = m_monster[tem_id]["monsterId"];
this->monsterName = m_monster[tem_id]["monsterName"];
this->monsterAtk = atoi(m_monster[tem_id]["monsterAtk"].c_str());
this->monsterDef = atoi(m_monster[tem_id]["monsterDef"].c_str());
this->monsterHp = atoi(m_monster[tem_id]["monsterHp"].c_str());
this->isFrozen = false;
}
void Monster::Attack(Hero * hero)
{
if (this->isFrozen)
{
cout << "<" << this->monsterName << "> 被冰冻,本回合无法攻击 <" << hero->heroName << "> " << endl;
return;
}
int harm_val = this->monsterAtk - hero->heroDef > 0 ? monsterAtk - hero->heroDef : 1;
hero->heroHp -= harm_val;
cout << "<" << monsterName << "> 攻击了 <" << hero->heroName << ">,造成: "<< harm_val <<" 点伤害" << endl;
}
| [
"dalechen0351@gmail.com"
] | dalechen0351@gmail.com |
8fe0a56cc55ce019a6b154f06aa9cc96a261d377 | d2c59879cbaa8f657da7124594607293a9ea2761 | /fdfr_demo/modules/mp/include/tuple.hpp | df77e8f96381dc6ed45f71e21fc6b772c235b631 | [] | no_license | freewind2016/bm1880-ai-demo-program | 9032cb2845a79b3bfebf270f8771ea6ee3f1e102 | d1634e5c314e346a1229c4df96efe9c37401cdd7 | refs/heads/master | 2022-06-01T02:39:57.883696 | 2020-03-20T01:56:43 | 2020-03-20T01:56:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,039 | hpp | #pragma once
#include <tuple>
#include "indices.hpp"
#include "tuple_cast.hpp"
namespace mp {
template <typename Tuple>
struct tuple_decay_impl;
template <typename... Types>
struct tuple_decay_impl<std::tuple<Types...>> {
using type = std::tuple<typename std::decay<Types>::type...>;
};
template <typename Tuple>
struct tuple_element_unique;
template <>
struct tuple_element_unique<std::tuple<>> {
static constexpr bool value = true;
};
template <typename T, typename... Ts>
struct tuple_element_unique<std::tuple<T, Ts...>> {
static constexpr bool value = !IndexOf<std::tuple<Ts...>, T>::valid && tuple_element_unique<std::tuple<Ts...>>::value;
};
template <typename T>
using tuple_decay = tuple_decay_impl<typename std::decay<T>::type>;
template <typename T, typename... Types>
T &tuple_get(std::tuple<Types...> &tuple) {
return std::get<IndexOf<std::tuple<Types...>, T>::value>(tuple);
}
template <typename T, typename... Types>
const T &tuple_get(const std::tuple<Types...> &tuple) {
return std::get<IndexOf<std::tuple<Types...>, T>::value>(tuple);
}
template <typename T, size_t... Idx>
inline std::tuple<typename std::tuple_element<Idx, typename std::decay<T>::type>::type...> tuple_subsequence(T &&tuple, Indices<Idx...>) {
return std::make_tuple(std::move(std::get<Idx>(tuple))...);
}
template <typename T, size_t... Idx>
inline std::tuple<typename std::decay<typename std::tuple_element<Idx, T>::type>::type...> subtuple_construct(T &&tuple, Indices<Idx...>) {
return std::make_tuple<typename std::decay<typename std::tuple_element<Idx, T>::type>::type...>(std::move(std::get<Idx>(tuple))...);
}
template <typename Tup, size_t... Idx>
inline std::tuple<typename std::remove_reference<typename std::tuple_element<Idx, typename std::decay<Tup>::type>::type>::type &&...>
subtuple_move(Tup &&tup, Indices<Idx...>) {
return std::forward_as_tuple(std::move(std::get<Idx>(tup))...);
}
template <typename... Types>
inline std::tuple<typename std::remove_reference<Types>::type &&...> tuple_move(std::tuple<Types...> &&t) {
return subtuple_move(std::move(t), typename MakeIndices<0, sizeof...(Types)>::type());
}
template <typename... Types>
inline std::tuple<typename std::remove_reference<Types>::type &&...> tuple_move(std::tuple<Types...> &t) {
return subtuple_move(std::move(t), typename MakeIndices<0, sizeof...(Types)>::type());
}
template <typename Tup, size_t... Idx>
inline std::tuple<typename std::tuple_element<Idx, typename std::decay<Tup>::type>::type...>
subtuple_forward(Tup &&tup, Indices<Idx...>) {
return std::forward_as_tuple(((typename std::tuple_element<Idx, typename std::decay<Tup>::type>::type)std::get<Idx>(tup))...);
}
template <typename... Types>
inline std::tuple<Types &&...> tuple_forward(std::tuple<Types...> &&t) {
return subtuple_forward(std::move(t), typename MakeIndices<0, sizeof...(Types)>::type());
}
template <typename RetType, typename InType, size_t... Idx>
inline RetType tuple_convert(InType &&tup, Indices<Idx...>) {
return std::forward_as_tuple(static_cast<typename std::tuple_element<Idx, typename std::decay<RetType>::type>::type>(std::get<Idx>(tup))...);
}
template <typename RetType, typename InType, size_t... Idx>
inline RetType subtuple_convert(InType &&tup, Indices<Idx...>) {
return tuple_convert<RetType>(
subtuple_forward(std::forward<InType>(tup), Indices<Idx...>()),
typename MakeIndices<0, std::tuple_size<RetType>::value>::type()
);
}
template <typename RetType, typename InType>
inline RetType subtuple_convert(InType &&tup) {
using indices_t = typename mp::SubIndices<typename mp::tuple_decay<InType>::type, typename mp::tuple_decay<RetType>::type>::type;
return subtuple_convert<RetType>(std::forward<InType>(tup), indices_t());
}
template <typename ToType, typename FromType>
inline ToType tuple_cast(FromType &&tuple) {
using indices_t = typename SubIndices<FromType, ToType>::type;
static_assert(!std::is_same<indices_t, void>::value, "tuple_cast: invalid conversion");
return tuple_subsequence(std::move(tuple), indices_t());
}
template <typename T, typename... Ts>
inline std::tuple<Ts...> tuple_pop_first(std::tuple<T, Ts...> &&tuple) {
typedef typename MakeIndices<1, sizeof...(Ts) + 1>::type indices_t;
return tuple_subsequence(std::move(tuple), indices_t());
}
template <typename ToType, typename FromType>
struct TupleCastValid {
using indices_t = typename SubIndices<FromType, ToType>::type;
static constexpr bool value = !std::is_same<indices_t, void>::value;
};
template <typename Tuple, template<typename> class Transform>
struct tuple_map;
template <typename... Types, template<typename> class Transform>
struct tuple_map<std::tuple<Types...>, Transform> {
using type = std::tuple<Transform<Types>...>;
};
template <typename Tuple, template<typename> class Predicate>
struct tuple_filter;
template <template<typename> class Predicate>
struct tuple_filter<std::tuple<>, Predicate> {
using type = std::tuple<>;
};
template <typename T, typename... Types, template<typename> class Predicate>
struct tuple_filter<std::tuple<T, Types...>, Predicate> {
using type = decltype(std::tuple_cat(
std::declval<typename std::conditional<Predicate<T>::value, std::tuple<T>, std::tuple<>>::type>(),
std::declval<typename tuple_filter<std::tuple<Types...>, Predicate>::type>()
));
};
template <typename Super, typename Sub, typename Index>
struct TupleDiffIndicesImpl {
using sub_index = IndexOf<Sub, typename std::tuple_element<Index::value, Super>::type>;
using recurse = TupleDiffIndicesImpl<
Super,
decltype(tuple_subsequence(
std::declval<Sub>(),
typename IndicesSubtract<
typename MakeIndices<0, std::tuple_size<Sub>::value>::type,
typename std::conditional<sub_index::valid, Indices<sub_index::value>, Indices<>>::type
>::type()
)),
std::integral_constant<size_t, Index::value + 1>
>;
using type = decltype(std::declval<typename std::conditional<sub_index::valid, Indices<>, Indices<Index::value>>::type>().concat(typename recurse::type()));
};
template <typename... Super, typename Sub>
struct TupleDiffIndicesImpl<std::tuple<Super...>, Sub, std::integral_constant<size_t, sizeof...(Super)>> {
using type = Indices<>;
};
template <typename Super, typename Sub>
using TupleDiffIndices = TupleDiffIndicesImpl<Super, Sub, std::integral_constant<size_t, 0>>;
} | [
"liang.wang02@bitmain.com"
] | liang.wang02@bitmain.com |
6ad3331773ed5c0e520fa0877f0d4ae150b3de66 | 5bf570d3729946b20fe24cf3ffbec25dea16378b | /editor/main.cpp | c618acc5b179681a03ca30402f8b11a11c37c873 | [
"Apache-2.0"
] | permissive | snumrl/SkelGen | 7566f56ccecf80009cbc5edda49cb2da26cc3591 | b8cf6d88b96d0e9323c637489264512d7caefaec | refs/heads/master | 2023-01-20T23:59:19.808312 | 2020-11-30T05:58:45 | 2020-11-30T05:58:45 | 289,837,018 | 31 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | cpp | #include <boost/filesystem.hpp>
#include <stdlib.h>
#include <memory>
#include "EditorWindow.h"
#include "../APTOpt/APTWindow.h"
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <string>
#include <GL/glut.h>
using namespace std;
void Render(int argc,char** argv,EditorWindow *editorWindow ){
cout<<"q: wp.x++"<<endl;
cout<<"w: wp.x--"<<endl;
cout<<"a: wp.y++"<<endl;
cout<<"s: wp.y--"<<endl;
cout<<"z: wp.z++"<<endl;
cout<<"x: wp.z--"<<endl;
cout << "current waypoint index : " << 1 << endl;
glutInit(&argc, argv);
editorWindow->InitWindow(1080,1080,"Render");
editorWindow->setInitialCameraView();
glutMainLoop();
}
void Render(int argc,char** argv,APTWindow *aptWindow ){
cout<<"ROM Representation"<<endl;
glutInit(&argc, argv);
aptWindow->InitWindow(800,800,"Render");
glutMainLoop();
}
void Exam(APTWindow *aptWindow)
{
aptWindow->checkTorque(aptWindow->mWorld->GetMusculoSkeletalSystem());
// aptWindow->drawAPTGraph(aptWindow->mWorld->GetCmpMusculoSkeletalSystem(), "RTG");
}
int main(int argc,char** argv)
{
// APTWindow *aptWindow = new APTWindow();
// Exam(aptWindow);
// Render(argc, argv, aptWindow);
EditorWindow *editorWindow = new EditorWindow();
// editorWindow->drawGraph();
Render(argc, argv, editorWindow);
return 0;
} | [
"umsukgod@hanmail.net"
] | umsukgod@hanmail.net |
cd595372c4ba722ace7b1c09cb1680fc7b72f487 | 7866cf16724c0e90d45ab5fb97448a6b865b82b3 | /cpp/samchon/library/StringUtil.hpp | b8dbd3387edac6424ba43fb18407a18b9afa78df | [
"BSD-3-Clause"
] | permissive | samchon/framework | 652d8077e6fc355538fd96b08cf2a13d421fae58 | bdfaad460e3e8edce72f0dd5168aad2cf68c839d | refs/heads/master | 2021-01-23T09:01:37.452889 | 2020-01-18T09:06:52 | 2020-01-18T09:06:52 | 39,832,985 | 95 | 39 | BSD-3-Clause | 2018-02-09T01:18:49 | 2015-07-28T12:38:14 | C++ | UTF-8 | C++ | false | false | 22,230 | hpp | #pragma once
#include <string>
#include <iostream>
#include <sstream>
#include <samchon/WeakString.hpp>
#include <samchon/IndexPair.hpp>
#include <samchon/library/Math.hpp>
namespace samchon
{
namespace library
{
/**
* @brief Utility class for string
*
* @details
* <p> StringUtil is an utility class providing lots of static methods for std::string. </p>
*
* <p> There are two methods to strength std::string to have addictional uility methods like trim and split.
* The way of first is to make std::string class inheriting from std::string.
* The second is to make StringUtil class having static methods. </p>
*
* <p> But those methods have problems. std::string class violates standard and StringUtil class violates
* principle of Object-Oriented Design. For the present, I've made the StringUtil class, but if you
* have a good opinion about the issue, please write your opinion on my github. </p>
*
* @image html cpp/subset/library_string.png
* @image latex cpp/subset/library_string.png
*
* @see library::WeakString
* @see samchon::library
* @author Jeongho Nam <http://samchon.org>
*/
class StringUtil
{
public:
/* ----------------------------------------------------------------------
SUBSTITUTE
---------------------------------------------------------------------- */
/**
* @brief Substitutes "{n}" tokens within the specified string with the respective arguments passed in.
*
* @param format The string to make substitutions in.\n
* This string can contain special tokens of the form {n}, where n is a zero based index,
* that will be replaced with the additional parameters found at that index if specified
* @param val Target value to substitute the minimum {n} tokens
* @param args Additional parameters that can be substituted in the str parameter at each {n} location,
* where n is an integer (zero based) index value into the varadics of values specified.
* @return New string with all of the {n} tokens replaced with the respective arguments specified.
*/
template <typename T, typename ... _Args>
static auto substitute(const std::string &format,
const T& val, const _Args& ... args) -> std::string
{
std::string &res = _substitute(format, val);
return StringUtil::substitute(res, args...);
};
template <typename T> static auto substitute(const std::string &format, const T& val) -> std::string
{
return _substitute(format, val);
};
/**
* @brief Substitutes "{n}" tokens within the specified sql-string with the respective arguments passed in.\n
* @warning substituteSQL creates the dynamic sql-statement.\n
* Not recommended when the dynamic sql-statement is not only for procedure.
*
* @param format The string to make substitutions in.\n
* This string can contain special tokens of the form {n}, where n is a zero based index,
* that will be replaced with the additional parameters found at that index if specified
* @param val Target value to substitute the minimum {n} tokens
* @param args Additional parameters that can be substituted in the str parameter at each {n} location,
* where n is an integer (zero based) index value into the varadics of values specified.
* @return New sql-string with all of the {n} tokens replaced with the respective arguments specified.
*/
template <typename T, typename ... _Args >
static auto substituteSQL(const std::string &format,
const T& value, const _Args& ... args) -> std::string
{
std::string &res = _substituteSQL(format, value);
return StringUtil::substituteSQL(res, args...);
};
template <typename T> static auto substituteSQL(const std::string &format, const T& value) -> std::string
{
return _substituteSQL(format, value);
};
protected:
template <typename T> static auto _substitute(const std::string &format, const T& value) -> std::string
{
std::vector<std::string> &parenthesisArray = betweens(format, { (char)'{' }, { (char)'}' });
std::vector<long> vec;
for (auto it = parenthesisArray.begin(); it != parenthesisArray.end(); it++)
if (isNumeric(*it) == true)
vec.push_back(stoi(*it));
size_t index = (size_t)Math::minimum(vec).getValue();
//replaceAll
std::string &to = toString(value);
return replaceAll(format, "{" + std::to_string(index) + "}", to);
};
template <typename T> static auto _substituteSQL(const std::string &format, const T& value) -> std::string
{
std::vector<std::string> &parenthesisArray = betweens(format, "{", "}");
std::vector<long> vec;
for (auto it = parenthesisArray.begin(); it != parenthesisArray.end(); it++)
if (isNumeric(*it) == true)
vec.push_back(stoi(*it));
size_t index = (size_t)Math::minimum(vec).getValue();
//replaceAll
std::string &to = toSQL(value);
return replaceAll(format, "{" + std::to_string(index) + "}", to);
};
/* ----------------------------------------------------------------------
SUBSTITUTE -> TO_STRING
---------------------------------------------------------------------- */
template <typename T>
static auto toString(const T &val) -> std::string
{
return std::to_string(val);
};
template<> static auto toString(const std::string &str) -> std::string
{
return str;
};
template<> static auto toString(const WeakString &str) -> std::string
{
return str.str();
};
static auto toString(const char *ptr) -> std::string
{
return ptr;
};
template <typename T>
static auto toSQL(const T &val) -> std::string
{
if (val == INT_MIN)
return "NULL";
return std::to_string(val);
};
template<> static auto toSQL(const bool &flag) -> std::string
{
return std::to_string(flag);
};
template<> static auto toSQL(const char &val) -> std::string
{
return toSQL(std::string({ val }));
};
template<> static auto toSQL(const std::string &str) -> std::string
{
return toSQL(WeakString(str));
};
template<> static auto toSQL(const WeakString &wstr) -> std::string
{
if (wstr.empty() == true)
return "NULL";
else
{
if (wstr.find("'") != std::string::npos)
return "'" + wstr.replaceAll("'", "''") + "'";
else
return "'" + wstr.str() + "'";
}
};
static auto toSQL(const char *ptr) -> std::string
{
return toSQL(std::string(ptr));
};
public:
/* ----------------------------------------------------------------------
NUMBER-FORMAT
IN MONETARY UNIT, ADD DELIMETER ','
COLOR-FORMAT
POSITIVE NUMBER IS RED,
NEGATIVE NUMBER IS BLUE
ZERO IS BLACK
---------------------------------------------------------------------- */
/**
* @brief Returns wheter the std::string represents Number or not\n
*
* @param str Target std::string to check
* @return Whether the std::string can be converted to Number or not
*/
static auto isNumeric(const std::string &str) -> bool
{
try
{
stoi(str);
//stod( replaceAll(str, ",", "") );
}
catch (const std::exception &)
{
return false;
}
catch (...)
{
return false;
}
return true;
};
/**
* @brief Number std::string to Number having ',' symbols
*
* @param str Target std::string you want to convert to Number
* @return Number from std::string
*/
static auto toNumber(const std::string &str) -> double
{
std::string &numStr = replaceAll(str, ",", "");
return stod(numStr);
};
/**
* @brief
*
* @details
* Returns a string converted from the number rounded off from specified precision with "," symbols
* ex) numberFormat(17151.339, 2) => 17,151.34
*
* @param val A number wants to convert to string
* @param precision Target precision of roundoff
* @return A string representing the number with roundoff and "," symbols
*/
static auto numberFormat(double val, int precision = 2) -> std::string
{
std::string str;
// FIRST, DO ROUND-OFF
val = round(val * pow(10, precision));
val = val / pow(10, precision);
// SEPERATE NUMBERS
bool is_negative = (val < 0);
unsigned long long natural = (unsigned long long)abs(val);
double fraction = abs(val) - (unsigned long long)abs(val);
// NATURAL NUMBER
if (natural == 0)
str = "0";
else
{
// NOT ZERO
size_t cipher_count = (size_t)log10(natural) + 1;
for (size_t i = 0; i <= cipher_count; i++)
{
size_t cipher = natural % (size_t)pow(10, i + 1);
cipher = (size_t)(cipher / pow(10, i));
if (i == cipher_count && cipher == 0)
continue;
// IS MULTIPLIER OF 3
if (i > 0 && i % 3 == 0)
str = "," + str;
// PUSH FRONT TO THE STRING
str = std::to_string(cipher) + str;
}
}
// NEGATIVE SIGN
if (is_negative == true)
str = "-" + str;
// ADD FRACTION
if (precision > 0 && fraction != 0)
{
fraction = (double)(unsigned long long)round(fraction * pow(10, precision));
size_t zeros = precision - (size_t)log10(fraction) - 1;
str += "." + std::string(zeros, '0') + std::to_string((unsigned long long)fraction);
}
return str;
};
/**
* @brief
* Returns a percentage string converted from the number rounded off from specified precision with "," symbols\n
* ex) percentFormat(11.3391, 1) => 1,133.9%
*
* @warning Do not multiply by 100 to the value representing percent
* @param val A number wants to convert to percentage string
* @param precision Target precision of roundoff
*/
static auto percentFormat(double val, int precision = 2) -> std::string
{
if (val == INT_MIN)
return "";
return numberFormat(val * 100, precision) + "%";
};
/**
* @brief
* Returns a string converted from the number rounded off from specified precision with "," symbols and color tag\n
* ex) numberFormat(17151.339, 2) => <font color='red'>17,151.34</font>
*
* @details
* Which color would be chosen
* \li Number is positive, color is RED
* \li Number is zero (0), color is BLACK
* \li Number is negative, color is BLUE
*
* @param val A number wants to convert to colored string
* @param precision Target precision of roundoff
* @return A colored string representing the number with roundoff and "," symbols
*/
static auto colorNumberFormat(double value, int precision = 2, double delimiter = 0.0) -> std::string
{
std::string color;
if (value > delimiter) color = "red";
else if (value == delimiter) color = "black";
else color = "blue";
return substitute
(
"<font color='{1}'>{2}</font>",
color,
numberFormat(value, precision)
);
};
/**
* @brief Returns a percentage string converted from the number rounded off from specified precision with "," symbols\n
* ex) percentFormat(11.3391, 1) => 1,133.9%
*
* @warning Do not multiply by 100 to the value representing percent
* @param val A number wants to convert to percentage string
* @param precision Target precision of roundoff
*/
static auto colorPercentFormat(double value, int precision = 2, double delimiter = 0.0) -> std::string
{
std::string color;
if (value > delimiter) color = "red";
else if (value == delimiter) color = "black";
else color = "blue";
return substitute
(
"<font color='{1}'>{2}</font>",
color,
percentFormat(value, precision)
);
};
/* ----------------------------------------------------------------------
TRIM -> WITH LTRIM & RTRIM
IT'S RIGHT, THE TRIM OF ORACLE
---------------------------------------------------------------------- */
/**
* @brief Removes all designated characters from the beginning and end of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the beginning and end
*/
static auto trim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).trim(delims).str();
};
/**
* @brief Removes all designated characters from the beginning of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the beginning
*/
static auto ltrim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).ltrim(delims).str();
};
/**
* @brief Removes all designated characters from the end of the specified string
*
* @param str The string should be trimmed
* @param delims Designated character(s)
* @return Updated string where designated characters was removed from the end
*/
static auto rtrim(const std::string &val, const std::vector<std::string> &delims) -> std::string
{
return WeakString(val).rtrim(delims).str();
};
static auto trim(const std::string &str) -> std::string
{
return WeakString(str).trim().str();
};
static auto ltrim(const std::string &str) -> std::string
{
return WeakString(str).ltrim().str();
};
static auto rtrim(const std::string &str) -> std::string
{
return WeakString(str).rtrim().str();
};
static auto trim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).trim(delim).str();
};
static auto ltrim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).ltrim(delim).str();
};
static auto rtrim(const std::string &str, const std::string &delim) -> std::string
{
return WeakString(str).rtrim(delim).str();
};
/* ----------------------------------------------------------------------
EXTRACTORS
---------------------------------------------------------------------- */
/**
* @brief Finds first occurence in string
*
* @details
* Finds first occurence position of each delim in the string after startIndex
* and returns the minimum position of them\n
* \n
* If startIndex is not specified, then starts from 0.\n
* If failed to find any substring, returns -1 (std::string::npos)
*
* @param str Target string to find
* @param delims The substrings of target(str) which to find
* @param startIndex Specified starting index of find. Default is 0
* @return pair\<size_t := position, string := matched substring\>
*/
static auto finds(const std::string &str,
const std::vector<std::string> &delims, size_t startIndex = 0) -> IndexPair<std::string>
{
IndexPair<WeakString> &iPair = WeakString(str).finds(delims, startIndex);
return { iPair.get_index(), iPair.getValue().str() };
};
/**
* @brief Finds last occurence in string
*
* @details
* Finds last occurence position of each delim in the string before endIndex
* and returns the maximum position of them\n
* \n
* If index is not specified, then starts str.size() - 1\n
* If failed to find any substring, returns -1 (std::string::npos)
*
* @param str Target string to find
* @param delims The substrings of target(str) which to find
* @param endIndex Specified starting index of find. Default is str.size() - 1
* @return pair\<size_t := position, string := matched substring\>
*/
static auto rfinds(const std::string &str,
const std::vector<std::string> &delims, size_t endIndex = SIZE_MAX) -> IndexPair<std::string>
{
IndexPair<WeakString> &iPair = WeakString(str).rfinds(delims, endIndex);
return { iPair.get_index(), iPair.getValue().str() };
};
/**
* @brief Generates a substring
*
* @details
* Extracts a string consisting of the character specified by startIndex and all characters up to endIndex - 1
* If endIndex is not specified, string::size() will be used instead.\n
* If endIndex is greater than startIndex, then those will be swapped
*
* @param str Target string to be applied substring
* @param startIndex Index of the first character.\n
* If startIndex is greater than endIndex, those will be swapped
* @param endIndex Index of the last character - 1.\n
If not specified, then string::size() will be used instead
* @return Extracted string by specified index(es)
*/
static auto substring(const std::string &str,
size_t startIndex, size_t endIndex = SIZE_MAX) -> std::string
{
return WeakString(str).substring(startIndex, endIndex).str();
};
/**
* @brief Generate a substring.
*
* @details
* <p> Extracts a substring consisting of the characters from specified start to end
* It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) </p>
*
* <p> ex) between("ABCD[EFGH]IJK", "[", "]") => "EFGH" </p>
*
* \li If start is not specified, extracts from begin of the string to end.
* \li If end is not specified, extracts from start to end of the string.
* \li If start and end are all omitted, returns str, itself.
*
* @param str Target string to be applied between
* @param start A string for separating substring at the front
* @param end A string for separating substring at the end
*
* @return substring by specified terms
*/
static auto between(const std::string &str,
const std::string &start = "", const std::string &end = "") -> std::string
{
return WeakString(str).between(start, end).str();
};
//TAB
/**
* @brief Adds tab(\t) character to first position of each line
*
* @param str Target str to add tabs
* @param n The size of tab to be added for each line
* @return A string added multiple tabs
*/
static auto addTab(const std::string &str, size_t n = 1) -> std::string
{
std::vector<std::string> &lines = split(str, "\n");
std::string val;
std::string tab;
size_t i;
val.reserve(val.size() + lines.size());
tab.reserve(n);
for (i = 0; i < n; i++)
tab += "\t";
for (i = 0; i < lines.size(); i++)
val.append(tab + lines[i] + ((i == lines.size() - 1) ? "" : "\n"));
return val;
};
//MULTIPLE STRINGS
/**
* @brief Generates substrings
* @details Splits a string into an array of substrings by dividing the specified delimiter
*
* @param str Target string to split
* @param delim The pattern that specifies where to split this string
* @return An array of substrings
*/
static auto split(const std::string &str, const std::string &delim) -> std::vector<std::string>
{
std::vector<WeakString> &arr = WeakString(str).split(delim);
std::vector<std::string> resArray(arr.size());
for (size_t i = 0; i < arr.size(); i++)
resArray[i] = move(arr[i].str());
return resArray;
};
/**
* @brief Generates substrings
*
* @details
* <p> Splits a string into an array of substrings dividing by specified delimeters of start and end.
* It's the array of substrings adjusted the between. </p>
*
* \li If startStr is omitted, it's same with the split by endStr not having last item
* \li If endStr is omitted, it's same with the split by startStr not having first item
* \li If startStr and endStar are all omitted, returns {str}
*
* @param str Target string to split by between
* @param start A string for separating substring at the front.
* If omitted, it's same with split(end) not having last item
* @param end A string for separating substring at the end.
* If omitted, it's same with split(start) not having first item
* @return An array of substrings
*/
static auto betweens
(
const std::string &str,
const std::string &start = "", const std::string &end = ""
) -> std::vector<std::string>
{
std::vector<WeakString> &arr = WeakString(str).betweens(start, end);
std::vector<std::string> resArray(arr.size());
for (size_t i = 0; i < arr.size(); i++)
resArray[i] = move(arr[i].str());
return resArray;
};
/* ----------------------------------------------------------------------
REPLACERS
---------------------------------------------------------------------- */
//ALPHABET-CONVERSION
/**
* @brief Returns a string that all uppercase characters are converted to lowercase.
*
* @param str Target string to convert uppercase to lowercase
* @return A string converted to lowercase
*/
static auto toLowerCase(const std::string &str) -> std::string
{
return WeakString(str).toLowerCase();
};
/**
* Returns a string all lowercase characters are converted to uppercase\n
*
* @param str Target string to convert lowercase to uppercase
* @return A string converted to uppercase
*/
static auto yoUpperCase(const std::string &str) -> std::string
{
return WeakString(str).yoUpperCase();
};
/**
* @brief Returns a string specified word is replaced
*
* @param str Target string to replace
* @param before Specific word you want to be replaced
* @param after Specific word you want to replace
* @return A string specified word is replaced
*/
static auto replaceAll
(
const std::string &str,
const std::string &before, const std::string &after
) -> std::string
{
return WeakString(str).replaceAll(before, after);
};
/**
* @brief Returns a string specified words are replaced
*
* @param str Target string to replace
* @param pairs A specific word's pairs you want to replace and to be replaced
* @return A string specified words are replaced
*/
static auto replaceAll(const std::string &str,
const std::vector<std::pair<std::string, std::string>> &pairs) -> std::string
{
return WeakString(str).replaceAll(pairs);
};
/**
* @brief Replace all HTML spaces to a literal space.
*
* @param str Target string to replace.
*/
static auto removeHTMLSpaces(const std::string &str) -> std::string
{
std::vector<std::pair<std::string, std::string>> pairs =
{
{ " ", " " },
{ "\t", " " },
{ " ", " " }
};
return replaceAll(str, pairs);
};
};
};
}; | [
"samchon@samchon.org"
] | samchon@samchon.org |
37c9f0410b42cbffd0167bf17c5198446c3dd3ac | 0d1645e912fc1477eef73245a75af85635a31bd8 | /sdk/js/include/nsIPresShell.h | 7a90912e51b8b6da1bb484e2d4f03e37b28ef101 | [
"MIT"
] | permissive | qianxj/XExplorer | a2115106560f771bc3edc084b7e986332d0e41f4 | 00e326da03ffcaa21115a2345275452607c6bab5 | refs/heads/master | 2021-09-03T13:37:39.395524 | 2018-01-09T12:06:29 | 2018-01-09T12:06:29 | 114,638,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,485 | h | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Steve Clark <buster@netscape.com>
* Dan Rosen <dr@netscape.com>
* Mihai Sucan <mihai.sucan@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****
*
* This Original Code has been modified by IBM Corporation.
* Modifications made by IBM described herein are
* Copyright (c) International Business Machines
* Corporation, 2000
*
* Modifications to Mozilla code or documentation
* identified per MPL Section 3.3
*
* Date Modified by Description of modification
* 05/03/2000 IBM Corp. Observer related defines for reflow
*/
/* a presentation of a document, part 2 */
#ifndef nsIPresShell_h___
#define nsIPresShell_h___
#include "nsTHashtable.h"
#include "nsHashKeys.h"
#include "nsISupports.h"
#include "nsQueryFrame.h"
#include "nsCoord.h"
#include "nsColor.h"
#include "nsEvent.h"
#include "nsCompatibility.h"
#include "nsFrameManagerBase.h"
#include "nsRect.h"
#include "mozFlushType.h"
#include "nsWeakReference.h"
#include <stdio.h> // for FILE definition
#include "nsChangeHint.h"
class nsIContent;
class nsIDocument;
class nsIFrame;
class nsPresContext;
class nsStyleSet;
class nsIViewManager;
class nsIView;
class nsIRenderingContext;
class nsIPageSequenceFrame;
class nsAString;
class nsCaret;
class nsFrameSelection;
class nsFrameManager;
class nsILayoutHistoryState;
class nsIReflowCallback;
class nsIDOMNode;
class nsIntRegion;
class nsIStyleSheet;
class nsCSSFrameConstructor;
class nsISelection;
template<class E> class nsCOMArray;
class nsWeakFrame;
class nsIScrollableFrame;
class gfxASurface;
class gfxContext;
class nsIDOMEvent;
class nsDisplayList;
class nsDisplayListBuilder;
class nsPIDOMWindow;
struct nsPoint;
struct nsIntPoint;
struct nsIntRect;
class nsRefreshDriver;
class nsARefreshObserver;
#ifdef ACCESSIBILITY
class nsAccessibilityService;
#endif
typedef short SelectionType;
typedef PRUint64 nsFrameState;
namespace mozilla {
namespace dom {
class Element;
} // namespace dom
namespace layers{
class LayerManager;
} // namespace layers
} // namespace mozilla
// Flags to pass to SetCapturingContent
//
// when assigning capture, ignore whether capture is allowed or not
#define CAPTURE_IGNOREALLOWED 1
// true if events should be targeted at the capturing content or its children
#define CAPTURE_RETARGETTOELEMENT 2
// true if the current capture wants drags to be prevented
#define CAPTURE_PREVENTDRAG 4
typedef struct CapturingContentInfo {
// capture should only be allowed during a mousedown event
PRPackedBool mAllowed;
PRPackedBool mRetargetToElement;
PRPackedBool mPreventDrag;
nsIContent* mContent;
} CapturingContentInfo;
#define NS_IPRESSHELL_IID \
{ 0x3a8030b5, 0x8d2c, 0x4cb3, \
{ 0xb5, 0xae, 0xb2, 0x43, 0xa9, 0x28, 0x02, 0x82 } }
// Constants for ScrollContentIntoView() function
#define NS_PRESSHELL_SCROLL_TOP 0
#define NS_PRESSHELL_SCROLL_BOTTOM 100
#define NS_PRESSHELL_SCROLL_LEFT 0
#define NS_PRESSHELL_SCROLL_RIGHT 100
#define NS_PRESSHELL_SCROLL_CENTER 50
#define NS_PRESSHELL_SCROLL_ANYWHERE -1
#define NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE -2
// debug VerifyReflow flags
#define VERIFY_REFLOW_ON 0x01
#define VERIFY_REFLOW_NOISY 0x02
#define VERIFY_REFLOW_ALL 0x04
#define VERIFY_REFLOW_DUMP_COMMANDS 0x08
#define VERIFY_REFLOW_NOISY_RC 0x10
#define VERIFY_REFLOW_REALLY_NOISY_RC 0x20
#define VERIFY_REFLOW_DURING_RESIZE_REFLOW 0x40
#undef NOISY_INTERRUPTIBLE_REFLOW
enum nsRectVisibility {
nsRectVisibility_kVisible,
nsRectVisibility_kAboveViewport,
nsRectVisibility_kBelowViewport,
nsRectVisibility_kLeftOfViewport,
nsRectVisibility_kRightOfViewport
};
/**
* Presentation shell interface. Presentation shells are the
* controlling point for managing the presentation of a document. The
* presentation shell holds a live reference to the document, the
* presentation context, the style manager, the style set and the root
* frame. <p>
*
* When this object is Release'd, it will release the document, the
* presentation context, the style manager, the style set and the root
* frame.
*/
// hack to make egcs / gcc 2.95.2 happy
class nsIPresShell_base : public nsISupports
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPRESSHELL_IID)
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIPresShell_base, NS_IPRESSHELL_IID)
class nsIPresShell : public nsIPresShell_base
{
protected:
typedef mozilla::layers::LayerManager LayerManager;
enum {
STATE_IGNORING_VIEWPORT_SCROLLING = 0x1,
STATE_USING_DISPLAYPORT = 0x2
};
public:
virtual NS_HIDDEN_(nsresult) Init(nsIDocument* aDocument,
nsPresContext* aPresContext,
nsIViewManager* aViewManager,
nsStyleSet* aStyleSet,
nsCompatibility aCompatMode) = 0;
/**
* All callers are responsible for calling |Destroy| after calling
* |EndObservingDocument|. It needs to be separate only because form
* controls incorrectly store their data in the frames rather than the
* content model and printing calls |EndObservingDocument| multiple
* times to make form controls behave nicely when printed.
*/
virtual NS_HIDDEN_(void) Destroy() = 0;
PRBool IsDestroying() { return mIsDestroying; }
// All frames owned by the shell are allocated from an arena. They
// are also recycled using free lists. Separate free lists are
// maintained for each frame type (aCode), which must always
// correspond to the same aSize value. AllocateFrame clears the
// memory that it returns.
virtual void* AllocateFrame(nsQueryFrame::FrameIID aCode, size_t aSize) = 0;
virtual void FreeFrame(nsQueryFrame::FrameIID aCode, void* aChunk) = 0;
// Objects closely related to the frame tree, but that are not
// actual frames (subclasses of nsFrame) are also allocated from the
// arena, and recycled via a separate set of per-size free lists.
// AllocateMisc does *not* clear the memory that it returns.
virtual void* AllocateMisc(size_t aSize) = 0;
virtual void FreeMisc(size_t aSize, void* aChunk) = 0;
/**
* Stack memory allocation:
*
* Callers who wish to allocate memory whose lifetime corresponds to
* the lifetime of a stack-allocated object can use this API. The
* caller must use a pair of calls to PushStackMemory and
* PopStackMemory, such that all stack object lifetimes are either
* entirely between the calls or containing both calls.
*
* Then, between the calls, the caller can call AllocateStackMemory to
* allocate memory from an arena pool that will be freed by the call
* to PopStackMemory.
*
* The allocations cannot be for more than 4044 bytes.
*/
virtual void PushStackMemory() = 0;
virtual void PopStackMemory() = 0;
virtual void* AllocateStackMemory(size_t aSize) = 0;
nsIDocument* GetDocument() const { return mDocument; }
nsPresContext* GetPresContext() const { return mPresContext; }
nsIViewManager* GetViewManager() const { return mViewManager; }
#ifdef _IMPL_NS_LAYOUT
nsStyleSet* StyleSet() const { return mStyleSet; }
nsCSSFrameConstructor* FrameConstructor() const { return mFrameConstructor; }
nsFrameManager* FrameManager() const {
return reinterpret_cast<nsFrameManager*>
(&const_cast<nsIPresShell*>(this)->mFrameManager);
}
#endif
/* Enable/disable author style level. Disabling author style disables the entire
* author level of the cascade, including the HTML preshint level.
*/
// XXX these could easily be inlined, but there is a circular #include
// problem with nsStyleSet.
NS_HIDDEN_(void) SetAuthorStyleDisabled(PRBool aDisabled);
NS_HIDDEN_(PRBool) GetAuthorStyleDisabled() const;
/*
* Called when stylesheets are added/removed/enabled/disabled to rebuild
* all style data for a given pres shell without necessarily reconstructing
* all of the frames. This will not reconstruct style synchronously; if
* you need to do that, call FlushPendingNotifications to flush out style
* reresolves.
* // XXXbz why do we have this on the interface anyway? The only consumer
* is calling AddOverrideStyleSheet/RemoveOverrideStyleSheet, and I think
* those should just handle reconstructing style data...
*/
virtual NS_HIDDEN_(void) ReconstructStyleDataExternal();
NS_HIDDEN_(void) ReconstructStyleDataInternal();
#ifdef _IMPL_NS_LAYOUT
void ReconstructStyleData() { ReconstructStyleDataInternal(); }
#else
void ReconstructStyleData() { ReconstructStyleDataExternal(); }
#endif
/** Setup all style rules required to implement preferences
* - used for background/text/link colors and link underlining
* may be extended for any prefs that are implemented via style rules
* - aForceReflow argument is used to force a full reframe to make the rules show
* (only used when the current page needs to reflect changed pref rules)
*
* - initially created for bugs 31816, 20760, 22963
*/
virtual NS_HIDDEN_(nsresult) SetPreferenceStyleRules(PRBool aForceReflow) = 0;
/**
* FrameSelection will return the Frame based selection API.
* You cannot go back and forth anymore with QI between nsIDOM sel and
* nsIFrame sel.
*/
already_AddRefed<nsFrameSelection> FrameSelection();
/**
* ConstFrameSelection returns an object which methods are safe to use for
* example in nsIFrame code.
*/
const nsFrameSelection* ConstFrameSelection() const { return mSelection; }
// Make shell be a document observer. If called after Destroy() has
// been called on the shell, this will be ignored.
virtual NS_HIDDEN_(void) BeginObservingDocument() = 0;
// Make shell stop being a document observer
virtual NS_HIDDEN_(void) EndObservingDocument() = 0;
/**
* Return whether InitialReflow() was previously called.
*/
PRBool DidInitialReflow() const { return mDidInitialReflow; }
/**
* Perform the initial reflow. Constructs the frame for the root content
* object and then reflows the frame model into the specified width and
* height.
*
* The coordinates for aWidth and aHeight must be in standard nscoords.
*
* Callers of this method must hold a reference to this shell that
* is guaranteed to survive through arbitrary script execution.
* Calling InitialReflow can execute arbitrary script.
*/
virtual NS_HIDDEN_(nsresult) InitialReflow(nscoord aWidth, nscoord aHeight) = 0;
/**
* Reflow the frame model into a new width and height. The
* coordinates for aWidth and aHeight must be in standard nscoord's.
*/
virtual NS_HIDDEN_(nsresult) ResizeReflow(nscoord aWidth, nscoord aHeight) = 0;
/**
* Reflow, and also change presshell state so as to only permit
* reflowing off calls to ResizeReflowOverride() in the future.
* ResizeReflow() calls are ignored after ResizeReflowOverride().
*/
virtual NS_HIDDEN_(nsresult) ResizeReflowOverride(nscoord aWidth, nscoord aHeight) = 0;
/**
* Returns true if ResizeReflowOverride has been called.
*/
virtual PRBool GetIsViewportOverridden() = 0;
/**
* Return true if the presshell expects layout flush.
*/
virtual PRBool IsLayoutFlushObserver() = 0;
/**
* Reflow the frame model with a reflow reason of eReflowReason_StyleChange
*/
virtual NS_HIDDEN_(void) StyleChangeReflow() = 0;
/**
* This calls through to the frame manager to get the root frame.
*/
virtual NS_HIDDEN_(nsIFrame*) GetRootFrameExternal() const;
nsIFrame* GetRootFrame() const {
#ifdef _IMPL_NS_LAYOUT
return mFrameManager.GetRootFrame();
#else
return GetRootFrameExternal();
#endif
}
/*
* Get root scroll frame from FrameManager()->GetRootFrame().
*/
nsIFrame* GetRootScrollFrame() const;
/*
* The same as GetRootScrollFrame, but returns an nsIScrollableFrame
*/
nsIScrollableFrame* GetRootScrollFrameAsScrollable() const;
/*
* The same as GetRootScrollFrame, but returns an nsIScrollableFrame.
* Can be called by code not linked into gklayout.
*/
virtual nsIScrollableFrame* GetRootScrollFrameAsScrollableExternal() const;
/*
* Gets nearest scrollable frame from current focused content or DOM
* selection if there is no focused content. The frame is scrollable with
* overflow:scroll or overflow:auto in some direction when aDirection is
* eEither. Otherwise, this returns a nearest frame that is scrollable in
* the specified direction.
*/
enum ScrollDirection { eHorizontal, eVertical, eEither };
nsIScrollableFrame* GetFrameToScrollAsScrollable(ScrollDirection aDirection);
/**
* Returns the page sequence frame associated with the frame hierarchy.
* Returns NULL if not a paginated view.
*/
virtual NS_HIDDEN_(nsIPageSequenceFrame*) GetPageSequenceFrame() const = 0;
/**
* Gets the real primary frame associated with the content object.
*
* In the case of absolutely positioned elements and floated elements,
* the real primary frame is the frame that is out of the flow and not the
* placeholder frame.
*/
virtual NS_HIDDEN_(nsIFrame*) GetRealPrimaryFrameFor(nsIContent* aContent) const = 0;
/**
* Gets the placeholder frame associated with the specified frame. This is
* a helper frame that forwards the request to the frame manager.
*/
virtual NS_HIDDEN_(nsIFrame*) GetPlaceholderFrameFor(nsIFrame* aFrame) const = 0;
/**
* Tell the pres shell that a frame needs to be marked dirty and needs
* Reflow. It's OK if this is an ancestor of the frame needing reflow as
* long as the ancestor chain between them doesn't cross a reflow root. The
* bit to add should be either NS_FRAME_IS_DIRTY or
* NS_FRAME_HAS_DIRTY_CHILDREN (but not both!).
*/
enum IntrinsicDirty {
// XXXldb eResize should be renamed
eResize, // don't mark any intrinsic widths dirty
eTreeChange, // mark intrinsic widths dirty on aFrame and its ancestors
eStyleChange // Do eTreeChange, plus all of aFrame's descendants
};
virtual NS_HIDDEN_(void) FrameNeedsReflow(nsIFrame *aFrame,
IntrinsicDirty aIntrinsicDirty,
nsFrameState aBitToAdd) = 0;
/**
* Tell the presshell that the given frame's reflow was interrupted. This
* will mark as having dirty children a path from the given frame (inclusive)
* to the nearest ancestor with a dirty subtree, or to the reflow root
* currently being reflowed if no such ancestor exists (inclusive). This is
* to be done immediately after reflow of the current reflow root completes.
* This method must only be called during reflow, and the frame it's being
* called on must be in the process of being reflowed when it's called. This
* method doesn't mark any intrinsic widths dirty and doesn't add any bits
* other than NS_FRAME_HAS_DIRTY_CHILDREN.
*/
virtual NS_HIDDEN_(void) FrameNeedsToContinueReflow(nsIFrame *aFrame) = 0;
virtual NS_HIDDEN_(void) CancelAllPendingReflows() = 0;
/**
* Recreates the frames for a node
*/
virtual NS_HIDDEN_(nsresult) RecreateFramesFor(nsIContent* aContent) = 0;
void PostRecreateFramesFor(mozilla::dom::Element* aElement);
void RestyleForAnimation(mozilla::dom::Element* aElement,
nsRestyleHint aHint);
/**
* Determine if it is safe to flush all pending notifications
* @param aIsSafeToFlush PR_TRUE if it is safe, PR_FALSE otherwise.
*
*/
virtual NS_HIDDEN_(PRBool) IsSafeToFlush() const = 0;
/**
* Flush pending notifications of the type specified. This method
* will not affect the content model; it'll just affect style and
* frames. Callers that actually want up-to-date presentation (other
* than the document itself) should probably be calling
* nsIDocument::FlushPendingNotifications.
*
* @param aType the type of notifications to flush
*/
virtual NS_HIDDEN_(void) FlushPendingNotifications(mozFlushType aType) = 0;
/**
* Callbacks will be called even if reflow itself fails for
* some reason.
*/
virtual NS_HIDDEN_(nsresult) PostReflowCallback(nsIReflowCallback* aCallback) = 0;
virtual NS_HIDDEN_(void) CancelReflowCallback(nsIReflowCallback* aCallback) = 0;
virtual NS_HIDDEN_(void) ClearFrameRefs(nsIFrame* aFrame) = 0;
/**
* Get a reference rendering context. This is a context that should not
* be rendered to, but is suitable for measuring text and performing
* other non-rendering operations.
*/
virtual already_AddRefed<nsIRenderingContext> GetReferenceRenderingContext() = 0;
/**
* Informs the pres shell that the document is now at the anchor with
* the given name. If |aScroll| is true, scrolls the view of the
* document so that the anchor with the specified name is displayed at
* the top of the window. If |aAnchorName| is empty, then this informs
* the pres shell that there is no current target, and |aScroll| must
* be false.
*/
virtual NS_HIDDEN_(nsresult) GoToAnchor(const nsAString& aAnchorName, PRBool aScroll) = 0;
/**
* Tells the presshell to scroll again to the last anchor scrolled to by
* GoToAnchor, if any. This scroll only happens if the scroll
* position has not changed since the last GoToAnchor. This is called
* by nsDocumentViewer::LoadComplete. This clears the last anchor
* scrolled to by GoToAnchor (we don't want to keep it alive if it's
* removed from the DOM), so don't call this more than once.
*/
virtual NS_HIDDEN_(nsresult) ScrollToAnchor() = 0;
/**
* Scrolls the view of the document so that the primary frame of the content
* is displayed in the window. Layout is flushed before scrolling.
*
* @param aContent The content object of which primary frame should be
* scrolled into view.
* @param aVPercent How to align the frame vertically. A value of 0
* (NS_PRESSHELL_SCROLL_TOP) means the frame's upper edge is
* aligned with the top edge of the visible area. A value of
* 100 (NS_PRESSHELL_SCROLL_BOTTOM) means the frame's bottom
* edge is aligned with the bottom edge of the visible area.
* For values in between, the point "aVPercent" down the frame
* is placed at the point "aVPercent" down the visible area. A
* value of 50 (NS_PRESSHELL_SCROLL_CENTER) centers the frame
* vertically. A value of NS_PRESSHELL_SCROLL_ANYWHERE means move
* the frame the minimum amount necessary in order for the entire
* frame to be visible vertically (if possible)
* @param aHPercent How to align the frame horizontally. A value of 0
* (NS_PRESSHELL_SCROLL_LEFT) means the frame's left edge is
* aligned with the left edge of the visible area. A value of
* 100 (NS_PRESSHELL_SCROLL_RIGHT) means the frame's right
* edge is aligned with the right edge of the visible area.
* For values in between, the point "aVPercent" across the frame
* is placed at the point "aVPercent" across the visible area.
* A value of 50 (NS_PRESSHELL_SCROLL_CENTER) centers the frame
* horizontally . A value of NS_PRESSHELL_SCROLL_ANYWHERE means move
* the frame the minimum amount necessary in order for the entire
* frame to be visible horizontally (if possible)
* @param aFlags If SCROLL_FIRST_ANCESTOR_ONLY is set, only the nearest
* scrollable ancestor is scrolled, otherwise all
* scrollable ancestors may be scrolled if necessary.
* If SCROLL_OVERFLOW_HIDDEN is set then we may scroll in a
* direction even if overflow:hidden is specified in that
* direction; otherwise we will not scroll in that direction
* when overflow:hidden is set for that direction.
* If SCROLL_NO_PARENT_FRAMES is set then we only scroll
* nodes in this document, not in any parent documents which
* contain this document in a iframe or the like.
*/
virtual NS_HIDDEN_(nsresult) ScrollContentIntoView(nsIContent* aContent,
PRIntn aVPercent,
PRIntn aHPercent,
PRUint32 aFlags) = 0;
enum {
SCROLL_FIRST_ANCESTOR_ONLY = 0x01,
SCROLL_OVERFLOW_HIDDEN = 0x02,
SCROLL_NO_PARENT_FRAMES = 0x04
};
/**
* Scrolls the view of the document so that the given area of a frame
* is visible, if possible. Layout is not flushed before scrolling.
*
* @param aRect relative to aFrame
* @param aVPercent see ScrollContentIntoView
* @param aHPercent see ScrollContentIntoView
* @param aFlags if SCROLL_FIRST_ANCESTOR_ONLY is set, only the
* nearest scrollable ancestor is scrolled, otherwise all
* scrollable ancestors may be scrolled if necessary
* if SCROLL_OVERFLOW_HIDDEN is set then we may scroll in a direction
* even if overflow:hidden is specified in that direction; otherwise
* we will not scroll in that direction when overflow:hidden is
* set for that direction
* If SCROLL_NO_PARENT_FRAMES is set then we only scroll
* nodes in this document, not in any parent documents which
* contain this document in a iframe or the like.
* @return true if any scrolling happened, false if no scrolling happened
*/
virtual PRBool ScrollFrameRectIntoView(nsIFrame* aFrame,
const nsRect& aRect,
PRIntn aVPercent,
PRIntn aHPercent,
PRUint32 aFlags) = 0;
/**
* Determine if a rectangle specified in the frame's coordinate system
* intersects the viewport "enough" to be considered visible.
* @param aFrame frame that aRect coordinates are specified relative to
* @param aRect rectangle in twips to test for visibility
* @param aMinTwips is the minimum distance in from the edge of the viewport
* that an object must be to be counted visible
* @return nsRectVisibility_kVisible if the rect is visible
* nsRectVisibility_kAboveViewport
* nsRectVisibility_kBelowViewport
* nsRectVisibility_kLeftOfViewport
* nsRectVisibility_kRightOfViewport rectangle is outside the viewport
* in the specified direction
*/
virtual nsRectVisibility GetRectVisibility(nsIFrame *aFrame,
const nsRect &aRect,
nscoord aMinTwips) const = 0;
/**
* Suppress notification of the frame manager that frames are
* being destroyed.
*/
virtual NS_HIDDEN_(void) SetIgnoreFrameDestruction(PRBool aIgnore) = 0;
/**
* Notification sent by a frame informing the pres shell that it is about to
* be destroyed.
* This allows any outstanding references to the frame to be cleaned up
*/
virtual NS_HIDDEN_(void) NotifyDestroyingFrame(nsIFrame* aFrame) = 0;
/**
* Get link location.
*/
virtual NS_HIDDEN_(nsresult) GetLinkLocation(nsIDOMNode* aNode, nsAString& aLocation) const = 0;
/**
* Get the caret, if it exists. AddRefs it.
*/
virtual NS_HIDDEN_(already_AddRefed<nsCaret>) GetCaret() const = 0;
/**
* Invalidate the caret's current position if it's outside of its frame's
* boundaries. This function is useful if you're batching selection
* notifications and might remove the caret's frame out from under it.
*/
virtual NS_HIDDEN_(void) MaybeInvalidateCaretPosition() = 0;
/**
* Set the current caret to a new caret. To undo this, call RestoreCaret.
*/
virtual void SetCaret(nsCaret *aNewCaret) = 0;
/**
* Restore the caret to the original caret that this pres shell was created
* with.
*/
virtual void RestoreCaret() = 0;
/**
* Should the images have borders etc. Actual visual effects are determined
* by the frames. Visual effects may not effect layout, only display.
* Takes effect on next repaint, does not force a repaint itself.
*
* @param aInEnable if PR_TRUE, visual selection effects are enabled
* if PR_FALSE visual selection effects are disabled
*/
NS_IMETHOD SetSelectionFlags(PRInt16 aInEnable) = 0;
/**
* Gets the current state of non text selection effects
* @return current state of non text selection,
* as set by SetDisplayNonTextSelection
*/
PRInt16 GetSelectionFlags() const { return mSelectionFlags; }
virtual nsISelection* GetCurrentSelection(SelectionType aType) = 0;
/**
* Interface to dispatch events via the presshell
* @note The caller must have a strong reference to the PresShell.
*/
virtual NS_HIDDEN_(nsresult) HandleEventWithTarget(nsEvent* aEvent,
nsIFrame* aFrame,
nsIContent* aContent,
nsEventStatus* aStatus) = 0;
/**
* Dispatch event to content only (NOT full processing)
* @note The caller must have a strong reference to the PresShell.
*/
virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
nsEvent* aEvent,
nsEventStatus* aStatus) = 0;
/**
* Dispatch event to content only (NOT full processing)
* @note The caller must have a strong reference to the PresShell.
*/
virtual NS_HIDDEN_(nsresult) HandleDOMEventWithTarget(nsIContent* aTargetContent,
nsIDOMEvent* aEvent,
nsEventStatus* aStatus) = 0;
/**
* Gets the current target event frame from the PresShell
*/
virtual NS_HIDDEN_(nsIFrame*) GetEventTargetFrame() = 0;
/**
* Gets the current target event frame from the PresShell
*/
virtual NS_HIDDEN_(already_AddRefed<nsIContent>) GetEventTargetContent(nsEvent* aEvent) = 0;
/**
* Get and set the history state for the current document
*/
virtual NS_HIDDEN_(nsresult) CaptureHistoryState(nsILayoutHistoryState** aLayoutHistoryState, PRBool aLeavingPage = PR_FALSE) = 0;
/**
* Determine if reflow is currently locked
* returns PR_TRUE if reflow is locked, PR_FALSE otherwise
*/
PRBool IsReflowLocked() const { return mIsReflowing; }
/**
* Called to find out if painting is suppressed for this presshell. If it is suppressd,
* we don't allow the painting of any layer but the background, and we don't
* recur into our children.
*/
PRBool IsPaintingSuppressed() const { return mPaintingSuppressed; }
/**
* Unsuppress painting.
*/
virtual NS_HIDDEN_(void) UnsuppressPainting() = 0;
/**
* Called to disable nsITheme support in a specific presshell.
*/
void DisableThemeSupport()
{
// Doesn't have to be dynamic. Just set the bool.
mIsThemeSupportDisabled = PR_TRUE;
}
/**
* Indicates whether theme support is enabled.
*/
PRBool IsThemeSupportEnabled() const { return !mIsThemeSupportDisabled; }
/**
* Get the set of agent style sheets for this presentation
*/
virtual nsresult GetAgentStyleSheets(nsCOMArray<nsIStyleSheet>& aSheets) = 0;
/**
* Replace the set of agent style sheets
*/
virtual nsresult SetAgentStyleSheets(const nsCOMArray<nsIStyleSheet>& aSheets) = 0;
/**
* Add an override style sheet for this presentation
*/
virtual nsresult AddOverrideStyleSheet(nsIStyleSheet *aSheet) = 0;
/**
* Remove an override style sheet
*/
virtual nsresult RemoveOverrideStyleSheet(nsIStyleSheet *aSheet) = 0;
/**
* Reconstruct frames for all elements in the document
*/
virtual nsresult ReconstructFrames() = 0;
/**
* Given aFrame, the root frame of a stacking context, find its descendant
* frame under the point aPt that receives a mouse event at that location,
* or nsnull if there is no such frame.
* @param aPt the point, relative to the frame origin
*/
virtual nsIFrame* GetFrameForPoint(nsIFrame* aFrame, nsPoint aPt) = 0;
/**
* See if reflow verification is enabled. To enable reflow verification add
* "verifyreflow:1" to your NSPR_LOG_MODULES environment variable
* (any non-zero debug level will work). Or, call SetVerifyReflowEnable
* with PR_TRUE.
*/
static PRBool GetVerifyReflowEnable();
/**
* Set the verify-reflow enable flag.
*/
static void SetVerifyReflowEnable(PRBool aEnabled);
virtual nsIFrame* GetAbsoluteContainingBlock(nsIFrame* aFrame);
#ifdef MOZ_REFLOW_PERF
virtual NS_HIDDEN_(void) DumpReflows() = 0;
virtual NS_HIDDEN_(void) CountReflows(const char * aName, nsIFrame * aFrame) = 0;
virtual NS_HIDDEN_(void) PaintCount(const char * aName,
nsIRenderingContext* aRenderingContext,
nsPresContext * aPresContext,
nsIFrame * aFrame,
PRUint32 aColor) = 0;
virtual NS_HIDDEN_(void) SetPaintFrameCount(PRBool aOn) = 0;
virtual PRBool IsPaintingFrameCounts() = 0;
#endif
#ifdef DEBUG
// Debugging hooks
virtual void ListStyleContexts(nsIFrame *aRootFrame, FILE *out,
PRInt32 aIndent = 0) = 0;
virtual void ListStyleSheets(FILE *out, PRInt32 aIndent = 0) = 0;
virtual void VerifyStyleTree() = 0;
#endif
static PRBool gIsAccessibilityActive;
static PRBool IsAccessibilityActive() { return gIsAccessibilityActive; }
#ifdef ACCESSIBILITY
/**
* Return accessibility service if accessibility is active.
*/
static nsAccessibilityService* AccService();
#endif
/**
* Stop all active elements (plugins and the caret) in this presentation and
* in the presentations of subdocuments. Resets painting to a suppressed state.
* XXX this should include image animations
*/
virtual void Freeze() = 0;
PRBool IsFrozen() { return mFrozen; }
/**
* Restarts active elements (plugins) in this presentation and in the
* presentations of subdocuments, then do a full invalidate of the content area.
*/
virtual void Thaw() = 0;
virtual void FireOrClearDelayedEvents(PRBool aFireEvents) = 0;
/**
* When this shell is disconnected from its containing docshell, we
* lose our container pointer. However, we'd still like to be able to target
* user events at the docshell's parent. This pointer allows us to do that.
* It should not be used for any other purpose.
*/
void SetForwardingContainer(nsWeakPtr aContainer)
{
mForwardingContainer = aContainer;
}
/**
* Render the document into an arbitrary gfxContext
* Designed for getting a picture of a document or a piece of a document
* Note that callers will generally want to call FlushPendingNotifications
* to get an up-to-date view of the document
* @param aRect is the region to capture into the offscreen buffer, in the
* root frame's coordinate system (if aIgnoreViewportScrolling is false)
* or in the root scrolled frame's coordinate system
* (if aIgnoreViewportScrolling is true). The coordinates are in appunits.
* @param aFlags see below;
* set RENDER_IS_UNTRUSTED if the contents may be passed to malicious
* agents. E.g. we might choose not to paint the contents of sensitive widgets
* such as the file name in a file upload widget, and we might choose not
* to paint themes.
* set RENDER_IGNORE_VIEWPORT_SCROLLING to ignore
* clipping/scrolling/scrollbar painting due to scrolling in the viewport
* set RENDER_CARET to draw the caret if one would be visible
* (by default the caret is never drawn)
* set RENDER_USE_LAYER_MANAGER to force rendering to go through
* the layer manager for the window. This may be unexpectedly slow
* (if the layer manager must read back data from the GPU) or low-quality
* (if the layer manager reads back pixel data and scales it
* instead of rendering using the appropriate scaling). It may also
* slow everything down if the area rendered does not correspond to the
* normal visible area of the window.
* set RENDER_ASYNC_DECODE_IMAGES to avoid having images synchronously
* decoded during rendering.
* (by default images decode synchronously with RenderDocument)
* set RENDER_DOCUMENT_RELATIVE to interpret |aRect| relative to the
* document instead of the CSS viewport
* @param aBackgroundColor a background color to render onto
* @param aRenderedContext the gfxContext to render to. We render so that
* one CSS pixel in the source document is rendered to one unit in the current
* transform.
*/
enum {
RENDER_IS_UNTRUSTED = 0x01,
RENDER_IGNORE_VIEWPORT_SCROLLING = 0x02,
RENDER_CARET = 0x04,
RENDER_USE_WIDGET_LAYERS = 0x08,
RENDER_ASYNC_DECODE_IMAGES = 0x10,
RENDER_DOCUMENT_RELATIVE = 0x20
};
virtual NS_HIDDEN_(nsresult) RenderDocument(const nsRect& aRect, PRUint32 aFlags,
nscolor aBackgroundColor,
gfxContext* aRenderedContext) = 0;
/**
* Renders a node aNode to a surface and returns it. The aRegion may be used
* to clip the rendering. This region is measured in CSS pixels from the
* edge of the presshell area. The aPoint, aScreenRect and aSurface
* arguments function in a similar manner as RenderSelection.
*/
virtual already_AddRefed<gfxASurface> RenderNode(nsIDOMNode* aNode,
nsIntRegion* aRegion,
nsIntPoint& aPoint,
nsIntRect* aScreenRect) = 0;
/**
* Renders a selection to a surface and returns it. This method is primarily
* intended to create the drag feedback when dragging a selection.
*
* aScreenRect will be filled in with the bounding rectangle of the
* selection area on screen.
*
* If the area of the selection is large, the image will be scaled down.
* The argument aPoint is used in this case as a reference point when
* determining the new screen rectangle after scaling. Typically, this
* will be the mouse position, so that the screen rectangle is positioned
* such that the mouse is over the same point in the scaled image as in
* the original. When scaling does not occur, the mouse point isn't used
* as the position can be determined from the displayed frames.
*/
virtual already_AddRefed<gfxASurface> RenderSelection(nsISelection* aSelection,
nsIntPoint& aPoint,
nsIntRect* aScreenRect) = 0;
void AddWeakFrameInternal(nsWeakFrame* aWeakFrame);
virtual void AddWeakFrameExternal(nsWeakFrame* aWeakFrame);
void AddWeakFrame(nsWeakFrame* aWeakFrame)
{
#ifdef _IMPL_NS_LAYOUT
AddWeakFrameInternal(aWeakFrame);
#else
AddWeakFrameExternal(aWeakFrame);
#endif
}
void RemoveWeakFrameInternal(nsWeakFrame* aWeakFrame);
virtual void RemoveWeakFrameExternal(nsWeakFrame* aWeakFrame);
void RemoveWeakFrame(nsWeakFrame* aWeakFrame)
{
#ifdef _IMPL_NS_LAYOUT
RemoveWeakFrameInternal(aWeakFrame);
#else
RemoveWeakFrameExternal(aWeakFrame);
#endif
}
#ifdef NS_DEBUG
nsIFrame* GetDrawEventTargetFrame() { return mDrawEventTargetFrame; }
#endif
/**
* Stop or restart non synthetic test mouse event handling on *all*
* presShells.
*
* @param aDisable If true, disable all non synthetic test mouse
* events on all presShells. Otherwise, enable them.
*/
virtual NS_HIDDEN_(void) DisableNonTestMouseEvents(PRBool aDisable) = 0;
/**
* Record the background color of the most recently drawn canvas. This color
* is composited on top of the user's default background color and then used
* to draw the background color of the canvas. See PresShell::Paint,
* PresShell::PaintDefaultBackground, and nsDocShell::SetupNewViewer;
* bug 488242, bug 476557 and other bugs mentioned there.
*/
void SetCanvasBackground(nscolor aColor) { mCanvasBackgroundColor = aColor; }
nscolor GetCanvasBackground() { return mCanvasBackgroundColor; }
/**
* Use the current frame tree (if it exists) to update the background
* color of the most recently drawn canvas.
*/
virtual void UpdateCanvasBackground() = 0;
/**
* Add a solid color item to the bottom of aList with frame aFrame and bounds
* aBounds. Checks first if this needs to be done by checking if aFrame is a
* canvas frame (if the FORCE_DRAW flag is passed then this check is skipped).
* aBackstopColor is composed behind the background color of the canvas, it is
* transparent by default. The ROOT_CONTENT_DOC_BG flag indicates that this is
* the background for the root content document.
*/
enum {
FORCE_DRAW = 0x01,
ROOT_CONTENT_DOC_BG = 0x02
};
virtual nsresult AddCanvasBackgroundColorItem(nsDisplayListBuilder& aBuilder,
nsDisplayList& aList,
nsIFrame* aFrame,
const nsRect& aBounds,
nscolor aBackstopColor = NS_RGBA(0,0,0,0),
PRUint32 aFlags = 0) = 0;
/**
* Add a solid color item to the bottom of aList with frame aFrame and
* bounds aBounds representing the dark grey background behind the page of a
* print preview presentation.
*/
virtual nsresult AddPrintPreviewBackgroundItem(nsDisplayListBuilder& aBuilder,
nsDisplayList& aList,
nsIFrame* aFrame,
const nsRect& aBounds) = 0;
/**
* Computes the backstop color for the view: transparent if in a transparent
* widget, otherwise the PresContext default background color. This color is
* only visible if the contents of the view as a whole are translucent.
*/
virtual nscolor ComputeBackstopColor(nsIView* aDisplayRoot) = 0;
void ObserveNativeAnonMutationsForPrint(PRBool aObserve)
{
mObservesMutationsForPrint = aObserve;
}
PRBool ObservesNativeAnonMutationsForPrint()
{
return mObservesMutationsForPrint;
}
virtual nsresult SetIsActive(PRBool aIsActive) = 0;
PRBool IsActive()
{
return mIsActive;
}
// mouse capturing
static CapturingContentInfo gCaptureInfo;
/**
* When capturing content is set, it traps all mouse events and retargets
* them at this content node. If capturing is not allowed
* (gCaptureInfo.mAllowed is false), then capturing is not set. However, if
* the CAPTURE_IGNOREALLOWED flag is set, the allowed state is ignored and
* capturing is set regardless. To disable capture, pass null for the value
* of aContent.
*
* If CAPTURE_RETARGETTOELEMENT is set, all mouse events are targeted at
* aContent only. Otherwise, mouse events are targeted at aContent or its
* descendants. That is, descendants of aContent receive mouse events as
* they normally would, but mouse events outside of aContent are retargeted
* to aContent.
*
* If CAPTURE_PREVENTDRAG is set then drags are prevented from starting while
* this capture is active.
*/
static void SetCapturingContent(nsIContent* aContent, PRUint8 aFlags);
/**
* Return the active content currently capturing the mouse if any.
*/
static nsIContent* GetCapturingContent()
{
return gCaptureInfo.mContent;
}
/**
* Allow or disallow mouse capturing.
*/
static void AllowMouseCapture(PRBool aAllowed)
{
gCaptureInfo.mAllowed = aAllowed;
}
/**
* Returns true if there is an active mouse capture that wants to prevent
* drags.
*/
static PRBool IsMouseCapturePreventingDrag()
{
return gCaptureInfo.mPreventDrag && gCaptureInfo.mContent;
}
/**
* Keep track of how many times this presshell has been rendered to
* a window.
*/
PRUint64 GetPaintCount() { return mPaintCount; }
void IncrementPaintCount() { ++mPaintCount; }
/**
* Get the root DOM window of this presShell.
*/
virtual already_AddRefed<nsPIDOMWindow> GetRootWindow() = 0;
/**
* Get the layer manager for the widget of the root view, if it has
* one.
*/
virtual LayerManager* GetLayerManager() = 0;
/**
* Track whether we're ignoring viewport scrolling for the purposes
* of painting. If we are ignoring, then layers aren't clipped to
* the CSS viewport and scrollbars aren't drawn.
*/
virtual void SetIgnoreViewportScrolling(PRBool aIgnore) = 0;
PRBool IgnoringViewportScrolling() const
{ return mRenderFlags & STATE_IGNORING_VIEWPORT_SCROLLING; }
/**
* Set a "resolution" for the document, which if not 1.0 will
* allocate more or fewer pixels for rescalable content by a factor
* of |resolution| in both dimensions. Return NS_OK iff the
* resolution bounds are sane, and the resolution of this was
* actually updated.
*
* The resolution defaults to 1.0.
*/
virtual nsresult SetResolution(float aXResolution, float aYResolution) = 0;
float GetXResolution() { return mXResolution; }
float GetYResolution() { return mYResolution; }
/**
* Dispatch a mouse move event based on the most recent mouse position if
* this PresShell is visible. This is used when the contents of the page
* moved (aFromScroll is false) or scrolled (aFromScroll is true).
*/
virtual void SynthesizeMouseMove(PRBool aFromScroll) = 0;
/**
* Refresh observer management.
*/
protected:
virtual PRBool AddRefreshObserverExternal(nsARefreshObserver* aObserver,
mozFlushType aFlushType);
PRBool AddRefreshObserverInternal(nsARefreshObserver* aObserver,
mozFlushType aFlushType);
virtual PRBool RemoveRefreshObserverExternal(nsARefreshObserver* aObserver,
mozFlushType aFlushType);
PRBool RemoveRefreshObserverInternal(nsARefreshObserver* aObserver,
mozFlushType aFlushType);
public:
PRBool AddRefreshObserver(nsARefreshObserver* aObserver,
mozFlushType aFlushType) {
#ifdef _IMPL_NS_LAYOUT
return AddRefreshObserverInternal(aObserver, aFlushType);
#else
return AddRefreshObserverExternal(aObserver, aFlushType);
#endif
}
PRBool RemoveRefreshObserver(nsARefreshObserver* aObserver,
mozFlushType aFlushType) {
#ifdef _IMPL_NS_LAYOUT
return RemoveRefreshObserverInternal(aObserver, aFlushType);
#else
return RemoveRefreshObserverExternal(aObserver, aFlushType);
#endif
}
/**
* Initialize and shut down static variables.
*/
static void InitializeStatics();
static void ReleaseStatics();
protected:
friend class nsRefreshDriver;
// IMPORTANT: The ownership implicit in the following member variables
// has been explicitly checked. If you add any members to this class,
// please make the ownership explicit (pinkerton, scc).
// these are the same Document and PresContext owned by the DocViewer.
// we must share ownership.
nsIDocument* mDocument; // [STRONG]
nsPresContext* mPresContext; // [STRONG]
nsStyleSet* mStyleSet; // [OWNS]
nsCSSFrameConstructor* mFrameConstructor; // [OWNS]
nsIViewManager* mViewManager; // [WEAK] docViewer owns it so I don't have to
nsFrameSelection* mSelection;
nsFrameManagerBase mFrameManager; // [OWNS]
nsWeakPtr mForwardingContainer;
#ifdef NS_DEBUG
nsIFrame* mDrawEventTargetFrame;
#endif
// Count of the number of times this presshell has been painted to
// a window
PRUint64 mPaintCount;
PRInt16 mSelectionFlags;
PRPackedBool mStylesHaveChanged;
PRPackedBool mDidInitialReflow;
PRPackedBool mIsDestroying;
PRPackedBool mIsReflowing;
PRPackedBool mPaintingSuppressed; // For all documents we initially lock down painting.
PRPackedBool mIsThemeSupportDisabled; // Whether or not form controls should use nsITheme in this shell.
PRPackedBool mIsActive;
PRPackedBool mFrozen;
PRPackedBool mObservesMutationsForPrint;
PRPackedBool mReflowScheduled; // If true, we have a reflow
// scheduled. Guaranteed to be
// false if mReflowContinueTimer
// is non-null.
PRPackedBool mSuppressInterruptibleReflows;
// A list of weak frames. This is a pointer to the last item in the list.
nsWeakFrame* mWeakFrames;
// Most recent canvas background color.
nscolor mCanvasBackgroundColor;
// Flags controlling how our document is rendered. These persist
// between paints and so are tied with retained layer pixels.
// PresShell flushes retained layers when the rendering state
// changes in a way that prevents us from being able to (usefully)
// re-use old pixels.
PRUint32 mRenderFlags;
// Used to force allocation and rendering of proportionally more or
// less pixels in the given dimension.
float mXResolution;
float mYResolution;
// Live pres shells, for memory and other tracking
typedef nsPtrHashKey<nsIPresShell> PresShellPtrKey;
static nsTHashtable<PresShellPtrKey> *sLiveShells;
static nsIContent* gKeyDownTarget;
};
/**
* Create a new empty presentation shell. Upon success, call Init
* before attempting to use the shell.
*/
nsresult
NS_NewPresShell(nsIPresShell** aInstancePtrResult);
#endif /* nsIPresShell_h___ */
| [
"qianxj15@sina.com"
] | qianxj15@sina.com |
9de019030097815bd1301f49917aed6cc20a7fe3 | 58a0ba5ee99ec7a0bba36748ba96a557eb798023 | /Olympiad Solutions/URI/2103.cpp | c14288ba9f542098178a97e56588f054ce382b66 | [
"MIT"
] | permissive | adityanjr/code-DS-ALGO | 5bdd503fb5f70d459c8e9b8e58690f9da159dd53 | 1c104c33d2f56fe671d586b702528a559925f875 | refs/heads/master | 2022-10-22T21:22:09.640237 | 2022-10-18T15:38:46 | 2022-10-18T15:38:46 | 217,567,198 | 40 | 54 | MIT | 2022-10-18T15:38:47 | 2019-10-25T15:50:28 | C++ | UTF-8 | C++ | false | false | 1,227 | cpp | // Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/2103
#include <cstdio>
#include <vector>
#define MAXN 10001
#define MODULO 1300031
using namespace std;
typedef pair<int,int> ii;
vector<ii> grafo[MAXN];
int processado_filhos[MAXN],processado_contar[MAXN],filhos[MAXN],resp,n,TC;
void dfs_filhos(int x){
processado_filhos[x] = 1;
filhos[x] = 1;
for(int i=0;i<grafo[x].size();i++){
int v = grafo[x][i].first;
if(!processado_filhos[v]){
dfs_filhos(v);
filhos[x] += filhos[v];
}
}
}
void dfs_contar(int x){
processado_contar[x] = 1;
for(int i=0;i<grafo[x].size();i++){
int v = grafo[x][i].first, peso = grafo[x][i].second;
if(!processado_contar[v]){
resp += ((n - filhos[v])*(filhos[v]) % MODULO) * peso;
resp %= MODULO;
dfs_contar(v);
}
}
}
int main(){
scanf("%d",&TC);
while(TC--){
scanf("%d",&n);
for(int i=1;i<=n;i++){
grafo[i].clear();
processado_filhos[i] = 0;
processado_contar[i] = 0;
}
resp = 0;
for(int i=1;i<n;i++){
int u,v,peso;
scanf("%d %d %d",&u,&v,&peso);
grafo[u].push_back(make_pair(v,peso));
grafo[v].push_back(make_pair(u,peso));
}
dfs_filhos(1);
dfs_contar(1);
printf("%d\n",resp);
}
return 0;
}
| [
"samant04aditya@gmail.com"
] | samant04aditya@gmail.com |
53b789a022a759f23f56cdcad97f91dd85f9a31c | 204c5937cdea475f5c3dafde6d770a74ae9b8919 | /ACM contest/2015多校/4/06.cpp | 6cef04d8354d93369ec41e5f172a789ab05b8914 | [] | no_license | mlz000/Algorithms | ad2c35e4441bcbdad61203489888b83627024b7e | 495eb701d4ec6b317816786ad5b38681fbea1001 | refs/heads/master | 2023-01-04T03:50:02.673937 | 2023-01-02T22:46:20 | 2023-01-02T22:46:20 | 101,135,823 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | #include <bits/stdc++.h>//construction
using namespace std;
#define pb push_back
typedef long long LL;
const int N = 30;
int a[N][N];
int main() {
int T;
LL k;
scanf("%d", &T);
while (T--) {
memset(a, 0, sizeof(a));
puts("28 21");
for (int i = 1; i <= 8; ++i)
for (int j = 1; j <= 8; ++j)
a[i][j] = 1;
for (int i = 9; i <= 27; ++i) a[i][i + 1] = 1;
scanf("%I64d", &k);
for (int i = 1; i <= 20; ++i, k /= 8)
for (int j = 1; j <= k % 8; ++j)
a[j][8 + i] = 1;
for (int i = 1; i <= 28; ++i) {
for (int j = 1; j <= 28; ++j) printf("%d", a[i][j]);
puts("");
}
}
return 0;
}
| [
"njumlz@gmail.com"
] | njumlz@gmail.com |
cfb7b53d63c4935bda131d45ea7602c930d8c311 | ccaf43320529059e43365b518fbfe7fa56a2a272 | /이동하기.cpp | 0d241b1b560da540ef35f01dd07ef211321189fa | [] | no_license | minsoonss/BOJ-Algospot | c02aeacfb1fa02909a3fb9a4c8ad1bc109325565 | bc3ead24d06e5632f5598b4772451875f026d4c5 | refs/heads/master | 2020-12-03T15:40:59.262840 | 2016-08-26T07:16:26 | 2016-08-26T07:16:26 | 66,530,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int d[1001][1001];
int main(){
int n,m,i,j;
cin >> n >> m;
for(i = 1; i <= n; i++){
for(j = 1; j <= m; j++){
cin >> d[i][j];
if(i == 0 && j > 0)d[i][j] += d[i][j-1];
else if(j == 0 && i > 0)d[i][j] += d[i-1][j];
else{
d[i][j]+=max(d[i-1][j-1],max(d[i-1][j],d[i][j-1]));
}
}
}
cout << d[n][m];
} | [
"wp024302@gmail.com"
] | wp024302@gmail.com |
e55e88103e29a45cb635acc3f4dfe1d4f31289aa | 55d51e429d2291e43a1d17ab41d41770978b3474 | /stepiiteration.cpp | 1b56f23d287ca73292bdb4d7e6c08ca0d81fcc2a | [] | no_license | victoriablackmore/Extract-MAUS-data | 31449e7aac37e4b093a991d055d6427bc589be0e | 3f6c7da343fa6094b7bc10929a47a71ead122881 | refs/heads/master | 2021-01-19T03:02:06.342674 | 2018-03-02T20:01:35 | 2018-03-02T20:01:35 | 54,506,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,974 | cpp | #include "stepiiteration.h"
StepIIteration::StepIIteration(StepIBeamLine *beamline)
{
//_name = name;
//_file = new TFile(_name.c_str(), "recreate");
_beamline = beamline;
_z = _beamline->GetZ1() - _beamline->GetZ0();
//The output tree
/*
_T = new TTree("T", "T");
_T->Branch("good", &_good, "good/I");
_T->Branch("delta_in", &_delta_in, "delta_in/D");
_T->Branch("t", &_t,"t/D");
_T->Branch("z", &_z,"z/D");
_T->Branch("beta", &_beta, "beta/D");
_T->Branch("gamma", &_gamma, "gamma/D");
_T->Branch("P", &_P,"P/D");
_T->Branch("dP", &_dP,"dP/D");
_T->Branch("x0",&_x0,"x0/D");
_T->Branch("y0",&_y0,"y0/D");
_T->Branch("x1",&_x1,"x1/D");
_T->Branch("y1",&_y1,"y1/D");
_T->Branch("ax0",&_ax0,"ax0/D");
_T->Branch("ay0",&_ay0,"ay0/D");
_T->Branch("ax1",&_ax1,"ax1/D");
_T->Branch("ay1",&_ay1,"ay1/D");
_T->Branch("delta_out", &_delta_out, "delta_out/D");
_T->Branch("Ax", &_Ax, "Ax/D");
_T->Branch("Ay", &_Ay, "Ay/D");
_T->Branch("Bx", &_Bx, "Bx/D");
_T->Branch("By", &_By, "By/D");
_T->Branch("muonID", &_muonIDNumber, "muonID/I");
*/
VBS = false;
}
void StepIIteration::ReconstructEvent(double t, double &delta, double x0, double x1, double y0, double y1, double mass, int muonIDNumber){
_muonIDNumber = muonIDNumber;
ReconstructEvent(t, delta, x0, x1, y0, y1, mass);
}
void StepIIteration::ReconstructEvent(double t, double &delta, double x0, double x1, double y0, double y1, double mass) {
//Input estimate of excess path length for these calculations
_delta_in = delta;
//Fill TTree branches with new leaves
_t = t;
_mass = 105.658;
_x0 = x0;
_y0 = y0;
_x1 = x1;
_y1 = y1;
//Calculate momentum estimate based on input estimate of delta
calculateMomentum(_t, _delta_in, _mass, _beta, _gamma, _P);
//Reconstruct angles
if (VBS) printf("%f %f %f %f %f %f %f %f %f\n",_x0, _ax0, _y0, _ay0, _x1, _ax1, _y1, _ay1, _P);
_beamline->CalculateAngles(_x0, _ax0, _y0, _ay0, _x1, _ax1, _y1, _ay1, _P);
if (VBS) printf("%f %f %f %f %f %f %f %f %f\n",_x0, _ax0, _y0, _ay0, _x1, _ax1, _y1, _ay1, _P);
//Calculate new improved estimate of excess path length delta
_delta_out = _beamline->CalculatePathLength(_x0, _ax0, _y0, _ay0, _P) - _z;
if(_delta_out > 50.0*u.mm()){
_good = 0;
}
//_delta_out = 30.0*u.mm();
if (VBS) printf("delta = %f\n",_delta_out);
//Make P an estimate of p before TOF1 by accounting for air (we think)
//_P -= 0.9*CLHEP::MeV;
_dP = momentumCorrection(_P);
_P -= _dP;
//Fill TTree
_good = 1;
// if(_delta_out > 100.0*u.mm()){
// _good = 0;
// std::cerr << "Warning: _delta_out > 100 mm\n";
// }
_Ax = _beamline->GetAx();
_Ay = _beamline->GetAy();
_Bx = _beamline->GetBx();
_By = _beamline->GetBy();
// _T->Fill();
//Better delta estimate by reference is output here, input for another ietartion if required
//delta = _delta_out;
delta = _delta_in + 0.5*(_delta_out-_delta_in);//damp delta
}
QHash<QString, double> StepIIteration::Result(){
QHash<QString, double> result;
result["x0"] = _x0;
result["y0"] = _y0;
result["ax0"] = _ax0;
result["ay0"] = _ay0;
result["x1"] = _x1;
result["y1"] = _y1;
result["ax1"] = _ax1;
result["ay1"] = _ay1;
result["P"] = _P;
result["dP"] = _dP;
result["good"] = _good;
result["mass"] = _mass;
return result;
}
void StepIIteration::Bad(double t, double x0, double x1, double y0, double y1, double mass, int muonIDNumber){
_muonIDNumber = muonIDNumber;
Bad(t, x0, x1, y0, y1, mass);
}
void StepIIteration::Bad(double t, double x0, double x1, double y0, double y1, double mass) {
_good = 0;
_delta_in = 0;
_t = t;
_mass = mass;
_x0 = x0;
_y0 = y0;
_x1 = x1;
_y1 = y1;
_delta_out = 0;
_dP = 0;
_P = 0;
//_T->Fill();
}
void StepIIteration::CHEAT(double t, double &delta, double x0, double ax0, double y0, double ay0, double mass) {
//Input estimate of excess path length for these calculations
_delta_in = delta;
//Fill TTree branches with new leaves
_t = t;
_mass = mass;
_x0 = x0;
_ax0 = ax0;
_y0 = y0;
_ay0 = ay0;
//Calculate momentum estimate based on input estimate of delta
calculateMomentum(_t, _delta_in, _mass, _beta, _gamma, _P);
//No need to reconstruct angles - that's our cheat
//Calculate new improved estimate of excess path length delta
_delta_out = _beamline->CalculatePathLength(_x0, _ax0, _y0, _ay0, _P) - _z;
//if (_delta_out<0.) printf("-ve delta: x0=%f, ax0=%f, y0=%f, y1=%f\n", );
//Fill TTree
_good = 1;
//_T->Fill();
//Make P an estimate of p before TOF1 by accounting for air (we think)
_dP = momentumCorrection(_P);
_P -= _dP;
//Better delta estimate by reference is output here, input for another ietartion if required
//delta = _delta_out;
delta = _delta_in + 0.5*(_delta_out-_delta_in);//damp delta
}
void StepIIteration::calculateMomentum(double t, double delta, double mass, double &beta, double &gamma, double &P) {
beta = einstein_beta(_z + delta, t);
if (VBS) printf("beta = %f\n",beta);
gamma = einstein_gamma(beta);
P = rel_mom(beta, gamma, mass);
//std::cerr << "P = " << P << ", given beta = " << beta << " and gamma = " << gamma << "\n";
}
void StepIIteration::Write() {
//_T->CloneTree();
//_file->Write();
}
double StepIIteration::einstein_beta(double z, double t) {
return ( z / t ) / u.c_light();
}
double StepIIteration::einstein_gamma(double beta) {
return 1. / sqrt( 1 - beta*beta );
}
double StepIIteration::rel_mom(double beta, double gamma, double mass) {
return beta * gamma * mass;//no c as m in natural units
}
double StepIIteration::momentumCorrection(double p) {
double E = sqrt(105.658*105.658 + p*p);
//Air
double density_air = 1.205e-3*u.g()/u.cm3();//g cm-3
double dp_air = (E/p) * (_z/2.)/u.cm() * dEdx(p, 0.49919, 85.7 * u.eV()) * density_air;
//BPM was present in Step I.. only need this if looking at old data:
// double density_BPM = 1.06*u.g()/u.cm3();//g cm-3
// double dp_BPM = (E/p) * ((-360*u.mm() -_beamline->GetZ0())/(_beamline->GetZ1()-_beamline->GetZ0()))*(2*0.8*u.mm())/u.cm() * dEdx(p, 0.53768, 67.8 *u.eV()) * density_BPM;//BPM is at -360mm
return dp_air; // + dp_BPM;
}
double StepIIteration::dEdx(double p, double ZoverA, double I) {
//I should be in eV
double K = 0.307075 * u.MeV();//g-1 cm2
double m_e = 0.510998910 * u.MeV();
double E = sqrt(105.658*105.658 + p*p);
double beta = p / E;
double gamma = einstein_gamma(beta);
return K * ZoverA * (log(2.*m_e*pow(beta*gamma,2.)/I)/pow(beta,2) - 1.);
}
StepIIteration::~StepIIteration(){
//delete _beamline;
//delete _T;
//delete _file;
}
| [
"vb@somemailaddress.com"
] | vb@somemailaddress.com |
81dd136780df0d5f3dcc385ddea4e2835b9f9987 | ed2f89fc0bfb136cbbd5a49733b7e46aadfdc0fd | /_MODEL_FOLDERS_/lightSpheres/lightSpheres_INIT.cpp | 29a55535f2e6ed7de43b3eec94cbe66cd6f8c94e | [] | no_license | marcclintdion/a7_3D_CUBE | 40975879cf0840286ad1c37d80f906db581e60c4 | 1ba081bf93485523221da32038cad718a1f823ea | refs/heads/master | 2021-01-20T12:00:32.550585 | 2015-09-19T03:25:14 | 2015-09-19T03:25:14 | 42,757,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,026 | cpp | #ifdef __APPLE__
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#endif
//===============================================================================================
lightSpheres_SHADER = glCreateProgram();
//---------------------------------------------------------------------
const GLchar *vertexSource_lightSpheres =
" #define highp \n"
" uniform highp vec4 light_POSITION_01; \n"
" uniform mat4 mvpMatrix; \n"
" uniform mat4 mvMatrix; \n"
" uniform mat4 lightMatrix; \n"
" attribute vec4 position; \n"
" attribute vec2 texture; \n"
" varying highp vec4 lightPosition_PASS; \n"
//-------------------------------------------
" uniform mat4 textureMatrix; \n"
" varying highp vec4 shadowTexcoord; \n"
" highp vec4 TEMP_shadowTexcoord; \n"
" uniform highp vec4 offset; \n"
//-------------------------------------------
" varying highp vec2 varTexcoord; \n"
//-----------------------------------------------------------------------------------------------------------------
" varying highp vec3 vertex_pos; \n"
//-----------------------------------------------------------------------------------------------------------------
" void main() \n"
" { \n"
//---------------------------------------------------------------------------------------------------------
" TEMP_shadowTexcoord = textureMatrix * mvpMatrix * position; \n"
" shadowTexcoord = TEMP_shadowTexcoord + offset; \n"
//---------------------------------------------------------------------------------------------------------
" lightPosition_PASS = normalize(lightMatrix * light_POSITION_01); \n"
" varTexcoord = texture; \n"
" gl_Position = mvpMatrix * position; \n"
" }\n";
//#################################################################################################################################
//#################################################################################################################################
//#################################################################################################################################
//#################################################################################################################################
//---------------------------------------------------------------------
lightSpheres_SHADER_VERTEX = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(lightSpheres_SHADER_VERTEX, 1, &vertexSource_lightSpheres, NULL);
glCompileShader(lightSpheres_SHADER_VERTEX);
//---------------------------------------------------------------------
const GLchar *fragmentSource_lightSpheres =
" #ifdef GL_ES \n"
" #else \n"
" #define highp \n"
" #endif \n"
" uniform sampler2DShadow ShadowTexture; \n"
" varying highp vec4 shadowTexcoord; \n"
" highp vec4 shadow; \n"
//--------------------------------------------
" uniform sampler2D Texture1; \n"
" uniform sampler2D NormalMap; \n"
//--------------------------------------------
" uniform highp float constantAttenuation; \n"
//--------------------------------------------
" varying highp vec4 lightPosition_PASS; \n"
" varying highp vec2 varTexcoord; \n"
//--------------------------------------------
" highp float NdotL2; \n"
" highp vec3 normal_2; \n"
" highp vec3 NormalTex; \n"
//-----------------------------------
" void main() \n"
" { \n"
//--------------------------------------------------------------------------------------------------
" vec4 shadowCoordinateWdivide = shadowTexcoord / shadowTexcoord.w; \n"
" shadowCoordinateWdivide.z += constantAttenuation; \n"
" float distanceFromLight = shadow2DProj(ShadowTexture, shadowTexcoord).r; \n"
" float shadow = 1.0; \n"
" if (shadowTexcoord.w > 0.0) \n"
" shadow = distanceFromLight < shadowCoordinateWdivide.z ? 0.3 : 1.0 ; \n"
//--------------------------------------------------------------------------------------------------
" NormalTex = texture2D(NormalMap, varTexcoord.xy).xyz; \n"
" NormalTex = (NormalTex - 0.5); \n"
" normal_2 = normalize(NormalTex); \n"
" NdotL2 = max(dot(normal_2, lightPosition_PASS.xyz), 0.0); \n"
//-----------------------------------------------------------------------------------------------------------------------------
" gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0) ; \n"
" }\n";
//---------------------------------------------------------------------
lightSpheres_SHADER_FRAGMENT = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(lightSpheres_SHADER_FRAGMENT, 1, &fragmentSource_lightSpheres, NULL);
glCompileShader(lightSpheres_SHADER_FRAGMENT);
//------------------------------------------------
glAttachShader(lightSpheres_SHADER, lightSpheres_SHADER_VERTEX);
glAttachShader(lightSpheres_SHADER, lightSpheres_SHADER_FRAGMENT);
//------------------------------------------------
glBindAttribLocation(lightSpheres_SHADER, 0, "position");
glBindAttribLocation(lightSpheres_SHADER, 1, "normal");
glBindAttribLocation(lightSpheres_SHADER, 2, "tangent");
glBindAttribLocation(lightSpheres_SHADER, 3, "texture");
//------------------------------------------------
glLinkProgram(lightSpheres_SHADER);
//------------------------------------------------
#ifdef __APPLE__
glDetachShader(lightSpheres_SHADER, lightSpheres_SHADER_VERTEX);
glDetachShader(lightSpheres_SHADER, lightSpheres_SHADER_FRAGMENT);
#endif
//------------------------------------------------
glDeleteShader(lightSpheres_SHADER_VERTEX);
glDeleteShader(lightSpheres_SHADER_FRAGMENT);
//---------------------------------------------------------------------------------------------------------------------------
UNIFORM_MODELVIEWPROJ_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "mvpMatrix");
UNIFORM_MODELVIEW_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "mvMatrix");
UNIFORM_LIGHT_MATRIX_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "lightMatrix");
UNIFORM_textureMatrix_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "textureMatrix");
UNIFORM_INVERSEMATRIX_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "inverseMatrix");
UNIFORM_offset_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "offset");
//-------------------------------------
UNIFORM_LIGHT_POSITION_01_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "light_POSITION_01");
UNIFORM_SHININESS_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "shininess");
//-------------------------------------
UNIFORM_QUADRATIC_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "quadraticAttenuation");
UNIFORM_LINEAR_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "linearAttenuation");
UNIFORM_CONSTANT_ATTENUATION_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "constantAttenuation");
//-------------------------------------
UNIFORM_TEXTURE_SHADOW_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "ShadowTexture");
UNIFORM_TEXTURE_DOT3_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "NormalMap");
UNIFORM_TEXTURE_lightSpheres = glGetUniformLocation(lightSpheres_SHADER, "Texture1");
//---------------------------------------------------------------------------------------------------------------------------
/*
#ifdef __APPLE__
filePathName = [[NSBundle mainBundle] pathForResource:@"lightSpheres_DOT3" ofType:@"bmp"];
image = imgLoadImage([filePathName cStringUsingEncoding:NSASCIIStringEncoding]);
glGenTextures(1, &lightSpheres_NORMALMAP);
glBindTexture(GL_TEXTURE_2D, lightSpheres_NORMALMAP);
ConfigureAndLoadTexture(image->data, image->width, image->height );
imgDestroyImage(image);
//---------------------
filePathName = [[NSBundle mainBundle] pathForResource:@"lightSpheres" ofType:@"png"];
image = imgLoadImage([filePathName cStringUsingEncoding:NSASCIIStringEncoding]);
glGenTextures(1, &lightSpheres_TEXTUREMAP);
glBindTexture(GL_TEXTURE_2D, lightSpheres_TEXTUREMAP);
ConfigureAndLoadTexture(image->data, image->width, image->height );
imgDestroyImage(image);
#endif
//------------------------------------------------------------------------------------------
#ifdef WIN32
loadTexture("_MODEL_FOLDERS_/lightSpheres/lightSpheres_DOT3.bmp", lightSpheres_NORMALMAP);
loadTexture("_MODEL_FOLDERS_/lightSpheres/lightSpheres.png", lightSpheres_TEXTUREMAP);
#endif
*/
//--------------------------------------------------------------------------------------------------------------------
#include "lightSpheres.cpp"
glGenBuffers(1, &lightSpheres_VBO);
glBindBuffer(GL_ARRAY_BUFFER, lightSpheres_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(lightSpheres), lightSpheres, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//--------------------------------------------------------------------------------------------------------------------
#include "lightSpheres_INDICES.cpp"
glGenBuffers(1, &lightSpheres_INDEX_VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lightSpheres_INDEX_VBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(lightSpheres_INDICES), lightSpheres_INDICES, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//====================================================================================================================
glGenFramebuffers(1, &geometryLightPass_fboId);
glGenTextures(1, &geometryLightPass_TEXTURE);
glBindTexture(GL_TEXTURE_2D, geometryLightPass_TEXTURE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)viewWidth / resize_LIGHTS_FBO, (GLsizei)viewHeight / resize_LIGHTS_FBO, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glBindFramebuffer(GL_FRAMEBUFFER, geometryLightPass_fboId);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, geometryLightPass_TEXTURE, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//=======================================================================================================================
srand(time(0));
//float randomVelocity[] = {0.0, 0.0, 0.0};
//float randomGravity = 0.0;
for(int i = 0; i < numberOfGeometryLights; i++)
{
lightSpheres_POSITION_ARRAY[i][0] = ((rand()% 10) - 5) *1.1;
lightSpheres_POSITION_ARRAY[i][1] = ((rand()% 10) - 5) *1.1;
lightSpheres_POSITION_ARRAY[i][2] = ((rand()% 10) - 5) *1.1;
//--------------------------------------------------------------------
lightSpheres_VELOCITY_ARRAY[i][0] = ((rand()% 10) - 5) *.002;
lightSpheres_VELOCITY_ARRAY[i][1] = ((rand()% 10) - 5) *.002;
lightSpheres_VELOCITY_ARRAY[i][2] = ((rand()% 10) - 5) *.002;
//--------------------------------------------------------------------
lightSpheres_ROTATION_ARRAY[i][0] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][1] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][2] = ((rand()% 10) - 5) *.002;
lightSpheres_ROTATION_ARRAY[i][3] = ((rand()% 10) - 5) *.002;
//--------------------------------------------------------------------
lightSpheres_SCALE_ARRAY[i][0] = ((rand()% 10) - 5) *0.4;
lightSpheres_SCALE_ARRAY[i][1] = lightSpheres_SCALE_ARRAY[i][0];
lightSpheres_SCALE_ARRAY[i][2] = lightSpheres_SCALE_ARRAY[i][0];
//--------------------------------------------------------------------
}
//#####################################################################################################################
| [
"marcclintdion@Marcs-iMac.local"
] | marcclintdion@Marcs-iMac.local |
aae84ca12777adbf4c14a7417d25158c733917e2 | e9907bc518adcd4770f6c62c2a792cbda396aff3 | /leetcode_path_with_minimum_effort.cpp | 0246a998180a41a1d354450fbeab09de42f9cecf | [] | no_license | md-qubais/DSA_updated | efa59fee40001b21c16fa76ef7bf300d725b5dfd | 93b9569670def3dc68073b133133642571d40631 | refs/heads/main | 2023-06-16T18:33:20.346480 | 2021-07-10T06:14:28 | 2021-07-10T06:14:28 | 384,624,998 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,633 | cpp | class Pair{
public:
int rows;
int cols;
int diff;
Pair(){
}
Pair(int rows,int cols,int diff){
this->rows=rows;
this->cols=cols;
this->diff=diff;
}
};
class compare{
public:
bool operator()(Pair p1,Pair p2){
return p1.diff>p2.diff;
}
};
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
priority_queue<Pair,vector<Pair>,compare> pq;
if(heights.size()==1 and heights[0].size()==1){
return 0;
}
int ans=0;
if(heights[0].size()>1) pq.push(Pair(0,1,abs(heights[0][0]-heights[0][1])));
if(heights.size()>1) pq.push(Pair(1,0,abs(heights[0][0]-heights[1][0])));
bool visited[1000][1000]={false};
while(!pq.empty()){
Pair temp=pq.top();
pq.pop();
if(visited[temp.rows][temp.cols]){
continue;
}
ans=max(ans,temp.diff);
if(temp.rows==heights.size()-1 and temp.cols==heights[0].size()-1){
return ans;
}
visited[temp.rows][temp.cols]=true;
int row_dir[]={1,-1,0,0};
int col_dir[]={0,0,1,-1};
for(int k=0;k<4;k++){
int row=temp.rows+row_dir[k];
int col=temp.cols+col_dir[k];
if(row<0 or col<0 or row>=heights.size() or col>=heights[0].size() or visited[row][col]){
continue;
}
pq.push(Pair(row,col,abs(heights[temp.rows][temp.cols]-heights[row][col])));
}
}
return ans;
}
}; | [
"hiq4dsa@gmail.com"
] | hiq4dsa@gmail.com |
c9d26134f06df057c4562147e7f77b12181b5645 | 5e59fe8bcdd12a2d375a58dbb719e1db395c7d16 | /mruby-sys/vendor/emscripten/system/lib/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace_emscripten.cc | 610770704cedb4491bec1144c87ba0a11154a9bd | [
"NCSA",
"MIT",
"MPL-2.0"
] | permissive | ifyouseewendy/artichoke | 4ec7f34dcd644bd1156ac54b87953eb070c22cd0 | 6f569cbb0273a468cbe49f4c60144bf189cfb7a0 | refs/heads/master | 2020-07-05T20:53:41.334690 | 2020-03-19T22:07:12 | 2020-03-20T01:41:30 | 202,770,950 | 1 | 0 | MIT | 2019-08-16T17:23:33 | 2019-08-16T17:23:32 | null | UTF-8 | C++ | false | false | 1,332 | cc | //===-- sanitizer_stacktrace_emscripten.cc --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//
// Implementation of fast stack unwinding for Emscripten.
//===----------------------------------------------------------------------===//
#ifdef __EMSCRIPTEN__
#include "sanitizer_common.h"
#include "sanitizer_stacktrace.h"
namespace __sanitizer {
extern "C" {
uptr emscripten_stack_snapshot();
uptr emscripten_return_address(int level);
u32 emscripten_stack_unwind_buffer(uptr pc, uptr *buffer, u32 depth);
}
uptr StackTrace::GetCurrentPc() {
return emscripten_stack_snapshot();
}
void BufferedStackTrace::FastUnwindStack(uptr pc, uptr bp, uptr stack_top,
uptr stack_bottom, u32 max_depth) {
bool saw_pc = false;
max_depth = Min(max_depth, kStackTraceMax);
size = emscripten_stack_unwind_buffer(pc, trace_buffer, max_depth);
trace_buffer[0] = pc;
size = Max(size, 1U);
}
} // namespace __sanitizer
#endif // __EMSCRIPTEN__
| [
"rjl@hyperbo.la"
] | rjl@hyperbo.la |
8e01190e73cb3a74e5910323e5f7f4266331ac79 | 14e00a226015c07522cc99b70fbcee5a2a8747d7 | /lab1/catkin_ws/src/libclfsm/src/FSMSuspensibleMachine.cc | 0ce38fce2989d1de85d6c9c76e394c36b86b53c0 | [
"Apache-2.0"
] | permissive | Joshua-Mitchell/robotics | 031fa1033bda465b813c40633da57886c3446a2c | 3f60f72bfaf9de4e2d65c7baac0dd57ee2d556b8 | refs/heads/master | 2020-04-27T13:01:25.073103 | 2019-03-10T14:49:08 | 2019-03-10T14:49:08 | 174,352,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,806 | cc | /*
* FSMSuspensibleMachine.cc
*
* Created by René Hexel on 24/09/11.
* Copyright (c) 2011-2014 Rene Hexel.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Rene Hexel.
*
* 4. Neither the name of the author nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "FSMSuspensibleMachine.h"
#include "FSMState.h"
using namespace FSM;
SuspensibleMachine::~SuspensibleMachine()
{
if (_deleteSuspendState && _suspendState)
delete _suspendState;
}
void SuspensibleMachine::setSuspendState(State *s, bool del)
{
if (_deleteSuspendState && _suspendState)
delete _suspendState;
_suspendState = s;
_deleteSuspendState = del;
}
void SuspensibleMachine::suspend()
{
using namespace std;
if (!_suspendState)
{
_suspendState = new State(-1, "Suspended");
if (!_suspendState)
throw "Unable to create dynamic suspend state";
_deleteSuspendState = true;
}
if (currentState() != _suspendState)
{
_resumeState = currentState();
setPreviousState(_resumeState);
if (debugSuspends)
cerr << "Suspend " << id() << ": " << previousState()->name() << " -> " << currentState()->name() << endl;
}
else if (debugSuspends > 1)
cerr << "Suspend " << id() << ": " << previousState()->name() << " -> " << currentState()->name() << " (re-suspend)" << endl;
setCurrentState(_suspendState);
}
void SuspensibleMachine::resume()
{
using namespace std;
State *curr = currentState();
/*
* only do anything if suspended
*/
if (curr != _suspendState)
{
if (debugSuspends > 1)
cerr << "Resume " << id() << ": " << currentState()->name() << " -> " << currentState()->name() << " (re-resume)" << endl;
return;
}
State *prev = _resumeState;
if (!prev || prev == _suspendState) prev = states()[0];
setPreviousState(curr);
setCurrentState(prev);
if (debugSuspends)
cerr << "Resume " << id() << ": " << curr->name() << " -> " << prev->name() << (prev == states()[0] ? " (initial)" : "") << endl;
}
| [
"joshua.mitchell4@griffithuni.edu.au"
] | joshua.mitchell4@griffithuni.edu.au |
72810cb6c26d450ba0a5477b47ab939b6551df94 | e097ca136d17ff092e89b3b54214ec09f347604f | /include/amtrs/lang/java/class/android/media/MediaPlayer.hpp | f603479ce13a65c8786b68cb7e8d9b2797f92369 | [
"BSD-2-Clause"
] | permissive | isaponsoft/libamtrs | 1c02063c06613cc43091d5341c132b45d3051ee0 | 0c5d4ebe7e0f23d260bf091a4ab73ab9809daa50 | refs/heads/master | 2023-01-14T16:48:23.908727 | 2022-12-28T02:27:46 | 2022-12-28T02:27:46 | 189,788,925 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,948 | hpp | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libamtrs__android__java_classes__android__media__MediaPlayer__hpp
#define __libamtrs__android__java_classes__android__media__MediaPlayer__hpp
AMTRS_JAVA_CLASSES_NAMESPACE_BEGIN
namespace android::content {
struct Context;
}
namespace android::net {
struct Uri;
}
namespace android::media {
AMTRS_JAVA_DEFINE_CLASS(MediaPlayer, java::lang::Object)
{
using Context = android::content::Context;
using Uri = android::net::Uri;
AMTRS_JAVA_CLASS_SIGNATURE("android/media/MediaPlayer");
// クラスメソッドとクラスフィールド
AMTRS_JAVA_DEFINE_STATIC_MEMBER
{
AMTRS_JAVA_STATICS_BASIC;
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_IO)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_MALFORMED)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_SERVER_DIED)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_TIMED_OUT)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_UNKNOWN)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_ERROR_UNSUPPORTED)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_BAD_INTERLEAVING)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_BUFFERING_END)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_BUFFERING_START)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_METADATA_UPDATE)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_NOT_SEEKABLE)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_STARTED_AS_NEXT)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_SUBTITLE_TIMED_OUT)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_UNKNOWN)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_UNSUPPORTED_SUBTITLE)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_VIDEO_RENDERING_START)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_INFO_VIDEO_TRACK_LAGGING)
AMTRS_JAVA_DEFINE_FIELD(jint, MEDIA_MIMETYPE_TEXT_SUBRIP)
AMTRS_JAVA_DEFINE_FIELD(jint, PREPARE_DRM_STATUS_PREPARATION_ERROR)
AMTRS_JAVA_DEFINE_FIELD(jint, PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR)
AMTRS_JAVA_DEFINE_FIELD(jint, PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR)
AMTRS_JAVA_DEFINE_FIELD(jint, PREPARE_DRM_STATUS_SUCCESS)
AMTRS_JAVA_DEFINE_FIELD(jint, SEEK_CLOSEST)
AMTRS_JAVA_DEFINE_FIELD(jint, SEEK_CLOSEST_SYNC)
AMTRS_JAVA_DEFINE_FIELD(jint, SEEK_NEXT_SYNC)
AMTRS_JAVA_DEFINE_FIELD(jint, SEEK_PREVIOUS_SYNC)
AMTRS_JAVA_DEFINE_FIELD(jint, VIDEO_SCALING_MODE_SCALE_TO_FIT)
AMTRS_JAVA_DEFINE_FIELD(jint, VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
AMTRS_JAVA_DEFINE_METHOD(create
, MediaPlayer(Context context, Uri uri)
)
};
// 動的メソッドと動的フィールド
AMTRS_JAVA_DEFINE_DYNAMICS_MEMBER
{
AMTRS_JAVA_DYNAMICS_BASIC;
AMTRS_JAVA_DEFINE_METHOD(start
, void()
)
AMTRS_JAVA_DEFINE_METHOD(stop
, void()
)
};
};
}
AMTRS_JAVA_CLASSES_NAMESPACE_END
#endif
| [
"isaponsoft@gmail.com"
] | isaponsoft@gmail.com |
5cb77790949fc5e25e6199110586b10ebe64a4f8 | 6278552a2faaef9534f8a599dae881063fe12cf5 | /src/main.cpp | 0385189adb3e5e823e71df088315f7b751cc9371 | [] | no_license | SyedAzizEnam/MPC-Controller | 0fc8eafc9888bc48ad3ceca367910c02a22d2d31 | 7698677f7f1c8d00e00be7fdfadb598b7603aa1c | refs/heads/master | 2020-06-16T18:27:04.724289 | 2017-07-30T20:31:00 | 2017-07-30T20:31:00 | 94,153,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,247 | cpp | #include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "MPC.h"
#include "json.hpp"
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.rfind("}]");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
// Evaluate a polynomial.
double polyeval(Eigen::VectorXd coeffs, double x) {
double result = 0.0;
for (int i = 0; i < coeffs.size(); i++) {
result += coeffs[i] * pow(x, i);
}
return result;
}
// Fit a polynomial.
// Adapted from
// https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716
Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals,
int order) {
assert(xvals.size() == yvals.size());
assert(order >= 1 && order <= xvals.size() - 1);
Eigen::MatrixXd A(xvals.size(), order + 1);
for (int i = 0; i < xvals.size(); i++) {
A(i, 0) = 1.0;
}
for (int j = 0; j < xvals.size(); j++) {
for (int i = 0; i < order; i++) {
A(j, i + 1) = A(j, i) * xvals(j);
}
}
auto Q = A.householderQr();
auto result = Q.solve(yvals);
return result;
}
int main() {
uWS::Hub h;
// MPC is initialized here!
MPC mpc;
h.onMessage([&mpc](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
string sdata = string(data).substr(0, length);
cout << sdata << endl;
if (sdata.size() > 2 && sdata[0] == '4' && sdata[1] == '2') {
string s = hasData(sdata);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
vector<double> ptsx = j[1]["ptsx"];
vector<double> ptsy = j[1]["ptsy"];
double px = j[1]["x"];
double py = j[1]["y"];
double psi = j[1]["psi"];
double v = j[1]["speed"];
// Transform ptsx and ptsy to car's reference
for (int i = 0; i< ptsx.size(); i++)
{
//translate
double t_x = ptsx[i] - px;
double t_y = ptsy[i] - py;
//rotate
ptsx[i] = t_x * cos(-psi) - t_y * sin(-psi);
ptsy[i] = t_x * sin(-psi) + t_y * cos(-psi);
}
//convert std::vector to Eigen::VectorXd
double* ptr_x = &ptsx[0];
Eigen::Map<Eigen::VectorXd> ptsx_v(ptr_x, ptsx.size());
double* ptr_y = &ptsy[0];
Eigen::Map<Eigen::VectorXd> ptsy_v(ptr_y, ptsy.size());
Eigen::VectorXd coeffs = polyfit(ptsx_v, ptsy_v, 3);
double cte = polyeval(coeffs, 0);
// simplified since px = py = psi = 0
double epsi = -atan(coeffs[1]);
Eigen::VectorXd state(6);
state << 0.0, 0.0, 0.0, v, cte, epsi;
double Lf = 2.67;
vector<double> mpc_results = mpc.Solve(state, coeffs);
double steer_value = mpc_results[0]/(deg2rad(25)*Lf);
double throttle_value = mpc_results[1];
json msgJson;
// NOTE: Remember to divide by deg2rad(25) before you send the steering value back.
// Otherwise the values will be in between [-deg2rad(25), deg2rad(25] instead of [-1, 1].
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = throttle_value;
//Display the MPC predicted trajectory
vector<double> mpc_x_vals;
vector<double> mpc_y_vals;
for (int i = 2; i < mpc_results.size(); i++)
{
if (i%2 == 0) {
mpc_x_vals.push_back(mpc_results[i]);
}
else {
mpc_y_vals.push_back(mpc_results[i]);
}
}
//.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system
// the points in the simulator are connected by a Green line
msgJson["mpc_x"] = mpc_x_vals;
msgJson["mpc_y"] = mpc_y_vals;
//Display the waypoints/reference line
vector<double> next_x_vals;
vector<double> next_y_vals;
double poly_inc = 2.5;
int num_points = 25;
for (int i = 0; i< num_points; i++)
{
next_x_vals.push_back(poly_inc*i);
next_y_vals.push_back(polyeval(coeffs, poly_inc*i));
}
//.. add (x,y) points to list here, points are in reference to the vehicle's coordinate system
// the points in the simulator are connected by a Yellow line
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
std::cout << msg << std::endl;
// Latency
// The purpose is to mimic real driving conditions where
// the car does actuate the commands instantly.
//
// Feel free to play around with this value but should be to drive
// around the track with 100ms latency.
//
// NOTE: REMEMBER TO SET THIS TO 100 MILLISECONDS BEFORE
// SUBMITTING.
this_thread::sleep_for(chrono::milliseconds(100));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| [
"azizenam@gmail.com"
] | azizenam@gmail.com |
bba78b98f6f8c58529862ea61b6201339bece2d1 | 4e68b2d90fbcf829435514ae3631c75b5ba2e438 | /src/yb/util/algorithm_util.h | aaa7fdecfb5bb1b5cbeba1dc269cacd4b3bb8bc2 | [
"OpenSSL",
"Apache-2.0",
"BSD-3-Clause",
"CC0-1.0",
"Unlicense",
"bzip2-1.0.6",
"dtoa",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | bhrgv-bolla/yugabyte-db | b4b2c22d76b0503e1f96d1279b858800ae138119 | 7b12cce17745647e1870f7f7b44a9a71068ceecd | refs/heads/master | 2020-03-11T20:50:05.257512 | 2018-04-19T06:56:16 | 2018-04-19T10:39:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | h | // Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#ifndef YB_UTIL_ALGORITHM_UTIL_H
#define YB_UTIL_ALGORITHM_UTIL_H
#include <algorithm>
#include "yb/util/enums.h"
namespace yb {
enum class SortOrder : uint8_t {
kAscending = 0,
kDescending
};
template<typename Iterator, typename Functor>
void SortByKey(Iterator begin,
Iterator end,
const Functor& f,
SortOrder sort_order = SortOrder::kAscending) {
using Value = typename Iterator::value_type;
const bool invert_order = sort_order == SortOrder::kDescending;
std::sort(begin, end, [invert_order, &f](const Value& a, const Value& b){
return f(a) < f(b) != invert_order;
});
}
}; // namespace yb
#endif // YB_UTIL_ALGORITHM_UTIL_H
| [
"mbautin@users.noreply.github.com"
] | mbautin@users.noreply.github.com |
d9d54298286227c10bef0dc7ba0b8aed62a4359a | bac649c895da8043ddb346a98ae1ae56a8d96a31 | /Codes/Light OJ/1053 - Higher Math/HigherMath.cpp | c7b1aee9bdaba100cd378292a8eee8dbe8a393b4 | [] | no_license | raihanthecooldude/ACM | f3d376554df7b744f771bbf559ab9e28e37a25cb | 4c4c6e5de49670abbd9976daf2ae723520874aea | refs/heads/master | 2021-07-02T00:46:57.203310 | 2019-05-27T17:59:37 | 2019-05-27T17:59:37 | 139,543,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | #include<bits/stdc++.h>
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
#define pi 3.1415927
#define MOD 1000000007
#define MAX 100005
#define UMAX 9223372036854775807
#define MAXARRAY 2000002
#define ll long long
#define nl '\n'
#define xx first
#define yy second
#define pb push_back
#define ss stringstream
int main()
{
int t, caseno=1;
cin>>t;
while(caseno<=t)
{
int a, b, c;
cin>>a>>b>>c;
if(((a*a)+(b*b)==(c*c)) || ((a*a)+(c*c)==(b*b)) || ((c*c)+(b*b)==(a*a)))
{
cout<<"Case "<<caseno<<": yes"<<endl;
}
else
{
cout<<"Case "<<caseno<<": no"<<endl;
}
caseno++;
}
return 0;
}
| [
"raihanthecooldude@gmail.com"
] | raihanthecooldude@gmail.com |
ac865118a1b6695a7f0ed7325e8024b41396cdef | 7d36d9de8ddcf9cc6890ee985d8d515ed67411f6 | /include/user_factors.h | 7949ab2a02466b67a050b7182d9a0be7a1d9de69 | [] | no_license | Calm-wy/monodepth_localization | 0002098f563664e9bf8f45577764643dbf4f5c55 | 8192faf6a6467920a440a41d159bcfb7c3a14e98 | refs/heads/master | 2020-06-17T05:51:06.682349 | 2019-05-24T02:05:02 | 2019-05-24T02:05:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,271 | h | /**
* @file slam_factors.h
* @brief User defined factors
*
*/
#include <isam/isam.h>
#include "user_nodes.h"
// NOTE: When you add a new factor, modify gparser.cpp/h to enable proper graph loading
// Unfortunately, currently no loading from native isam is supported.
#pragma once
namespace Eigen {
typedef Matrix<double, 1, 1> Matrix1d;
}
namespace isam {
class Sonar3d {
public:
static const int dim = 3;
static const char* name() {
return "Sonar2d";
}
private:
Pose2d m_pose;
};
class Plane3d_Factor : public FactorT<Plane3d> {
Plane3d_Node* _plane;
public:
Plane3d_Factor (Plane3d_Node *plane,
const Plane3d& measure, const Noise& noise)
: FactorT<Plane3d> ("Plane3d_Factor", Plane3d::dim, noise, measure),
_plane (plane) {
_nodes.resize(1);
_nodes[0] = plane;
}
void initialize () {
if (!_plane->initialized ()) {
Plane3d predict (_measure);
_plane->init (predict);
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
const Plane3d& plane = _plane->value (s);
Eigen::Vector3d err = plane.vector () - _measure.vector ();
return err;
}
private:
};
class Pose3d_Plane3d_Factor : public FactorT<Plane3d> {
Pose3d_Node* _pose;
Plane3d_Node* _plane;
public:
Pose3d_Plane3d_Factor (Pose3d_Node *pose, Plane3d_Node *plane,
const Plane3d& measure, const Noise& noise)
: FactorT<Plane3d> ("Pose3d_Plane3d_Factor", Plane3d::dim, noise, measure),
_pose (pose),
_plane (plane) {
_nodes.resize(2);
_nodes[0] = pose;
_nodes[1] = plane;
}
void initialize () {
require(_pose->initialized (),
"Pose3d_Plane3d_Factor requires pose to be initialized");
if (!_plane->initialized ()) {
Pose3d pose = _pose->value ();
Plane3d predict (_measure.oplus (pose));
/* std::cout << "measure: " << std::endl; */
/* std::cout << _measure << std::endl; */
/* std::cout << "pose: " << std::endl; */
/* std::cout << pose << std::endl; */
/* std::cout << "predict: " << std::endl; */
/* std::cout << predict << std::endl; */
_plane->init (predict);
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
const Pose3d& thisPose = _pose->value (s);
const Plane3d& plane = _plane->value (s);
Plane3d predict = plane.ominus (thisPose);
Eigen::Vector3d err = predict.vector () - _measure.vector ();
return err;
}
private:
};
/* Pose i and pose j observe two planar patches, k and l respectively, that are
* coplanar */
class Piecewise_Planar_Factor : public Factor {
Pose3d_Node *_posei;
Pose3d_Node *_posej;
Plane3d_Node *_planek;
Plane3d_Node *_planel;
public:
Piecewise_Planar_Factor (Pose3d_Node* posei, Pose3d_Node* posej,
Plane3d_Node* planek, Plane3d_Node* planel,
const Noise& noise,
Anchor3d_Node *anchor1=NULL, Anchor3d_Node *anchor2=NULL)
: Factor ("Piecewise_Planar_Factor", Plane3d::dim, noise),
_posei (posei),
_posej (posej),
_planek (planek),
_planel (planel) {
require((anchor1==NULL && anchor2==NULL) || (anchor1!=NULL && anchor2!=NULL),
"slam3d: Piecewise_Planar_Factor requires either 0 or 2 anchor nodes");
if (anchor1) {
_nodes.resize(6);
_nodes[4] = anchor1;
_nodes[5] = anchor2;
} else {
_nodes.resize(4);
}
_nodes[0] = posei;
_nodes[1] = posej;
_nodes[2] = planek;
_nodes[3] = planel;
}
void initialize () {
if (_nodes.size () == 4) {
require (_posei->initialized () && _posej->initialized () &&
_planek->initialized () && _planel->initialized (),
"Piecewise_Planar_Factor requires both poses and both planes to be initialized");
}
else if (_nodes.size () == 6) {
require (_posei->initialized () && _posej->initialized () &&
_planek->initialized () && _planel->initialized () &&
_nodes[4]->initialized () && _nodes[5]->initialized (),
"Piecewise_Planar_Factor requires both poses, both planes, and both anchors to be initialized");
}
}
Eigen::VectorXd basic_error (Selector s = ESTIMATE) const {
Vector3d err;
if (_nodes.size () == 4) {
/* std::cout << std::endl; */
const Pose3d& posei = _posei->value (s);
const Pose3d& posej = _posej->value (s);
const Plane3d& planek = _planek->value (s);
const Plane3d& planel = _planel->value (s);
#ifdef NON_GLOBAL_PLANES
Plane3d planeik = planek;
Plane3d planejl = planel;
#else
/* return planek.vector () - planel.vector (); */
Plane3d planeik = planek.ominus (posei);
/* Plane3d planeil = planel.ominus (posei); */
Plane3d planejl = planel.ominus (posej);
#endif
Pose3d poseji = posei.ominus (posej);
/* std::cout << "CHECK" << std::endl; */
Plane3d planejlPred = planeik.oplus (poseji);
/* std::cout << "DONE" << std::endl; */
err = planejl.vector () - planejlPred.vector ();
/* const Pose3d& posei = _posei->value (s); */
/* const Pose3d& posej = _posej->value (s); */
/* const Plane3d& planek = _planek->value (s); */
/* const Plane3d& planel = _planel->value (s); */
/* /\* Plane3d planeik = planek.oplus (posei); *\/ */
/* /\* Plane3d planeil = planel.oplus (posei); *\/ */
/* /\* err = planeik.vector () - planeil.vector (); *\/ */
/* /\* err = planek.vector () - planel.vector (); *\/ */
/* Plane3d planeik = planek.ominus (posei); */
/* Plane3d planejl = planel.ominus (posej); */
/* /\* std::cout << "plane ik: " << std::endl; *\/ */
/* /\* std::cout << planeik << std::endl; *\/ */
/* /\* std::cout << "plane k: " << std::endl; *\/ */
/* /\* std::cout << planek << std::endl; *\/ */
/* /\* std::cout << "plane l: " << std::endl; *\/ */
/* /\* std::cout << planel << std::endl; *\/ */
/* /\* std::cout << "plane ik: " << std::endl; *\/ */
/* /\* std::cout << planeik << std::endl; *\/ */
/* /\* std::cout << "plane jl: " << std::endl; *\/ */
/* /\* std::cout << planejl << std::endl; *\/ */
/* Pose3d poseij = posej.ominus (posei); */
/* Plane3d planejlPred = planeik.ominus (poseij); */
/* err = planejlPred.vector () - planejl.vector (); */
/* /\* std::cout << "plane jl pred: " << std::endl; *\/ */
/* /\* std::cout << planejlPred << std::endl; *\/ */
/* std::cout << std::endl; */
/* std::cout << posei << std::endl; */
/* std::cout << posej << std::endl; */
/* std::cout << poseij << std::endl; */
/* std::cout << planejl << std::endl; */
/* std::cout << planelPred << std::endl; */
/* std::cout << err << std::endl; */
/* std::cout << "------------------------------" << std::endl; */
}
else if (_nodes.size () == 6) {
/* std::cout << std::endl; */
const Pose3d& a1 = dynamic_cast<Pose3d_Node*>(_nodes[4])->value(s);
const Pose3d& a2 = dynamic_cast<Pose3d_Node*>(_nodes[5])->value(s);
Pose3d a1Inv = Pose3d (a1.oTw ());
Pose3d a2Inv = Pose3d (a2.oTw ());
const Pose3d& posei = _posei->value (s);
const Pose3d& posej = _posej->value (s);
const Plane3d& planek = _planek->value (s);
const Plane3d& planel = _planel->value (s);
#ifdef GLOBAL_PLANES
Plane3d planeik = planek.oplus (a1);
Plane3d planejl = planel.oplus (a2);
#else
/* return planek.vector () - planel.vector (); */
Plane3d planeik = planek.ominus (a1Inv).ominus (a1.oplus (posei));
/* Plane3d planeil = planel.ominus (posei); */
Plane3d planejl = planel.ominus (a2Inv).ominus (a2.oplus (posej));
#endif
Pose3d poseji = a1.oplus (posei).ominus (a2.oplus (posej));
/* std::cout << "CHECK" << std::endl; */
Plane3d planejlPred = planeik.oplus (poseji);
/* std::cout << "DONE" << std::endl; */
err = planejl.vector () - planejlPred.vector ();
}
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << " " << noise_to_string(_noise);
}
};
// A 2d constraint between sonar frames
class Sonar2d_Factor : public FactorT<Pose2d> {
const Pose3d_Node* _pose1;
const Pose3d_Node* _pose2;
Pose3d _sonar_frame1;
Pose3d _sonar_frame2;
public:
/**
* Constructor.
* @param pose1 The pose from which the measurement starts.
* @param pose2 The pose to which the measurement extends.
* @param measure The relative measurement from pose1 to pose2 (pose2 in pose1's frame).
* @param noise The 3x3 square root information matrix (upper triangular).
* @sonar_frame1 the transformation from pose1 to the sonar frame.
* @sonar_frame2 the transfomration from pose2 to the sonar frame.
*/
Sonar2d_Factor(Pose3d_Node* pose1, Pose3d_Node* pose2,
const Pose2d& measure, const Noise& noise,
Pose3d sonar_frame1, Pose3d sonar_frame2)
: FactorT<Pose2d>("Sonar2d_Factor", 3, noise, measure),
_pose1(pose1),
_pose2(pose2),
_sonar_frame1(sonar_frame1),
_sonar_frame2(sonar_frame2)
{
_nodes.resize(2);
_nodes[0] = pose1;
_nodes[1] = pose2;
}
void initialize() {
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// @todo add predicted sonar transformation
// @todo add sonar transformation from vehicle body
const Pose3d& p1 = _pose1->value(s);
const Pose3d& p2 = _pose2->value(s);
Pose3d predicted = (p2.oplus(_sonar_frame2)).ominus(p1.oplus(_sonar_frame1));
Eigen::VectorXd p(3);
p << predicted.x(), predicted.y(), predicted.yaw(); // Predicted
Eigen::VectorXd err(3);
err << p(0)-_measure.x(), p(1)-_measure.y(), p(2)-_measure.t();
err(2) = standardRad(err(2));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << _measure << " " << noise_to_string(_noise) << " " << _sonar_frame1 << " " << _sonar_frame2;
}
};
// xyz factor
class Pose3d_xyz_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector3d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 3x3 square root information matrix (upper triangular).
*/
Pose3d_xyz_Factor(Pose3d_Node* pose, const Eigen::Vector3d& pose_partial, const Noise& noise)
: Factor("Pose3d_xyz_Factor", 3, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(3);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1), pose.z() - _pose_partial(2);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ", " << _pose_partial(2) << ") " << noise_to_string(_noise);
}
};
// xyh factor
class Pose3d_xyh_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector3d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 3x3 square root information matrix (upper triangular).
*/
Pose3d_xyh_Factor(Pose3d_Node* pose, const Eigen::Vector3d& pose_partial, const Noise& noise)
: Factor("Pose3d_xyh_Factor", 3, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(3);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1), pose.yaw() - _pose_partial(2);
err(2) = standardRad(err(2));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ", " << _pose_partial(2) << ") " << noise_to_string(_noise);
}
};
// h factor
class Pose3d_h_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Matrix1d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 1x1 square root information matrix (upper triangular).
*/
Pose3d_h_Factor(Pose3d_Node* pose, const Eigen::Matrix1d& pose_partial, const Noise& noise)
: Factor("Pose3d_h_Factor", 1, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(1);
err << pose.yaw() - _pose_partial(0);
err(0) = standardRad(err(0));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ") " << noise_to_string(_noise);
}
};
// z factor
class Pose3d_z_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Matrix1d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 1x1 square root information matrix (upper triangular).
*/
Pose3d_z_Factor(Pose3d_Node* pose, const Eigen::Matrix1d& pose_partial, const Noise& noise)
: Factor("Pose3d_z_Factor", 1, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(1);
err << pose.z() - _pose_partial(0);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ") " << noise_to_string(_noise);
}
};
// rp factor
class Pose3d_rp_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_rp_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise)
: Factor("Pose3d_rp_Factor", 2, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.roll() - _pose_partial(0), pose.pitch() - _pose_partial(1);
err(0) = standardRad(err(0));
err(1) = standardRad(err(1));
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") " << noise_to_string(_noise);
}
};
// xy factor
class Pose3d_xy_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_xy_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise)
: Factor("Pose3d_xy_Factor", 2, noise), _pose(pose), _pose_partial(pose_partial)
{
_nodes.resize(1);
_nodes[0] = pose;
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") " << noise_to_string(_noise);
}
};
class Pose3d_MaxMix_xy_Factor : public Factor {
const Pose3d_Node* _pose;
public:
const Eigen::Vector2d _pose_partial;
Noise _noise1;
Noise _noise2;
double _w1;
double _w2;
Eigen::Matrix2d _L1;
Eigen::Matrix2d _L2;
double _c1;
double _c2;
/**
* Constructor.
* @param pose The pose node the pose_partial acts on.
* @param pose_partial The actual pose_partial measurement.
* @param sqrtinf The 2x2 square root information matrix (upper triangular).
*/
Pose3d_MaxMix_xy_Factor(Pose3d_Node* pose, const Eigen::Vector2d& pose_partial, const Noise& noise1, const Noise& noise2, double w1, double w2)
: Factor("Pose3d_MaxMix_xy_Factor", 2, Information(Eigen::Matrix2d::Identity())),
_pose(pose), _pose_partial(pose_partial), _noise1(noise1), _noise2(noise2), _w1(w1), _w2(w2)
{
_nodes.resize(1);
_nodes[0] = pose;
_L1 = _noise1.sqrtinf().transpose() * _noise1.sqrtinf();
_L2 = _noise1.sqrtinf().transpose() * _noise2.sqrtinf();
_c1 = _w1/(2.0*M_PI*sqrt(1.0/_L1.determinant()));
_c2 = _w2/(2.0*M_PI*sqrt(1.0/_L2.determinant()));
}
void initialize() {
// Partial pose_partial is not used for initialization
}
Eigen::VectorXd basic_error(Selector s = LINPOINT) const {
// associated pose x,y,z,h,p,r
const Pose3d& pose = _pose->value(s);
Eigen::VectorXd err(2);
err << pose.x() - _pose_partial(0), pose.y() - _pose_partial(1);
double d1 = (err.transpose()*_L1*err);
double p1 = _c1 * exp (-0.5*d1);
double d2 = (err.transpose()*_L2*err);
double p2 = _c2 * exp (-0.5*d2);
if (p1 > p2) {
return _noise1.sqrtinf() * err;
} else {
return _noise2.sqrtinf() * err;
}
}
void write(std::ostream &out) const {
Factor::write(out);
out << " (" << _pose_partial(0) << ", "<< _pose_partial(1) << ") ";
out << _w1 << " " << noise_to_string(_noise1);
out << _w2 << " " << noise_to_string(_noise1);
}
};
/**
* This class is for the plane measurement
* @author Hyunchul Roh (rohs_@kaist.ac.kr)
*/
class Wall3d_Wall3d_Factor : public FactorT<Point3d> {
Pose3d_Node* _pose1;
Pose3d_Node* _pose2;
public:
Wall3d_Wall3d_Factor(Pose3d_Node* pose1, Pose3d_Node* pose2, const Point3d& measure, const Noise& noise, Wall3d *wall1, Wall3d *wall2,
Anchor3d_Node *anchor1 = NULL, Anchor3d_Node *anchor2 = NULL)
: FactorT<Point3d>("Wall3d_Wall3d_Factor", 3, noise, measure), _pose1(pose1), _pose2(pose2) {
require((wall1 == NULL && wall2 == NULL) || (wall1 != NULL && wall2 != NULL),
"slam3d: Wall3d_Wall3d_Factor requires either 0 or 2 wall");
require((anchor1 == NULL && anchor2 == NULL) || (anchor1 != NULL && anchor2 != NULL),
"slam3d: Wall3d_Wall3d_Factor requires either 0 or 2 anchor nodes");
if (anchor1) {
_nodes.resize(4);
_nodes[2] = anchor1;
_nodes[3] = anchor2;
}
else {
_nodes.resize(2);
}
_nodes[0] = pose1;
_nodes[1] = pose2;
_wall1 = wall1;
_wall2 = wall2;
}
void initialize() {
if (_nodes.size() == 2) {
require(_nodes[0]->initialized() && _nodes[1]->initialized(), "Plane3d_Plane3d_Factor: both nodes have to be initialized");
}
else if (_nodes.size() == 4) {
require(_nodes[0]->initialized() && _nodes[1]->initialized() && _nodes[2]->initialized() && _nodes[3]->initialized(), "Plane3d_Plane3d_Factor: both nodes and both anchors have to be initialized");
}
}
Eigen::VectorXd basic_error(Selector s = ESTIMATE) const {
const Pose3d& p1 = _pose1->value(s);
const Pose3d& p2 = _pose2->value(s);
Pose3d p21;
p21 = p1.ominus(p2);
Plane3d plane1 = _wall1->normal();
Plane3d plane2 = _wall2->normal();
Plane3d plane2_cvt_to_plane1 = plane2.ominus(p21);
double dot_product = (plane2_cvt_to_plane1.x()*plane1.x() + plane2_cvt_to_plane1.y()*plane1.y() + plane2_cvt_to_plane1.z()*plane1.z()) / (plane2_cvt_to_plane1.d()*plane1.d());
double err_angle = 1.0 - fabs(dot_product);
Point3d wall2_cvt_to_wall1 = _wall2->ptxfer(p21);
//double err_d1 = (plane1.x() * wall2_cvt_to_wall1.x() + plane1.y() * wall2_cvt_to_wall1.y() + plane1.z() * wall2_cvt_to_wall1.z() + _wall1->d()) / sqrt(plane1.x()*plane1.x() + plane1.y()*plane1.y() + plane1.z()*plane1.z());
double tmpd = -(plane2_cvt_to_plane1.x() * wall2_cvt_to_wall1.x() + plane2_cvt_to_plane1.y() * wall2_cvt_to_wall1.y() + plane2_cvt_to_plane1.z() * wall2_cvt_to_wall1.z());
double err_d2 = (plane2_cvt_to_plane1.x() * _wall1->cx() + plane2_cvt_to_plane1.y() * _wall1->cy() + plane2_cvt_to_plane1.z() * _wall1->cz() + tmpd) / sqrt(plane2_cvt_to_plane1.x()*plane2_cvt_to_plane1.x() + plane2_cvt_to_plane1.y()*plane2_cvt_to_plane1.y() + plane2_cvt_to_plane1.z()*plane2_cvt_to_plane1.z());
//printf("%2.3f %2.3f %2.3f\n", err_angle, err_d1, err_d2);
Eigen::VectorXd err(3);// = predicted_plane.vector() - _measure.vector();
err(0) = standardRad(err_angle);
err(1) = 0;// abs(err_d1);
err(2) = fabs(err_d2);
return err;
}
void write(std::ostream &out) const {
Factor::write(out);
out << " " << _measure << " " << noise_to_string(_noise);
}
private:
Wall3d* _wall1;
Wall3d* _wall2;
};
} // namespace isam
| [
"youngji.brigid.kim@gmail.com"
] | youngji.brigid.kim@gmail.com |
64234dca87cdc115173958f640c332b8c24b619e | d09092dbe69c66e916d8dd76d677bc20776806fe | /.libs/puno_automatic_generated/inc/types/com/sun/star/awt/XMouseListener.hpp | c3495449258d432c60d891692743ec31b235eb65 | [] | no_license | GXhua/puno | 026859fcbc7a509aa34ee857a3e64e99a4568020 | e2f8e7d645efbde5132b588678a04f70f1ae2e00 | refs/heads/master | 2020-03-22T07:35:46.570037 | 2018-07-11T02:19:26 | 2018-07-11T02:19:26 | 139,710,567 | 0 | 0 | null | 2018-07-04T11:03:58 | 2018-07-04T11:03:58 | null | UTF-8 | C++ | false | false | 1,513 | hpp | #ifndef INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
#define INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
#include "sal/config.h"
#include "com/sun/star/awt/XMouseListener.hdl"
#include "com/sun/star/awt/MouseEvent.hpp"
#include "com/sun/star/lang/XEventListener.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Type.hxx"
#include "cppu/unotype.hxx"
namespace com { namespace sun { namespace star { namespace awt {
inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::awt::XMouseListener const *) {
static typelib_TypeDescriptionReference * the_type = 0;
if ( !the_type )
{
typelib_TypeDescriptionReference * aSuperTypes[1];
aSuperTypes[0] = ::cppu::UnoType< const ::css::uno::Reference< ::css::lang::XEventListener > >::get().getTypeLibType();
typelib_static_mi_interface_type_init( &the_type, "com.sun.star.awt.XMouseListener", 1, aSuperTypes );
}
return * reinterpret_cast< ::css::uno::Type * >( &the_type );
}
} } } }
SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::uno::Reference< ::css::awt::XMouseListener > const *) {
return ::cppu::UnoType< ::css::uno::Reference< ::css::awt::XMouseListener > >::get();
}
::css::uno::Type const & ::css::awt::XMouseListener::static_type(SAL_UNUSED_PARAMETER void *) {
return ::cppu::UnoType< ::css::awt::XMouseListener >::get();
}
#endif // INCLUDED_COM_SUN_STAR_AWT_XMOUSELISTENER_HPP
| [
"guoxinhua@10.10.12.142"
] | guoxinhua@10.10.12.142 |
f89bc743c3b956d4a2b8bc2764230d6ca0cfd4fa | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/AI/aiCastleLynelBattle.h | ff1ec332e671195a3d4d1e953a6d905629f7963b | [] | 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 | 530 | h | #pragma once
#include "Game/AI/AI/aiLynelBattle.h"
#include "KingSystem/ActorSystem/actAiAi.h"
namespace uking::ai {
class CastleLynelBattle : public LynelBattle {
SEAD_RTTI_OVERRIDE(CastleLynelBattle, LynelBattle)
public:
explicit CastleLynelBattle(const InitArg& arg);
~CastleLynelBattle() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
};
} // namespace uking::ai
| [
"leo@leolam.fr"
] | leo@leolam.fr |
d1ce39cc84771ff1a302fc27ee3523c8d97d47d0 | a0320ceb1fb8d62cef8729b9c7245a25543398b1 | /Queues/slidingWindowMax.cpp | b38a489db4739ab49783a325c22777115a857339 | [] | no_license | Utkal97/Data-Structures-and-Algorithms | d558d847b8651fb0f6bd89026cca6d900f496fe2 | 6eca25b8ec71a118cda35c85d150ef6ae01b3243 | refs/heads/master | 2022-04-13T10:32:34.909651 | 2020-04-04T12:04:00 | 2020-04-04T12:04:00 | 247,907,610 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | #include<bits/stdc++.h>
#include "DoubleEndedQueue.h"
using namespace std;
vector<int> slidingWindow(int A[], int len, int window_size) {
DoubleEndedQueue q;
for(int ind=0;ind<window_size;ind++) {
while(!q.empty() && A[ind] >= A[q.back()])
int popped = q.pop_back();
q.push_back(ind);
}
vector<int> answer;
answer.push_back(A[q.front()]);
for(int ind=window_size; ind<len; ind++) {
while(!q.empty() && ind-q.front() >= window_size)
q.pop_front();
while(!q.empty() && A[ind]>=A[q.back()])
q.pop_back();
q.push_back(ind);
answer.push_back(A[q.front()]);
}
return answer;
}
int main() {
int input[8] = {1,3,-1,-3,5,3,6,7};
int k = 3;
vector<int> ans = slidingWindow(input, 8, k);
for(int i=0; i<ans.size(); i++) {
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
} | [
"utkal.s15@iiits.in"
] | utkal.s15@iiits.in |
d4ff8968b5b5f272fd0da6da4fe70202a45b3096 | fa59cfedc5f57e881679fb0b5046da8c911229ca | /9465 스티커.cpp | 75007d318d104fd8d516d62b1630b47e91af4021 | [] | no_license | ju214425/algorithm | e2862df2c55490b97aefffaec99bb449a9db7e1f | db6d96eda3272a7faddaf11fdd02534d6231eafc | refs/heads/master | 2023-07-02T21:32:53.718629 | 2023-06-25T06:04:57 | 2023-06-25T06:04:57 | 193,701,850 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | cpp | // #include <iostream>
// using namespace std;
// int max(int num1, int num2){
// return num1 > num2 ? num1 : num2;
// }
// int main(){
// int numberOfTests;
// cin >> numberOfTests;
// int answerArr[numberOfTests + 1];
// for(int i = 1 ; i <= numberOfTests ; i++){
// int length;
// cin >> length;
// int arr[length + 1][2];
// int dp[length + 1];
// int temp = 0;
// for(int j = 0 ; j < 2 ; j++){
// for(int k = 1 ; k <= length ; k++){
// cin >> arr[k][j];
// }
// }
// dp[0] = 0;
// dp[1] = max(arr[1][0], arr[1][1]);
// dp[2] = max(arr[1][0] + arr[2][1], arr[1][1] + arr[2][0]);
// for(int j = 3 ; j <= length ; j++){
// int cur = max(arr[j][0], arr[j][1]);
// int check = 0;
// if(dp[j-1] == dp[j-2] + arr[j-1][0]){
// check = arr[j][1];
// }
// else{
// check = arr[j][0];
// }
// dp[j] = max(dp[j-2] + cur, dp[j-1] + check);
// }
// answerArr[i] = dp[length];
// }
// for(int i = 1 ; i <= numberOfTests ; i++){
// cout << answerArr[i] << endl;
// }
// return 0;
// }
#include <cstdio>
#include <algorithm>
using namespace std;
int arr[100005][2];
int dp[100005][2];
int main(){
int t, answer;
scanf("%d", &t);
for(int i = 0 ; i < t ; i++){
int n;
scanf("%d", &n);
for(int j = 0 ; j < n ; j++){
scanf("%d", &arr[j][0]);
}
for(int j = 0 ; j < n ; j++){
scanf("%d", &arr[j][1]);
}
dp[0][0] = arr[0][0];
dp[0][1] = arr[0][1];
dp[1][0] = arr[0][1] + arr[1][0];
dp[1][1] = arr[0][0] + arr[1][1];
for(int j = 2 ; j < n ; j++){
dp[j][0] = arr[j][0] + max(dp[j-1][1], dp[j-2][1]);
dp[j][1] = arr[j][1] + max(dp[j-1][0], dp[j-2][0]);
}
answer = max(dp[n-1][0], dp[n-1][1]);
printf("%d\n", answer);
}
} | [
"2016025841@hanyang.ac.kr"
] | 2016025841@hanyang.ac.kr |
d2d465366486abacf468cc9740266a07717f3043 | 1c1b09bba3a951df1b9dd24debc1d2b840477b89 | /FIT2096_Assignment2b_WillStojic/Player.cpp | 9ff1553e68656cef72b74bc39e4d442e041b1aca | [] | no_license | WillStojic/FIT2096_Assignment2b | 8e0e73dd98d808edefec526f5c5201cea46e40ce | 10f86d919d6cf44d318effaf1cef588b4f27f8a2 | refs/heads/master | 2020-03-17T00:37:11.510144 | 2018-05-28T19:06:30 | 2018-05-28T19:06:30 | 133,123,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,096 | cpp | #include "Player.h"
#include "MathsHelper.h"
Player::Player(InputController* input)
: PhysicsObject(Vector3(MathsHelper::RandomRange(1, 48), 0, MathsHelper::RandomRange(1, 48)))
{
m_input = input;
// The player is much stronger than any monster on the board
m_health = 200.0f;
m_gems = 0;
//starting ammo
m_ammo = 8;
m_score = 0;
m_monstersDefeated = 0;
//amount of frames before the player can fire another bullet.
m_fireRate = 15;
//movement attributes
m_moveSpeed = 5.0f;
m_jumpStrength = 0.3f;
//player has no mesh, therefore bounds are manually set, mesh is kept relatively thin, so the player can dodge bullets more easily
m_boundingBox = new CBoundingBox(m_position + Vector3(-0.15f, 0.0f, -0.15f), m_position + Vector3(0.15f, 1.8f, 0.15f));
}
Player::~Player() {}
void Player::Update(float timestep, FirstPersonCamera* &camera, BulletFactory* &bulletFactory)
{
m_position = Vector3::Lerp(m_position, m_targetPosition, timestep * m_moveSpeed);
//disables player input, if health is below 0
if (m_health <= 0)
{
//player falls on their back when dead.
camera->SetPosition(m_position + Vector3(0.0f, 0.3f, 0.0f));
}
else
{
//attaches camera to player
camera->SetPosition(m_position + Vector3(0.0f, 1.6f, 0.0f));
//save on function calls by intialising local variables
float m_heading = camera->GetHeading();
float m_pitch = camera->GetPitch();
// Accumulate change in mouse position
m_heading += m_input->GetMouseDeltaX() * camera->GetRotationSpeed() * timestep;
m_pitch += m_input->GetMouseDeltaY() * camera->GetRotationSpeed() * timestep;
// Limit how far the player can look down and up
m_pitch = MathsHelper::Clamp(m_pitch, ToRadians(-80.0f), ToRadians(80.0f));
camera->SetHeading(m_heading);
camera->SetPitch(m_pitch);
// Wrap heading and pitch up in a matrix so we can transform our look at vector
// Heading is controlled by MouseX (horizontal movement) but it is a rotation around Y
// Pitch controlled by MouseY (vertical movement) but it is a rotation around X
Matrix heading = Matrix::CreateRotationY(m_heading);
Matrix pitch = Matrix::CreateRotationX(m_pitch);
// Transform a world right vector from world space into local space
Vector3 localRight = Vector3::TransformNormal(Vector3(1, 0, 0), heading);
// Essentially our local forward vector but always parallel with the ground
// Remember a cross product gives us a vector perpendicular to the two input vectors
Vector3 localForwardXZ = localRight.Cross(Vector3(0, 1, 0));
// We're going to need this a lot. Store it locally here to save on our function calls
Vector3 currentPos = camera->GetPosition();
Vector3 translation = m_position;
//moves the player's position
if (m_input->GetKeyHold('W'))
{
translation += localForwardXZ;
}
if (m_input->GetKeyHold('S'))
{
translation -= localForwardXZ;
}
if (m_input->GetKeyHold('A'))
{
translation -= localRight;
}
if (m_input->GetKeyHold('D'))
{
translation += localRight;
}
if (m_input->GetKeyHold(VK_SHIFT))
{
m_moveSpeed = 10;
}
else
m_moveSpeed = 5;
if (m_input->GetKeyDown(VK_SPACE) && m_position.y < 0.1)
{
this->Jump(m_jumpStrength);
}
m_targetPosition = translation;
// Combine pitch and heading into one matrix for convenience
Matrix lookAtRotation = pitch * heading;
// Transform a world forward vector into local space (take pitch and heading into account)
Vector3 lookAt = Vector3::TransformNormal(Vector3(0, 0, 1), lookAtRotation);
m_headOffPoint = (lookAt * 10) + currentPos;
//handles shooting input
++m_shootTicker;
if (m_input->GetMouseDown(0) && m_shootTicker > m_fireRate && m_ammo != 0)
{
//creates bullet trajectory
Vector3 aim = lookAt * 50;
aim += currentPos;
Vector3 offset = Vector3::TransformNormal(Vector3(0, 0, 0.5), lookAtRotation) + currentPos;
//spawns bullet
bulletFactory->InitialiseBullet(offset, aim, BulletType::PLAYER);
//reduces ammo after each shot
--m_ammo;
//resets shoot ticker, thus meaning the player will have to wait a set amount of frames to shoot again
m_shootTicker = 0;
}
// At this point, our look-at vector is still relative to the origin
// Add our position to it so it originates from the camera and points slightly in front of it
// Remember the look-at vector needs to describe a point in the world relative to the origin
lookAt += currentPos;
//orient player's y rotation to camera
m_rotY = lookAt.y;
// Use parent's mutators so isDirty flags get flipped
camera->SetLookAt(lookAt);
camera->SetPosition(currentPos);
m_boundingBox->SetMin(m_position + Vector3(-0.05f, 1.1f, -0.05f));
m_boundingBox->SetMax(m_position + Vector3(0.05f, 1.8f, 0.05f));
PhysicsObject::Update(timestep);
}
}
//simple adjustment to player variable once item is collided with.
void Player::PickupItem(ItemType itemType)
{
if (itemType == ItemType::HEALTH)
m_health += 10;
else if (itemType == ItemType::AMMO)
m_ammo += 4;
else if (itemType == ItemType::GEM)
{
++m_gems;
m_score += 40;
}
}
| [
"wsto0001@student.monash.edu"
] | wsto0001@student.monash.edu |
738e66fc4c9d586f015fa82e0b35213033daead3 | 9cf25c7877689dda2918a9c8f3a07b16f3549d9d | /Engine/Audio/AudioSystem.h | 49c8618800933de69f04b3eedddbbd78d3023c92 | [] | no_license | spo0kyman/GAT150 | e6b9befcde1eb3124e562884e94e5cb5727b3356 | ced74e960215ce5b0265636062195cda3e5ff9db | refs/heads/master | 2022-12-10T19:00:32.010359 | 2020-09-02T01:33:57 | 2020-09-02T01:33:57 | 284,793,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | h | #pragma once
#include "Core/System.h"
#include "fmod.hpp"
namespace nc {
class AudioSystem : public System {
public:
virtual bool Startup() override;
virtual void Shutdown() override;
virtual void Update() override;
friend class Sound;
protected:
FMOD::System* m_system{ nullptr };
};
} | [
"61479588+spo0kyman@users.noreply.github.com"
] | 61479588+spo0kyman@users.noreply.github.com |
5f281b56ca2a8fea8425a2da4aecbc23a01262b6 | d7fe5077a5694265c4bab15b7acbc8a4424ddd89 | /naive/src/Analysis/NoPredBlocks.cpp | 53309420f754752b92a1003d6f3468476e136741 | [] | no_license | fengjixuchui/acsac17wip | 56cfcea51e30d36f2f5fe5b0ef511ba2ae4ce83f | 5b93e78b96978977a485149c32594d85b1ae329d | refs/heads/master | 2023-03-16T19:33:31.606714 | 2020-11-02T16:29:10 | 2020-11-02T16:29:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | cpp | #include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#include "NoPredBlocks.h"
void
NoPredBlocks::getAnalysisUsage(AnalysisUsage &AU) const
{
AU.setPreservesCFG();
}
bool
NoPredBlocks::runOnModule(Module &M)
{
unsigned long long total_blocks = 0;
unsigned long long blocks_without_predecessors = 0;
unsigned long long blocks_without_successors = 0;
unsigned long long island_blocks = 0;
for (Function &F : M) {
bool entryBlock = true;
for (BasicBlock &B : F) {
++total_blocks;
bool hasSuccessor = false;
if (succ_begin(&B) != succ_begin(&B)) {
hasSuccessor = true;
} else {
++blocks_without_successors;
}
bool hasPredecessor = false;
if (pred_begin(&B) != pred_end(&B)) {
hasPredecessor = true;
} else {
++blocks_without_predecessors;
}
if (hasSuccessor == false && hasPredecessor == false) {
if (entryBlock == false) {
++island_blocks;
}
}
entryBlock = false;
}
}
errs() << "Total blocks: " << total_blocks << "\n";
errs() << "Island blocks: " << island_blocks << "\n";
errs() << "Blocks w/o preds: " << blocks_without_predecessors << "\n";
errs() << "Blocks w/o successors: " << blocks_without_successors << "\n";
return true;
}
char NoPredBlocks::ID = 0;
static RegisterPass<NoPredBlocks> XX("no-pred-blocks", "");
| [
"areiter@veracode.com"
] | areiter@veracode.com |
1f7ec6eb173e5aa4aeac2048080cdbd639d5296b | 4a7f31f146b1397455887c7e7ed30cdd5982b2bd | /includes/strategy/create.hpp | 6975326c8e416e7f2b1e74cb378cc919dec749f0 | [] | no_license | Disabled77/metaprogramming | 5ac73c2b4bc5e7034a16fcec133a1cdca2ae1ed2 | 010c9ae991b5bea98d5168fd3eddb93c0a7f6164 | refs/heads/master | 2020-03-29T05:58:43.258986 | 2017-06-29T13:19:22 | 2017-06-29T13:19:22 | 94,656,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | hpp | #pragma once
namespace strategy {
template<class T>
struct NewCreate{
template<class... Args>
static T* create(Args... args){
return new T { args... };
}
};
template<class T>
struct MallocCreate{
template<class... Args>
static T* create(Args... args){
T* object = reinterpret_cast<T*>(malloc(sizeof(T)));
new (object) T { args... };
return object;
}
};
template<class T>
struct PrototypCreate{
PrototypCreate(T* (functionPrototype)(T) = nullptr):
functionPrototype_ { functionPrototype }
{}
void setPrototype(T* (functionPrototype)(T)){
functionPrototype_ = functionPrototype;
}
template<class... Args>
T* create(T value) const {
T* variable = functionPrototype_(value);
return variable;
}
T* (*functionPrototype_)(T);
};
} // namespace strategy
| [
"dmitry.belous89@gmail.com"
] | dmitry.belous89@gmail.com |
f1aefb530612b66eb0bf6dbf1f17bc073d75cad7 | b2c2de30aec8f6cd84162f9fdf3ab23614b6d963 | /opencv/sources/modules/core/test/test_rand.cpp | 9cb683aa55220d714b8b46a32b3ed069f3830cb2 | [
"BSD-3-Clause"
] | permissive | ASeoighe/5thYearProject | aeaecde5eb289bcc09f570cb8815fcda2b2367a6 | 772aff2b30f04261691171a1039c417c386785c4 | refs/heads/master | 2021-09-14T11:41:11.701841 | 2018-04-24T22:30:41 | 2018-04-24T22:30:41 | 112,224,159 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,981 | cpp | #include "test_precomp.hpp"
using namespace cv;
using namespace std;
class Core_RandTest : public cvtest::BaseTest
{
public:
Core_RandTest();
protected:
void run(int);
bool check_pdf(const Mat& hist, double scale, int dist_type,
double& refval, double& realval);
};
Core_RandTest::Core_RandTest()
{
}
static double chi2_p95(int n)
{
static float chi2_tab95[] = {
3.841f, 5.991f, 7.815f, 9.488f, 11.07f, 12.59f, 14.07f, 15.51f,
16.92f, 18.31f, 19.68f, 21.03f, 21.03f, 22.36f, 23.69f, 25.00f,
26.30f, 27.59f, 28.87f, 30.14f, 31.41f, 32.67f, 33.92f, 35.17f,
36.42f, 37.65f, 38.89f, 40.11f, 41.34f, 42.56f, 43.77f };
static const double xp = 1.64;
CV_Assert(n >= 1);
if( n <= 30 )
return chi2_tab95[n-1];
return n + sqrt((double)2*n)*xp + 0.6666666666666*(xp*xp - 1);
}
bool Core_RandTest::check_pdf(const Mat& hist, double scale,
int dist_type, double& refval, double& realval)
{
Mat hist0(hist.size(), CV_32F);
const int* H = (const int*)hist.data;
float* H0 = ((float*)hist0.data);
int i, hsz = hist.cols;
double sum = 0;
for( i = 0; i < hsz; i++ )
sum += H[i];
CV_Assert( fabs(1./sum - scale) < FLT_EPSILON );
if( dist_type == CV_RAND_UNI )
{
float scale0 = (float)(1./hsz);
for( i = 0; i < hsz; i++ )
H0[i] = scale0;
}
else
{
double sum2 = 0, r = (hsz-1.)/2;
double alpha = 2*sqrt(2.)/r, beta = -alpha*r;
for( i = 0; i < hsz; i++ )
{
double x = i*alpha + beta;
H0[i] = (float)exp(-x*x);
sum2 += H0[i];
}
sum2 = 1./sum2;
for( i = 0; i < hsz; i++ )
H0[i] = (float)(H0[i]*sum2);
}
double chi2 = 0;
for( i = 0; i < hsz; i++ )
{
double a = H0[i];
double b = H[i]*scale;
if( a > DBL_EPSILON )
chi2 += (a - b)*(a - b)/(a + b);
}
realval = chi2;
double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0));
refval = chi2_pval*0.01;
return realval <= refval;
}
void Core_RandTest::run( int )
{
static int _ranges[][2] =
{{ 0, 256 }, { -128, 128 }, { 0, 65536 }, { -32768, 32768 },
{ -1000000, 1000000 }, { -1000, 1000 }, { -1000, 1000 }};
const int MAX_SDIM = 10;
const int N = 2000000;
const int maxSlice = 1000;
const int MAX_HIST_SIZE = 1000;
int progress = 0;
RNG& rng = ts->get_rng();
RNG tested_rng = theRNG();
test_case_count = 200;
for( int idx = 0; idx < test_case_count; idx++ )
{
progress = update_progress( progress, idx, test_case_count, 0 );
ts->update_context( this, idx, false );
int depth = cvtest::randInt(rng) % (CV_64F+1);
int c, cn = (cvtest::randInt(rng) % 4) + 1;
int type = CV_MAKETYPE(depth, cn);
int dist_type = cvtest::randInt(rng) % (CV_RAND_NORMAL+1);
int i, k, SZ = N/cn;
Scalar A, B;
double eps = 1.e-4;
if (depth == CV_64F)
eps = 1.e-7;
bool do_sphere_test = dist_type == CV_RAND_UNI;
Mat arr[2], hist[4];
int W[] = {0,0,0,0};
arr[0].create(1, SZ, type);
arr[1].create(1, SZ, type);
bool fast_algo = dist_type == CV_RAND_UNI && depth < CV_32F;
for( c = 0; c < cn; c++ )
{
int a, b, hsz;
if( dist_type == CV_RAND_UNI )
{
a = (int)(cvtest::randInt(rng) % (_ranges[depth][1] -
_ranges[depth][0])) + _ranges[depth][0];
do
{
b = (int)(cvtest::randInt(rng) % (_ranges[depth][1] -
_ranges[depth][0])) + _ranges[depth][0];
}
while( abs(a-b) <= 1 );
if( a > b )
std::swap(a, b);
unsigned r = (unsigned)(b - a);
fast_algo = fast_algo && r <= 256 && (r & (r-1)) == 0;
hsz = min((unsigned)(b - a), (unsigned)MAX_HIST_SIZE);
do_sphere_test = do_sphere_test && b - a >= 100;
}
else
{
int vrange = _ranges[depth][1] - _ranges[depth][0];
int meanrange = vrange/16;
int mindiv = MAX(vrange/20, 5);
int maxdiv = MIN(vrange/8, 10000);
a = cvtest::randInt(rng) % meanrange - meanrange/2 +
(_ranges[depth][0] + _ranges[depth][1])/2;
b = cvtest::randInt(rng) % (maxdiv - mindiv) + mindiv;
hsz = min((unsigned)b*9, (unsigned)MAX_HIST_SIZE);
}
A[c] = a;
B[c] = b;
hist[c].create(1, hsz, CV_32S);
}
cv::RNG saved_rng = tested_rng;
int maxk = fast_algo ? 0 : 1;
for( k = 0; k <= maxk; k++ )
{
tested_rng = saved_rng;
int sz = 0, dsz = 0, slice;
for( slice = 0; slice < maxSlice; slice++, sz += dsz )
{
dsz = slice+1 < maxSlice ? (int)(cvtest::randInt(rng) % (SZ - sz + 1)) : SZ - sz;
Mat aslice = arr[k].colRange(sz, sz + dsz);
tested_rng.fill(aslice, dist_type, A, B);
}
}
if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) > eps)
{
ts->printf( cvtest::TS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" );
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
for( c = 0; c < cn; c++ )
{
const uchar* data = arr[0].data;
int* H = hist[c].ptr<int>();
int HSZ = hist[c].cols;
double minVal = dist_type == CV_RAND_UNI ? A[c] : A[c] - B[c]*4;
double maxVal = dist_type == CV_RAND_UNI ? B[c] : A[c] + B[c]*4;
double scale = HSZ/(maxVal - minVal);
double delta = -minVal*scale;
hist[c] = Scalar::all(0);
for( i = c; i < SZ*cn; i += cn )
{
double val = depth == CV_8U ? ((const uchar*)data)[i] :
depth == CV_8S ? ((const schar*)data)[i] :
depth == CV_16U ? ((const ushort*)data)[i] :
depth == CV_16S ? ((const short*)data)[i] :
depth == CV_32S ? ((const int*)data)[i] :
depth == CV_32F ? ((const float*)data)[i] :
((const double*)data)[i];
int ival = cvFloor(val*scale + delta);
if( (unsigned)ival < (unsigned)HSZ )
{
H[ival]++;
W[c]++;
}
else if( dist_type == CV_RAND_UNI )
{
if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) )
{
H[ival < 0 ? 0 : HSZ-1]++;
W[c]++;
}
else
{
putchar('^');
}
}
}
if( dist_type == CV_RAND_UNI && W[c] != SZ )
{
ts->printf( cvtest::TS::LOG, "Uniform RNG gave values out of the range [%g,%g) on channel %d/%d\n",
A[c], B[c], c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90)
{
ts->printf( cvtest::TS::LOG, "Normal RNG gave too many values out of the range (%g+4*%g,%g+4*%g) on channel %d/%d\n",
A[c], B[c], A[c], B[c], c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
double refval = 0, realval = 0;
if( !check_pdf(hist[c], 1./W[c], dist_type, refval, realval) )
{
ts->printf( cvtest::TS::LOG, "RNG failed Chi-square test "
"(got %g vs probable maximum %g) on channel %d/%d\n",
realval, refval, c, cn);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
}
// Monte-Carlo test. Compute volume of SDIM-dimensional sphere
// inscribed in [-1,1]^SDIM cube.
if( do_sphere_test )
{
int SDIM = cvtest::randInt(rng) % (MAX_SDIM-1) + 2;
int N0 = (SZ*cn/SDIM), n = 0;
double r2 = 0;
const uchar* data = arr[0].data;
double scale[4], delta[4];
for( c = 0; c < cn; c++ )
{
scale[c] = 2./(B[c] - A[c]);
delta[c] = -A[c]*scale[c] - 1;
}
for( i = k = c = 0; i <= SZ*cn - SDIM; i++, k++, c++ )
{
double val = depth == CV_8U ? ((const uchar*)data)[i] :
depth == CV_8S ? ((const schar*)data)[i] :
depth == CV_16U ? ((const ushort*)data)[i] :
depth == CV_16S ? ((const short*)data)[i] :
depth == CV_32S ? ((const int*)data)[i] :
depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i];
c &= c < cn ? -1 : 0;
val = val*scale[c] + delta[c];
r2 += val*val;
if( k == SDIM-1 )
{
n += r2 <= 1;
r2 = 0;
k = -1;
}
}
double V = ((double)n/N0)*(1 << SDIM);
// the theoretically computed volume
int sdim = SDIM % 2;
double V0 = sdim + 1;
for( sdim += 2; sdim <= SDIM; sdim += 2 )
V0 *= 2*CV_PI/sdim;
if( fabs(V - V0) > 0.3*fabs(V0) )
{
ts->printf( cvtest::TS::LOG, "RNG failed %d-dim sphere volume test (got %g instead of %g)\n",
SDIM, V, V0);
ts->printf( cvtest::TS::LOG, "depth = %d, N0 = %d\n", depth, N0);
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
}
}
}
TEST(Core_Rand, quality) { Core_RandTest test; test.safe_run(); }
class Core_RandRangeTest : public cvtest::BaseTest
{
public:
Core_RandRangeTest() {}
~Core_RandRangeTest() {}
protected:
void run(int)
{
Mat a(Size(1280, 720), CV_8U, Scalar(20));
Mat af(Size(1280, 720), CV_32F, Scalar(20));
theRNG().fill(a, RNG::UNIFORM, -DBL_MAX, DBL_MAX);
theRNG().fill(af, RNG::UNIFORM, -DBL_MAX, DBL_MAX);
int n0 = 0, n255 = 0, nx = 0;
int nfmin = 0, nfmax = 0, nfx = 0;
for( int i = 0; i < a.rows; i++ )
for( int j = 0; j < a.cols; j++ )
{
int v = a.at<uchar>(i,j);
double vf = af.at<float>(i,j);
if( v == 0 ) n0++;
else if( v == 255 ) n255++;
else nx++;
if( vf < FLT_MAX*-0.999f ) nfmin++;
else if( vf > FLT_MAX*0.999f ) nfmax++;
else nfx++;
}
CV_Assert( n0 > nx*2 && n255 > nx*2 );
CV_Assert( nfmin > nfx*2 && nfmax > nfx*2 );
}
};
TEST(Core_Rand, range) { Core_RandRangeTest test; test.safe_run(); }
TEST(Core_RNG_MT19937, regression)
{
cv::RNG_MT19937 rng;
int actual[61] = {0, };
const size_t length = (sizeof(actual) / sizeof(actual[0]));
for (int i = 0; i < 10000; ++i )
{
actual[(unsigned)(rng.next() ^ i) % length]++;
}
int expected[length] = {
177, 158, 180, 177, 160, 179, 143, 162,
177, 144, 170, 174, 165, 168, 168, 156,
177, 157, 159, 169, 177, 182, 166, 154,
144, 180, 168, 152, 170, 187, 160, 145,
139, 164, 157, 179, 148, 183, 159, 160,
196, 184, 149, 142, 162, 148, 163, 152,
168, 173, 160, 181, 172, 181, 155, 153,
158, 171, 138, 150, 150 };
for (size_t i = 0; i < length; ++i)
{
ASSERT_EQ(expected[i], actual[i]);
}
}
<<<<<<< HEAD
=======
TEST(Core_Rand, Regression_Stack_Corruption)
{
int bufsz = 128; //enough for 14 doubles
AutoBuffer<uchar> buffer(bufsz);
size_t offset = 0;
cv::Mat_<cv::Point2d> x(2, 3, (cv::Point2d*)(buffer+offset)); offset += x.total()*x.elemSize();
double& param1 = *(double*)(buffer+offset); offset += sizeof(double);
double& param2 = *(double*)(buffer+offset); offset += sizeof(double);
param1 = -9; param2 = 2;
cv::theRNG().fill(x, cv::RNG::NORMAL, param1, param2);
ASSERT_EQ(param1, -9);
ASSERT_EQ(param2, 2);
}
>>>>>>> 4a5a6cfc1ba26f73cbd6c6fcaf561ca6dbced81d
| [
"aaronjoyce2@gmail.com"
] | aaronjoyce2@gmail.com |
c81101c7bcbb78273876a76b1be5dba551b25a7f | cb796fe6cdd2b58782cd5bbd6b7bd29d4ea6a298 | /f1000/doc/fwsdk/IQA_LIB_uBlaze_rev1_5/include/hxx/ADC1_CH13.hxx | 8e11b0d2e4dc9c333947d90c46e33aa7565b76f6 | [] | no_license | IQAnalog/iqa_external | b0098d5102d8d7b462993fce081544bd2db00e52 | 13e2c782699f962fb19de9987933cbef66b47ce1 | refs/heads/master | 2023-03-23T13:46:16.550707 | 2021-03-24T18:03:22 | 2021-03-24T18:03:22 | 350,906,829 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,857 | hxx | //*******************************************************************************
// __ __ *
// / \/ \ *
// \ \ *
// I Q - A N A L O G *
// \ \ IQ-Analog Corp *
// \__/\__/ www.iqanalog.com *
// *
//------------------------------------------------------------------------------*
// *
// Copyright (C) 2018-2019 IQ-Analog Corp. All rights reserved. *
// *
//------------------------------------------------------------------------------*
// IQ-Analog CONFIDENTIAL *
//------------------------------------------------------------------------------*
// *
// This file is released with "Government Purpose Rights" as defined *
// in DFARS SUBPART 227.71, clause 252.227-7013. *
// *
//*******************************************************************************
// Generated by RMM 3.3
// IQ-Analog Corp. 2013-2018.
#ifndef __ADC1_CH13_HXX__
#define __ADC1_CH13_HXX__
#define ADC1_CH13_TDC_LUT00 (REG_ADC1_CH13+0x0)
#define ADC1_CH13_TDC_LUT01 (REG_ADC1_CH13+0x4)
#define ADC1_CH13_TDC_LUT02 (REG_ADC1_CH13+0x8)
#define ADC1_CH13_TDC_LUT03 (REG_ADC1_CH13+0xc)
#define ADC1_CH13_TDC_LUT04 (REG_ADC1_CH13+0x10)
#define ADC1_CH13_TDC_LUT05 (REG_ADC1_CH13+0x14)
#define ADC1_CH13_TDC_LUT06 (REG_ADC1_CH13+0x18)
#define ADC1_CH13_TDC_LUT07 (REG_ADC1_CH13+0x1c)
#define ADC1_CH13_TDC_LUT08 (REG_ADC1_CH13+0x20)
#define ADC1_CH13_TDC_BUS_ACCESS (REG_ADC1_CH13+0x24)
#define ADC1_CH13_TDC_OFFSET_AND_GAIN (REG_ADC1_CH13+0x28)
#define ADC1_CH13_TDC_TI_CAL (REG_ADC1_CH13+0x2c)
#define ADC1_CH13_TDC_MISC (REG_ADC1_CH13+0x30)
#define ADC1_CH13_TDC_CAL (REG_ADC1_CH13+0x34)
#define ADC1_CH13_TDC_DITHER (REG_ADC1_CH13+0x38)
#define ADC1_CH13_TDC_BIT_WEIGHTS0 (REG_ADC1_CH13+0x3c)
#define ADC1_CH13_TDC_BIT_WEIGHTS1 (REG_ADC1_CH13+0x40)
#define ADC1_CH13_TDC_STATUS (REG_ADC1_CH13+0x44)
#endif /* __ADC1_CH13_HXX__ */
| [
"rudyl@iqanalog.com"
] | rudyl@iqanalog.com |
0a5682a2d63acfb8051b3aac6eda419494723205 | d970f0f7275b7fb13bf315de797d5e38a06aa655 | /include/sico/frames/object_local.hpp | 4bfc9ec3d3ab56847a51a14888ea3565280f819b | [
"MIT"
] | permissive | fjacomme/sico | d5e4ece8a8600990135873900fd9cf4eada910f1 | 501b8f08313e4394ac8585167b74374e2ae3da09 | refs/heads/master | 2023-01-10T22:21:25.653182 | 2020-11-10T13:45:01 | 2020-11-10T13:45:01 | 264,876,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,616 | hpp | #pragma once
#include "sico/conversions/enu_local.hpp"
#include "sico/conversions/local_local.hpp"
#include "sico/frames/local_tangent.hpp"
#include "sico/types/orientations.hpp"
namespace sico {
/// Local Frame for an object positioned in an ENU frame
class frame_object {
protected:
frame_enu frame;
quat_enu quat;
public:
frame_object(pos_lla const& ref, ori_enu const& ori)
: frame(ref)
, quat(ori)
{
}
void set_ref(pos_lla const& ref, ori_enu const& ori)
{
frame.set_ref(ref);
quat = quat_enu(ori);
}
pos_local to_local(pos_lla const& p) const { return to_local(frame.to_enu(p)); }
pos_lla to_lla(pos_local const& p) const { return frame.to_lla(to_enu(p)); }
pos_local to_local(pos_enu const& p) const { return sico::to_local(p, quat); }
pos_enu to_enu(pos_local const& p) const { return sico::to_enu(p, quat); }
};
/// Local frame for an object on another object
class frame_child_object {
protected:
pos_local ref;
quat_local quat;
public:
frame_child_object(pos_local const& child_pos, ori_local const& ori)
: ref(child_pos)
, quat(ori)
{
}
void set_ref(pos_local const& child_pos, ori_local const& ori)
{
ref = child_pos;
quat = quat_local(ori);
}
pos_local to_child(pos_local const& p) const { return sico::to_child(ref, quat, p); }
pos_local to_parent(pos_local const& p) const { return sico::to_parent(ref, quat, p); }
};
} // namespace sico
//
// Simulation-Coordinates library
// Author F.Jacomme
// MIT Licensed
// | [
"florian@jacomme.fr"
] | florian@jacomme.fr |
f17a18611b4aafb084acbedfb8133a625c2f4030 | 5506803b1e48b519a748510fac5be2047319a333 | /example/oglplus/025_reflected_torus.cpp | 8975c29e862fd514d99c66424a8b9bcf671b8782 | [
"BSL-1.0"
] | permissive | James-Z/oglplus | dc5ed546094c891aeabffcba2db45cfc78e08ef9 | a43867907d5d132ba253178232e8852f51c83e6b | refs/heads/master | 2020-05-29T11:08:14.386144 | 2014-02-13T18:33:03 | 2014-02-13T18:33:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,882 | cpp | /**
* @example oglplus/025_reflected_torus.cpp
* @brief Shows how to draw a torus reflected in a horizontal plane
*
* @oglplus_screenshot{025_reflected_torus}
*
* Copyright 2008-2013 Matus Chochlik. 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)
*
* @oglplus_example_uses_cxx11{FUNCTION_TEMPLATE_DEFAULT_ARGS}
*
* @oglplus_example_uses_gl{GL_VERSION_3_3}
* @oglplus_example_uses_gl{GL_ARB_separate_shader_objects;GL_EXT_direct_state_access}
*/
#include <oglplus/gl.hpp>
#include <oglplus/all.hpp>
#include <oglplus/opt/smart_enums.hpp>
#include <oglplus/shapes/twisted_torus.hpp>
#include <cmath>
#include "example.hpp"
namespace oglplus {
class ReflectionExample : public Example
{
private:
// the torus vertex attribute builder
shapes::TwistedTorus make_torus;
// here will be stored the indices used by the drawing instructions
shapes::TwistedTorus::IndexArray torus_indices;
// the instructions for drawing the torus
shapes::DrawingInstructions torus_instr;
// wrapper around the current OpenGL context
Context gl;
// Vertex shaders for the normally rendered and the reflected objects
VertexShader vs_norm;
VertexShader vs_refl;
// Geometry shader for the reflected objects
GeometryShader gs_refl;
// Fragment shader
FragmentShader fs;
// Programs
Program prog_norm;
Program prog_refl;
// A vertex array object for the torus
VertexArray torus;
// A vertex array object for the reflective plane
VertexArray plane;
// VBOs for the torus' vertices and normals
Buffer torus_verts, torus_normals;
// VBOs for the plane's vertices and normals
Buffer plane_verts, plane_normals;
public:
ReflectionExample(void)
: torus_indices(make_torus.Indices())
, torus_instr(make_torus.Instructions())
, vs_norm(ObjectDesc("Vertex-Normal"))
, vs_refl(ObjectDesc("Vertex-Reflection"))
, gs_refl(ObjectDesc("Geometry-Reflection"))
{
namespace se = oglplus::smart_enums;
// Set the normal object vertex shader source
vs_norm.Source(
"#version 330\n"
"in vec4 Position;"
"in vec3 Normal;"
"out vec3 geomColor;"
"out vec3 geomNormal;"
"out vec3 geomLight;"
"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
"uniform vec3 LightPos;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" geomColor = Normal;"
" geomNormal = mat3(ModelMatrix)*Normal;"
" geomLight = LightPos-gl_Position.xyz;"
" gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
"}"
);
// compile it
vs_norm.Compile();
// Set the reflected object vertex shader source
// which just passes data to the geometry shader
vs_refl.Source(
"#version 330\n"
"in vec4 Position;"
"in vec3 Normal;"
"out vec3 vertNormal;"
"void main(void)"
"{"
" gl_Position = Position;"
" vertNormal = Normal;"
"}"
);
// compile it
vs_refl.Compile();
// Set the reflected object geometry shader source
// This shader creates a reflection matrix that
// relies on the fact that the reflection is going
// to be done by the y-plane
gs_refl.Source(
"#version 330\n"
"layout(triangles) in;"
"layout(triangle_strip, max_vertices = 6) out;"
"in vec3 vertNormal[];"
"uniform mat4 ProjectionMatrix;"
"uniform mat4 CameraMatrix;"
"uniform mat4 ModelMatrix;"
"out vec3 geomColor;"
"out vec3 geomNormal;"
"out vec3 geomLight;"
"uniform vec3 LightPos;"
"mat4 ReflectionMatrix = mat4("
" 1.0, 0.0, 0.0, 0.0,"
" 0.0,-1.0, 0.0, 0.0,"
" 0.0, 0.0, 1.0, 0.0,"
" 0.0, 0.0, 0.0, 1.0 "
");"
"void main(void)"
"{"
" for(int v=0; v!=gl_in.length(); ++v)"
" {"
" vec4 Position = gl_in[v].gl_Position;"
" gl_Position = ModelMatrix * Position;"
" geomColor = vertNormal[v];"
" geomNormal = mat3(ModelMatrix)*vertNormal[v];"
" geomLight = LightPos - gl_Position.xyz;"
" gl_Position = "
" ProjectionMatrix *"
" CameraMatrix *"
" ReflectionMatrix *"
" gl_Position;"
" EmitVertex();"
" }"
" EndPrimitive();"
"}"
);
// compile it
gs_refl.Compile();
// set the fragment shader source
fs.Source(
"#version 330\n"
"in vec3 geomColor;"
"in vec3 geomNormal;"
"in vec3 geomLight;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float l = length(geomLight);"
" float d = l > 0.0 ? dot("
" geomNormal, "
" normalize(geomLight)"
" ) / l : 0.0;"
" float i = 0.2 + max(d, 0.0) * 2.0;"
" fragColor = vec4(abs(geomNormal)*i, 1.0);"
"}"
);
// compile it
fs.Compile();
// attach the shaders to the normal rendering program
prog_norm.AttachShader(vs_norm);
prog_norm.AttachShader(fs);
// link it
prog_norm.Link();
// attach the shaders to the reflection rendering program
prog_refl.AttachShader(vs_refl);
prog_refl.AttachShader(gs_refl);
prog_refl.AttachShader(fs);
// link it
prog_refl.Link();
// bind the VAO for the torus
torus.Bind();
// bind the VBO for the torus vertices
torus_verts.Bind(se::Array());
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Positions(data);
// upload the data
Buffer::Data(se::Array(), data);
// setup the vertex attribs array for the vertices
typedef VertexAttribArray VAA;
VertexAttribSlot
loc_norm = VAA::GetLocation(prog_norm, "Position"),
loc_refl = VAA::GetLocation(prog_refl, "Position");
assert(loc_norm == loc_refl);
VertexAttribArray attr(loc_norm);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the torus normals
torus_normals.Bind(se::Array());
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Normals(data);
// upload the data
Buffer::Data(se::Array(), data);
// setup the vertex attribs array for the normals
typedef VertexAttribArray VAA;
VertexAttribSlot
loc_norm = VAA::GetLocation(prog_norm, "Normal"),
loc_refl = VAA::GetLocation(prog_refl, "Normal");
assert(loc_norm == loc_refl);
VertexAttribArray attr(loc_norm);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VAO for the plane
plane.Bind();
// bind the VBO for the plane vertices
plane_verts.Bind(se::Array());
{
GLfloat data[4*3] = {
-2.0f, 0.0f, 2.0f,
-2.0f, 0.0f, -2.0f,
2.0f, 0.0f, 2.0f,
2.0f, 0.0f, -2.0f
};
// upload the data
Buffer::Data(se::Array(), 4*3, data);
// setup the vertex attribs array for the vertices
prog_norm.Use();
VertexAttribArray attr(prog_norm, "Position");
attr.Setup<Vec3f>();
attr.Enable();
}
// bind the VBO for the torus normals
plane_normals.Bind(se::Array());
{
GLfloat data[4*3] = {
-0.1f, 1.0f, 0.1f,
-0.1f, 1.0f, -0.1f,
0.1f, 1.0f, 0.1f,
0.1f, 1.0f, -0.1f
};
// upload the data
Buffer::Data(se::Array(), 4*3, data);
// setup the vertex attribs array for the normals
prog_norm.Use();
VertexAttribArray attr(prog_norm, "Normal");
attr.Setup<Vec3f>();
attr.Enable();
}
VertexArray::Unbind();
Vec3f lightPos(2.0f, 2.0f, 3.0f);
prog_norm.Use();
SetUniform(prog_norm, "LightPos", lightPos);
prog_refl.Use();
SetUniform(prog_refl, "LightPos", lightPos);
//
gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
gl.ClearDepth(1.0f);
gl.ClearStencil(0);
}
void Reshape(GLuint width, GLuint height)
{
gl.Viewport(width, height);
Mat4f projection = CamMatrixf::PerspectiveX(
Degrees(65),
double(width)/height,
1, 40
);
SetProgramUniform(prog_norm, "ProjectionMatrix", projection);
SetProgramUniform(prog_refl, "ProjectionMatrix", projection);
}
void Render(double time)
{
namespace se = oglplus::smart_enums;
gl.Clear().ColorBuffer().DepthBuffer().StencilBuffer();
// make the camera matrix orbiting around the origin
// at radius of 3.5 with elevation between 15 and 90 degrees
Mat4f camera = CamMatrixf::Orbiting(
Vec3f(),
6.5,
Degrees(time * 135),
Degrees(15 + (-SineWave(0.25+time/12.5)+1.0)*0.5*75)
);
ModelMatrixf model = ModelMatrixf::Translation(0.0f, 1.5f, 0.0);
ModelMatrixf identity;
//
SetProgramUniform(prog_norm, "CameraMatrix", camera);
SetProgramUniform(prog_refl, "CameraMatrix", camera);
// draw the plane into the stencil buffer
prog_norm.Use();
gl.Disable(se::Blend());
gl.Disable(se::DepthTest());
gl.Enable(se::StencilTest());
gl.ColorMask(false, false, false, false);
gl.StencilFunc(se::Always(), 1, 1);
gl.StencilOp(se::Keep(), se::Keep(), se::Replace());
Uniform<Mat4f> model_matrix_norm(prog_norm, "ModelMatrix");
model_matrix_norm.Set(identity);
plane.Bind();
gl.DrawArrays(se::TriangleStrip(), 0, 4);
gl.ColorMask(true, true, true, true);
gl.Enable(se::DepthTest());
gl.StencilFunc(se::Equal(), 1, 1);
gl.StencilOp(se::Keep(), se::Keep(), se::Keep());
// draw the torus using the reflection program
prog_refl.Use();
Uniform<Mat4f>(prog_refl, "ModelMatrix").Set(model);
torus.Bind();
torus_instr.Draw(torus_indices);
gl.Disable(se::StencilTest());
prog_norm.Use();
// draw the torus using the normal object program
model_matrix_norm.Set(model);
torus_instr.Draw(torus_indices);
// blend-in the plane
gl.Enable(se::Blend());
gl.BlendEquation(se::Max());
model_matrix_norm.Set(identity);
plane.Bind();
gl.DrawArrays(se::TriangleStrip(), 0, 4);
}
bool Continue(double time)
{
return time < 30.0;
}
};
void setupExample(ExampleParams& /*params*/){ }
std::unique_ptr<ExampleThread> makeExampleThread(
Example& /*example*/,
unsigned /*thread_id*/,
const ExampleParams& /*params*/
){ return std::unique_ptr<ExampleThread>(); }
std::unique_ptr<Example> makeExample(const ExampleParams& /*params*/)
{
return std::unique_ptr<Example>(new ReflectionExample);
}
} // namespace oglplus
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
32d907a959be20b0a7f350d9f9f48cd127c5b872 | 005f6e37941b66536f6719a7bb94ab4d3d7cf418 | /src/prx_packages/manipulation/simulation/plants/simple_planning_manipulator.hpp | cf0d19db06161c1d56bbe2efd93e3f80d4a464a5 | [] | no_license | warehouse-picking-automation-challenges/ru_pracsys | c56b9a873218fefb91658e08b74c4a1bc7e16628 | 786ce2e3e0d70d01c951028a90c117a0f23d0804 | refs/heads/master | 2021-05-31T05:52:33.396310 | 2016-02-07T22:34:39 | 2016-02-07T22:34:39 | 39,845,771 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,801 | hpp | ///**
// * @file simple_planning_manipulator.hpp
// *
// * @copyright Software License Agreement (BSD License)
// * Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick
// * All Rights Reserved.
// * For a full description see the file named LICENSE.
// *
// * Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris
// *
// * Email: pracsys@googlegroups.com
// */
//
//#pragma once
//
//#ifndef PRX_SIMPLE_PLANNING_MANIPULATOR_PLANT_HPP
//#define PRX_SIMPLE_PLANNING_MANIPULATOR_PLANT_HPP
//
//#include "prx/utilities/definitions/defs.hpp"
//#include "simple_manipulator.hpp"
//
//namespace prx
//{
// namespace packages
// {
// namespace manipulation
// {
//
// class simple_planning_manipulator_plant_t : public simple_manipulator_plant_t
// {
//
// public:
//
// simple_planning_manipulator_plant_t();
//
// virtual ~simple_planning_manipulator_plant_t();
//
// virtual void init(const util::parameter_reader_t * reader, const util::parameter_reader_t* template_reader = NULL);
//
// void propagate(const double simulation_step);
//
// virtual void update_phys_configs(util::config_list_t& configs) const;
//
// virtual void get_effectors_name(std::vector<std::string>& names) const;
//
// virtual bool is_grasping() const;
//
// virtual void get_end_effector_position(std::vector<double>& pos);
//
// virtual void IK_solver(util::config_t& effector_config, std::vector<double>& state_vec);
//
// /** @copydoc plant_t::steering_function(const state_t*, const state_t*, plan_t&)*/
// void steering_function(const sim::state_t* start, const sim::state_t* goal, sim::plan_t& result_plan);
//
// /** @copydoc plant_t::append_contingency(plan_t&, double)*/
// void append_contingency(sim::plan_t& result_plan, double duration);
//
// protected:
//
// /** Indexer for state variable : X */
// const static unsigned VAR_X;
//
// /** Indexer for state variable : Y */
// const static unsigned VAR_Y;
//
// /** Indexer for state variable : Z */
// const static unsigned VAR_Z;
//
// /** Indexer for state variable : THETA X */
// const static unsigned VAR_TX;
//
// /** Indexer for state variable : THETA Y */
// const static unsigned VAR_TY;
//
// /** Indexer for state variable : THETA Z */
// const static unsigned VAR_TZ;
//
// /** Indexer for grasping control variable G */
// const static unsigned VAR_G;
//
// /** Internal state & control memory */
// double _x;
// double _y;
// double _z;
// double _tx;
// double _ty;
// double _tz;
// double _g;
//
// double _cx;
// double _cy;
// double _cz;
// double _ctx;
// double _cty;
// double _ctz;
// double _cg;
//
// mutable util::config_t end_effector_config;
// util::config_t *end_effector_relative_config;
// util::config_t *rside_config;
// util::config_t *lside_config;
// util::config_t *rfinger_config;
// util::config_t *lfinger_config;
// std::string right_finger_name;
// std::string left_finger_name;
// std::string right_side_name;
// std::string left_side_name;
// double effector_distance;
// double side_x;
// double side_y;
// double finger_y;
// double side_grasp_y;
// double finger_grasp_y;
// double max_grasp;
// double end_effector_position;
// double prev_g;
//
// util::vector_t tmp_pos;
// std::vector<double> tmp_state;
// mutable util::quaternion_t tmp_orient;
// util::config_t tmp_config;
//
// /**
// * The maximum distance for the plant in a simulation step.
// * @brief The maximum distance for the plant in a simulation step.
// */
// double max_step;
//
// /**
// * The step for a specific distance.
// * @brief The step for a specific distance.
// */
// double interpolation_step;
//
// /**
// * The total cover before change control.
// * @brief The total cover before change control.
// */
// double dist;
//
// /**
// * A flag for the next step.
// * @brief A flag for the next step.
// */
// bool reset;
//
// /**
// * To copy the initial state before the interpolation.
// * @brief To copy the initial state before the interpolation.
// */
// sim::state_t* initial_state;
//
// /**
// * To copy the plant's state into to do interpolation and copying and such.
// * @brief To copy the plant's state into to do interpolation and copying and such.
// */
// sim::state_t* state;
//
// /**
// * Used to check if the rigid body is actually making progress.
// * @brief Used to check if the rigid body is actually making progress.
// */
// sim::state_t* hold_state;
//
// /**
// * Holds the state from the last propagation.
// * @brief Holds the state from the last propagation.
// */
// sim::state_t* prior_state;
//
// /**
// * The previously used control by the system.
// * @brief The previously used control by the system.
// */
// sim::control_t* prior_control;
//
// /**
// * To copy the plant's control into in order to do equivalence checking.
// * @brief To copy the plant's control into in order to do equivalence checking.
// */
// sim::control_t* control;
//
// };
// }
// }
//}
//
//#endif | [
"kostas.bekris@cs.rutgers.edu"
] | kostas.bekris@cs.rutgers.edu |
7b2ae70b2d51805efb79e23a08bad42f317de492 | c7ebab4f0bb325fddd99e2e6952241e6d5177faf | /Buffer.cpp | 71800e3bd44133ec88cb9c7e770712955754ef38 | [] | no_license | zhuqiweigit/mymuduo | d1cd19a4a10ad7c2d2d327dafa3a6c9379d8c76a | 31701d4b72cf29051bf721ea1d720535b048b39c | refs/heads/main | 2023-03-08T03:49:18.547494 | 2021-02-26T12:51:39 | 2021-02-26T12:51:39 | 342,574,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include "Buffer.h"
#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>
/**
* 维护了一个vector<char>Buffer, 和两个读写的int Index,使用int而非指针或迭代器,是因为vector的迭代器失效问题
*
* Buffer的布局: 0-----8---------------readIndex--------------writeIndex-----------------size-----capacity
* 空白头部 读过后的空闲区 待读数据 可写的空白区
*
* append函数:往buffer写入数据,写之前先检查可写空白区间够不够,如果不够,就使用makeSpace扩容。
*
* makeSpace:先检查【读后的空白区 + 可写的空白区】是否够写
* 不够:直接扩容,假设需要写入n字节,则扩容至 writeIndex + n
* 够:把待读数据挪动到开头,把空白区合并即可
*
* 注:我们使用的容量,应该看size,而非capacity。
*/
size_t Buffer::readFd(int fd, int* saveErrno){
char extrabuf[65536] = {0};
struct iovec vec[2];
const size_t writable = writeableBytes();
vec[0].iov_base = beginWrite();
vec[0].iov_len = writable;
vec[1].iov_base = extrabuf;
vec[1].iov_len = sizeof extrabuf;
const int iovcnt = writable < sizeof(extrabuf) ? 2 : 1;
const size_t n = ::readv(fd, vec, iovcnt);
if(n < 0){
*saveErrno = errno;
}else if(n <= writable){
writeIndex_ += n;
}else{
writeIndex_ = buffer_.size();
append(extrabuf, n - writable);
}
return n;
}
size_t Buffer::writeFd(int fd, int* saveErrno){
size_t n = ::write(fd, peek(), readableBytes());
if(n < 0){
*saveErrno = errno;
}
return n;
} | [
"XXX@xx.com"
] | XXX@xx.com |
eca14227b5f94317f3910073e25394fc21122137 | 0a7c02bd90d575c2238cc25340cc670515452b05 | /data/dlopen/lib.cc | cbbe083de86d0ba3aec96826453a1fa906664b18 | [] | no_license | 010ric/inMemory_DBSystem_course | 181df3633b2bd24158e92b6bbaefef47777df45d | ced3d8ed10ecd46e347021544650a57481067c2e | refs/heads/main | 2023-01-14T03:51:54.829329 | 2020-11-21T10:47:44 | 2020-11-21T10:47:44 | 314,787,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cc | extern "C" int foo(int x) { return x * 2; }
| [
"mturic@inovex.de"
] | mturic@inovex.de |
b8523ef664f336fbafe38f036dc8317fc6b50dca | d5dd043940702693d9308670d00d1b179f33e874 | /MIXKEY_NEW_CODE/Adafruit-GFX-Library-master/Adafruit_GFX.h | 5c1b92dc763b8fe8aa42be38e29ddb7adf25f341 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | OasysLab/MIXKEY_NEW_CODE_NBIoT_3G | 520dc2f087cfddaa021f30723425b356c4c02cd1 | 82f1b79f034ab4389e3b7d6829b0cda1ac035181 | refs/heads/master | 2020-03-23T12:00:19.337505 | 2018-07-19T05:58:52 | 2018-07-19T05:58:52 | 141,531,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,006 | h | #ifndef _ADAFRUIT_GFX_H
#define _ADAFRUIT_GFX_H
#if ARDUINO >= 100
#include "Arduino.h"
#include "Print.h"
#else
#include "WProgram.h"
#endif
#include "gfxfont.h"
class Adafruit_GFX : public Print {
public:
Adafruit_GFX(int16_t w, int16_t h); // Constructor
// This MUST be defined by the subclass:
virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0;
// These MAY be overridden by the subclass to provide device-specific
// optimized code. Otherwise 'generic' versions are used.
virtual void
drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color),
drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color),
drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color),
drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color),
fillScreen(uint16_t color),
invertDisplay(boolean i);
// These exist only with Adafruit_GFX (no subclass overrides)
void
drawConnectedLogo(),
drawLogo(),
drawConnectLogo(),
drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
uint16_t color),
fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color),
fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername,
int16_t delta, uint16_t color),
drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
int16_t x2, int16_t y2, uint16_t color),
fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1,
int16_t x2, int16_t y2, uint16_t color),
drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
int16_t radius, uint16_t color),
fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h,
int16_t radius, uint16_t color),
drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color, uint16_t bg),
drawBitmap(int16_t x, int16_t y, uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawBitmap(int16_t x, int16_t y, uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color, uint16_t bg),
drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap,
int16_t w, int16_t h, uint16_t color),
drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color,
uint16_t bg, uint8_t size),
setCursor(int16_t x, int16_t y),
setTextColor(uint16_t c),
setTextColor(uint16_t c, uint16_t bg),
setTextSize(uint8_t s),
setTextWrap(boolean w),
setRotation(uint8_t r),
cp437(boolean x=true),
setFont(const GFXfont *f = NULL),
getTextBounds(char *string, int16_t x, int16_t y,
int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h),
getTextBounds(const __FlashStringHelper *s, int16_t x, int16_t y,
int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h);
#if ARDUINO >= 100
virtual size_t write(uint8_t);
#else
virtual void write(uint8_t);
#endif
int16_t height(void) const;
int16_t width(void) const;
uint8_t getRotation(void) const;
// get current cursor position (get rotation safe maximum values, using: width() for x, height() for y)
int16_t getCursorX(void) const;
int16_t getCursorY(void) const;
protected:
const int16_t
WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes
int16_t
_width, _height, // Display w/h as modified by current rotation
cursor_x, cursor_y;
uint16_t
textcolor, textbgcolor;
uint8_t
textsize,
rotation;
boolean
wrap, // If set, 'wrap' text at right edge of display
_cp437; // If set, use correct CP437 charset (default is off)
GFXfont
*gfxFont;
};
class Adafruit_GFX_Button {
public:
Adafruit_GFX_Button(void);
void initButton(Adafruit_GFX *gfx, int16_t x, int16_t y,
uint8_t w, uint8_t h, uint16_t outline, uint16_t fill,
uint16_t textcolor, char *label, uint8_t textsize);
void drawButton(boolean inverted = false);
boolean contains(int16_t x, int16_t y);
void press(boolean p);
boolean isPressed();
boolean justPressed();
boolean justReleased();
private:
Adafruit_GFX *_gfx;
int16_t _x, _y;
uint16_t _w, _h;
uint8_t _textsize;
uint16_t _outlinecolor, _fillcolor, _textcolor;
char _label[10];
boolean currstate, laststate;
};
class GFXcanvas1 : public Adafruit_GFX {
public:
GFXcanvas1(uint16_t w, uint16_t h);
~GFXcanvas1(void);
void drawPixel(int16_t x, int16_t y, uint16_t color),
fillScreen(uint16_t color);
uint8_t *getBuffer(void);
private:
uint8_t *buffer;
};
class GFXcanvas16 : public Adafruit_GFX {
GFXcanvas16(uint16_t w, uint16_t h);
~GFXcanvas16(void);
void drawPixel(int16_t x, int16_t y, uint16_t color),
fillScreen(uint16_t color);
uint16_t *getBuffer(void);
private:
uint16_t *buffer;
};
#endif // _ADAFRUIT_GFX_H
| [
"qqlinebotapi@gmail.com"
] | qqlinebotapi@gmail.com |
de80a75a3b3eeadd4f3649dc92f5e2357c4e9e17 | a3634de7800ae5fe8e68532d7c3a7570b9c61c5b | /codechef/JUNE17PRMQ2.cpp | 7baaa3cebf4b6cb9faedcb6066d9c87412c279a0 | [] | no_license | MayankChaturvedi/competitive-coding | a737a2a36b8aa7aea1193f2db4b32b081f78e2ba | 9e9bd21de669c7b7bd29a262b29965ecc80ad621 | refs/heads/master | 2020-03-18T01:39:29.447631 | 2018-02-19T15:04:32 | 2018-02-19T15:04:32 | 134,152,930 | 0 | 1 | null | 2018-05-20T13:27:35 | 2018-05-20T13:27:34 | null | UTF-8 | C++ | false | false | 3,533 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
inline void fastRead_int(long long &x)
{ register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-')
{ neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked())
{ x = (x<<1) + (x<<3) + c - 48;
}
}
const int MAXN=1e5+2, MAXIND=4*MAXN;
vector<int> Segtree[MAXIND]; //Array and Segtree will follow 0-based and 1-based indexing respectively.
vector<int> Array[MAXN];
int primes[168]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853,
857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997};
//initializes Segtree from Array.
void initialize(int node, int b, int e, int N)
{ if (b == e)
Segtree[node] = Array[b];
else
{ //compute the values in the left and right subtrees
initialize(2*node, b, (b+e)/2, N);
initialize(2*node + 1, (b+e)/2 + 1, e, N);
Segtree[node].resize(Segtree[2*node].size() + Segtree[2*node +1].size());
merge(Segtree[2*node].begin(), Segtree[2*node].end(), Segtree[2*node +1].begin(), Segtree[2*node +1].end(), Segtree[node].begin());
sort(Segtree[node].begin(), Segtree[node].end());
}
//printf("%d ",node);
//for(int i : Segtree[node])
//printf("%d ",i);
//printf("\n");
}
int query(int node, int b, int e, int i, int j, int X, int Y)
{
int p1, p2;
//if the current interval doesn't intersect
//the query interval return -1
if (i > e || j < b)
return -1;
//if the current interval is included in
//the query interval return Segtree[node]
if (b >= i && e <= j)
{ auto lowerlimit= lower_bound(Segtree[node].begin(), Segtree[node].end(), X);
auto upperlimit= upper_bound(Segtree[node].begin(), Segtree[node].end(), Y);
return upperlimit-lowerlimit;
}
p1 = query(2*node, b, (b+e)/2, i, j, X, Y);
p2 = query(2*node + 1, (b+e)/2 + 1, e, i, j, X, Y);
if (p1 == -1)
return p2;
if (p2 == -1)
return p1;
return p1 + p2;
}
int main()
{ long long N;
fastRead_int(N);
long long a[N];
for(int i=0; i<N; i++)
fastRead_int(a[i]);
long long Q;
fastRead_int(Q);
for(int i=0; i<N; i++)
{ long long temp=a[i];
for(int j=0; j<168 && temp>1; j++)
{ while(temp % primes[j] == 0)
{ Array[i].push_back(primes[j]);
temp/=primes[j];
}
}
if(temp>1)
{ Array[i].push_back(temp);
}
}
initialize(1, 0, N-1, N);
while(Q--) //For each query, we search for L to R on all of the 168 segment trees.
{ long long L, R, X, Y;
fastRead_int(L);
fastRead_int(R);
fastRead_int(X);
fastRead_int(Y);
L--; R--;
long long que=query(1, 0, N-1, L, R, X, Y);
printf("%lld\n",que);
}
return 0;
}
| [
"f20160006@goa.bits-pilani.ac.in"
] | f20160006@goa.bits-pilani.ac.in |
1e2eab60eaa70114bb684e4ee635db610d8af8a5 | 391dede5cf715071d5fac9ac376d26c3b4edf040 | /linux/my_application.cc | 83d3efea9d28fd5e5102f095dd9f54cf29a81926 | [] | no_license | Vritika21/intertwined | 5fa0450fd9632f83b8722fcb25c2a1fefd9586f6 | d22dbd787fcc5a8543f56f9e79cd7894fd1c76fc | refs/heads/master | 2023-04-06T22:49:55.002306 | 2021-04-08T21:50:23 | 2021-04-08T21:50:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,654 | cc | #include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen *screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "intertwined");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
}
else {
gtk_window_set_title(window, "intertwined");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar ***arguments, int *exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject *object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
nullptr));
}
| [
"madhurmaurya365@gmail.com"
] | madhurmaurya365@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.