blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
62a02b532a70ef5de3e58e2e3f8c8f0226b19241
87f82a52aa160db6e7a762a27b2fad87e07eb49a
/lazysegtree.hpp
8d239894ef6a3101644a751f38d12d211bec4375
[ "CC0-1.0" ]
permissive
Vidit24/cp-black_box
cfe4d0ab1b7144dba8ec78032d13fd6c26285515
50c22d3d6cbb9674c106152c8392ba087ae51937
refs/heads/main
2023-08-15T12:57:57.867969
2021-10-16T11:56:47
2021-10-16T11:56:47
398,625,380
0
1
CC0-1.0
2021-10-16T11:06:16
2021-08-21T18:02:25
HTML
UTF-8
C++
false
false
4,934
hpp
#ifndef ATCODER_LAZYSEGTREE_HPP #define ATCODER_LAZYSEGTREE_HPP 1 #include <algorithm> #include <atcoder/internal_bit> #include <cassert> #include <iostream> #include <vector> namespace atcoder { template <class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S), F (*composition)(F, F), F (*id)()> struct lazy_segtree { public: lazy_segtree() : lazy_segtree(0) {} lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {} lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); lz = std::vector<F>(size, id()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); return d[p]; } S prod(int l, int r) { assert(0 <= l && l <= r && r <= _n); if (l == r) return e(); l += size; r += size; for (int i = log; i >= 1; i--) { if (((l >> i) << i) != l) push(l >> i); if (((r >> i) << i) != r) push(r >> i); } S sml = e(), smr = e(); while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() { return d[1]; } void apply(int p, F f) { assert(0 <= p && p < _n); p += size; for (int i = log; i >= 1; i--) push(p >> i); d[p] = mapping(f, d[p]); for (int i = 1; i <= log; i++) update(p >> i); } void apply(int l, int r, F f) { assert(0 <= l && l <= r && r <= _n); if (l == r) return; l += size; r += size; for (int i = log; i >= 1; i--) { if (((l >> i) << i) != l) push(l >> i); if (((r >> i) << i) != r) push((r - 1) >> i); } { int l2 = l, r2 = r; while (l < r) { if (l & 1) all_apply(l++, f); if (r & 1) all_apply(--r, f); l >>= 1; r >>= 1; } l = l2; r = r2; } for (int i = 1; i <= log; i++) { if (((l >> i) << i) != l) update(l >> i); if (((r >> i) << i) != r) update((r - 1) >> i); } } template <bool (*g)(S)> int max_right(int l) { return max_right(l, [](S x) { return g(x); }); } template <class G> int max_right(int l, G g) { assert(0 <= l && l <= _n); assert(g(e())); if (l == _n) return _n; l += size; for (int i = log; i >= 1; i--) push(l >> i); S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!g(op(sm, d[l]))) { while (l < size) { push(l); l = (2 * l); if (g(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*g)(S)> int min_left(int r) { return min_left(r, [](S x) { return g(x); }); } template <class G> int min_left(int r, G g) { assert(0 <= r && r <= _n); assert(g(e())); if (r == 0) return 0; r += size; for (int i = log; i >= 1; i--) push((r - 1) >> i); S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!g(op(d[r], sm))) { while (r < size) { push(r); r = (2 * r + 1); if (g(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; std::vector<F> lz; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } void all_apply(int k, F f) { d[k] = mapping(f, d[k]); if (k < size) lz[k] = composition(f, lz[k]); } void push(int k) { all_apply(2 * k, lz[k]); all_apply(2 * k + 1, lz[k]); lz[k] = id(); } }; } // namespace atcoder #endif // ATCODER_LAZYSEGTREE_HPP
[ "noreply@github.com" ]
noreply@github.com
573c20d6f6fd9fc01c7dbd9d83a00e1698901e99
6e20207f8aff0f0ad94f05bd025810c6b10a1d5f
/SDK/EnhancedJollyBrolly_Recipe_classes.h
cebd4bd9c098c3ffb4f2822798b2368d03cb6bea
[]
no_license
zH4x-SDK/zWeHappyFew-SDK
2a4e246d8ee4b58e45feaa4335f1feb8ea618a4a
5906adc3edfe1b5de86b7ef0a0eff38073e12214
refs/heads/main
2023-08-17T06:05:18.561339
2021-08-27T13:36:09
2021-08-27T13:36:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
691
h
#pragma once // Name: WeHappyFew, Version: 1.8.8 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass EnhancedJollyBrolly_Recipe.EnhancedJollyBrolly_Recipe_C // 0x0000 (0x00F8 - 0x00F8) class UEnhancedJollyBrolly_Recipe_C : public UCraftingRecipe { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass EnhancedJollyBrolly_Recipe.EnhancedJollyBrolly_Recipe_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
6ebd386bf0f998b282a685350817c3bb7801ecfd
66e457f024afcd0f9e9002f1021b09bc44368973
/BFS&DFS/미로탐색.cpp
308be0b9b49c54fae6e057c80609c491de03ebf9
[]
no_license
EunSeong-Seo/coding_test
75aa6e08daa819f97cec3280abe11ec619d6661d
3afe9af737260cf3d53acb56fa8d14ce0ca81904
refs/heads/master
2023-05-13T23:38:52.099302
2021-05-29T14:08:38
2021-05-29T14:08:38
341,887,536
0
0
null
null
null
null
UHC
C++
false
false
825
cpp
#include <iostream> #include <queue> #include <stdio.h> using namespace std; int map[110][110]; bool vis[110][110]; int n,m; int dx[4]={-1,0,1,0}; int dy[4]={0,1,0,-1}; void bfs(int fx,int fy){ queue<pair<int,int>>q; vis[fx][fy]= 1; q.push({fx,fy}); while(!q.empty()){ int x = q.front().first; int y = q.front().second; q.pop(); //@@@ 틀렸던 부분@@@ for(int dir =0; dir<4;dir++){ int nx = x +dx[dir]; int ny = y + dy[dir]; if(nx<0||ny<0||nx>=n||ny>=m)continue; if(vis[nx][ny]||map[nx][ny]==0) continue; vis[nx][ny]=1; map[nx][ny]=map[x][y]+1; //@@@ 틀렸던 부분@@@ q.push({nx,ny}); } } } int main(){ cin>> n>>m; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ scanf("%1d", &map[i][j]); } } bfs(0,0); cout<<map[n-1][m-1]<<'\n'; }
[ "seoun4612@gmail.com" ]
seoun4612@gmail.com
8e576a26f61749b62fc060a087915718dbb2bfb8
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/compute/routes/v1/mocks/mock_routes_connection.h
b2b39fc0ac462e037ef8b82f0fbc4816630bf112
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
2,961
h
// Copyright 2023 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/compute/routes/v1/routes.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_COMPUTE_ROUTES_V1_MOCKS_MOCK_ROUTES_CONNECTION_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_COMPUTE_ROUTES_V1_MOCKS_MOCK_ROUTES_CONNECTION_H #include "google/cloud/compute/routes/v1/routes_connection.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace compute_routes_v1_mocks { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /** * A class to mock `RoutesConnection`. * * Application developers may want to test their code with simulated responses, * including errors, from an object of type `RoutesClient`. To do so, * construct an object of type `RoutesClient` with an instance of this * class. Then use the Google Test framework functions to program the behavior * of this mock. * * @see [This example][bq-mock] for how to test your application with GoogleTest. * While the example showcases types from the BigQuery library, the underlying * principles apply for any pair of `*Client` and `*Connection`. * * [bq-mock]: @cloud_cpp_docs_link{bigquery,bigquery-read-mock} */ class MockRoutesConnection : public compute_routes_v1::RoutesConnection { public: MOCK_METHOD(Options, options, (), (override)); MOCK_METHOD( future<StatusOr<google::cloud::cpp::compute::v1::Operation>>, DeleteRoutes, (google::cloud::cpp::compute::routes::v1::DeleteRoutesRequest const& request), (override)); MOCK_METHOD(StatusOr<google::cloud::cpp::compute::v1::Route>, GetRoutes, (google::cloud::cpp::compute::routes::v1::GetRoutesRequest const& request), (override)); MOCK_METHOD( future<StatusOr<google::cloud::cpp::compute::v1::Operation>>, InsertRoutes, (google::cloud::cpp::compute::routes::v1::InsertRoutesRequest const& request), (override)); MOCK_METHOD( StreamRange<google::cloud::cpp::compute::v1::Route>, ListRoutes, (google::cloud::cpp::compute::routes::v1::ListRoutesRequest request), (override)); }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace compute_routes_v1_mocks } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_COMPUTE_ROUTES_V1_MOCKS_MOCK_ROUTES_CONNECTION_H
[ "noreply@github.com" ]
noreply@github.com
99882e3c602e6490a905ae257ef437144fffa67d
0ed94159731f436244e922ad6312fb2a83a98c17
/src/graphics/font_file.h
b943a53307560602b84143337cc9bdfb96074faf
[ "Zlib" ]
permissive
4Che/LD49-brimstone
b22dd8db1d7e4a47cd3729ebd189381dafc48548
6fd67d0709600fdab1c7d4c6013047df58a26d67
refs/heads/master
2023-08-27T23:53:54.436301
2021-10-04T14:17:57
2021-10-04T14:17:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,215
h
#pragma once #include <algorithm> #include <functional> #include <exception> #include <utility> #include <ft2build.h> #include FT_FREETYPE_H // Ugh. #include "graphics/font.h" #include "graphics/image.h" #include "macros/finally.h" #include "program/errors.h" #include "stream/readonly_data.h" #include "strings/format.h" #include "utils/mat.h" #include "utils/packing.h" #include "utils/unicode_ranges.h" #include "utils/unicode.h" namespace Graphics { // Unlike most other graphics classes, `FontFile` doesn't rely on SDL or OpenGL. You can safely use it even if they aren't initialized. class FontFile { inline static bool ft_initialized = 0; inline static FT_Library ft_context = 0; inline static int open_font_count = 0; struct Data { FT_Face ft_font = 0; Stream::ReadOnlyData file; }; Data data; public: FontFile() {} // File is copied into the font, since FreeType requires original data to be available when the font is used. (Since files are ref-counted, file contents aren't copied.) // `size` is measured in pixels. Normally you only provide height, but you can also provide width. In this case, `[x,0]` and `[0,x]` are equivalent to `[x,x]` due to how FreeType operates. // Some font files contain several fonts; `index` determines which one of them is loaded. Upper 16 bits of `index` contain so-called "variation" (sub-font?) index, which starts from 1. Use 0 to load the default one. FontFile(Stream::ReadOnlyData file, int size, int index = 0) : FontFile(file, ivec2(0, size), index) {} FontFile(Stream::ReadOnlyData file, ivec2 size, int index = 0) { if (!ft_initialized) { ft_initialized = !FT_Init_FreeType(&ft_context); if (!ft_initialized) Program::Error("Unable to initialize FreeType."); // We don't unload the library if this constructor throws after this point. } data.file = std::move(file); // Memory files are ref-counted, but moving won't hurt. FT_Open_Args args{}; args.flags = FT_OPEN_MEMORY; args.memory_base = data.file.data(); args.memory_size = data.file.size(); if (FT_Open_Face(ft_context, &args, index, &data.ft_font)) Program::Error("Unable to load font `", data.file.name(), "`."); FINALLY_ON_THROW( FT_Done_Face(data.ft_font); ) if (FT_Set_Pixel_Sizes(data.ft_font, size.x, size.y)) { // This size is not available. Out of courtesy we print a list of available sizes. // Convert the requested size to printable format. if (size.y == 0) size.x = size.y; else if (size.x == 0) size.y = size.x; std::string requested_size; if (size.x == size.y) requested_size = STR((size.y)); else requested_size = STR((size.x), "x", (size.y)); // Get the list of available sizes. std::string size_list; for (int i = 0; i < int(data.ft_font->num_fixed_sizes); i++) { if (i != 0) size_list += ", "; ivec2 this_size(data.ft_font->available_sizes[i].width, data.ft_font->available_sizes[i].height); if (this_size.x == this_size.y) size_list += STR((this_size.y)); else size_list += STR((this_size.x), "x", (this_size.y)); } Program::Error(STR("Bitmap font `", (data.file.name()), "`", (index != 0 ? STR("[",(index),"]") : ""), " doesn't support size ", (requested_size), ".", (size_list.empty() ? "" : STR("\nAvailable sizes are: ", (size_list), ".")))); } open_font_count++; // This must remain at the bottom of the constructor in case something throws. } FontFile(FontFile &&other) noexcept : data(std::exchange(other.data, {})) {} FontFile &operator=(FontFile other) noexcept { std::swap(data, other.data); return *this; } ~FontFile() { if (data.ft_font) { FT_Done_Face(data.ft_font); open_font_count--; } } static void UnloadLibrary() // Use this to unload freetype. This function throws if you have opened fonts. { if (open_font_count > 0) Program::Error("Unable to unload FreeType: ", open_font_count, " fonts are still in use."); if (ft_initialized) return; FT_Done_FreeType(ft_context); ft_initialized = 0; } explicit operator bool() const { return bool(data.ft_font); } int Ascent() const { return data.ft_font->size->metrics.ascender >> 6; // Ascent is stored as 26.6 fixed point and it's supposed to be already rounded, so we truncate it. } int Descent() const { return -(data.ft_font->size->metrics.descender >> 6); // See `Ascent()` for why we bit-shift. Note that we also have to negate descent to make it positive. } int Height() const { return Ascent() + Descent(); } int LineSkip() const { return data.ft_font->size->metrics.height >> 6; // Huh, freetype calls it 'height'. See `Ascent()` for why we bit-shift. } int LineGap() const { return LineSkip() - Height(); } bool HasKerning() const { return FT_HAS_KERNING(data.ft_font); } int Kerning(uint32_t a, uint32_t b) const // Returns 0 if there is no kerning for this font. Add the returned value to horizontal offset between two glyphs. { if (!HasKerning()) return 0; FT_Vector vec; if (FT_Get_Kerning(data.ft_font, FT_Get_Char_Index(data.ft_font, a), FT_Get_Char_Index(data.ft_font, b), FT_KERNING_DEFAULT, &vec)) return 0; return (vec.x + (1 << 5)) >> 6; // The kerning is measured in 26.6 fixed point pixels, so we round it. } // Constructs a functor to return kerning. Freetype font handle is copied into the functior, you should keep corresponding object alive as long as you need it. // If the font doesn't support kerning, null functor is returned. std::function<int(uint32_t, uint32_t)> KerningFunc() const { if (!HasKerning()) return 0; return [ft_font = data.ft_font](uint16_t a, uint16_t b) -> int { FT_Vector vec; if (FT_Get_Kerning(ft_font, FT_Get_Char_Index(ft_font, a), FT_Get_Char_Index(ft_font, b), FT_KERNING_DEFAULT, &vec)) return 0; return (vec.x + (1 << 5)) >> 6; // See `Kerning()` for why we bit-shift. }; } // This always returns `true` for 0xFFFD `Unicode::default_char`, since freetype itself seems to able to draw it if it's not included in the font. bool HasGlyph(uint32_t ch) const { return bool(FT_Get_Char_Index(data.ft_font, ch)) || ch == Unicode::default_char; } enum RenderFlags { none = 0, monochrome = 1 << 0, // Render without antialiasing. Combine with `hinting_mode_monochrome` for best results. avoid_bitmaps = 1 << 1, // If the font contains both bitmaps and outlines (aka vector characters) hinting_disable = 1 << 2, // Completely disable hinting. hinting_prefer_autohinter = 1 << 3, // Prefer auto-hinter over the hinting instructions built into the font. hinting_disable_autohinter = 1 << 4, // Disable auto-hinter. (It's already avoided by default.) hinting_mode_light = 1 << 5, // Alternative hinting mode. hinting_mode_monochrome = 1 << 6, // Hinting mode for monochrome rendering. monochrome_with_hinting = monochrome | hinting_mode_monochrome, }; friend constexpr RenderFlags operator|(RenderFlags a, RenderFlags b) {return RenderFlags(int(a) | int(b));} friend constexpr RenderFlags operator&(RenderFlags a, RenderFlags b) {return RenderFlags(int(a) & int(b));} struct GlyphData { Image image; ivec2 offset; int advance; }; // Throws on failure. In particular, throws if the font has no such glyph. GlyphData GetGlyph(uint32_t ch, RenderFlags flags) const { try { if (!HasGlyph(ch)) Program::Error("No such glyph."); long loading_flags = 0; if (flags & avoid_bitmaps ) loading_flags |= FT_LOAD_NO_BITMAP; if (flags & hinting_disable ) loading_flags |= FT_LOAD_NO_HINTING; if (flags & hinting_prefer_autohinter ) loading_flags |= FT_LOAD_FORCE_AUTOHINT; if (flags & hinting_disable_autohinter) loading_flags |= FT_LOAD_NO_AUTOHINT; if (flags & hinting_mode_light ) loading_flags |= FT_LOAD_TARGET_LIGHT; if (flags & hinting_mode_monochrome ) loading_flags |= FT_LOAD_TARGET_MONO; FT_Render_Mode render_mode = (flags & monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; if (FT_Load_Char(data.ft_font, ch, loading_flags) != 0 || FT_Render_Glyph(data.ft_font->glyph, render_mode) != 0) { if (ch != Unicode::default_char) Program::Error("Unknown error."); // We can't render the default character (aka [?]), try the plain question mark instead. if (HasGlyph('?')) return GetGlyph('?', flags); // Return an empty glyph. GlyphData ret; ret.offset = ivec2(0); ret.advance = 0; return ret; } auto glyph = data.ft_font->glyph; auto bitmap = glyph->bitmap; bool is_antialiased; switch (bitmap.pixel_mode) { case FT_PIXEL_MODE_MONO: is_antialiased = 0; break; case FT_PIXEL_MODE_GRAY: is_antialiased = 1; break; default: Program::Error("Bitmap format ", bitmap.pixel_mode, " is not supported."); break; } GlyphData ret; ivec2 size = ivec2(bitmap.width, bitmap.rows); ret.offset = ivec2(glyph->bitmap_left, -glyph->bitmap_top); ret.advance = (glyph->advance.x + (1 << 5)) >> 6; // Advance is measured in 26.6 fixed point pixels, so we round it. ret.image = Image(size); if (is_antialiased) { for (int y = 0; y < size.y; y++) for (int x = 0; x < size.x; x++) ret.image.UnsafeAt(ivec2(x,y)) = u8vec3(255).to_vec4(bitmap.buffer[bitmap.pitch * y + x]); } else { for (int y = 0; y < size.y; y++) { uint8_t *byte_ptr = bitmap.buffer + bitmap.pitch * y; uint8_t byte; for (int x = 0; x < size.x; x++) { if (x % 8 == 0) byte = *byte_ptr++; ret.image.UnsafeAt(ivec2(x,y)) = u8vec3(255).to_vec4(byte & 128 ? 255 : 0); byte <<= 1; } } } return ret; } catch (std::exception &e) { Program::Error("Unable to render glyph ", ch, " for font `", data.file.name(), "`:\n", e.what()); } } }; struct FontAtlasEntry { enum Flags { none = 0, no_default_glyph = 0b1, no_line_gap = 0b10, }; friend constexpr Flags operator|(Flags a, Flags b) {return Flags(int(a) | int(b));} friend constexpr Flags operator&(Flags a, Flags b) {return Flags(int(a) & int(b));} Font *target = 0; const FontFile *source = 0; const Unicode::CharSet *glyphs = 0; FontFile::RenderFlags render_flags = FontFile::none; Flags flags = none; FontAtlasEntry() {} FontAtlasEntry(Font &target, const FontFile &source, const Unicode::CharSet &glyphs, FontFile::RenderFlags render_flags = FontFile::none, Flags flags = none) : target(&target), source(&source), glyphs(&glyphs), render_flags(render_flags), flags(flags) {} }; inline void MakeFontAtlas(Image &image, ivec2 pos, ivec2 size, const std::vector<FontAtlasEntry> &entries, bool add_gaps = 1) // Throws on failure. { if (!image.RectInBounds(pos, size)) Program::Error("Invalid target rectangle for a font atlas."); struct Glyph { Font::Glyph *target = 0; Image image; }; std::vector<Glyph> glyphs; std::vector<Packing::Rect> rects; for (const FontAtlasEntry &entry : entries) { // Save font metrics. entry.target->SetAscent(entry.source->Ascent()); entry.target->SetDescent(entry.source->Descent()); entry.target->SetLineSkip(entry.flags & entry.no_line_gap ? entry.source->Height() : entry.source->LineSkip()); entry.target->SetKerningFunc(entry.source->KerningFunc()); auto AddGlyph = [&](uint32_t ch) { if (!entry.source->HasGlyph(ch)) return; // Copy glyph to the font. FontFile::GlyphData glyph_data = entry.source->GetGlyph(ch, entry.render_flags); Font::Glyph &font_glyph = (ch != Unicode::default_char ? entry.target->Insert(ch) : entry.target->DefaultGlyph()); font_glyph.size = glyph_data.image.Size(); font_glyph.offset = glyph_data.offset; font_glyph.advance = glyph_data.advance; // Save it into the glyph vector. glyphs.push_back({&font_glyph, std::move(glyph_data.image)}); // We rely on the fact that Graphics::Font doesn't invalidate references on insertions. // Save it into the rect vector. rects.emplace_back(font_glyph.size); }; // Save the default glyph. if (!(entry.flags & entry.no_default_glyph) && !entry.glyphs->Contains(Unicode::default_char)) AddGlyph(Unicode::default_char); // Save the rest of the glyphs. for (uint32_t ch : *entry.glyphs) AddGlyph(ch); } // Pack rectangles. if (Packing::PackRects(size, rects.data(), rects.size(), add_gaps)) Program::Error("Unable to fit the font atlas for into ", size.x, 'x', size.y, " rectangle."); // Fill target area with transparent black. image.UnsafeFill(pos, size, u8vec4(0)); // Export results. for (size_t i = 0; i < glyphs.size(); i++) { ivec2 glyph_pos = pos + rects[i].pos; glyphs[i].target->texture_pos = glyph_pos; image.UnsafeDrawImage(glyphs[i].image, glyph_pos); } } }
[ "blckcat@inbox.ru" ]
blckcat@inbox.ru
e7a3d81b5f17b9303bcbc3f83eb2a24819951e67
9973a6f1627e435c947b9c4ecb75ed56e1ece045
/src/main.cpp
27fadecba88d028fd4800a85499b76f19822c71b
[ "MIT" ]
permissive
corigan01/Pable-Programming-Language
9bd1488b8e5316a13bfb9bd5aab2628f496078b0
433d27c85961ca9093d084de19f454d43882eb4e
refs/heads/master
2023-02-03T09:45:34.116944
2020-09-30T22:43:26
2020-09-30T22:43:26
284,293,528
2
1
MIT
2020-09-30T22:43:27
2020-08-01T16:07:14
C++
UTF-8
C++
false
false
38,572
cpp
#include "TokenHandler.h" int main(int argc, char** argv) { auto start = std::chrono::high_resolution_clock::now(); std::ios_base::sync_with_stdio(false); // arg input std::string WorkingFileName = ""; for (int i = 0; i < argc; i ++) { std::string InputArgs = std::string(argv[i]); dis.out(D_INFO, InputArgs); if (InputArgs == "--DEBUG_INFO") { dis.__DEBUG_ON = true; } else if (InputArgs == "--help") { std::cout << R"( ___ __ __ _____ _ __ / _ \___ _/ / / /__ / ___/__ __ _ ___ (_) /__ ____ / ___/ _ `/ _ \/ / -_) / /__/ _ \/ ' \/ _ \/ / / -_) __/ /_/ \_,_/_.__/_/\__/ \___/\___/_/_/_/ .__/_/_/\__/_/ _____________________________________/_/________________ /___/___/___/___/___/___/___/___/___/___/___/___/___/___/ CopyRight (C) 2020 Team @Hexcode - Repl.it : Github - Corigan01 ---------------------------------------------------------------------------------------------- Compiler Options: --help : Brings up the Help menu for the compiler --DEBUG_INFO : Gives all parsing and compile operations going on inside of the compiler "Filename" : Gives a file for the compiler to compile ---------------------------------------------------------------------------------------------- Example on basic use ./Compiler "main.pable" ---------------------------------------------------------------------------------------------- )" << std::endl; } else if (InputArgs[0] != '-' && InputArgs.find("./") == std::string::npos) { WorkingFileName = InputArgs; } else if (InputArgs.find("./") != std::string::npos) { ; } else { std::cout << "Input " << InputArgs << " is not a vailid input" << std::endl; } } if (WorkingFileName == "") { std::cout << "You must enter a file name to compile!" << std::endl; exit(1); } // token start FileIO file; file.ReadFile(WorkingFileName); FileIO Token_file; Token_file.FileContent = { "help", "out $VAR_STRING", "in", "string", "int", "bool", "color_out", "if", "end", "while", "break", "readfile"}; std::vector<std::string> VarTypesInToken = {"string", "int"}; std::vector<Token> Tokens; std::vector<Var> Pable_vars; // This is a globles std::vector<Scope> pable_scope; int RestartLine = -1; int RestartLineHold = -1; int EndRestartLine = -1; bool RestartIfHeld = 0; for (auto i : Token_file.FileContent) { auto output = split(i, " "); if (output.size() > 1) { Token token; token.token = output[0]; output.erase(output.begin()); token.TokenContent = output; token.NumArg = output.size(); for (auto i : output) { if (i == "$VAR_STRING") { token.VartypeInArg.push_back(VAR_STRING); } else if (i == "$VAR_INT") { token.VartypeInArg.push_back(VAR_INT); } else { dis.out(D_ERROR, "Arg type with name --> " + i + " can not be found in the list of args!"); usleep(1000); exit(1); } } Tokens.push_back(token); } else if (output.size() == 1) { Token token; token.token = output[0]; token.NumArg = 0; Tokens.push_back(token); } else { continue; } } auto PableFileContent = file.FileContent; int lineMove = 0; for (int ParseLineN = 0; ParseLineN < PableFileContent.size(); ParseLineN++) { // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if (RestartLine != -1) { ParseLineN = RestartLine; RestartLine = -1; dis.out(D_INFO, "We restarted code at line --> " + std::to_string(ParseLineN)); } std::string i = PableFileContent[ParseLineN + lineMove]; WorkingLine = ParseLineN; //std::cout << __LINE__ << std::endl; //i = RemoveWhiteSpace(i); dis.out(D_INFO, i); int commentfound = i.find("#"); int eb = i.size(); if (commentfound != -1) { for (int e = 0; e < (eb - commentfound); e++ ) { i.erase(i.begin() + commentfound); } } //Pable_in() int found_input = i.find("in("); eb = i.size(); if (found_input != -1) { std::string pableInput; std::cout << "Pable Program input: "; std::getline (std::cin, pableInput); dis.out(D_FILE, "Got input with content of --> " + pableInput); pableInput.insert(0, "\""); pableInput.push_back('\"'); for (int e = 0; e < 4; e ++) { i.erase(i.begin() + found_input); } i.insert(found_input, pableInput); } //Pable_Randomizer int foundRand_input = i.find("rand("); eb = i.size(); if (found_input != -1) { } /* ------------------------------------------------ OPERATORS SEGMENT ------------------------------------------------ */ BeginAgain: found_input = i.find_first_of("*/+-"); eb = i.size(); if (found_input != -1) { int InsertSizeB = 0, InsertSizeE = 0; StringSplit splite = SplitString(i, "*/+-"); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.BeforeChar); // before char operations first check std::string FinalS1 = ""; std::string FinalS2 = ""; std::string FinalS2Pre = splite.AfterChar; int FoundPos1 = 0; int found_S1_back = splite.BeforeChar.find_last_of("= ("); FoundPos1 = found_S1_back; for (int e = 0; e < found_S1_back + 1; e++) { InsertSizeB++; splite.BeforeChar.erase(splite.BeforeChar.begin()); } FinalS1 = splite.BeforeChar; bool FirstCharNeg = 0; if (!(FinalS1.size() > 0)) { FirstCharNeg = 1; splite.AfterChar.erase(splite.AfterChar.begin()); StringSplit FinalSpliteDiff = SplitString(splite.AfterChar, "*/+-"); if (FinalSpliteDiff.BeforeChar.size() == 0) { goto FinalAfterCal; } RemoveWhiteSpace(FinalSpliteDiff.AfterChar); RemoveWhiteSpaceBack(FinalSpliteDiff.BeforeChar); // after check but still before char found_S1_back = FinalSpliteDiff.BeforeChar.find_last_of("= ("); FoundPos1 = found_input; if (found_S1_back != -1) { for (int e = 0; e < found_S1_back + 1; e++) { InsertSizeB++; FinalSpliteDiff.BeforeChar.erase(FinalSpliteDiff.BeforeChar.begin()); } } FinalS2Pre = FinalSpliteDiff.AfterChar; FinalS1 = FinalSpliteDiff.BeforeChar; } InsertSizeE = FinalS1.size() + FinalS2Pre.size(); RemoveWhiteSpace(FinalS2Pre); std::string FinalS2Pre_Load = FinalS2Pre; FinalS2Pre_Load.erase(FinalS2Pre_Load.begin()); int RemoveAccum = 0; for (int e = 0; e < FinalS2Pre_Load.size(); e++) { if (FinalS2Pre_Load[e - RemoveAccum] == ' ') { FinalS2Pre_Load.erase(FinalS2Pre_Load.begin() + e - RemoveAccum); RemoveAccum ++; } } if (FirstCharNeg) FinalS1.insert(FinalS1.begin(), '-'); bool NegFlag = 0; if (FinalS2Pre_Load[0] == '-') { FinalS2Pre_Load.erase(FinalS2Pre_Load.begin()); NegFlag =1; } int FoundSecond = FinalS2Pre_Load.find_first_of("+-*/"); std::string AppendAfter = ""; if (FoundSecond != -1) { for (int e = 0; e < FoundSecond; e ++) { FinalS2 += FinalS2Pre_Load[e]; //InsertSizeE++; } for (int e = FoundSecond; e < FinalS2Pre_Load.size(); e++) { AppendAfter += FinalS2Pre_Load[e]; } } else { FinalS2 = FinalS2Pre_Load; //InsertSizeE = FinalS2.size(); } if (NegFlag) FinalS2.insert(FinalS2.begin(), '-'); dis.out(D_DEBUG, "FINALS2 = " + FinalS2); char FirstCharInFinal = FinalS2Pre[0]; int FinalOutput = 0; dis.out(D_FILE, "Got " + FinalS1 + " and " + FinalS2 + " for calculation!"); for (auto e : Pable_vars) { if (e.VarName == FinalS1) { FinalS1 = e.VarContent; } if (e.VarName == FinalS2) { FinalS2 = e.VarContent; } } try { switch (FirstCharInFinal) { case '-': FinalOutput = std::stoi(FinalS1) - std::stoi(FinalS2); break; case '+': FinalOutput = std::stoi(FinalS1) + std::stoi(FinalS2); break; case '/': FinalOutput = std::stoi(FinalS1) / std::stoi(FinalS2); break; case '*': FinalOutput = std::stoi(FinalS1) * std::stoi(FinalS2); break; default: Pable_ERROR("Unsupported Token"); break; } } catch(const std::exception& e) { Pable_ERROR("Unstable Operators - Convert to int failed or a illegal operation was found!"); } // int i = 4 + 3 dis.out(D_FILE, "Got Calculation Output of " + std::to_string(FinalOutput)); int FoundPos2 = FinalS2.size(); dis.out(D_DEBUG, "Got Pos 1: " + std::to_string(InsertSizeB) + " and Pos2: " + std::to_string(InsertSizeE + InsertSizeB)); int Accum = i.size(); for (int e = InsertSizeB; e < Accum; e++) { i.erase(i.begin() + InsertSizeB ); //Accum++; } i.insert( InsertSizeB , std::to_string(FinalOutput) + AppendAfter); dis.out(D_INFO, "GOTL: " + i); goto BeginAgain; } FinalAfterCal: RemoveWhiteSpace(i); RemoveWhiteSpaceBack(i); std::string FoundPosUss = std::to_string(i[0]); if (FoundStringDef(i)) { dis.out(D_INFO, "Found useless var"); continue; } else if (FoundPosUss.find_first_of("-01234567890") == std::string::npos) { continue; } /* ------------------------------------------------ built-ins ------------------------------------------------ */ if (i.size() > 0) { size_t found = i.find_first_of(" (="); std::string FoundToken = i; std::string args = ""; if (found != std::string::npos) { dis.out(D_FILE, "Found out command at a pos : " + std::to_string(found)); for (int e = found; e < i.size(); e++) { args.push_back(FoundToken[found]); FoundToken.erase(FoundToken.begin() + found); } RemoveWhiteSpace(args); dis.out(D_FILE, "Found token --> \'" + FoundToken + "\' with args --> \'" + args + "\'"); } bool FoundInArray = 0; bool FoundComment = 0; for (auto e : Tokens) { if (FoundToken == e.token) { FoundInArray = 1; } } RemoveWhiteSpace(FoundToken); RemoveWhiteSpaceBack(FoundToken); bool CC_Con = 0; for (int e = 0; e < Pable_vars.size(); e++) { if (Pable_vars[e].VarName == FoundToken) { std::string LatArg = args; if (CheckIfEqual(LatArg)) { LatArg.erase(LatArg.begin()); } else { Pable_ERROR("You need to have a = to define a var"); } RemoveWhiteSpace(LatArg); std::string VarContent; dis.out(D_DEBUG, "Var Is equal to " + std::to_string(Pable_vars[e].VarType)); if (Pable_vars[e].VarType == VAR_STRING) VarContent = ExtractStringDef(LatArg); else if (Pable_vars[e].VarType == VAR_INT) { VarContent = LatArg; } else { Pable_ERROR("Could not reassign var"); } dis.out(D_INFO, "Found Var reassign \'" + FoundToken + "\' and content of --> \'" + VarContent + "\'"); Pable_vars[e].VarContent = VarContent; CC_Con = 1; } } if (CC_Con) { continue; } if (!FoundInArray) { Pable_ERROR( "Token with name --> \'" + FoundToken + "\' was not found in the list of tokens!\n\tOf command --> " + i); } // Pabble_out() if (FoundToken == "out") { if (args.size() > 0) { if (args[0] == '(') { args.erase(args.begin()); RemoveWhiteSpace(args); if (FoundStringDef(args)) { std::cout << ExtractStringDef(args) << std::endl; } else { if (!IsfoundinVar(Pable_vars, args)) { Pable_ERROR("Need '\"' to begin a string def because var with name could not be found in the list of defined vars!"); } } } else { Pable_ERROR("Need '(' to begin a function call!"); } } } //Pable_if(): else if (FoundToken == "if"){ dis.out(D_DEBUG, "Found if statement"); if (args.size() > 0) { if (args[0] == '(') { args.erase(args.begin()); RemoveWhiteSpace(args); bool output = 0; //std::string FoundIf = ExtractStringDef(args); if(args.find_first_of(">=<!") == -1 ){ output = args == "true)"; if (!output) { if (args != "false)") { Pable_ERROR("You must use true or false in an if statement!"); } } } else { StringSplit splite = SplitString(args, "=><!"); RemoveWhiteSpace(splite.BeforeChar); RemoveWhiteSpace(splite.AfterChar); std::string FirstClause = ""; std::string SecondClause = ""; //dis.out(D_DEBUG, FirstClause); //dis.out(D_DEBUG, SecondClause); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); char CharUse = splite.AfterChar[0]; bool isInt = 0; splite.AfterChar.erase(splite.AfterChar.begin()); splite.AfterChar.erase(splite.AfterChar.begin() + splite.AfterChar.size() - 1); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.BeforeChar); std::string PableVar = ""; std::string FirstChar = std::to_string(splite.BeforeChar[0]); if(CheckIfVar(Pable_vars, splite.BeforeChar)){ splite.BeforeChar += ")"; PableVar = FoundVarContent(Pable_vars, splite.BeforeChar); FirstClause = PableVar; } else if (FoundStringDef(splite.BeforeChar)) { FirstClause = ExtractStringDef(splite.BeforeChar); dis.out(D_INFO, "Found String Def for BeforeChar"); } else if (FirstChar.find_first_of("-0123456789") != std::string::npos) { FirstClause = ExtractIntDef(splite.BeforeChar); dis.out(D_INFO, "Found Int Def for BeforeChar"); } else FirstChar = std::to_string(splite.AfterChar[0]); if(CheckIfVar(Pable_vars, splite.AfterChar)){ splite.AfterChar += ")"; PableVar = FoundVarContent(Pable_vars, splite.AfterChar); SecondClause = PableVar; } else if (FoundStringDef(splite.AfterChar)) { SecondClause = ExtractStringDef(splite.AfterChar); dis.out(D_INFO, "Found String Def for AfterChar"); } else if (FirstChar.find_first_of("-0123456789") != std::string::npos) { SecondClause = std::to_string(ExtractIntDef(splite.AfterChar)); dis.out(D_INFO, "Found Int Def for AfterChar"); } dis.out(D_INFO, "Check if First and Second is equal > " + FirstClause + " : " + SecondClause); switch (CharUse) { case '=': output = FirstClause == SecondClause; break; case '>': if (isInt) output = FirstClause > SecondClause; else Pable_ERROR("Can only do \'>\' on a number not a string!"); break; case '<': if (isInt) output = FirstClause < SecondClause; else Pable_ERROR("Can only do \'<\' on a number not a string!"); break; case '!': if (isInt) output = FirstClause != SecondClause; else Pable_ERROR("Can only do \'!\' on a number not a string!"); break; default: Pable_ERROR("Operation not supported!"); break; } } int FoundLineOf = ParseLineN; int FoundEndToif = -1; for (int e = ParseLineN; e < PableFileContent.size(); e++) { std::string TempFound = PableFileContent[e]; RemoveWhiteSpace(TempFound); RemoveWhiteSpaceBack(TempFound); if(TempFound == "end") { FoundEndToif = e; dis.out(D_FILE, "Found the end to the if statement at pos " + std::to_string(e + 1)); } } if (FoundEndToif == -1) { Pable_ERROR("Could not find the end to the if statement!"); } if (output){ dis.out(D_INFO, "Found that the if statement is true! I sure dont!"); } else { dis.out(D_INFO, "Found that the if statement is false! I sure do!"); RestartLine = FoundEndToif; continue; } } } } //Pable_while() else if (FoundToken == "while"){ dis.out(D_DEBUG, "Found while loop"); if (args.size() > 0) { if (args[0] == '(') { args.erase(args.begin()); RemoveWhiteSpace(args); bool output = 0; //std::string FoundIf = ExtractStringDef(args); if(args.find_first_of(">=<!") == -1 ){ output = args == "true)"; if (!output) { if (args != "false)") { Pable_ERROR("You must use true or false in a while statement!"); } } //while(this == this) while(true) } else { StringSplit splite = SplitString(args, "=<>!"); RemoveWhiteSpace(splite.BeforeChar); RemoveWhiteSpace(splite.AfterChar); std::string FirstClause = ""; std::string SecondClause = ""; //dis.out(D_DEBUG, FirstClause); //dis.out(D_DEBUG, SecondClause); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); char CharUse = splite.AfterChar[0]; bool isInt = 0; splite.AfterChar.erase(splite.AfterChar.begin()); splite.AfterChar.erase(splite.AfterChar.begin() + splite.AfterChar.size() - 1); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.BeforeChar); std::string PableVar = ""; std::string FirstChar = std::to_string(splite.BeforeChar[0]); if(CheckIfVar(Pable_vars, splite.BeforeChar)){ splite.BeforeChar += ")"; PableVar = FoundVarContent(Pable_vars, splite.BeforeChar); FirstClause = PableVar; } else if (FoundStringDef(splite.BeforeChar)) { FirstClause = ExtractStringDef(splite.BeforeChar); dis.out(D_INFO, "Found String Def for BeforeChar"); } else if (FirstChar.find_first_of("-0123456789") != std::string::npos) { FirstClause = ExtractIntDef(splite.BeforeChar); dis.out(D_INFO, "Found Int Def for BeforeChar"); } else FirstChar = std::to_string(splite.AfterChar[0]); if(CheckIfVar(Pable_vars, splite.AfterChar)){ splite.AfterChar += ")"; PableVar = FoundVarContent(Pable_vars, splite.AfterChar); SecondClause = PableVar; isInt = 1; } else if (FoundStringDef(splite.AfterChar)) { SecondClause = ExtractStringDef(splite.AfterChar); dis.out(D_INFO, "Found String Def for AfterChar"); } else if (FirstChar.find_first_of("-0123456789") != std::string::npos) { SecondClause = std::to_string(ExtractIntDef(splite.AfterChar)); dis.out(D_INFO, "Found Int Def for AfterChar"); isInt = 1; } dis.out(D_INFO, "Check if First and Second is equal > " + FirstClause + " : " + SecondClause); switch (CharUse) { case '=': output = FirstClause == SecondClause; break; case '>': if (isInt) output = FirstClause > SecondClause; else Pable_ERROR("Can only do \'>\' on a number not a string!"); break; case '<': if (isInt) output = FirstClause < SecondClause; else Pable_ERROR("Can only do \'<\' on a number not a string!"); break; case '!': if (isInt) output = FirstClause != SecondClause; else Pable_ERROR("Can only do \'!\' on a number not a string!"); break; default: Pable_ERROR("Operation not supported!"); break; } } int FoundLineOf = ParseLineN; int FoundEndToif = -1; for (int e = ParseLineN; e < PableFileContent.size(); e++) { std::string TempFound = PableFileContent[e]; RemoveWhiteSpace(TempFound); RemoveWhiteSpaceBack(TempFound); if(TempFound == "end") { FoundEndToif = e; dis.out(D_FILE, "Found the end to the while statement at pos " + std::to_string(e + 1)); } } if (FoundEndToif == -1) { Pable_ERROR("Could not find the end to the while statement!"); } if (output){ dis.out(D_INFO, "Found that the while statement is true! I sure dont!"); RestartLineHold = ParseLineN; RestartIfHeld = 1; EndRestartLine = FoundEndToif; dis.out(D_INFO, "FoundLineOf: " + std::to_string(RestartLineHold)); } else { dis.out(D_INFO, "Found that the while statement is false! I sure do!"); RestartLine = FoundEndToif; continue; } } } } else if (FoundToken == "break") { dis.out(D_WARNING, "Breaking From loop"); RestartLine = EndRestartLine; RestartLineHold = -1; RestartIfHeld = 0; EndRestartLine = -1; } //for(int e = somethin | e < somethin | e++): //color_out() else if (FoundToken == "color_out"){ if(args.size() > 0){ if(args[0] == '('){ args.erase(args.begin()); RemoveWhiteSpace(args); if(FoundStringDef(args)){ StringSplit splite = SplitString(args, ","); RemoveWhiteSpace(splite.BeforeChar); RemoveWhiteSpace(splite.AfterChar); std::string Output = ExtractStringDef(args); std::string Color = splite.AfterChar; RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); splite.AfterChar.erase(splite.AfterChar.begin()); splite.AfterChar.erase(splite.AfterChar.begin() + splite.AfterChar.size() - 1); RemoveWhiteSpace(splite.AfterChar); RemoveWhiteSpaceBack(splite.AfterChar); Color = splite.AfterChar; dis.out(D_INFO, "Found Output:" + Output); dis.out(D_INFO, "Found Color:" + Color); if(Color == "GREEN"){ std::cout << D_COLOR::greenM << Output << D_COLOR::defM << std::endl; } else if(Color == "BLUE"){ std::cout << D_COLOR::blueM << Output << D_COLOR::defM << std::endl; } else if(Color == "RED"){ std::cout << D_COLOR::redM << Output << D_COLOR::defM << std::endl; } else if(Color == "YELLOW"){ std::cout << D_COLOR::yellowM << Output << D_COLOR::defM << std::endl; } else if(Color == "MAGENTA"){ std::cout << D_COLOR::magentaM << Output << D_COLOR::defM << std::endl; } else { Pable_ERROR("We do not support that color yet!"); } } } } } //end else if (FoundToken == "end") { dis.out(D_INFO, "Found End of the statement!"); if (RestartIfHeld) { RestartLine = RestartLineHold; RestartIfHeld = 0; } } else if (FoundToken == "readfile"){ if (args.size() > 0) { if (args[0] == '(') { args.erase(args.begin()); RemoveWhiteSpace(args); if (FoundStringDef(args)){ std::cout << ExtractStringDef(args) << std::endl; std::string FileName = ExtractStringDef(args); FileIO OpenedFile; OpenedFile.ReadFile(FileName); for (auto e : OpenedFile.FileContent) { std::cout << e << std::endl; } } } } } //Pabble_string else if (FoundToken == "string") { StringSplit splite = SplitString(args, " ("); std::string VarName = splite.BeforeChar; std::string LatArg = splite.AfterChar; RemoveWhiteSpace(LatArg); if (CheckIfEqual(LatArg)) { LatArg.erase(LatArg.begin()); } else { Pable_ERROR("You need to have a = to define a var"); } RemoveWhiteSpace(LatArg); Var TempVar; if (VAR_STRING != DetectVarType(LatArg)) { Pable_ERROR("A string def needs to have a string as a definer!"); } if (FoundStringDef(LatArg)) { std::string VarContent = ExtractStringDef(LatArg); dis.out(D_INFO, "Found Var with name of \'" + VarName + "\' and content of --> \'" + VarContent + "\'"); TempVar.StoreVar(VAR_STRING, VarContent, VarName); Pable_vars.push_back(TempVar); } else { Pable_ERROR("Unknown char --> " + LatArg[0]); } } //Pabble_int else if (FoundToken == "int") { StringSplit splite = SplitString(args, " (="); std::string VarName = splite.BeforeChar; std::string LatArg = splite.AfterChar; RemoveWhiteSpace(LatArg); if (CheckIfEqual(LatArg)) { LatArg.erase(LatArg.begin()); } else { Pable_ERROR("You need to have a = to define a var"); } RemoveWhiteSpace(LatArg); Var TempVar; if (VAR_INT != DetectVarType(LatArg)) { Pable_ERROR("A int def needs to have a int as a definer!"); } std::string FirstChar = std::to_string(LatArg[0]); if (FirstChar.find_first_of("-0123456789") != std::string::npos) { std::string VarContent = std::to_string(ExtractIntDef(LatArg)); dis.out(D_INFO, "Found Var with name of \'" + VarName + "\' and content of --> \'" + VarContent + "\'"); TempVar.StoreVar(VAR_INT, VarContent, VarName); Pable_vars.push_back(TempVar); } else { Pable_ERROR("Unknown char --> " + std::to_string(LatArg[0])); } } else if (FoundToken == "help") { std::cout << D_COLOR::greenM << R"( Help with the Pable Programming language ------------------------------- Built-ins: in(), out() Variable Types: string, int -------------------------------- Getting started program: -------------------------------- string MyStr = in() # this will set the string \'MyStr\' to whatever you input out(MyStr) # this will output the content of \'MyStr\' --------------------------------)" << D_COLOR::defM << std::endl; } else { Pable_ERROR("Command not supported yet, we are working on it!\n\t--> " + i); } } else { dis.out(D_WARNING, "Null line"); } //std::cout << __LINE__ << std::endl; } auto end = std::chrono::high_resolution_clock::now(); double time_taken = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; std::cout << std::endl << "Pable compiled in: " << std::fixed << time_taken << std::setprecision(9); std::cout << " seconds" << std::endl; return 0; }
[ "corigan01@gmail.com" ]
corigan01@gmail.com
8596fa1ab0692ed4f08cad4b8ae7af0bf5439451
fc987ace8516d4d5dfcb5444ed7cb905008c6147
/media/base/mime_util_internal.h
0ef772c72ed2c16e3c01226401f48beb45a69ba1
[ "BSD-3-Clause" ]
permissive
nfschina/nfs-browser
3c366cedbdbe995739717d9f61e451bcf7b565ce
b6670ba13beb8ab57003f3ba2c755dc368de3967
refs/heads/master
2022-10-28T01:18:08.229807
2020-09-07T11:45:28
2020-09-07T11:45:28
145,939,440
2
4
BSD-3-Clause
2022-10-13T14:59:54
2018-08-24T03:47:46
null
UTF-8
C++
false
false
7,021
h
// Copyright 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. #ifndef MEDIA_BASE_MIME_UTIL_INTERNAL_H_ #define MEDIA_BASE_MIME_UTIL_INTERNAL_H_ #include <map> #include <string> #include <vector> #include "base/containers/hash_tables.h" #include "base/macros.h" #include "media/base/media_export.h" #include "media/base/mime_util.h" #include "media/base/video_codecs.h" namespace media { namespace internal { // Internal utility class for handling mime types. Should only be invoked by // tests and the functions within mime_util.cc -- NOT for direct use by others. class MEDIA_EXPORT MimeUtil { public: MimeUtil(); ~MimeUtil(); enum Codec { INVALID_CODEC, PCM, MP3, AC3, EAC3, MPEG2_AAC, MPEG4_AAC, VORBIS, OPUS, H264, HEVC, VP8, VP9, MPEG4, THEORA, LAST_CODEC = THEORA }; // Platform configuration structure. Controls which codecs are supported at // runtime. Also used by tests to simulate platform differences. struct PlatformInfo { bool has_platform_decoders = false; bool has_platform_vp8_decoder = false; bool has_platform_vp9_decoder = false; bool supports_opus = false; bool is_unified_media_pipeline_enabled = false; }; // See mime_util.h for more information on these methods. bool IsSupportedMediaMimeType(const std::string& mime_type) const; void ParseCodecString(const std::string& codecs, std::vector<std::string>* codecs_out, bool strip); SupportsType IsSupportedMediaFormat(const std::string& mime_type, const std::vector<std::string>& codecs, bool is_encrypted) const; void RemoveProprietaryMediaTypesAndCodecs(); // Checks special platform specific codec restrictions. Returns true if // |codec| is supported when contained in |mime_type_lower_case|. // |is_encrypted| means the codec will be used with encrypted blocks. // |platform_info| describes the availability of various platform features; // see PlatformInfo for more details. static bool IsCodecSupportedOnPlatform( Codec codec, const std::string& mime_type_lower_case, bool is_encrypted, const PlatformInfo& platform_info); private: typedef base::hash_set<int> CodecSet; typedef std::map<std::string, CodecSet> MediaFormatMappings; struct CodecEntry { CodecEntry() : codec(INVALID_CODEC), is_ambiguous(true) {} CodecEntry(Codec c, bool ambiguous) : codec(c), is_ambiguous(ambiguous) {} Codec codec; bool is_ambiguous; }; typedef std::map<std::string, CodecEntry> StringToCodecMappings; // Initializes the supported media types into hash sets for faster lookup. void InitializeMimeTypeMaps(); // Initializes the supported media formats (|media_format_map_|). void AddSupportedMediaFormats(); // Adds |mime_type| with the specified codecs to |media_format_map_|. void AddContainerWithCodecs(const std::string& mime_type, const CodecSet& codecs_list, bool is_proprietary_mime_type); // Returns IsSupported if all codec IDs in |codecs| are unambiguous and are // supported in |mime_type_lower_case|. MayBeSupported is returned if at least // one codec ID in |codecs| is ambiguous but all the codecs are supported. // IsNotSupported is returned if |mime_type_lower_case| is not supported or at // least one is not supported in |mime_type_lower_case|. |is_encrypted| means // the codec will be used with encrypted blocks. SupportsType AreSupportedCodecs(const CodecSet& supported_codecs, const std::vector<std::string>& codecs, const std::string& mime_type_lower_case, bool is_encrypted) const; // Converts a codec ID into an Codec enum value and indicates // whether the conversion was ambiguous. // Returns true if this method was able to map |codec_id| with // |mime_type_lower_case| to a specific Codec enum value. |codec| and // |is_ambiguous| are only valid if true is returned. Otherwise their value is // undefined after the call. // |is_ambiguous| is true if |codec_id| did not have enough information to // unambiguously determine the proper Codec enum value. If |is_ambiguous| // is true |codec| contains the best guess for the intended Codec enum value. // |profile| and |level| indicate video codec profile and level (unused for // audio codecs). // |is_encrypted| means the codec will be used with encrypted blocks. bool StringToCodec(const std::string& mime_type_lower_case, const std::string& codec_id, Codec* codec, bool* is_ambiguous, VideoCodecProfile* out_profile, uint8_t* out_level, bool is_encrypted) const; // Returns true if |codec| is supported when contained in // |mime_type_lower_case|. Note: This method will always return false for // proprietary codecs if |allow_proprietary_codecs_| is set to false. // |is_encrypted| means the codec will be used with encrypted blocks. bool IsCodecSupported(Codec codec, const std::string& mime_type_lower_case, bool is_encrypted) const; // Returns true if |codec| refers to a proprietary codec. bool IsCodecProprietary(Codec codec) const; // Returns true and sets |*default_codec| if |mime_type| has a default codec // associated with it. Returns false otherwise and the value of // |*default_codec| is undefined. bool GetDefaultCodecLowerCase(const std::string& mime_type_lower_case, Codec* default_codec) const; // Returns true if |mime_type_lower_case| has a default codec associated with // it and IsCodecSupported() returns true for that particular codec. // |is_encrypted| means the codec will be used with encrypted blocks. bool IsDefaultCodecSupportedLowerCase(const std::string& mime_type_lower_case, bool is_encrypted) const; #if defined(OS_ANDROID) // Indicates the support of various codecs within the platform. PlatformInfo platform_info_; #endif // A map of mime_types and hash map of the supported codecs for the mime_type. MediaFormatMappings media_format_map_; // List of proprietary containers in |media_format_map_|. std::vector<std::string> proprietary_media_containers_; // Whether proprietary codec support should be advertised to callers. bool allow_proprietary_codecs_; // Lookup table for string compare based string -> Codec mappings. StringToCodecMappings string_to_codec_map_; DISALLOW_COPY_AND_ASSIGN(MimeUtil); }; } // namespace internal } // namespace media #endif // MEDIA_BASE_MIME_UTIL_INTERNAL_H_
[ "hukun@nfschina.com" ]
hukun@nfschina.com
bdc57fea99f986e419bbb983a388218b29a0dbeb
6d8ddc2d137f22b1b08fb15fcfde7a88826fbb7c
/Protocol/Packets/GetAccountMoneyResponsePacket.h
9ab0f7aecfc19334c05f9f68c2f739cef4d052ce
[]
no_license
renair/BankServer
757425f9d373b56c558f4149398770457598c1da
069726f254d02bf280398f4e3b04287af14b9d69
refs/heads/master
2021-08-29T17:01:38.573449
2017-12-14T11:03:04
2017-12-14T11:03:04
104,252,818
2
0
null
null
null
null
UTF-8
C++
false
false
870
h
#ifndef GETACCOUNTMONEYRESPONSEPACKET_H #define GETACCOUNTMONEYRESPONSEPACKET_H #include "../Packet.h" class GetAccountMoneyResponsePacket : public Packet { private: // Fields. quint64 _accountId; quint64 _amount; // MC. virtual char specificGetID() const; virtual PacketHolder specificClone() const; virtual QByteArray specificDump() const; virtual void specificLoad(QBuffer&); public: GetAccountMoneyResponsePacket(); GetAccountMoneyResponsePacket(quint64 accountId, quint64 amount); ~GetAccountMoneyResponsePacket(); quint64& accountId() { return _accountId; } quint64& amount() { return _amount; } quint64 accountId() const { return _accountId; } quint64 amount() const { return _amount; } }; #endif // GETACCOUNTMONEYRESPONSEPACKET_H
[ "platinium9889@gmail.com" ]
platinium9889@gmail.com
c8d306f55b37e7c32fc99277163de3809dc2eba4
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/chrome/browser/win/conflicts/module_blacklist_cache_updater_unittest.cc
619a477d9daffb7ce5356077c7e006761c34b6fb
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
15,593
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/win/conflicts/module_blacklist_cache_updater.h" #include <windows.h> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_util.h" #include "base/hash/sha1.h" #include "base/i18n/case_conversion.h" #include "base/logging.h" #include "base/optional.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_path_override.h" #include "base/test/task_environment.h" #include "base/test/test_reg_util_win.h" #include "base/win/pe_image.h" #include "base/win/registry.h" #include "chrome/browser/win/conflicts/module_blacklist_cache_util.h" #include "chrome/browser/win/conflicts/module_info.h" #include "chrome/browser/win/conflicts/module_list_filter.h" #include "chrome/common/chrome_paths.h" #include "chrome/install_static/install_util.h" #include "content/public/common/process_type.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr base::FilePath::CharType kCertificatePath[] = FILE_PATH_LITERAL("CertificatePath"); constexpr base::FilePath::CharType kCertificateSubject[] = FILE_PATH_LITERAL("CertificateSubject"); constexpr base::FilePath::CharType kDllPath1[] = FILE_PATH_LITERAL("c:\\path\\to\\module.dll"); constexpr base::FilePath::CharType kDllPath2[] = FILE_PATH_LITERAL("c:\\some\\shellextension.dll"); // Returns a new ModuleInfoData marked as loaded into the browser process but // otherwise empty. ModuleInfoData CreateLoadedModuleInfoData() { ModuleInfoData module_data; module_data.module_properties |= ModuleInfoData::kPropertyLoadedModule; module_data.process_types |= ProcessTypeToBit(content::PROCESS_TYPE_BROWSER); module_data.inspection_result = base::make_optional<ModuleInspectionResult>(); return module_data; } // Returns a new ModuleInfoData marked as loaded into the process with a // CertificateInfo that matches kCertificateSubject. ModuleInfoData CreateSignedLoadedModuleInfoData() { ModuleInfoData module_data = CreateLoadedModuleInfoData(); module_data.inspection_result->certificate_info.type = CertificateInfo::Type::CERTIFICATE_IN_FILE; module_data.inspection_result->certificate_info.path = base::FilePath(kCertificatePath); module_data.inspection_result->certificate_info.subject = kCertificateSubject; return module_data; } void GetModulePath(HMODULE module_handle, base::FilePath* module_path) { base::FilePath result; wchar_t buffer[MAX_PATH]; DWORD length = ::GetModuleFileName(module_handle, buffer, MAX_PATH); ASSERT_NE(length, 0U); ASSERT_LT(length, static_cast<DWORD>(MAX_PATH)); *module_path = base::FilePath(buffer); } // Returns true if the cache path registry key value exists. bool RegistryKeyExists() { base::win::RegKey reg_key(HKEY_CURRENT_USER, install_static::GetRegistryPath() .append(third_party_dlls::kThirdPartyRegKeyName) .c_str(), KEY_READ); return reg_key.HasValue(third_party_dlls::kBlFilePathRegValue); } } // namespace class ModuleBlacklistCacheUpdaterTest : public testing::Test, public ModuleDatabaseEventSource { protected: ModuleBlacklistCacheUpdaterTest() : dll1_(kDllPath1), dll2_(kDllPath2), task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME), user_data_dir_override_(chrome::DIR_USER_DATA), module_list_filter_(CreateModuleListFilter()), module_blacklist_cache_path_( ModuleBlacklistCacheUpdater::GetModuleBlacklistCachePath()) { exe_certificate_info_.type = CertificateInfo::Type::CERTIFICATE_IN_FILE; exe_certificate_info_.path = base::FilePath(kCertificatePath); exe_certificate_info_.subject = kCertificateSubject; } void SetUp() override { ASSERT_TRUE(base::CreateDirectory(module_blacklist_cache_path().DirName())); ASSERT_NO_FATAL_FAILURE( registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER)); } std::unique_ptr<ModuleBlacklistCacheUpdater> CreateModuleBlacklistCacheUpdater() { return std::make_unique<ModuleBlacklistCacheUpdater>( this, exe_certificate_info_, module_list_filter_, initial_blacklisted_modules_, base::BindRepeating( &ModuleBlacklistCacheUpdaterTest::OnModuleBlacklistCacheUpdated, base::Unretained(this)), false); } void RunUntilIdle() { task_environment_.RunUntilIdle(); } void FastForwardBy(base::TimeDelta delta) { task_environment_.FastForwardBy(delta); // The expired timer callback posts a task to update the cache. Wait for it // to finish. task_environment_.RunUntilIdle(); } base::FilePath& module_blacklist_cache_path() { return module_blacklist_cache_path_; } bool on_cache_updated_callback_invoked() { return on_cache_updated_callback_invoked_; } // ModuleDatabaseEventSource: void AddObserver(ModuleDatabaseObserver* observer) override {} void RemoveObserver(ModuleDatabaseObserver* observer) override {} const base::FilePath dll1_; const base::FilePath dll2_; private: scoped_refptr<ModuleListFilter> CreateModuleListFilter() { chrome::conflicts::ModuleList module_list; // Include an empty blacklist and whitelist. module_list.mutable_blacklist(); module_list.mutable_whitelist(); // Serialize the module list to the user data directory. base::FilePath module_list_path; if (!base::PathService::Get(chrome::DIR_USER_DATA, &module_list_path)) return nullptr; module_list_path = module_list_path.Append(FILE_PATH_LITERAL("ModuleList.bin")); std::string contents; if (!module_list.SerializeToString(&contents) || base::WriteFile(module_list_path, contents.data(), static_cast<int>(contents.size())) != static_cast<int>(contents.size())) { return nullptr; } auto module_list_filter = base::MakeRefCounted<ModuleListFilter>(); if (!module_list_filter->Initialize(module_list_path)) return nullptr; return module_list_filter; } void OnModuleBlacklistCacheUpdated( const ModuleBlacklistCacheUpdater::CacheUpdateResult& result) { on_cache_updated_callback_invoked_ = true; } base::test::TaskEnvironment task_environment_; registry_util::RegistryOverrideManager registry_override_manager_; base::ScopedPathOverride user_data_dir_override_; CertificateInfo exe_certificate_info_; scoped_refptr<ModuleListFilter> module_list_filter_; std::vector<third_party_dlls::PackedListModule> initial_blacklisted_modules_; base::FilePath module_blacklist_cache_path_; bool on_cache_updated_callback_invoked_ = false; DISALLOW_COPY_AND_ASSIGN(ModuleBlacklistCacheUpdaterTest); }; TEST_F(ModuleBlacklistCacheUpdaterTest, OneThirdPartyModule) { EXPECT_FALSE(base::PathExists(module_blacklist_cache_path())); auto module_blacklist_cache_updater = CreateModuleBlacklistCacheUpdater(); // Simulate some arbitrary module loading into the process. ModuleInfoKey module_key(dll1_, 0, 0); module_blacklist_cache_updater->OnNewModuleFound( module_key, CreateLoadedModuleInfoData()); module_blacklist_cache_updater->OnModuleDatabaseIdle(); RunUntilIdle(); EXPECT_TRUE(base::PathExists(module_blacklist_cache_path())); EXPECT_TRUE(on_cache_updated_callback_invoked()); EXPECT_TRUE(RegistryKeyExists()); // Check the cache. third_party_dlls::PackedListMetadata metadata; std::vector<third_party_dlls::PackedListModule> blacklisted_modules; base::MD5Digest md5_digest; EXPECT_EQ(ReadResult::kSuccess, ReadModuleBlacklistCache(module_blacklist_cache_path(), &metadata, &blacklisted_modules, &md5_digest)); EXPECT_EQ(1u, blacklisted_modules.size()); ASSERT_EQ( ModuleBlacklistCacheUpdater::ModuleBlockingDecision::kDisallowedImplicit, module_blacklist_cache_updater->GetModuleBlockingState(module_key) .blocking_decision); } TEST_F(ModuleBlacklistCacheUpdaterTest, IgnoreMicrosoftModules) { EXPECT_FALSE(base::PathExists(module_blacklist_cache_path())); // base::RunLoop run_loop; auto module_blacklist_cache_updater = CreateModuleBlacklistCacheUpdater(); // Simulate a Microsoft module loading into the process. base::win::PEImage kernel32_image(::GetModuleHandle(L"kernel32.dll")); ASSERT_TRUE(kernel32_image.module()); base::FilePath module_path; ASSERT_NO_FATAL_FAILURE(GetModulePath(kernel32_image.module(), &module_path)); ASSERT_FALSE(module_path.empty()); uint32_t module_size = kernel32_image.GetNTHeaders()->OptionalHeader.SizeOfImage; uint32_t time_date_stamp = kernel32_image.GetNTHeaders()->FileHeader.TimeDateStamp; ModuleInfoKey module_key(module_path, module_size, time_date_stamp); ModuleInfoData module_data = CreateLoadedModuleInfoData(); module_data.inspection_result = InspectModule(module_key.module_path); module_blacklist_cache_updater->OnNewModuleFound(module_key, module_data); module_blacklist_cache_updater->OnModuleDatabaseIdle(); RunUntilIdle(); EXPECT_TRUE(base::PathExists(module_blacklist_cache_path())); EXPECT_TRUE(on_cache_updated_callback_invoked()); EXPECT_TRUE(RegistryKeyExists()); // Check the cache. third_party_dlls::PackedListMetadata metadata; std::vector<third_party_dlls::PackedListModule> blacklisted_modules; base::MD5Digest md5_digest; EXPECT_EQ(ReadResult::kSuccess, ReadModuleBlacklistCache(module_blacklist_cache_path(), &metadata, &blacklisted_modules, &md5_digest)); EXPECT_EQ(0u, blacklisted_modules.size()); ASSERT_EQ( ModuleBlacklistCacheUpdater::ModuleBlockingDecision::kAllowedMicrosoft, module_blacklist_cache_updater->GetModuleBlockingState(module_key) .blocking_decision); } // Tests that modules with a matching certificate subject are whitelisted. TEST_F(ModuleBlacklistCacheUpdaterTest, WhitelistMatchingCertificateSubject) { EXPECT_FALSE(base::PathExists(module_blacklist_cache_path())); auto module_blacklist_cache_updater = CreateModuleBlacklistCacheUpdater(); // Simulate the module loading into the process. ModuleInfoKey module_key(dll1_, 0, 0); module_blacklist_cache_updater->OnNewModuleFound( module_key, CreateSignedLoadedModuleInfoData()); module_blacklist_cache_updater->OnModuleDatabaseIdle(); RunUntilIdle(); EXPECT_TRUE(base::PathExists(module_blacklist_cache_path())); EXPECT_TRUE(on_cache_updated_callback_invoked()); EXPECT_TRUE(RegistryKeyExists()); // Check the cache. third_party_dlls::PackedListMetadata metadata; std::vector<third_party_dlls::PackedListModule> blacklisted_modules; base::MD5Digest md5_digest; EXPECT_EQ(ReadResult::kSuccess, ReadModuleBlacklistCache(module_blacklist_cache_path(), &metadata, &blacklisted_modules, &md5_digest)); EXPECT_EQ(0u, blacklisted_modules.size()); ASSERT_EQ(ModuleBlacklistCacheUpdater::ModuleBlockingDecision:: kAllowedSameCertificate, module_blacklist_cache_updater->GetModuleBlockingState(module_key) .blocking_decision); } // Make sure IMEs are allowed while shell extensions are blacklisted. TEST_F(ModuleBlacklistCacheUpdaterTest, RegisteredModules) { EXPECT_FALSE(base::PathExists(module_blacklist_cache_path())); auto module_blacklist_cache_updater = CreateModuleBlacklistCacheUpdater(); // Set the respective bit for registered modules. ModuleInfoKey module_key1(dll1_, 123u, 456u); ModuleInfoData module_data1 = CreateLoadedModuleInfoData(); module_data1.module_properties |= ModuleInfoData::kPropertyIme; ModuleInfoKey module_key2(dll2_, 456u, 789u); ModuleInfoData module_data2 = CreateLoadedModuleInfoData(); module_data2.module_properties |= ModuleInfoData::kPropertyShellExtension; // Simulate the modules loading into the process. module_blacklist_cache_updater->OnNewModuleFound(module_key1, module_data1); module_blacklist_cache_updater->OnNewModuleFound(module_key2, module_data2); module_blacklist_cache_updater->OnModuleDatabaseIdle(); RunUntilIdle(); EXPECT_TRUE(base::PathExists(module_blacklist_cache_path())); EXPECT_TRUE(on_cache_updated_callback_invoked()); EXPECT_TRUE(RegistryKeyExists()); // Check the cache. third_party_dlls::PackedListMetadata metadata; std::vector<third_party_dlls::PackedListModule> blacklisted_modules; base::MD5Digest md5_digest; EXPECT_EQ(ReadResult::kSuccess, ReadModuleBlacklistCache(module_blacklist_cache_path(), &metadata, &blacklisted_modules, &md5_digest)); // Make sure the only blacklisted module is the shell extension. ASSERT_EQ(1u, blacklisted_modules.size()); ASSERT_EQ(ModuleBlacklistCacheUpdater::ModuleBlockingDecision::kAllowedIME, module_blacklist_cache_updater->GetModuleBlockingState(module_key1) .blocking_decision); ASSERT_EQ( ModuleBlacklistCacheUpdater::ModuleBlockingDecision::kDisallowedImplicit, module_blacklist_cache_updater->GetModuleBlockingState(module_key2) .blocking_decision); third_party_dlls::PackedListModule expected; const std::string module_basename = base::UTF16ToUTF8( base::i18n::ToLower(module_key2.module_path.BaseName().value())); base::SHA1HashBytes(reinterpret_cast<const uint8_t*>(module_basename.data()), module_basename.length(), &expected.basename_hash[0]); const std::string module_code_id = GenerateCodeId(module_key2); base::SHA1HashBytes(reinterpret_cast<const uint8_t*>(module_code_id.data()), module_code_id.length(), &expected.code_id_hash[0]); EXPECT_TRUE(internal::ModuleEqual()(expected, blacklisted_modules[0])); } TEST_F(ModuleBlacklistCacheUpdaterTest, DisableModuleAnalysis) { EXPECT_FALSE(base::PathExists(module_blacklist_cache_path())); auto module_blacklist_cache_updater = CreateModuleBlacklistCacheUpdater(); module_blacklist_cache_updater->DisableModuleAnalysis(); // Simulate some arbitrary module loading into the process. ModuleInfoKey module_key(dll1_, 0, 0); module_blacklist_cache_updater->OnNewModuleFound( module_key, CreateLoadedModuleInfoData()); module_blacklist_cache_updater->OnModuleDatabaseIdle(); RunUntilIdle(); EXPECT_TRUE(base::PathExists(module_blacklist_cache_path())); EXPECT_TRUE(on_cache_updated_callback_invoked()); EXPECT_TRUE(RegistryKeyExists()); // Check the cache. third_party_dlls::PackedListMetadata metadata; std::vector<third_party_dlls::PackedListModule> blacklisted_modules; base::MD5Digest md5_digest; EXPECT_EQ(ReadResult::kSuccess, ReadModuleBlacklistCache(module_blacklist_cache_path(), &metadata, &blacklisted_modules, &md5_digest)); // The module is not added to the blacklist. EXPECT_EQ(0u, blacklisted_modules.size()); ASSERT_EQ(ModuleBlacklistCacheUpdater::ModuleBlockingDecision::kNotAnalyzed, module_blacklist_cache_updater->GetModuleBlockingState(module_key) .blocking_decision); }
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
6f8fadec39fd50a97a23c35819f5d580c1d15d23
1f692873720d3bc7dee3a49dfc667d93610f1956
/Qt/txbmp/mainwindow.cpp
7b089192f2b2b9434776a74f1a13113ba362dd81
[]
no_license
JanusErasmus/LEDtable
8b5db8cb0cfec707f6835cb99254413b8c99396a
7f2aa6dbfca32c5b8b3ec3a21f4e793716044336
refs/heads/master
2021-01-21T06:18:26.069880
2018-02-26T07:15:20
2018-02-26T07:15:20
83,204,563
2
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "bmp_reader.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mSender = new HDLCsender("/dev/ttyACM0"); mListener = new SerialListener(mSender); mListener->start(); connect(ui->updateButton, SIGNAL(clicked(bool)), this, SLOT(buttonPress())); } void MainWindow::buttonPress() { BMPreader reader("test.bmp"); uint8_t buff[2048]; int len = reader.getBuffer(buff, 2048); mListener->sendData(buff, len); } MainWindow::~MainWindow() { delete ui; }
[ "janus@kses.net" ]
janus@kses.net
ea667db384be473c396c841a01643d833764c402
662d1ed777689777e21eaa408da20e77209c6517
/Paladin.cpp
3f2fb22350bdf623447c36d274d5218cfbec81c8
[]
no_license
PWrW4/PO_Gladiators
e92ac822f390bdf2e1ea99d9988dc361a85f500a
aee42a8e23127787f7eff716c12365cab98ddf34
refs/heads/master
2020-11-30T20:28:31.602321
2017-10-25T08:34:57
2017-10-25T08:34:57
230,472,326
0
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
#include "Paladin.h" void Paladin::magicianAttack(Hero& _enemy) { int damageToDo = 0; switch (getHeroType()) { case HeroType::Magical: damageToDo = _enemy.getHp() + _enemy.getMagicalResistance() - (getDamage()*0.5) - getMagicalItem()->getItemMagic(); if (damageToDo>0) { _enemy.setHp(_enemy.getHp()-damageToDo); } break; case HeroType::Phisical: damageToDo = _enemy.getHp() - getMagicalItem()->getItemMagic(); if (damageToDo>0) { _enemy.setHp(_enemy.getHp() - damageToDo); } break; default: break; } if (getHp() < 100) { if (getHp()<90) { setHp(getHp() + 10); } else { setHp(100); } } } Paladin::Paladin(string S,int _damege, int _defence, int _magicalResistance, int _move, int _attackdistance, int _Hp, int _id, MagicialItem* _item) : Magician(_item), Hero(S,_damege, _defence, _magicalResistance, _move, _attackdistance, _Hp, _id) { } Paladin::~Paladin() { }
[ "wojtek.wroclaw@hotmail.com" ]
wojtek.wroclaw@hotmail.com
d2fb2478c1ab0875ac467325a9d3b0bd91c74355
747ff671a07efeae5946a5bb7ec965bda80b7090
/SDLGameSandbox/Texture.h
fa637f77fd7bef3167b81fb0db98fd8f1e001c1c
[]
no_license
simson0606/SDLGameSandbox
19665d2b857673424e9b5733500a92d50931e4a6
e719796993eb89e17062be108102bfd16b8afd35
refs/heads/master
2020-03-29T21:54:37.584670
2018-09-26T08:27:16
2018-09-26T08:27:16
150,393,714
0
0
null
null
null
null
UTF-8
C++
false
false
529
h
#ifndef _TEXTURE_H #define _TEXTURE_H #include "GameEntity.h" #include <SDL.h> #include "AssetManager.h" class Texture : public GameEntity { protected: SDL_Texture* mTex; Graphics* mGraphics; int mWidth; int mHeight; bool mClipped; SDL_Rect mRenderRect; SDL_Rect mClippedRect; public: Texture(std::string filename); Texture(std::string filename, int x, int y, int width, int height); Texture(std::string text, std::string fontPath, int size, SDL_Color color); ~Texture(); virtual void Render(); }; #endif
[ "simon.heij@gmail.com" ]
simon.heij@gmail.com
796f3c9ab0877434131bfdfe959fdcac2e154fad
3bbf8a6c3d629c6a612d6d33ca220eecdb935e12
/aws-cpp-sdk-kinesisanalyticsv2/include/aws/kinesisanalyticsv2/model/DeleteApplicationCloudWatchLoggingOptionRequest.h
a3693d7c820f9be787b2cb7fa220264454e4946d
[ "MIT", "Apache-2.0", "JSON" ]
permissive
julio-gorge/aws-sdk-cpp
a8c067adf072ff43c686a15092e54ad2393cc1d4
06b0d54110172b3cf9b3f5602060304e36afd225
refs/heads/master
2021-10-22T15:00:07.328784
2019-03-11T12:08:52
2019-03-11T12:08:52
161,850,005
0
0
Apache-2.0
2018-12-14T23:11:43
2018-12-14T23:11:43
null
UTF-8
C++
false
false
7,003
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h> #include <aws/kinesisanalyticsv2/KinesisAnalyticsV2Request.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace KinesisAnalyticsV2 { namespace Model { /** */ class AWS_KINESISANALYTICSV2_API DeleteApplicationCloudWatchLoggingOptionRequest : public KinesisAnalyticsV2Request { public: DeleteApplicationCloudWatchLoggingOptionRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DeleteApplicationCloudWatchLoggingOption"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The application name.</p> */ inline const Aws::String& GetApplicationName() const{ return m_applicationName; } /** * <p>The application name.</p> */ inline void SetApplicationName(const Aws::String& value) { m_applicationNameHasBeenSet = true; m_applicationName = value; } /** * <p>The application name.</p> */ inline void SetApplicationName(Aws::String&& value) { m_applicationNameHasBeenSet = true; m_applicationName = std::move(value); } /** * <p>The application name.</p> */ inline void SetApplicationName(const char* value) { m_applicationNameHasBeenSet = true; m_applicationName.assign(value); } /** * <p>The application name.</p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithApplicationName(const Aws::String& value) { SetApplicationName(value); return *this;} /** * <p>The application name.</p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithApplicationName(Aws::String&& value) { SetApplicationName(std::move(value)); return *this;} /** * <p>The application name.</p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithApplicationName(const char* value) { SetApplicationName(value); return *this;} /** * <p>The version ID of the application. You can retrieve the application version * ID using <a>DescribeApplication</a>.</p> */ inline long long GetCurrentApplicationVersionId() const{ return m_currentApplicationVersionId; } /** * <p>The version ID of the application. You can retrieve the application version * ID using <a>DescribeApplication</a>.</p> */ inline void SetCurrentApplicationVersionId(long long value) { m_currentApplicationVersionIdHasBeenSet = true; m_currentApplicationVersionId = value; } /** * <p>The version ID of the application. You can retrieve the application version * ID using <a>DescribeApplication</a>.</p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithCurrentApplicationVersionId(long long value) { SetCurrentApplicationVersionId(value); return *this;} /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline const Aws::String& GetCloudWatchLoggingOptionId() const{ return m_cloudWatchLoggingOptionId; } /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline void SetCloudWatchLoggingOptionId(const Aws::String& value) { m_cloudWatchLoggingOptionIdHasBeenSet = true; m_cloudWatchLoggingOptionId = value; } /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline void SetCloudWatchLoggingOptionId(Aws::String&& value) { m_cloudWatchLoggingOptionIdHasBeenSet = true; m_cloudWatchLoggingOptionId = std::move(value); } /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline void SetCloudWatchLoggingOptionId(const char* value) { m_cloudWatchLoggingOptionIdHasBeenSet = true; m_cloudWatchLoggingOptionId.assign(value); } /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithCloudWatchLoggingOptionId(const Aws::String& value) { SetCloudWatchLoggingOptionId(value); return *this;} /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithCloudWatchLoggingOptionId(Aws::String&& value) { SetCloudWatchLoggingOptionId(std::move(value)); return *this;} /** * <p>The <code>CloudWatchLoggingOptionId</code> of the Amazon CloudWatch logging * option to delete. You can get the <code>CloudWatchLoggingOptionId</code> by * using the <a>DescribeApplication</a> operation. </p> */ inline DeleteApplicationCloudWatchLoggingOptionRequest& WithCloudWatchLoggingOptionId(const char* value) { SetCloudWatchLoggingOptionId(value); return *this;} private: Aws::String m_applicationName; bool m_applicationNameHasBeenSet; long long m_currentApplicationVersionId; bool m_currentApplicationVersionIdHasBeenSet; Aws::String m_cloudWatchLoggingOptionId; bool m_cloudWatchLoggingOptionIdHasBeenSet; }; } // namespace Model } // namespace KinesisAnalyticsV2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
92975d0a5d110b99fc1c339a3ec3c97b1bc22a49
f72df1a2f07b741994bcd3e213519edb2e747579
/SDL_Vulkan_Test/app_files.cpp
34299ea6352d48019983e7a5754032d19deffd25
[]
no_license
Elbagast/SDL_Vulkan_Test
77a85eecbe8db4e0cbe4754ef8ecffacb2e2021b
895d5884b1a383e316ca02b3f4fb97b5e0dd1c68
refs/heads/master
2020-03-20T01:21:48.801195
2018-08-08T18:23:46
2018-08-08T18:23:46
137,073,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,588
cpp
#include "app_files.hpp" #include <iostream> #include <filesystem> #include <fstream> #include <cassert> #include <memory> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace { decltype(auto) imp_get_dirpath(std::string const& a_arg0) { using namespace std::experimental::filesystem; return path{ u8path(a_arg0).remove_filename() }; } } std::string sdlxvulkan::get_dirpath(std::string const& a_arg0) { return imp_get_dirpath(a_arg0).u8string(); } std::string sdlxvulkan::get_filepath(std::string const& a_arg0, std::string const& a_filename) { using namespace std::experimental::filesystem; path l_directory = imp_get_dirpath(a_arg0); path l_filepath{ l_directory / u8path(a_filename) }; std::string l_result{ l_filepath.u8string() }; if (!exists(l_filepath)) { throw std::runtime_error{ std::string{ "Filesystem: File does not exist: " } + l_result }; } return l_result; } /* std::string sdlxvulkan::get_shader_filepath(std::string const& a_arg0, std::string const& a_filename) { using namespace std::experimental::filesystem; path const l_directory{ u8path(a_arg0).remove_filename() }; path l_filepath{ l_directory / u8path(a_filename) }; std::string l_result{ l_filepath.u8string() }; if (!exists(l_filepath)) { throw std::runtime_error{ std::string{ "Filesystem: Shader file does not exist: " } + l_result }; } // Open the file and get the data... //std::cout << "Getting shader file: " << l_result << std::endl; return l_result; }; */ std::vector<char> sdlxvulkan::get_file_bytes(std::string const& a_filepath) { // Open the file and seek to the end std::ifstream l_filestream{ a_filepath, std::ios::ate | std::ios::binary }; if (!l_filestream.is_open()) { throw std::runtime_error{ std::string{ "Filesystem: Could not open file " } +a_filepath }; } // Get the file size in bytes std::size_t l_file_size = l_filestream.tellg(); std::vector<char> l_file_buffer{}; l_file_buffer.resize(l_file_size); // Go to the start l_filestream.seekg(0); // get all the file at once l_filestream.read(l_file_buffer.data(), l_file_size); l_filestream.close(); return l_file_buffer; } namespace { class STB_Pixel_Deleter { public: void operator()(stbi_uc* a_ptr) const noexcept { stbi_image_free(a_ptr); } }; using STB_Pixels = std::unique_ptr<stbi_uc, STB_Pixel_Deleter>; } sdlxvulkan::STB_Image::STB_Image(std::string const& a_filepath) : m_width{0}, m_height{0}, m_channels{0}, m_size{0}, m_data{nullptr} { m_data = stbi_load(a_filepath.c_str(), &m_width, &m_height, &m_channels, STBI_rgb_alpha); if (m_data == nullptr) { throw std::runtime_error{ std::string{"STB: failed to load an image file: "} + a_filepath }; } assert(m_width != 0); assert(m_height != 0); //assert(m_channels == STBI_rgb_alpha); // catch the pointer with its deleter function //std::unique_ptr<stbi_uc, std::add_pointer_t<decltype(stbi_image_free)>> l_caught{ l_pixels, stbi_image_free }; //STB_Pixels l_caught{ l_pixels }; m_size = m_width * m_height * 4; std::cout << "image made: " << a_filepath << " w=" << m_width << " h=" << m_height << " c=" << m_channels << " s=" << m_size << std::endl; /* // this copy op is damn slow m_data.reserve(l_size); for (std::size_t l_index = 0; l_index != l_size; ++l_index, ++l_pixels) { m_data.push_back(static_cast<char>(*l_pixels)); } assert(m_data.size() == l_size);*/ //stbi_image_free(l_pixels); } sdlxvulkan::STB_Image::~STB_Image() { stbi_image_free(m_data); }
[ "elbagast@gmail.com" ]
elbagast@gmail.com
8a5ad01af0cf5664212840faa04d10103c3dbc7a
98b6c7cedf3ab2b09f16b854b70741475e07ab64
/www.cplusplus.com-20180131/reference/cstdlib/atexit/atexit.cpp
8ad6b216378f7bb89d59786cf7d639cd2b9c0c4c
[]
no_license
yull2310/book-code
71ef42766acb81dde89ce4ae4eb13d1d61b20c65
86a3e5bddbc845f33c5f163c44e74966b8bfdde6
refs/heads/master
2023-03-17T16:35:40.741611
2019-03-05T08:38:51
2019-03-05T08:38:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
/* atexit example */ #include <stdio.h> /* puts */ #include <stdlib.h> /* atexit */ void fnExit1 (void) { puts ("Exit function 1."); } void fnExit2 (void) { puts ("Exit function 2."); } int main () { atexit (fnExit1); atexit (fnExit2); puts ("Main function."); return 0; }
[ "zhongtao.chen@yourun.com" ]
zhongtao.chen@yourun.com
8adff482178f5bd45f3bb53f0628acb41240a07e
6c77cf237697f252d48b287ae60ccf61b3220044
/aws-cpp-sdk-dlm/include/aws/dlm/DLMErrors.h
29833fce47dc64df6feae25b6b3506d698433b12
[ "MIT", "Apache-2.0", "JSON" ]
permissive
Gohan/aws-sdk-cpp
9a9672de05a96b89d82180a217ccb280537b9e8e
51aa785289d9a76ac27f026d169ddf71ec2d0686
refs/heads/master
2020-03-26T18:48:43.043121
2018-11-09T08:44:41
2018-11-09T08:44:41
145,232,234
1
0
Apache-2.0
2018-08-30T13:42:27
2018-08-18T15:42:39
C++
UTF-8
C++
false
false
2,001
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/core/client/CoreErrors.h> #include <aws/dlm/DLM_EXPORTS.h> namespace Aws { namespace DLM { enum class DLMErrors { //From Core// ////////////////////////////////////////////////////////////////////////////////////////// INCOMPLETE_SIGNATURE = 0, INTERNAL_FAILURE = 1, INVALID_ACTION = 2, INVALID_CLIENT_TOKEN_ID = 3, INVALID_PARAMETER_COMBINATION = 4, INVALID_QUERY_PARAMETER = 5, INVALID_PARAMETER_VALUE = 6, MISSING_ACTION = 7, // SDK should never allow MISSING_AUTHENTICATION_TOKEN = 8, // SDK should never allow MISSING_PARAMETER = 9, // SDK should never allow OPT_IN_REQUIRED = 10, REQUEST_EXPIRED = 11, SERVICE_UNAVAILABLE = 12, THROTTLING = 13, VALIDATION = 14, ACCESS_DENIED = 15, RESOURCE_NOT_FOUND = 16, UNRECOGNIZED_CLIENT = 17, MALFORMED_QUERY_STRING = 18, SLOW_DOWN = 19, REQUEST_TIME_TOO_SKEWED = 20, INVALID_SIGNATURE = 21, SIGNATURE_DOES_NOT_MATCH = 22, INVALID_ACCESS_KEY_ID = 23, NETWORK_CONNECTION = 99, UNKNOWN = 100, /////////////////////////////////////////////////////////////////////////////////////////// INTERNAL_SERVER= static_cast<int>(Aws::Client::CoreErrors::SERVICE_EXTENSION_START_RANGE) + 1, INVALID_REQUEST, LIMIT_EXCEEDED }; namespace DLMErrorMapper { AWS_DLM_API Aws::Client::AWSError<Aws::Client::CoreErrors> GetErrorForName(const char* errorName); } } // namespace DLM } // namespace Aws
[ "magmarco@amazon.com" ]
magmarco@amazon.com
85c1b303f4abb50675602c1c4a6ac9613815335b
2f66097093e8d828cad6cca1ea27c055613464d2
/bettermaze.h
3272c558f5ed3f3f2beb96a34202256aa6ebc864
[]
no_license
liuzhiwu123/Maze
d60325d02773ec019efc456925dee8fb8523d08a
91c738a94eb2913109abfe985d07c4c88ec39d2c
refs/heads/master
2021-03-06T18:16:17.837498
2020-03-12T10:28:38
2020-03-12T10:28:38
246,215,462
0
0
null
null
null
null
GB18030
C++
false
false
6,556
h
#include<iostream> #include<queue> using namespace std; //广度遍历,寻找迷宫的最短路径 //需要定义一个额外的记录路径的数组,以便回朔路径,因为一直在队头出队,所以所走过的路径信息会不断丢失 class Node { public: Node(int u = 1, int d = 1, int l = 1, int r = 1, int a = 0, int b = 0, int da = 0) :x(a), y(b), left(l), right(r), up(u), down(d), data(da) {} void setleft(int val) { left = val; } void setright(int val) { right = val; } void setup(int val) { up = val; } void setdown(int val) { down = val; } void setlocal(int a, int b, int da) { x = a; y = b; data = da; } void setdata(int val) { data = val; } int Right() { return right; } int Left() { return left; } int Up() { return up; } int Down() { return down; } int point() { return (x * 10) + y; } int X() { return x; } int Y() { return y; } void show() { cout << data << " " << left << " " << right << " " << up << " " << down << " " << endl; } void showrount() { cout << data << " "; } private: int x, y, data; int left, right, up, down; }; class maze { public: maze(int a = 5, int** ar = nullptr) { squar = new Node*[a]; road = new Node[a*a]; for (int i = 0; i < a; i++) { squar[i] = new Node[a]; } for (int i = 0; i < a; i++) { for (int j = 0; j < a - 1; j++)//设置right { if (ar[i][j + 1] == 0) squar[i][j].setright(0); } } for (int i = 0; i < a; i++)//设置左边 { for (int j = 1; j < a; j++) { if (ar[i][j - 1] == 0) { squar[i][j].setleft(0); } } } for (int i = 1; i < a; i++)//设置up { for (int j = 0; j < a; j++) { if (ar[i - 1][j] == 0) { squar[i][j].setup(0); } } } for (int i = 0; i < a - 1; i++)//设置down { for (int j = 0; j < a; j++) { if (ar[i + 1][j] == 0) { squar[i][j].setdown(0); } } } for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { squar[i][j].setlocal(i, j, ar[i][j]); //squar[i][j].show(); } } } void start(int a)//依然是右下左上 { int x = 0, y = 0; que.push(squar[0][0]); while (!que.empty()) { x = que.front().X(); y = que.front().Y(); if (que.front().Right() == 0) { squar[x][y].setright(1); squar[x][y + 1].setleft(1);//及时 int flag = 9; flag=checkque(squar[x][y + 1], 1);//检查是否将要入队的点已经在队里,在的话设置方向,不在当没执行这句。 que.push(squar[x][y + 1]); int val = (x * a) + y + 1; road[val] = squar[x][y];//把当前节点放到下一个节点一位数组位置上,以便于回朔。取出来下一个节点的左边进行计算就会在一维数组对应到当前节点,取出来当前节点的坐标进行计算就会对应到上一个节点在一维数组中的位置 if (check(squar[x][y + 1],a)) { break; } } if (que.front().Down() == 0) { squar[x][y].setdown(1); squar[x + 1][y].setup(1); int flag = 9; flag=checkque(squar[x+1][y], 2);//检查是否将要入队的点已经在队里,在的话设置方向,不在当没执行这句。 que.push(squar[x + 1][y]); int val = (x + 1) * a + y; road[val] = squar[x][y]; if (check(squar[x + 1][y],a)) { break; } } if (que.front().Left() == 0) { squar[x][y].setleft(1); squar[x][y-1].setright(1); int flag = 9; flag=checkque(squar[x][y - 1], 3);//检查是否将要入队的点已经在队里,在的话设置方向,不在当没执行这句。 que.push(squar[x][y-1]); int val = x * a + y - 1; road[val] = squar[x][y]; if (check(squar[x ][y-1],a)) { break; } } if (que.front().Up() == 0) { squar[x][y].setup(1); squar[x-1][y].setdown(1); int flag = 9; flag=checkque(squar[x-1][y], 4);//检查是否将要入队的点已经在队里,在的话设置方向,不在当没执行这句。 que.push(squar[x-1][y]); int val = (x - 1)*a + y; road[val] = squar[x][y]; if (check(squar[x-1][y],a)) { break; } } cout << "a"; que.pop(); } if (que.empty()) { cout << "no road" << endl; } else { setroad(a); showroad(a); } } void setroad(int a) { int x = a - 1, y = a - 1; //x*a+y下标下存放的是上一个节点,因为是把路径上的上一个节点存放到下一个节点坐标对应的下标下 如:(3.4)的下一节点是(3,5),下是(4,5) //就把(3,4)放到road[3*a+4]下,(3,5)放到road[4*a+5]下,回朔是取出road[4*a+5]里的就找到了(3,5),取出road[3*a+4]就找到了(3,4) while (x != 0 || y != 0) { int val = x * a + y; squar[x][y].setdata(2); x = road[val].X(); y = road[val].Y(); cout << x << "," << y << " "; } squar[x][y].setdata(2); } bool checkque(Node &node,int dir)//检查是否是已经在队里 { if (que.size() == 1) { return 0; } Node tmp = que.front(); Node stp = tmp; que.pop(); que.push(tmp); tmp = que.front(); int flag = 0; while (tmp.X() != stp.X() || tmp.Y() != stp.Y()) { if (tmp.X() == node.X() && tmp.Y() == node.Y()) { switch (dir) { case 1:tmp.setleft(1); break; case 2:tmp.setup(1); break; case 3:tmp.setright(1); break; case 4:tmp.setdown(1); break; } flag = 1; } que.pop(); que.push(tmp); tmp = que.front(); } return flag; } bool check( Node &node,int a)//检查是否是出口 { if (node.X() == a - 1 && node.Y() == a - 1) { return true; } return false; } void showroad(int a) { for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { squar[i][j].showrount(); } cout << endl; } } private: Node** squar; queue<Node> que; Node* road; //road的用法:把当前节点放到下一个节点row*col所对应的一维数组下标下,这样倒数第二个节点就放在在了对应一维下标下,最后一个元素(出口) //就默认用坐标记录,这样回朔时出口左边计算到一位数组下标下,就找到了倒数第二个节点,倒数第二个节点坐标计算就对应到了倒数第三个节点所在一位数组的下标 };
[ "347939046@qq.com" ]
347939046@qq.com
492d81d17ed154df1ab9b41ccbc103c2f7e0c212
4ee74f25e910b8f53893d1ae16b1728ade8747d3
/lib/DebugInfo/PDB/Raw/PDBFileBuilder.cpp
ebe88dfa5876e9d1308e332911122220220066d8
[ "NCSA" ]
permissive
ErikCorryGoogle/llvm
16f0e4ff1c322ba817643f1480e7bdcbc19bdb1d
93627d9415b3a5d7319bf35890fd7ce3044c7b6f
refs/heads/master
2021-01-04T22:26:04.503453
2016-09-13T13:17:42
2016-09-13T13:17:42
68,111,429
2
0
null
2016-09-13T13:35:35
2016-09-13T13:35:35
null
UTF-8
C++
false
false
5,011
cpp
//===- PDBFileBuilder.cpp - PDB File Creation -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/PDBFileBuilder.h" #include "llvm/ADT/BitVector.h" #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/StreamInterface.h" #include "llvm/DebugInfo/MSF/StreamWriter.h" #include "llvm/DebugInfo/PDB/Raw/DbiStream.h" #include "llvm/DebugInfo/PDB/Raw/DbiStreamBuilder.h" #include "llvm/DebugInfo/PDB/Raw/InfoStream.h" #include "llvm/DebugInfo/PDB/Raw/InfoStreamBuilder.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" #include "llvm/DebugInfo/PDB/Raw/TpiStream.h" #include "llvm/DebugInfo/PDB/Raw/TpiStreamBuilder.h" using namespace llvm; using namespace llvm::codeview; using namespace llvm::msf; using namespace llvm::pdb; using namespace llvm::support; PDBFileBuilder::PDBFileBuilder(BumpPtrAllocator &Allocator) : Allocator(Allocator) {} Error PDBFileBuilder::initialize(const msf::SuperBlock &Super) { auto ExpectedMsf = MSFBuilder::create(Allocator, Super.BlockSize, Super.NumBlocks); if (!ExpectedMsf) return ExpectedMsf.takeError(); auto &MsfResult = *ExpectedMsf; if (auto EC = MsfResult.setBlockMapAddr(Super.BlockMapAddr)) return EC; Msf = llvm::make_unique<MSFBuilder>(std::move(MsfResult)); Msf->setFreePageMap(Super.FreeBlockMapBlock); Msf->setUnknown1(Super.Unknown1); return Error::success(); } MSFBuilder &PDBFileBuilder::getMsfBuilder() { return *Msf; } InfoStreamBuilder &PDBFileBuilder::getInfoBuilder() { if (!Info) Info = llvm::make_unique<InfoStreamBuilder>(); return *Info; } DbiStreamBuilder &PDBFileBuilder::getDbiBuilder() { if (!Dbi) Dbi = llvm::make_unique<DbiStreamBuilder>(Allocator); return *Dbi; } TpiStreamBuilder &PDBFileBuilder::getTpiBuilder() { if (!Tpi) Tpi = llvm::make_unique<TpiStreamBuilder>(Allocator); return *Tpi; } Expected<msf::MSFLayout> PDBFileBuilder::finalizeMsfLayout() const { if (Info) { uint32_t Length = Info->calculateSerializedLength(); if (auto EC = Msf->setStreamSize(StreamPDB, Length)) return std::move(EC); } if (Dbi) { uint32_t Length = Dbi->calculateSerializedLength(); if (auto EC = Msf->setStreamSize(StreamDBI, Length)) return std::move(EC); } if (Tpi) { uint32_t Length = Tpi->calculateSerializedLength(); if (auto EC = Msf->setStreamSize(StreamTPI, Length)) return std::move(EC); } return Msf->build(); } Expected<std::unique_ptr<PDBFile>> PDBFileBuilder::build(std::unique_ptr<msf::WritableStream> PdbFileBuffer) { auto ExpectedLayout = finalizeMsfLayout(); if (!ExpectedLayout) return ExpectedLayout.takeError(); auto File = llvm::make_unique<PDBFile>(std::move(PdbFileBuffer), Allocator); File->ContainerLayout = *ExpectedLayout; if (Info) { auto ExpectedInfo = Info->build(*File, *PdbFileBuffer); if (!ExpectedInfo) return ExpectedInfo.takeError(); File->Info = std::move(*ExpectedInfo); } if (Dbi) { auto ExpectedDbi = Dbi->build(*File, *PdbFileBuffer); if (!ExpectedDbi) return ExpectedDbi.takeError(); File->Dbi = std::move(*ExpectedDbi); } if (Tpi) { auto ExpectedTpi = Tpi->build(*File, *PdbFileBuffer); if (!ExpectedTpi) return ExpectedTpi.takeError(); File->Tpi = std::move(*ExpectedTpi); } if (File->Info && File->Dbi && File->Info->getAge() != File->Dbi->getAge()) return llvm::make_error<RawError>( raw_error_code::corrupt_file, "PDB Stream Age doesn't match Dbi Stream Age!"); return std::move(File); } Error PDBFileBuilder::commit(const msf::WritableStream &Buffer) { StreamWriter Writer(Buffer); auto ExpectedLayout = finalizeMsfLayout(); if (!ExpectedLayout) return ExpectedLayout.takeError(); auto &Layout = *ExpectedLayout; if (auto EC = Writer.writeObject(*Layout.SB)) return EC; uint32_t BlockMapOffset = msf::blockToOffset(Layout.SB->BlockMapAddr, Layout.SB->BlockSize); Writer.setOffset(BlockMapOffset); if (auto EC = Writer.writeArray(Layout.DirectoryBlocks)) return EC; auto DirStream = WritableMappedBlockStream::createDirectoryStream(Layout, Buffer); StreamWriter DW(*DirStream); if (auto EC = DW.writeInteger(static_cast<uint32_t>(Layout.StreamSizes.size()))) return EC; if (auto EC = DW.writeArray(Layout.StreamSizes)) return EC; for (const auto &Blocks : Layout.StreamMap) { if (auto EC = DW.writeArray(Blocks)) return EC; } if (Info) { if (auto EC = Info->commit(Layout, Buffer)) return EC; } if (Dbi) { if (auto EC = Dbi->commit(Layout, Buffer)) return EC; } if (Tpi) { if (auto EC = Tpi->commit(Layout, Buffer)) return EC; } return Buffer.commit(); }
[ "zturner@google.com" ]
zturner@google.com
a7ac9d0ab63a1bc370772a09aa5747e63aa60add
c3afc3b5f4aa09b9c237b78af50917f26ef163d0
/lexeme.cpp
4057305ebeb2a3a7216ce79a080befdce1d61777
[]
no_license
OFITSEROVLAD/My_Interpreter
451738a04f93b2a77374e164683cf65c01f04b06
cc9b1f047471253c37cceb2dc4b6d6a944480045
refs/heads/master
2022-11-11T12:17:18.723200
2020-06-17T15:42:16
2020-06-17T15:42:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,274
cpp
#include "lexeme.h" using namespace std; ///////////////////////// Класс Lex ////////////////////////// Lex::Lex ( type_of_lex t, int v, string v_str, int str, int chr): t_lex (t), v_lex (v), str_v_lex(v_str), str_lex (str), chr_lex (chr) { } type_of_lex Lex::get_type () { return t_lex; } int Lex::get_value () { return v_lex; } int Lex::get_str () { return str_lex; } int Lex::get_chr () { return chr_lex; } string Lex::get_string () { return str_v_lex; } ///////////////////// Класс Ident //////////////////////////// Ident::Ident() { declare = false; assign = false; } char* Ident::get_name () { return name; } void Ident::put_name (const char *n) { name = new char [ strlen(n)+1]; strcpy(name,n); } bool Ident::get_declare () { return declare; } void Ident::put_declare () { declare = true; } type_of_lex Ident::get_type () { return type; } void Ident::put_type (type_of_lex t) { type = t; } bool Ident::get_assign () { return assign; } void Ident::put_assign () { assign = true; } int Ident::get_value () { return value; } string Ident::get_string () { return str_value; } void Ident::put_value (int v) { value = v; } void Ident::put_value (string v) { str_value = v; } ////////////////////// Класс Tabl_ident /////////////////////// Tabl_ident::Tabl_ident ( int max_size ) { p = new Ident [size = max_size]; top = 1; } Tabl_ident::~Tabl_ident () { delete [] p; } Ident& Tabl_ident::operator[] ( int k ) { return p[k]; } int Tabl_ident::put ( const char *buf ) { for ( int j = 1; j < top; j++ ) { if ( !strcmp ( buf, p[j].get_name() ) ) { return j; } } p[top].put_name(buf); ++top; return top-1; } ///////////////////// Класс Scanner ////////////////////////////// void Scanner::clear () { buf_top = 0; for ( int j = 0; j < 80; j++ ) { buf[j] = '\0'; } } void Scanner::add () { if ( buf_top < 79 ) { buf [ buf_top++ ] = c; } } int Scanner::look ( const char *buf, const char **list ) { int i = 0; while (list[i]) { if ( !strcmp(buf, list[i]) ) { return i; } ++i; } return 0; } void Scanner::gc () { c = fgetc (fp); if (c == '\n' || c == '\r') { str1 = str; chr1 = chr; str += 1; chr = 0; } else if (c== '\t') { str1 = str; chr1 = chr; chr += 4; } else { str1 = str; chr1 = chr; chr +=1; } } Scanner::Scanner ( const char * program ) { fp = fopen ( program, "r" ); CS = H; clear(); str = 1; chr = 0; gc(); } //////////////////////////////////////////////////////////////////// const char * Scanner::TW [] = {"", "program", "int", "string", "if", "else", "while", "read", "write", "not", "and", "or", "do", "boolean", "true", "false", "break", NULL}; const char * TW1 [] = {"LEX_NULL", "LEX_PROGRAM", "LEX_INT", "LEX_STRING", "LEX_IF", "LEX_ELSE", "LEX_WHILE", "LEX_READ", "LEX_WRITE", "LEX_NOT", "LEX_AND", "LEX_OR", "LEX_DO", "LEX_BOOLEAN", "LEX_TRUE", "LEX_FALSE", "LEX_BREAK", "LEX_NULL"}; type_of_lex Scanner::words [] = {LEX_NULL, LEX_PROGRAM, LEX_INT, LEX_STRING, LEX_IF, LEX_ELSE, LEX_WHILE, LEX_READ, LEX_WRITE, LEX_NOT, LEX_AND, LEX_OR, LEX_DO, LEX_BOOLEAN, LEX_TRUE, LEX_FALSE, LEX_BREAK, LEX_NULL}; //////////////////////////////////////////////////////////////////// const char * Scanner::TD [] = {"", "", ";", ",", "(", ")", "=", "<", ">", "%", "+", "-", "*", "/", "<=", "!=", ">=", "==", "{", "}", NULL}; const char * TD1 [] = {"LEX_NULL", "LEX_FIN", "LEX_SEMICOLON", "LEX_COMMA", "LEX_LPAREN", "LEX_RPAREN", "LEX_EQ", "LEX_LSS", "LEX_GTR", "LEX_PERCENT", "LEX_PLUS", "LEX_MINUS", "LEX_TIMES", "LEX_SLASH", "LEX_LEQ", "LEX_NEQ", "LEX_GEQ", "LEX_EQEQ", "LEX_LCBR", "LEX_RCBR", "LEX_NULL"}; type_of_lex Scanner::dlms [] = {LEX_NULL, LEX_FIN, LEX_SEMICOLON, LEX_COMMA, LEX_LPAREN, LEX_RPAREN, LEX_EQ, LEX_LSS, LEX_GTR, LEX_PERCENT, LEX_PLUS, LEX_MINUS, LEX_TIMES, LEX_SLASH, LEX_LEQ, LEX_NEQ, LEX_GEQ, LEX_EQEQ, LEX_LCBR, LEX_RCBR, LEX_NULL}; //////////////////////////////////////////////////////////////////// Tabl_ident TID ( 100 ); //////////////////////////////////////////////////////////////////// Lex Scanner::get_lex () { int d, j; CS = H; do { switch(CS) { case H: if ( c ==' ') { gc(); } else if (c == '\n' || c == '\r') { gc(); } else if (c == '\t') { gc(); } else if ( isalpha(c) ) { clear(); add(); gc(); CS = IDENT; } else if ( isdigit(c) ) { d = c - '0'; gc(); CS = NUMB; } else if ( c == '<' || c == '>' || c == '=') { clear(); add(); gc(); CS = ALE; } else if ( c == '"') { clear(); // add(); gc(); CS = STR; } else if (c == EOF) { return Lex(LEX_FIN, 0, st, str, chr); } else if (c == '!') { clear(); add(); gc(); CS = NEQ; } else if (c == '/') { clear(); gc(); CS = COMMENT_1; } else CS = DELIM; break; case IDENT: j = look (buf, TW); if ( isalpha(c) || isdigit(c) ) { add(); gc(); } else if (j) { cout.width(25); cout << buf; cout.width(20); cout << TW1[j]; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex (words[j], j, st, str1, chr1 - buf_top + 1); } else { j = TID.put(buf); cout.width(25); cout << buf; cout.width(20); cout << "LEX_ID"; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex (LEX_ID, j, st, str1, chr1 - buf_top + 1); } break; case NUMB: if ( isdigit(c) ) { d = d * 10 + (c - '0'); gc(); } else { cout.width(25); cout << d; cout.width(20); cout << "LEX_NUM" ; cout.width(25); cout << d; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex (LEX_NUM, d, st, str1, chr1 - buf_top + 1); } break; case ALE: if ( c == '=') { add(); gc(); j = look ( buf, TD ); cout.width(25); cout << buf; cout.width(20); cout << TD1[j]; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex ( dlms[j], j, st, str1, chr1 - buf_top + 1); } else { j = look ( buf, TD ); cout.width(25); cout << buf; cout.width(20); cout << TD1[j]; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex ( dlms[j], j, st,str1, chr1 - buf_top + 1); } break; case STR: if ( c == EOF) { throw " LEX ERROR: no end of string"; } else if ( c != '"' ) { add(); gc(); } else { // add(); gc(); cout.width(25); cout << buf; cout.width(20); cout << "LEX_STR" ; cout.width(25); cout << buf; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex (LEX_STR, 0, buf, str1, chr1 - buf_top + 1); } break; case COMMENT_1: if (c == EOF) { throw " LEX ERROR: unexpected '/' in the end"; } else if ( c == '*' ) { gc(); CS = COMMENT_2; } else { throw " LEX ERROR: expected '*' after '/'"; } break; case COMMENT_2: if (c == EOF) { throw " LEX ERROR: no end of comment"; } else if ( c == '*' ) { gc(); CS = COMMENT_3; } else { gc(); } break; case COMMENT_3: if (c == EOF) { throw " LEX ERROR: no end of comment"; } else if ( c == '/' ) { gc(); CS = H; } else if ( c == '*') { gc(); } else { gc(); CS = COMMENT_2; } break; case NEQ: if (c == '=') { add(); gc(); j = look ( buf, TD ); cout.width(25); cout << buf; cout.width(20); cout << "LEX_NEQ"; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex ( LEX_NEQ, j, st, str1, chr1 - buf_top + 1); } else { throw '!'; } break; case DELIM: clear(); add(); j = look ( buf, TD); if (j) { gc(); cout.width(25); cout << buf; cout.width(20); cout << TD1[j]; cout.width(25); cout << j; cout.width(5); cout << str1; cout.width(5); cout << chr1 - buf_top + 1<< endl; return Lex ( dlms[j], j, st, str1, chr1 - buf_top + 1); } else { throw c; } break; }//end switch } while (true); }
[ "ofitserovlad@gmail.com" ]
ofitserovlad@gmail.com
b19ec400ad31ba3cee392c5c762d35d50e8bcd99
90047daeb462598a924d76ddf4288e832e86417c
/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper_unittest.cc
edef6131ae19d7e53759824b69540eb8b35bde95
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
7,965
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/scheduler/child/scheduler_helper.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/test/simple_test_tick_clock.h" #include "cc/test/ordered_simple_task_runner.h" #include "platform/scheduler/base/lazy_now.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/base/test_time_source.h" #include "platform/scheduler/child/scheduler_tqm_delegate_for_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::Return; namespace blink { namespace scheduler { namespace { void AppendToVectorTestTask(std::vector<std::string>* vector, std::string value) { vector->push_back(value); } void AppendToVectorReentrantTask(base::SingleThreadTaskRunner* task_runner, std::vector<int>* vector, int* reentrant_count, int max_reentrant_count) { vector->push_back((*reentrant_count)++); if (*reentrant_count < max_reentrant_count) { task_runner->PostTask( FROM_HERE, base::Bind(AppendToVectorReentrantTask, base::Unretained(task_runner), vector, reentrant_count, max_reentrant_count)); } } }; // namespace class SchedulerHelperTest : public testing::Test { public: SchedulerHelperTest() : clock_(new base::SimpleTestTickClock()), mock_task_runner_(new cc::OrderedSimpleTaskRunner(clock_.get(), false)), main_task_runner_(SchedulerTqmDelegateForTest::Create( mock_task_runner_, base::WrapUnique(new TestTimeSource(clock_.get())))), scheduler_helper_(new SchedulerHelper(main_task_runner_)), default_task_runner_(scheduler_helper_->DefaultTaskQueue()) { clock_->Advance(base::TimeDelta::FromMicroseconds(5000)); } ~SchedulerHelperTest() override {} void TearDown() override { // Check that all tests stop posting tasks. mock_task_runner_->SetAutoAdvanceNowToPendingTasks(true); while (mock_task_runner_->RunUntilIdle()) { } } void RunUntilIdle() { mock_task_runner_->RunUntilIdle(); } template <typename E> static void CallForEachEnumValue(E first, E last, const char* (*function)(E)) { for (E val = first; val < last; val = static_cast<E>(static_cast<int>(val) + 1)) { (*function)(val); } } protected: std::unique_ptr<base::SimpleTestTickClock> clock_; scoped_refptr<cc::OrderedSimpleTaskRunner> mock_task_runner_; scoped_refptr<SchedulerTqmDelegateForTest> main_task_runner_; std::unique_ptr<SchedulerHelper> scheduler_helper_; scoped_refptr<base::SingleThreadTaskRunner> default_task_runner_; DISALLOW_COPY_AND_ASSIGN(SchedulerHelperTest); }; TEST_F(SchedulerHelperTest, TestPostDefaultTask) { std::vector<std::string> run_order; default_task_runner_->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D1")); default_task_runner_->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D2")); default_task_runner_->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D3")); default_task_runner_->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D4")); RunUntilIdle(); EXPECT_THAT(run_order, testing::ElementsAre(std::string("D1"), std::string("D2"), std::string("D3"), std::string("D4"))); } TEST_F(SchedulerHelperTest, TestRentrantTask) { int count = 0; std::vector<int> run_order; default_task_runner_->PostTask( FROM_HERE, base::Bind(AppendToVectorReentrantTask, base::RetainedRef(default_task_runner_), &run_order, &count, 5)); RunUntilIdle(); EXPECT_THAT(run_order, testing::ElementsAre(0, 1, 2, 3, 4)); } TEST_F(SchedulerHelperTest, IsShutdown) { EXPECT_FALSE(scheduler_helper_->IsShutdown()); scheduler_helper_->Shutdown(); EXPECT_TRUE(scheduler_helper_->IsShutdown()); } TEST_F(SchedulerHelperTest, DefaultTaskRunnerRegistration) { EXPECT_EQ(main_task_runner_->default_task_runner(), scheduler_helper_->DefaultTaskQueue()); scheduler_helper_->Shutdown(); EXPECT_EQ(nullptr, main_task_runner_->default_task_runner()); } TEST_F(SchedulerHelperTest, GetNumberOfPendingTasks) { std::vector<std::string> run_order; scheduler_helper_->DefaultTaskQueue()->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D1")); scheduler_helper_->DefaultTaskQueue()->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "D2")); scheduler_helper_->ControlTaskQueue()->PostTask( FROM_HERE, base::Bind(&AppendToVectorTestTask, &run_order, "C1")); EXPECT_EQ(3U, scheduler_helper_->GetNumberOfPendingTasks()); RunUntilIdle(); EXPECT_EQ(0U, scheduler_helper_->GetNumberOfPendingTasks()); } namespace { class MockTaskObserver : public base::MessageLoop::TaskObserver { public: MOCK_METHOD1(DidProcessTask, void(const base::PendingTask& task)); MOCK_METHOD1(WillProcessTask, void(const base::PendingTask& task)); }; void NopTask() {} } // namespace TEST_F(SchedulerHelperTest, ObserversNotifiedFor_DefaultTaskRunner) { MockTaskObserver observer; scheduler_helper_->AddTaskObserver(&observer); scheduler_helper_->DefaultTaskQueue()->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_CALL(observer, WillProcessTask(_)).Times(1); EXPECT_CALL(observer, DidProcessTask(_)).Times(1); RunUntilIdle(); } TEST_F(SchedulerHelperTest, ObserversNotNotifiedFor_ControlTaskQueue) { MockTaskObserver observer; scheduler_helper_->AddTaskObserver(&observer); scheduler_helper_->ControlTaskQueue()->PostTask(FROM_HERE, base::Bind(&NopTask)); EXPECT_CALL(observer, WillProcessTask(_)).Times(0); EXPECT_CALL(observer, DidProcessTask(_)).Times(0); RunUntilIdle(); } namespace { class MockObserver : public SchedulerHelper::Observer { public: MOCK_METHOD1(OnUnregisterTaskQueue, void(const scoped_refptr<TaskQueue>& queue)); MOCK_METHOD2(OnTriedToExecuteBlockedTask, void(const TaskQueue& queue, const base::PendingTask& task)); }; } // namespace TEST_F(SchedulerHelperTest, OnUnregisterTaskQueue) { MockObserver observer; scheduler_helper_->SetObserver(&observer); scoped_refptr<TaskQueue> task_queue = scheduler_helper_->NewTaskQueue( TaskQueue::Spec(TaskQueue::QueueType::TEST)); EXPECT_CALL(observer, OnUnregisterTaskQueue(_)).Times(1); task_queue->UnregisterTaskQueue(); scheduler_helper_->SetObserver(nullptr); } TEST_F(SchedulerHelperTest, OnTriedToExecuteBlockedTask) { MockObserver observer; scheduler_helper_->SetObserver(&observer); scoped_refptr<TaskQueue> task_queue = scheduler_helper_->NewTaskQueue( TaskQueue::Spec(TaskQueue::QueueType::TEST) .SetShouldReportWhenExecutionBlocked(true)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter = task_queue->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); task_queue->PostTask(FROM_HERE, base::Bind(&NopTask)); // Trick |task_queue| into posting a DoWork. By default PostTask with a // disabled queue won't post a DoWork until we enable the queue. voter->SetQueueEnabled(true); voter->SetQueueEnabled(false); EXPECT_CALL(observer, OnTriedToExecuteBlockedTask(_, _)).Times(1); RunUntilIdle(); scheduler_helper_->SetObserver(nullptr); } } // namespace scheduler } // namespace blink
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
9be82b58e83ca8e7db7ad03761dc95a6204c2c70
5dbbcd5e1df606adefcb11b798219665ef3c8aab
/SWIG_CGAL/HalfedgeDS/HalfedgeDS_handles.h
dce451c11cc89cf6cb0cf63fcdcb3e06614d3686
[ "BSL-1.0" ]
permissive
sciencectn/cgal-bindings
f769d75153eac46bf1a4b3773860da031097eb74
e7a38a7852a50bb107b9be997a10a7e4a3f3c74b
refs/heads/master
2020-12-24T12:05:14.022263
2018-05-20T02:09:04
2018-05-20T02:09:04
32,248,691
37
6
BSL-1.0
2018-04-17T18:43:40
2015-03-15T06:50:57
C++
UTF-8
C++
false
false
4,271
h
// ------------------------------------------------------------------------------ // Copyright (c) 2013 GeometryFactory (FRANCE) // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ------------------------------------------------------------------------------ #ifndef SWIG_CGAL_HALFEDGEDS_HALFEDGEDS_HANDLE_H #define SWIG_CGAL_HALFEDGEDS_HALFEDGEDS_HANDLE_H #include <SWIG_CGAL/Common/Macros.h> #include <SWIG_CGAL/Kernel/Point_2.h> template <class HDS_cpp> class HDSHalfedge_wrapper; template <class HDS_cpp> class HDSVertex_wrapper; template <class HDS_cpp> class HDSFace_wrapper { typename HDS_cpp::Face_handle data; public: #ifndef SWIG typedef typename HDS_cpp::Face_handle cpp_base; const cpp_base& get_data() const {return data;} cpp_base& get_data() {return data;} HDSFace_wrapper(const cpp_base& base):data(base){} #endif // Creation HDSFace_wrapper():data(){} // Operations available if Supports_face_halfedge == CGAL::Tag_true SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSHalfedge_wrapper<HDS_cpp>,halfedge) SWIG_CGAL_FORWARD_CALL_1(void,set_halfedge,HDSHalfedge_wrapper<HDS_cpp>) //Deep copy typedef HDSFace_wrapper<HDS_cpp> Self; Self deepcopy() const {return Self(get_data());} void deepcopy(const Self& other){get_data()=other.get_data();} //equality functions DEFINE_EQUALITY_OPERATORS(Self); //hash function DEFINE_HASH_FUNCTION_FOR_HANDLE }; template <class HDS_cpp> class HDSHalfedge_wrapper { typename HDS_cpp::Halfedge_handle data; public: #ifndef SWIG typedef typename HDS_cpp::Halfedge_handle cpp_base; const cpp_base& get_data() const {return data;} cpp_base& get_data() {return data;} HDSHalfedge_wrapper(const cpp_base& base):data(base){} #endif /// Creation HDSHalfedge_wrapper():data(){} /// Operations SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSHalfedge_wrapper<HDS_cpp>,opposite) //this does not exist and is a mistake in the concept //SWIG_CGAL_FORWARD_CALL_1(void,set_opposite,HDSHalfedge_wrapper<HDS_cpp>) SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSHalfedge_wrapper<HDS_cpp>,next) SWIG_CGAL_FORWARD_CALL_1(void,set_next,HDSHalfedge_wrapper<HDS_cpp>) SWIG_CGAL_FORWARD_CALL_0(bool,is_border) /// Operations available if Supports_halfedge_prev == CGAL::Tag_true SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSHalfedge_wrapper<HDS_cpp>,prev) SWIG_CGAL_FORWARD_CALL_1(void,set_prev,HDSHalfedge_wrapper<HDS_cpp>) // Operations available if Supports_halfedge_vertex == CGAL::Tag_true SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSVertex_wrapper<HDS_cpp>,vertex) SWIG_CGAL_FORWARD_CALL_1(void,set_vertex,HDSVertex_wrapper<HDS_cpp>) // Operations available if Supports_halfedge_face == CGAL::Tag_true SWIG_CGAL_FORWARD_CALL_0(HDSFace_wrapper<HDS_cpp>,face) SWIG_CGAL_FORWARD_CALL_1(void,set_face,HDSFace_wrapper<HDS_cpp>); //Deep copy typedef HDSHalfedge_wrapper<HDS_cpp> Self; Self deepcopy() const {return Self(get_data());} void deepcopy(const Self& other){get_data()=other.get_data();} //equality functions DEFINE_EQUALITY_OPERATORS(Self); //hash function DEFINE_HASH_FUNCTION_FOR_HANDLE }; template <class HDS_cpp> class HDSVertex_wrapper{ typename HDS_cpp::Vertex_handle data; public: #ifndef SWIG typedef typename HDS_cpp::Vertex_handle cpp_base; const cpp_base& get_data() const {return data;} cpp_base& get_data() {return data;} HDSVertex_wrapper(const cpp_base& base):data(base){} #endif // Creation HDSVertex_wrapper():data(){} // Operations available if Supports_vertex_halfedge == CGAL::Tag_true SWIG_CGAL_FORWARD_CALL_AND_REF_0(HDSHalfedge_wrapper<HDS_cpp>,halfedge) SWIG_CGAL_FORWARD_CALL_1(void,set_halfedge,HDSHalfedge_wrapper<HDS_cpp>) // Operations with point SWIG_CGAL_FORWARD_CALL_AND_REF_0(Point_2,point) void set_point( const Point_2& p){get_data()->point()=p.get_data();} //Deep copy typedef HDSVertex_wrapper<HDS_cpp> Self; Self deepcopy() const {return Self(get_data());} void deepcopy(const Self& other){get_data()=other.get_data();} //equality functions DEFINE_EQUALITY_OPERATORS(Self); //hash function DEFINE_HASH_FUNCTION_FOR_HANDLE }; #endif //SWIG_CGAL_HALFEDGEDS_HALFEDGEDS_HANDLE_H
[ "sloriot.ml@gmail.com" ]
sloriot.ml@gmail.com
16e367b6af732d3a55d6d34be81b307ecdef65c7
13f1ff12873c242e56e53feed402bd1fb6b7405c
/hw4-XiaoLeS-master/src/include/AST/VariableReference.hpp
8c28d889054460b561947fe9843d1337d08d4ce8
[ "MIT" ]
permissive
battlebrian/CompilerDesign
4460acfc29f25345077f4b717143c3f2df3bdb46
7bd9883d94d60655e26f403cb24af2ef67f9343a
refs/heads/main
2023-08-31T09:42:37.297351
2021-10-12T15:00:45
2021-10-12T15:00:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
888
hpp
#ifndef __AST_VARIABLE_REFERENCE_NODE_H #define __AST_VARIABLE_REFERENCE_NODE_H #include "AST/expression.hpp" #include <memory> #include <vector> class VariableReferenceNode : public ExpressionNode { public: typedef std::vector<std::unique_ptr<ExpressionNode>> Exprs; VariableReferenceNode(const uint32_t line, const uint32_t col, const char *p_name); VariableReferenceNode(const uint32_t line, const uint32_t col, const char *p_name, Exprs *p_indices); ~VariableReferenceNode() = default; const char *getNameCString() const; int getDimensionNum(); void accept(AstNodeVisitor &p_visitor) override; void visitChildNodes(AstNodeVisitor &p_visitor) override; bool checkIndexType(uint32_t&, uint32_t&); void updateDirty(); private: const std::string name; Exprs indices; }; #endif
[ "wlsun.ee06@nycu.edu.tw" ]
wlsun.ee06@nycu.edu.tw
71d40dd93c01bee3d761e99607d85e99bb0ae296
c85ca01b5e9edaf815c8fde506a44e6bab9b7c72
/windows/runner/main.cpp
1b5a3e9a47fbe44ce24697edd66b825348f9f61c
[]
no_license
ramanan-ramesh/bluestacks_assignment
62f41f05517d7640423fb8dbf809ea46c7d447c5
5d17d0061e8472ee6a8b6d82fc23187fe5fc3612
refs/heads/master
2023-07-11T17:02:13.929610
2021-08-24T05:16:29
2021-08-24T05:16:29
399,343,339
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include "flutter_window.h" #include "run_loop.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); RunLoop run_loop; flutter::DartProject project(L"data"); std::vector<std::string> command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(&run_loop, project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"bluestacks_assignment", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); ::CoUninitialize(); return EXIT_SUCCESS; }
[ "ramanan.ramesh@siemens-healthineers.com" ]
ramanan.ramesh@siemens-healthineers.com
cebddbcef0f359044e3bfcbbdc868c6f2e67e9b0
3b6e34ada25b36dcee465c2295c079d85c253eaa
/Stack.cpp
c5944d4ddb84b5fbc44f7276dd2c0e2b9c43c402
[]
no_license
Jiinja/PA7
14eade179ef0e1dc4c731c83cb39f6f2d1bb8226
72509055c292ff9b579026f33e4b3a58ed043a27
refs/heads/master
2023-08-30T09:08:42.458858
2021-11-15T05:47:58
2021-11-15T05:47:58
427,181,385
0
1
null
null
null
null
UTF-8
C++
false
false
2,131
cpp
/***************************************************************************************** * Programmer: Josh Maloy * * Class: CptS 122, Fall 2021; Lab Section 1 * * Programming Assignment: PA7 * * Date: November 12, 2021 * * Description: this file defines all methods for the Stack class * ******************************************************************************************/ #include "Stack.h" Stack::Stack() { this->array = new std::string[100]; this->top = -1; } Stack::~Stack() { //delete this->array; } bool Stack::push(std::string newData) { bool result = false; if (top != 99) //if there is room { top++; this->array[top] = newData; result = true; } return result; } bool Stack::pop() { bool result = false; if (top != 0) { top--; result = true; } return result; } std::string Stack::peak() { if (top == -1) return "N/A"; return this->array[this->top]; } bool Stack::isEmpty() { return (top == 0); } bool Stack::removeDate(string date) { bool found = false; for (int i = 0; i <= this->top; i++) { if (this->array[i] == date) { found = true; } if (found) { array[i] = array[i + 1]; } } if (found) this->top--; return found; } string Stack::getString() { string result = ""; for (int i = 0; i <= top; i++) { result = ("," + this->array[i]) + result; } result = (std::to_string(this->top + 1) + result); return result; } std::ofstream& operator<<(std::ofstream& lhs, Stack& rhs) { lhs << rhs.getString(); return lhs; } std::ifstream& operator>>(std::ifstream& lhs, Stack& rhs) { int num; string line; lhs >> line; num = stoi(line.substr(0, line.find_first_of(","))); line = line.substr(line.find_first_of(",")+1); for (int i = 0; i < num-1; i++) { rhs.push(line.substr(0, line.find_first_of(","))); line = line.substr(line.find_first_of(",")+1); } if (num > 0) { rhs.push(line); } return lhs; }
[ "pianoboy@live.com" ]
pianoboy@live.com
aae62224d8cf7509cf9b0171afa2c00a1440f859
5793887005d7507a0a08dc82f389d8b8849bc4ed
/vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6735m/core/camshot/MultiShot/MultiShotNcc.cpp
56db8ed6b7d5a2fc85c6b7d3ffc9a85c57034bb2
[]
no_license
wangbichao/dual_camera_x
34b0e70bf2dc294c7fa077c637309498654430fa
fa4bf7e6d874adb7cf4c658235a8d24399f29f30
refs/heads/master
2020-04-05T13:40:56.119933
2017-07-10T13:57:33
2017-07-10T13:57:33
94,966,927
3
0
null
null
null
null
UTF-8
C++
false
false
16,846
cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /******************************************************************************************** * LEGAL DISCLAIMER * * (Header of MediaTek Software/Firmware Release or Documentation) * * BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED * FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS * ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY * WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK * ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION * OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH * RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE * FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS * OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES. ************************************************************************************************/ #define LOG_TAG "CamShot/MultiShotNcc" // #include <mtkcam/Log.h> #define MY_LOGV(fmt, arg...) CAM_LOGV(fmt, ##arg) #define MY_LOGD(fmt, arg...) CAM_LOGD(fmt, ##arg) #define MY_LOGI(fmt, arg...) CAM_LOGI(fmt, ##arg) #define MY_LOGW(fmt, arg...) CAM_LOGW(fmt, ##arg) #define MY_LOGE(fmt, arg...) CAM_LOGE(fmt, ##arg) #define FUNCTION_LOG_START MY_LOGD("[%s] +", __FUNCTION__); #define FUNCTION_LOG_END MY_LOGD("[%s] -", __FUNCTION__); // #include <cutils/properties.h> // #if (MTKCAM_BASIC_PACKAGE != 1) #include <linux/cache.h> #endif // #include <mtkcam/common.h> #include <mtkcam/common/hw/hwstddef.h> // #include <mtkcam/v1/camutils/CamMisc.h> #include <mtkcam/v1/camutils/CamProfile.h> // #include <mtkcam/drv_common/imem_drv.h> // #include <mtkcam/hal/aaa_hal_base.h> // #include <mtkcam/campipe/IPipe.h> #include <mtkcam/campipe/ICamIOPipe.h> #include <mtkcam/campipe/IPostProcPipe.h> // #include <mtkcam/drv/res_mgr_drv.h> #include <mtkcam/campipe/pipe_mgr_drv.h> // #include <mtkcam/camshot/_callbacks.h> #include <mtkcam/camshot/_params.h> #include <mtkcam/camshot/ISImager.h> #include "../inc/ImageUtils.h" #include <DpBlitStream.h> //[CS]+ extern "C" { #include "jpeglib.h" #include "jerror.h" } // #include "../inc/CamShotImp.h" #include "../inc/MultiShot.h" // using namespace android; using namespace NSCamPipe; using namespace NS3A; class ResMgrDrv; class PipeMgrDrv; #define MEDIA_PATH "/sdcard/" #define CHECK_OBJECT(x) { if (x == NULL) { MY_LOGE("Null %s Object", #x); return MFALSE;}} /******************************************************************************* * ********************************************************************************/ namespace NSCamShot { //////////////////////////////////////////////////////////////////////////////// /******************************************************************************* * ********************************************************************************/ MultiShotNcc:: MultiShotNcc( EShotMode const eShotMode, char const*const szCamShotName ) : MultiShot(eShotMode, szCamShotName) { } /******************************************************************************* * ********************************************************************************/ MultiShotNcc:: ~MultiShotNcc( ) { } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: start(SensorParam const & rSensorParam, MUINT32 u4ShotCount) { FUNCTION_LOG_START; AutoCPTLog cptlog(Event_MShot_start); mSensorParam = rSensorParam; // dumpSensorParam(mSensorParam); MY_LOGD("[start] enabled msg (nitify, data) = (0x%x, 0x%x)", mi4NotifyMsgSet, mi4DataMsgSet); // if (!isDataMsgEnabled(ECamShot_DATA_MSG_ALL) && !isNotifyMsgEnabled(ECamShot_NOTIFY_MSG_ALL)) { MY_LOGE("[start] No data msg enable !"); return MFALSE; } mbSet3ACapMode = MTRUE; mbCancelShot = MFALSE; mbIsLastShot = MFALSE; mu4JpegCount = 0; mu4ShotCount = u4ShotCount; mbJpegSemPost = MFALSE; ::sem_init(&semJpeg, 0, 0); ::sem_init(&semThumbnail, 0, 0); ::sem_init(&semStartEnd, 0, 0); MY_LOGD("mu4ShotCount = %d", mu4ShotCount); EImageFormat eImgFmt = querySensorFmt(rSensorParam.u4DeviceID, rSensorParam.u4Scenario, rSensorParam.u4Bitdepth); CPTLogStr(Event_MShot_start, CPTFlagSeparator, "create/init CamIOPipe"); // (1). Create Instance if (NULL == mpCamIOPipe) { mpCamIOPipe = ICamIOPipe::createInstance(eSWScenarioID_CAPTURE_NORMAL, static_cast<EScenarioFmt>(mapScenarioType(eImgFmt))); CHECK_OBJECT(mpCamIOPipe); // (2). Query port property #warning [TODO] Query port property // (3). init mpCamIOPipe->init(); } // (2) prepare buffer CPTLogStr(Event_MShot_start, CPTFlagSeparator, "prepare buffer"); // (2.1) raw buffer mRawImgBufInfo = querySensorRawImgBufInfo(); // (2.2) yuv buffer mYuvImgBufInfoWrite = queryYuvRawImgBufInfo(); mYuvImgBufInfoReady = queryYuvRawImgBufInfo(); mYuvImgBufInfoRead = queryYuvRawImgBufInfo(); // (2.3) PostView buffer mPostViewImgBufInfoWrite = queryPostViewImgInfo(); mPostViewImgBufInfoReady = queryPostViewImgInfo(); mPostViewImgBufInfoRead = queryPostViewImgInfo(); // (2.4) jpeg buffer mJpegImgBufInfoWrite = queryJpegImgBufInfo(); mJpegImgBufInfoReady = queryJpegImgBufInfo(); // (2.5) Thumb buffer mThumbImgBufInfoYuv = queryThumbYuvImgBufInfo(); mThumbImgBufInfoWrite = queryThumbImgBufInfo(); mThumbImgBufInfoReady = queryThumbImgBufInfo(); mThumbImgBufInfoTemp = queryThumbTempImgBufInfo(); // (3) init thread CPTLogStr(Event_MShot_start, CPTFlagSeparator, "init image create thread"); initImageCreateThread(); // (4) start c-shot loop CPTLogStr(Event_MShot_start, CPTFlagSeparator, "wakeup create thread"); mpImageCreateThread->postCommand(Command(Command::eID_WAKEUP)); //onCreateImage(); FUNCTION_LOG_END; // return MTRUE; } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: stop() { FUNCTION_LOG_START; AutoCPTLog cptlog(Event_MShot_stop); #warning [TODO] for continouous shot // [CS]+ // (1) mbCancelShot = MTRUE; // (2) wait start end CPTLogStr(Event_MShot_stop, CPTFlagSeparator, "wait start end"); ::sem_wait(&semStartEnd); // must call before thread stop, to sure the lastimage notify callback do. // (3) uninit thread CPTLogStr(Event_MShot_stop, CPTFlagSeparator, "uninit image create thread"); uninitImageCreateThread(); // (4) end continuous shot jobs in 3A NS3A::Hal3ABase *p3AObj = Hal3ABase::createInstance(mSensorParam.u4DeviceID); p3AObj->endContinuousShotJobs(); p3AObj->destroyInstance(); // (5) destroy CamIOPipe CPTLogStr(Event_MShot_stop, CPTFlagSeparator, "destroy/uninit CamIOPipe"); CHECK_OBJECT(mpCamIOPipe) MBOOL ret = mpCamIOPipe->uninit(); if (!ret) { MY_LOGE("mpCamIOPipe->uninit() fail "); } mpCamIOPipe = NULL; // (6) prepare buffer freeShotMem(); // [CS]- FUNCTION_LOG_END; // return MTRUE; } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: initImageCreateThread() { FUNCTION_LOG_START; // (0) create display thread status_t status = OK; mpImageCreateThread = IImageCreateThread::createInstance(IMAGE_CREATE, this); if ( mpImageCreateThread == 0 || OK != (status = mpImageCreateThread->run(LOG_TAG)) ) { MY_LOGE( "Fail to run ImageCreateThread - mpImageCreateThread.get(%p), status[%s(%d)]", mpImageCreateThread.get(), ::strerror(-status), -status ); return MFALSE; } mpYuvImageCreateThread = IImageCreateThread::createInstance(YUV_IMAGE_CREATE, this); if ( mpYuvImageCreateThread == 0 || OK != (status = mpYuvImageCreateThread->run(LOG_TAG)) ) { MY_LOGE( "Fail to run YuvImageCreateThread - mpYuvImageCreateThread.get(%p), status[%s(%d)]", mpYuvImageCreateThread.get(), ::strerror(-status), -status ); return MFALSE; } mpThumbnailImageCreateThread = IImageCreateThread::createInstance(THUMBNAIL_IMAGE_CREATE, this); if ( mpThumbnailImageCreateThread == 0 || OK != (status = mpThumbnailImageCreateThread->run(LOG_TAG)) ) { MY_LOGE( "Fail to run ThumbnailImageCreateThread - mpThumbnailImageCreateThread.get(%p), status[%s(%d)]", mpThumbnailImageCreateThread.get(), ::strerror(-status), -status ); return MFALSE; } mpJpegImageCreateThread = IImageCreateThread::createInstance(JPEG_IMAGE_CREATE, this); if ( mpJpegImageCreateThread == 0 || OK != (status = mpJpegImageCreateThread->run(LOG_TAG)) ) { MY_LOGE( "Fail to run JpegImageCreateThread - mpJpegImageCreateThread.get(%p), status[%s(%d)]", mpJpegImageCreateThread.get(), ::strerror(-status), -status ); return MFALSE; } FUNCTION_LOG_END; return MTRUE; } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: onCreateImage() { AutoCPTLog cptlog(Event_MShot_onCreateImage); mpYuvImageCreateThread->postCommand(Command(Command::eID_WAKEUP)); MUINT32 u4ShotCount = 0; //MBOOL bCShotEndCB = false; // (3) loop, handle jpeg buffer while(u4ShotCount<mu4ShotCount) { CPTLogStr(Event_MShot_onCreateImage, CPTFlagSeparator, "wait jpeg done"); ::sem_wait(&semJpeg); CPTLogStr(Event_MShot_onCreateImage, CPTFlagSeparator, "handle callback"); if(mbCancelShot || u4ShotCount==mu4ShotCount-1) // last frame { mbIsLastShot = MTRUE; MY_LOGD("notify last shot will callback"); handleNotifyCallback(ECamShot_NOTIFY_MSG_CSHOT_END, 0, 0); handleNotifyCallback(ECamShot_NOTIFY_MSG_FOCUS_VALUE, mFocusVal.u4ValH, mFocusVal.u4ValL); handleDataCallback(ECamShot_DATA_MSG_JPEG, (mThumbImgBufInfoReady.u4BufVA), mu4ThumbnailReadySize, reinterpret_cast<MUINT8*>(mJpegImgBufInfoReady.u4BufVA), mu4JpegReadySize); finishJpegBufCallback(); break; } handleNotifyCallback(ECamShot_NOTIFY_MSG_FOCUS_VALUE, mFocusVal.u4ValH, mFocusVal.u4ValL); handleDataCallback(ECamShot_DATA_MSG_JPEG, (mThumbImgBufInfoReady.u4BufVA), mu4ThumbnailReadySize, reinterpret_cast<MUINT8*>(mJpegImgBufInfoReady.u4BufVA), mu4JpegReadySize); finishJpegBufCallback(); u4ShotCount++; } // (7) start end CPTLogStr(Event_MShot_start, CPTFlagSeparator, "post start end sem"); ::sem_post(&semStartEnd); return MTRUE; } /******************************************************************************* * ********************************************************************************/ MVOID MultiShotNcc:: getReadBuf() { //FUNCTION_LOG_START; Mutex::Autolock lock(mYuvReadyBufMtx); ImgBufInfo rYuvImgBufInfo = mYuvImgBufInfoRead; mYuvImgBufInfoRead = mYuvImgBufInfoReady; mYuvImgBufInfoReady = rYuvImgBufInfo; ImgBufInfo rPostViewBufInfo = mPostViewImgBufInfoRead; mPostViewImgBufInfoRead = mPostViewImgBufInfoReady; mPostViewImgBufInfoReady = rPostViewBufInfo; mFocusValRead = mFocusValReady; mbJpegSemPost = MFALSE; // means new Jpeg compress begin //FUNCTION_LOG_END; } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: returnJpegBuf() { //FUNCTION_LOG_START; MBOOL ret = MTRUE; Mutex::Autolock lock(mJpegReadyBufMtx); if( mu4JpegReadySize == 0 ) { // switch buffer when callback is done ImgBufInfo rJpegImgBufInfo = mJpegImgBufInfoWrite; mJpegImgBufInfoWrite = mJpegImgBufInfoReady; mJpegImgBufInfoReady = rJpegImgBufInfo; mu4JpegReadySize = mu4JpegWriteSize; ImgBufInfo rThumbImgBufInfo = mThumbImgBufInfoWrite; mThumbImgBufInfoWrite = mThumbImgBufInfoReady; mThumbImgBufInfoReady = rThumbImgBufInfo; mu4ThumbnailReadySize = mu4ThumbnailWriteSize; mFocusVal = mFocusValRead; } else { MY_LOGW("jpeg callback not done yet"); ret = MFALSE; } return ret; //FUNCTION_LOG_END; } /******************************************************************************* * ********************************************************************************/ MBOOL MultiShotNcc:: sendCommand(MINT32 cmd, MINT32 arg1, MINT32 arg2, MINT32 arg3) { FUNCTION_LOG_START; MBOOL ret = MTRUE; // switch (cmd) { case ECamShot_CMD_SET_CSHOT_SPEED: if(arg1 > 0) { mu4ShotSpeed = arg1; ret = MTRUE; } else { MY_LOGD("set invalid shot speed: %d", arg1); ret = MFALSE; } break; default: break; } // FUNCTION_LOG_END; // return ret; } //////////////////////////////////////////////////////////////////////////////// }; //namespace NSCamShot
[ "wangbichao@live.com" ]
wangbichao@live.com
45f792c844bf10ea19bfa2c9fd5a34d1840bf957
90c9dc885340e28c421f129396a593b9b60e0ce1
/src/GAME/zNPCTurret.cpp
dc8232d20b4192f6fa708237d25bb4bbf08a779d
[]
no_license
Gota7/incredibles
3b493718fb1a1145371811966a2024b5c8fec39f
14dd4a94edbe84c30482a8e873b5c8e9f48d1535
refs/heads/main
2023-06-16T12:38:46.252815
2021-07-10T07:59:53
2021-07-10T07:59:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,921
cpp
#include "zNPCTurret.h" #include <types.h> // func_8013C438 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "in_range__Q24zNPC7up_downFP15xAnimTransitionP11xAnimSingle") // func_8013C440 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "not_in_range__Q24zNPC7up_downFP15xAnimTransitionP11xAnimSingle") // func_8013C468 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_states__Q24zNPC7up_downFP10xAnimTable") // func_8013C59C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_transitions__Q24zNPC7up_downFP10xAnimTable") // func_8013C6D8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "anin_range__Q24zNPC7up_downFP15xAnimTransitionP11xAnimSinglePv") // func_8013C734 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "annot_in_range__Q24zNPC7up_downFP15xAnimTransitionP11xAnimSinglePv") // func_8013C790 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC7up_downFf") // func_8013C890 #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "enter_state__Q24zNPC7up_downFPC39behavior_implementation_esc__0_Q24zNPC6common_esc__1_") // func_8013C8C8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exit_state__Q24zNPC7up_downFv") // func_8013C8E8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC7up_downFv") // func_8013C96C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "reset__Q24zNPC7up_downFv") // func_8013C984 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "system_event__Q24zNPC7up_downFP5xBaseP5xBaseUiPCfP5xBaseUi") // func_8013C9A0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "grabbable__Q24zNPC7up_downF8GrabType") // func_8013C9B0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "noticed__Q24zNPC12up_down_spinFP15xAnimTransitionP11xAnimSingle") // func_8013C9B8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "not_in_range__Q24zNPC12up_down_spinFP15xAnimTransitionP11xAnimSingle") // func_8013CA04 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_states__Q24zNPC12up_down_spinFP10xAnimTable") // func_8013CB3C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_transitions__Q24zNPC12up_down_spinFP10xAnimTable") // func_8013CC7C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "annoticed__Q24zNPC12up_down_spinFP15xAnimTransitionP11xAnimSinglePv") // func_8013CCD8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "annot_in_range__Q24zNPC12up_down_spinFP15xAnimTransitionP11xAnimSinglePv") // func_8013CD34 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "system_event__Q24zNPC12up_down_spinFP5xBaseP5xBaseUiPCfP5xBaseUi") // func_8013CD50 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC12up_down_spinFf") // func_8013CE34 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "enter_state__Q24zNPC12up_down_spinFPC8behavior") // func_8013CE80 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exit_state__Q24zNPC12up_down_spinFv") // func_8013CEA0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC12up_down_spinFv") // func_8013CF78 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "reset__Q24zNPC12up_down_spinFv") // func_8013CFAC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "update__Q24zNPC12up_down_spinFf") // func_8013D1AC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "xMat3x3RMulVec__FP5xVec3PC7xMat3x3PC5xVec3_27") // func_8013D210 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_states__Q24zNPC12turret_alertFP10xAnimTable") // func_8013D304 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "add_transitions__Q24zNPC12turret_alertFP10xAnimTable") // func_8013D3B8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "anoverheated__Q24zNPC12turret_alertFP15xAnimTransitionP11xAnimSinglePv") // func_8013D414 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "overheated__Q24zNPC12turret_alertFP15xAnimTransitionP11xAnimSingle") // func_8013D428 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "update__Q24zNPC12turret_alertFf") // func_8013D668 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "glow_enable__Q24zNPC12turret_alertFv") // func_8013D6E0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "size__Q24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_Fv") // func_8013D6E8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "__vc__Q24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_Fi") // func_8013D6F8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "glow_disable__Q24zNPC12turret_alertFv") // func_8013D74C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "glow_hide__Q24zNPC12turret_alertFv") // func_8013D7A8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "smoke__Q24zNPC12turret_alertFv") // func_8013D7FC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "size__Q24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_Fv") // func_8013D804 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "__vc__Q24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_Fi") // func_8013D814 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "aim__Q24zNPC12turret_alertFf") // func_8013D894 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "fire__Q24zNPC12turret_alertFv") // func_8013D8EC #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "enter_state__Q24zNPC12turret_alertFPC39behavior_implementation_esc__0_Q24zNPC6common_esc__1_") // func_8013D954 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exit_state__Q24zNPC12turret_alertFv") // func_8013D98C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC12turret_alertFv") // func_8013DADC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "add_states__Q24zNPC22shoot_along_movepointsFP10xAnimTable") // func_8013DB8C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "add_transitions__Q24zNPC22shoot_along_movepointsFP10xAnimTable") // func_8013DBEC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_next_movepoint__Q24zNPC22shoot_along_movepointsFv") // func_8013DC4C #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "enter_state__Q24zNPC22shoot_along_movepointsFPC39behavior_implementation_esc__0_Q24zNPC6common_esc__1_") // func_8013DCB8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC22shoot_along_movepointsFv") // func_8013DD38 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "reset__Q24zNPC22shoot_along_movepointsFv") // func_8013DD44 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "aim_at__Q24zNPC22shoot_along_movepointsFRC5xVec3f") // func_8013DDB0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "fire__Q24zNPC22shoot_along_movepointsFv") // func_8013DE08 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "update__Q24zNPC22shoot_along_movepointsFf") // func_8013DFAC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exit_state__Q24zNPC9glow_boneFv") // func_8013DFD0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_position__Q24zNPC9glow_boneFv") // func_8013E0C4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "enable__Q24zNPC9glow_boneFv") // func_8013E0FC #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "disable__Q24zNPC9glow_boneFv") // func_8013E134 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "hide__Q24zNPC9glow_boneFv") // func_8013E160 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "update__Q24zNPC9glow_boneFf") // func_8013E210 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "reset__Q24zNPC9glow_boneFv") // func_8013E21C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC9glow_boneFv") // func_8013E338 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "get_parameter_esc__0_5xVec3_esc__1___Q24zNPC4baseFPCciP5xVec35xVec3_0") // func_8013E3A0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_parameter_esc__0_i_esc__1___Q24zNPC4baseFPCciPii_2") // func_8013E408 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "enter_state__Q24zNPC10smoke_boneFPC8behavior") // func_8013E41C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "start__Q24zNPC10smoke_boneFv") // func_8013E428 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "update__Q24zNPC10smoke_boneFf") // func_8013E4E4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "reset__Q24zNPC10smoke_boneFv") // func_8013E4F0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC10smoke_boneFv") // func_8013E5C4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_parameter_esc__0_f_esc__1___Q24zNPC4baseFPCciPff_1") // func_8013E634 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC24turret_follow_movepointsFv") // func_8013E6A4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "set_start_movepoint__Q24zNPC24turret_follow_movepointsFv") // func_8013E6B0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC6turretFv") // func_8013E7F4 #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "add_behavior_esc__0_Q24zNPC6common_esc__1___Q24zNPC6commonFP39behavior_implementation_esc__0_Q24zNPC6common_esc__1_Sc_10") // func_8013E820 #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "add_behavior_esc__0_Q24zNPC6common_esc__1___16behavior_managerFP39behavior_implementation_esc__0_Q24zNPC6common_esc__1_PQ24zNPC6commonSc_10") // func_8013E878 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC24turret_follow_movepointsFv") // func_8013E8B4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "__ct__Q24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_Fv") // func_8013E8F0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "__ct__Q24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_Fv") // func_8013E92C #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "__ct__Q24zNPC12turret_alertFRQ24zNPC32bone_container_esc__0_Q24zNPC8aim_bone_esc__1_RQ24zNPC35bone_container_esc__0_Q24zNPC10laser_bone_esc__1_RQ24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_RQ24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_") // func_8013E9AC #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "__ct__Q24zNPC22shoot_along_movepointsFRQ24zNPC32bone_container_esc__0_Q24zNPC8aim_bone_esc__1_RQ24zNPC35bone_container_esc__0_Q24zNPC10laser_bone_esc__1_") // func_8013E9F8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC7up_downFv") // func_8013EA34 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "static_scene_setup__Q24zNPC6turretFv") // func_8013EA34 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "setup__Q24zNPC6turretFv") // func_8013EA78 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC11spin_turretFv") // func_8013EBA0 #pragma GLOBAL_ASM( \ "asm/GAME/zNPCTurret.s", \ "__ct__Q24zNPC12up_down_spinFRQ24zNPC32bone_container_esc__0_Q24zNPC8aim_bone_esc__1_") // func_8013EBE4 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "static_scene_setup__Q24zNPC11spin_turretFv") // func_8013EC08 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__dt__Q24zNPC11spin_turretFv") // func_8013EC60 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_type_name__Q24zNPC11spin_turretCFv") // func_8013EC70 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__dt__Q24zNPC6turretFv") // func_8013ECC8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "get_type_name__Q24zNPC6turretCFv") // func_8013ECD8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC10smoke_boneFv") // func_8013ECE8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exclusive__Q24zNPC10smoke_boneFv") // func_8013ECF0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC10smoke_boneFf") // func_8013ED58 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC9glow_boneFv") // func_8013ED68 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "exclusive__Q24zNPC9glow_boneFv") // func_8013ED70 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC9glow_boneFf") // func_8013ED78 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC22shoot_along_movepointsFv") // func_8013ED88 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC22shoot_along_movepointsFf") // func_8013ED98 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC12turret_alertFv") // func_8013EDA8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "runnable__Q24zNPC12turret_alertFf") // func_8013EDB0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC12up_down_spinFv") // func_8013EDC0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "getName__Q24zNPC7up_downFv") // func_8013EDD0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "runnable__Q24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_Ff") // func_8013EDD8 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "runnable__Q24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_Ff") // func_8013EDE0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "init__Q24zNPC33bone_container_esc__0_Q24zNPC9glow_bone_esc__1_Fv") // func_8013EEE0 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC9glow_boneFv") // func_8013EF1C #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "is_valid_bone__Q24zNPC9glow_boneFPQ24zNPC6commoni") // func_8013EF48 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", \ "init__Q24zNPC35bone_container_esc__0_Q24zNPC10smoke_bone_esc__1_Fv") // func_8013F048 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "__ct__Q24zNPC10smoke_boneFv") // func_8013F084 #pragma GLOBAL_ASM("asm/GAME/zNPCTurret.s", "is_valid_bone__Q24zNPC10smoke_boneFPQ24zNPC6commoni")
[ "32021834+seilweiss@users.noreply.github.com" ]
32021834+seilweiss@users.noreply.github.com
47f79f7979e94a58ab16b3f44946d7e9ce843a48
609318d9ec96e9926bde067c83b04fd00c3ca4d8
/Audio/DemoApp.h
a1f3b2ba0b71fe8bf6040fd3cbcd78e28f2acfc0
[]
no_license
RyanAdamsGD/Audio
9f625747ced7beaee7b5ed6665b94a1ea0a49a20
ad3521941282aee207d8f3e235b2abab12b3be93
refs/heads/master
2021-01-10T15:29:11.049068
2015-12-31T21:44:43
2015-12-31T21:44:43
47,565,703
0
0
null
null
null
null
UTF-8
C++
false
false
2,547
h
#pragma once #include "stdAfx.h" #include "WinAudioCapture.h" #include "WinAudioRenderer.h" #include <thread> #include <dwrite.h> #include <vector> #pragma comment(lib,"d2d1") #pragma comment(lib, "Dwrite") class DemoApp { public: DemoApp(); ~DemoApp(); // Register the window class and call methods for instantiating drawing resources HRESULT Initialize(); // Process and dispatch messages void RunMessageLoop(); void Update(); bool finished; std::thread updateLoop; bool StartCapture(int TargetDurationInSec, int TargetLatency); void StopCapture(); void StopAudioRender(); void CreateRenderQueue(int BufferDurationInSeconds); private: // Initialize device-independent resources. HRESULT CreateDeviceIndependentResources(); // Initialize device-dependent resources. HRESULT CreateDeviceResources(); // Release device-dependent resource. void DiscardDeviceResources(); IMMDevice* GetDefaultCaptureDevice(); IMMDevice* GetDefaultRenderDevice(); void RenderWaveData(float* data, int size, int channelCount); void DrawPoints(D2D1_POINT_2F** const data, int size, int channelCount); void Start(); //only call this after calling draw points //because I'm too laze to extract it all void DrawString(int x, int y,const std::wstring& text); void FindFrequencyInHerz(float* data, int size, int channelCount); // Resize the render target. void OnResize( UINT width, UINT height ); // The windows procedure. static LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ); //d2d HWND m_hwnd; ID2D1Factory* m_pDirect2dFactory; ID2D1HwndRenderTarget* m_pRenderTarget; ID2D1SolidColorBrush* m_pLightSlateGrayBrush; ID2D1SolidColorBrush* m_pCornflowerBlueBrush; IDWriteFactory* m_pDWriteFactory; IDWriteTextFormat* m_pTextFormat; struct DrawnString { float x, y; const std::wstring text; DrawnString() :text(std::to_wstring(0)){} DrawnString(float x, float y, const std::wstring& text) :x(x), y(y), text(text){} }; std::vector<DrawnString> stringsToRender; //rendering WinAudioRenderer* renderer; RenderBuffer* renderQueue; RenderBuffer* currentRenderBufferBeingWrittenTo; BYTE* currentRenderBufferPosition; size_t previousCaptureBufferSize; //copies the data from the capturer into the render buffer void WriteCaptureBufferToRenderBuffer(); //capturing WinAudioCapture* capturer; BYTE *captureBuffer; size_t captureBufferSize; D2D1_SIZE_U windowSize; //has the capturer start writing over the old data void ResetCaptureBuffer(); };
[ "ryan.adams.gd@gmail.com" ]
ryan.adams.gd@gmail.com
4ede0c0983a097cf7bf2543bbae190f63285d6d9
aae1d55e0b47b38db0c84c2b87888499a59e1bcb
/eco314/lab3/3/test.cpp
15d1a713f761c7e284b071fc2c6ba67ef3fb218f
[]
no_license
sauloantuness/unifei
a530f6536243d23a2f391e46880fd24d83e88f58
84fa6530a2130e6ee7c9283c792cd0ef77ddde35
refs/heads/master
2020-04-10T06:44:28.910809
2014-07-19T15:56:45
2014-07-19T15:56:45
10,576,290
0
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
#include <iostream> #include "TrianguloRetangulo.h" using namespace std; int main(){ TrianguloRetangulo NT(1,1,2); // Triangulo invalido TrianguloRetangulo TR(8,6,10); cout << "Modo (a):" << endl; TR.imprime('a'); cout << endl; cout << "Modo (b):" << endl; TR.imprime('b'); cout << endl; cout << "Modo (c):" << endl; TR.imprime('c'); cout << endl; cout << "Modo (d):" << endl; TR.imprime('d'); cout << endl; if(TR.ehTriangulo()) cout << "Eh Triangulo" << endl; else cout << "Nao eh Triangulo" << endl; if(TR.ehRetangulo()) cout << "Eh Retangulo" << endl; else cout << "Nao eh Retangulo" << endl; TR.Quinhentos(); return 0; }
[ "saulo@saulo-note.(none)" ]
saulo@saulo-note.(none)
0ca144f9f06797418f6f176e3177796bae313703
5c9ab4c32e80ee9e556970c5bfe4eb7408f08c5e
/libs/glow-extras/viewer/glow-extras/viewer/layout.cc
60687dd5fb9bfe3a4b91ec5694cd37fae79d0d5b
[ "MIT" ]
permissive
petrarce/real_time_graphics
f1db9f88d4786c30ae6fb0d0ca5af11b80ba630c
2cb5698d0697f6bad2ebf44a02f4ddf62050d17b
refs/heads/master
2020-08-24T12:04:47.494194
2020-02-07T19:10:29
2020-02-07T19:10:29
216,822,057
1
0
null
null
null
null
UTF-8
C++
false
false
2,472
cc
#include "layout.hh" namespace { template <int D> constexpr tg::comp<D, int> tg_ifloor(tg::comp<D, float> const& v) { tg::comp<D, int> res; for (auto i = 0; i < D; ++i) res[i] = tg::ifloor(v[i]); return res; } } void glow::viewer::layout::build_linear_nodes( glow::viewer::layout::tree_node& root, tg::ipos2 rootStart, tg::isize2 rootSize, std::vector<glow::viewer::layout::linear_node>& out, int margin) { auto scnt = int(root.children.size()); if (scnt == 0) { // Leaf, write to out out.emplace_back(rootStart, rootSize, std::move(root.scene)); return; } // copy intended auto rows = root.layoutSettings.rows; auto cols = root.layoutSettings.cols; // auto-grid if (rows == -1 && cols == -1) { auto bestVal = std::numeric_limits<float>::max(); for (auto ir = 1; ir <= scnt; ++ir) { auto r = ir; auto c = (scnt + r - 1) / r; while ((r - 1) * c >= scnt) --r; TG_ASSERT(r * c >= scnt); TG_ASSERT((r - 1) * c <= scnt); TG_ASSERT(r * (c - 1) <= scnt); TG_ASSERT(r >= 1); TG_ASSERT(c >= 1); auto ar = (rootSize.width / float(c)) / (rootSize.height / float(r)); auto val = tg::max(root.layoutSettings.aspectRatio / ar, ar / root.layoutSettings.aspectRatio); if (val < bestVal) { bestVal = val; rows = r; cols = c; } } } else if (rows == -1) // fixed cols { TG_ASSERT(cols > 0); rows = (scnt + cols - 1) / cols; } else if (cols == -1) // fixed rows { TG_ASSERT(rows > 0); cols = (scnt + rows - 1) / rows; } TG_ASSERT(rows * cols >= scnt); TG_ASSERT(rows >= 1); TG_ASSERT(cols >= 1); for (auto i = 0; i < scnt; ++i) { auto& child = root.children[unsigned(i)]; auto const c = i % cols; auto const r = i / cols; auto const start = rootStart + tg::ivec2(tg_ifloor(tg::comp2(rootSize) * tg::comp2(c, r) / tg::comp2(cols, rows))); auto const end = rootStart + tg::ivec2(tg_ifloor(tg::comp2(rootSize) * tg::comp2(c + 1, r + 1) / tg::comp2(cols, rows))); auto const size = end - start - tg::ivec2(margin); // Descend build_linear_nodes(child, start, tg::isize2(size), out, margin); } }
[ "yinglun.liu.it.happens@gmail.com" ]
yinglun.liu.it.happens@gmail.com
ca464f293b1a48132096cd821313de7f903dcd33
8a0a4d70c8626bdbf08f2c6a1856a159e885e0b5
/NSIS/tags/alpha2/Source/script.cpp
9fe9ad2394fe916feb49a2c70b1159d8d6fde0fc
[]
no_license
joelnb/nsis
c77ad193314fd3f23fd104d924dfbee7e3e959e7
cb26737974acb558c61a143458a79984e724f381
refs/heads/master
2022-09-13T03:33:20.860809
2022-09-02T20:03:18
2022-09-02T20:03:18
142,794,118
1
0
null
null
null
null
UTF-8
C++
false
false
117,734
cpp
#include <windows.h> #include <stdio.h> #include <shlobj.h> #include "tokens.h" #include "build.h" #include "util.h" #include "exedata.h" #include "ResourceEditor.h" #include "DialogTemplate.h" #include "exehead/resource.h" #ifndef FOF_NOERRORUI #define FOF_NOERRORUI 0x0400 #endif #define MAX_INCLUDEDEPTH 10 #define MAX_LINELENGTH 4096 static const char *usrvars="$0\0$1\0$2\0$3\0$4\0$5\0$6\0$7\0$8\0$9\0" "$R0\0$R1\0$R2\0$R3\0$R4\0$R5\0$R6\0$R7\0$R8\0$R9\0" "$CMDLINE\0$INSTDIR\0$OUTDIR\0$EXEDIR\0"; int CEXEBuild::process_script(FILE *fp, char *curfilename, int *lineptr) { if (has_called_write_output) { ERROR_MSG("Error (process_script): write_output already called, can't continue\n"); return PS_ERROR; } int ret=parseScript(fp,curfilename,lineptr,0); if (ret == PS_ENDIF) ERROR_MSG("!endif: stray !endif\n"); if (IS_PS_ELSE(ret)) ERROR_MSG("!else: stray !else\n"); if (m_linebuild.getlen()) { ERROR_MSG("Error: invalid script: last line ended with \\\n"); return PS_ERROR; } return ret; } #define PRINTHELP() { print_help(line.gettoken_str(0)); return PS_ERROR; } int CEXEBuild::doParse(const char *str, FILE *fp, const char *curfilename, int *lineptr, int ignore) { LineParser line; int res; while (*str == ' ' || *str == '\t') str++; // if ignoring, ignore all lines that don't begin with !. if (ignore && *str!='!') return PS_OK; if (m_linebuild.getlen()>1) m_linebuild.resize(m_linebuild.getlen()-2); m_linebuild.add(str,strlen(str)+1); // remove trailing slash and null if (str[0] && CharPrev(str,str+strlen(str))[0] == '\\') return PS_OK; res=line.parse((char*)m_linebuild.get()); m_linebuild.resize(0); if (res) { if (res==-2) ERROR_MSG("Error: unterminated string parsing line at %s:%d\n",curfilename,*lineptr); else ERROR_MSG("Error: error parsing line (%s:%d)\n",curfilename,*lineptr); return PS_ERROR; } parse_again: if (line.getnumtokens() < 1) return PS_OK; int np,op; int tkid=get_commandtoken(line.gettoken_str(0),&np,&op); if (tkid == -1) { char *p=line.gettoken_str(0); if (p[0] && p[strlen(p)-1]==':') { if (p[0] == '!' || (p[0] >= '0' && p[0] <= '9') || p[0] == '$' || p[0] == '-' || p[0] == '+') { ERROR_MSG("Invalid label: %s (labels cannot begin with !, $, -, +, or 0-9)\n",line.gettoken_str(0)); return PS_ERROR; } if (add_label(line.gettoken_str(0))) return PS_ERROR; line.eattoken(); goto parse_again; } ERROR_MSG("Invalid command: %s\n",line.gettoken_str(0)); return PS_ERROR; } int v=line.getnumtokens()-(np+1); if (v < 0 || (op >= 0 && v > op)) // opt_parms is -1 for unlimited { ERROR_MSG("%s expects %d",line.gettoken_str(0),np); if (op < 0) ERROR_MSG("+"); if (op > 0) ERROR_MSG("-%d",op); ERROR_MSG(" parameters, got %d.\n",line.getnumtokens()-1); PRINTHELP() } int is_elseif=0; if (!fp && (tkid == TOK_P_ELSE || tkid == TOK_P_IFNDEF || tkid == TOK_P_IFDEF)) { ERROR_MSG("Error: !if/!else/!ifdef can only be specified in file mode, not in command/macro mode\n"); return PS_ERROR; } if (tkid == TOK_P_ELSE) { if (line.getnumtokens() == 1) return PS_ELSE; line.eattoken(); int v=line.gettoken_enum(0,"ifdef\0ifndef\0"); if (v < 0) PRINTHELP() if (line.getnumtokens() == 1) PRINTHELP() if (!v) tkid = TOK_P_IFDEF; else tkid = TOK_P_IFNDEF; is_elseif=1; } if (tkid == TOK_P_IFNDEF || tkid == TOK_P_IFDEF) { int istrue=0; if (!ignore || is_elseif) { int mod=0; int p; // pure left to right precedence. Not too powerful, but useful. for (p = 1; p < line.getnumtokens(); p ++) { if (p & 1) { int new_s=!!definedlist.find(line.gettoken_str(p)); if (tkid == TOK_P_IFNDEF) new_s=!new_s; if (mod == 0) istrue = istrue || new_s; else istrue = istrue && new_s; } else { mod=line.gettoken_enum(p,"|\0&\0||\0&&\0"); if (mod == -1) PRINTHELP() mod &= 1; } } if (is_elseif) { if (istrue) return PS_ELSE_IF1; return PS_ELSE_IF0; } } int r; int hasexec=0; istrue=!istrue; for (;;) { r=parseScript(fp,curfilename,lineptr, ignore || hasexec || istrue); if (!istrue) hasexec=1; if (r == PS_ELSE_IF0) istrue=1; else if (r == PS_ELSE_IF1) istrue=0; else break; } if (r == PS_ELSE) { r=parseScript(fp,curfilename,lineptr, ignore || hasexec); if (IS_PS_ELSE(r)) { ERROR_MSG("!else: stray !else\n"); return PS_ERROR; } } if (r == PS_EOF) { ERROR_MSG("!ifdef: open at EOF - need !endif\n"); return PS_ERROR; } if (r == PS_ERROR) return r; return PS_OK; } if (tkid == TOK_P_ENDIF) return PS_ENDIF; if (!ignore) { int ret=doCommand(tkid,line,fp,curfilename,*lineptr); if (ret != PS_OK) return ret; } return PS_OK; } void CEXEBuild::ps_addtoline(const char *str, GrowBuf &linedata, StringList &hist) { // convert $\r, $\n to their literals // preprocessor replace ${VAR} with whatever value // note that if VAR does not exist, ${VAR} will go through unmodified const char *in=str; while (*in) { int add=1; char *t; char c=*in; t=CharNext(in); if (t-in > 1) // handle multibyte chars (no escape) { linedata.add((void*)in,t-in); in=t; continue; } in=t; if (c == '$') { if (in[0] == '\\') { if (in[1] == 'r') { in+=2; c='\r'; } else if (in[1] == 'n') { in+=2; c='\n'; } } else if (in[0] == '{') { char *s=strdup(in+1); char *t=s; while (*t) { if (*t == '}') break; t=CharNext(t); } if (*t && t!=s) { *t=0; t=definedlist.find(s); if (t && hist.find(s,0)<0) { in+=strlen(s)+2; add=0; hist.add(s,0); ps_addtoline(t,linedata,hist); hist.delbypos(hist.find(s,0)); } } free(s); } } if (add) linedata.add((void*)&c,1); } } int CEXEBuild::parseScript(FILE *fp, const char *curfilename, int *lineptr, int ignore) { char str[MAX_LINELENGTH]; for (;;) { char *p=str; *p=0; fgets(str,MAX_LINELENGTH,fp); (*lineptr)++; if (feof(fp)&&!str[0]) break; // remove trailing whitespace while (*p) p++; if (p > str) p--; while (p >= str && (*p == '\r' || *p == '\n' || *p == ' ' || *p == '\t')) p--; *++p=0; StringList hist; GrowBuf linedata; ps_addtoline(str,linedata,hist); linedata.add((void*)"",1); int ret=doParse((char*)linedata.get(),fp,curfilename,lineptr,ignore); if (ret != PS_OK) return ret; } return PS_EOF; } int CEXEBuild::process_oneline(char *line, char *curfilename, int lineptr) { StringList hist; GrowBuf linedata; ps_addtoline(line,linedata,hist); linedata.add((void*)"",1); return doParse((char*)linedata.get(),NULL,curfilename,&lineptr,0); } int CEXEBuild::process_jump(LineParser &line, int wt, int *offs) { const char *s=line.gettoken_str(wt); int v; if (!stricmp(s,"0") || !stricmp(s,"")) *offs=0; else if ((v=line.gettoken_enum(wt,usrvars))>=0) { *offs=-v-1; // to jump to a user variable target, -variable_index-1 is stored. } else { if ((s[0] == '-' || s[0] == '+') && !atoi(s+1)) { ERROR_MSG("Error: Goto targets beginning with '+' or '-' must be followed by nonzero integer (relative jump)\n"); return 1; } if ((s[0] >= '0' && s[0] <= '9') || s[0] == '$' || s[0] == '!') { ERROR_MSG("Error: Goto targets cannot begin with 0-9, $, !\n"); return 1; } *offs=ns_label.add(s,0); } return 0; } int CEXEBuild::doCommand(int which_token, LineParser &line, FILE *fp, const char *curfilename, int linecnt) { static const char *rootkeys[2] = { "HKCR\0HKLM\0HKCU\0HKU\0HKCC\0HKDD\0HKPD\0", "HKEY_CLASSES_ROOT\0HKEY_LOCAL_MACHINE\0HKEY_CURRENT_USER\0HKEY_USERS\0HKEY_CURRENT_CONFIG\0HKEY_DYN_DATA\0HKEY_PERFORMANCE_DATA\0" }; static HKEY rootkey_tab[] = { HKEY_CLASSES_ROOT,HKEY_LOCAL_MACHINE,HKEY_CURRENT_USER,HKEY_USERS,HKEY_CURRENT_CONFIG,HKEY_DYN_DATA,HKEY_PERFORMANCE_DATA }; entry ent={0,}; switch (which_token) { // macro shit /////////////////////////////////////////////////////////////////////////////// case TOK_P_MACRO: { if (!line.gettoken_str(1)[0]) PRINTHELP() char *t=(char *)m_macros.get(); while (t && *t) { if (!stricmp(t,line.gettoken_str(1))) break; t+=strlen(t)+1; // advance over parameters while (*t) t+=strlen(t)+1; t++; // advance over data while (*t) t+=strlen(t)+1; if (t-(char *)m_macros.get() >= m_macros.getlen()-1) break; t++; } if (t && *t) { ERROR_MSG("!macro: macro named \"%s\" already found!\n",line.gettoken_str(1)); return PS_ERROR; } m_macros.add(line.gettoken_str(1),strlen(line.gettoken_str(1))+1); int pc; for (pc=2; pc < line.getnumtokens(); pc ++) { if (!line.gettoken_str(pc)[0]) { ERROR_MSG("!macro: macro parameter %d is empty, not valid!\n",pc-1); return PS_ERROR; } int a; for (a=2; a < pc; a ++) { if (!stricmp(line.gettoken_str(pc),line.gettoken_str(a))) { ERROR_MSG("!macro: macro parameter named %s is used multiple times!\n", line.gettoken_str(pc)); return PS_ERROR; } } m_macros.add(line.gettoken_str(pc),strlen(line.gettoken_str(pc))+1); } m_macros.add("",1); for (;;) { char str[MAX_LINELENGTH]; char *p=str; str[0]=0; fgets(str,MAX_LINELENGTH,fp); if (feof(fp) || !str[0]) { ERROR_MSG("!macro \"%s\": unterminated (no !macroend found in file)!\n",line.gettoken_str(1)); return PS_ERROR; } // remove trailing whitespace while (*p) p++; if (p > str) p--; while (p >= str && (*p == '\r' || *p == '\n' || *p == ' ' || *p == '\t')) p--; *++p=0; LineParser l2; l2.parse(str); if (!stricmp(l2.gettoken_str(0),"!macroend")) break; if (str[0]) m_macros.add(str,strlen(str)+1); else m_macros.add(" ",2); } m_macros.add("",1); } return PS_OK; case TOK_P_MACROEND: ERROR_MSG("!macroend: no macro currently open.\n"); return PS_ERROR; case TOK_P_INSERTMACRO: { if (!line.gettoken_str(1)[0]) PRINTHELP() char *t=(char *)m_macros.get(); while (t && *t) { if (!stricmp(t,line.gettoken_str(1))) break; t+=strlen(t)+1; // advance over parms while (*t) t+=strlen(t)+1; t++; // advance over data while (*t) t+=strlen(t)+1; if (t-(char *)m_macros.get() >= m_macros.getlen()-1) break; t++; } SCRIPT_MSG("!insertmacro: %s\n",line.gettoken_str(1)); if (!t || !*t) { ERROR_MSG("!insertmacro: macro named \"%s\" not found!\n",line.gettoken_str(1)); return PS_ERROR; } t+=strlen(t)+1; GrowBuf l_define_names; DefineList l_define_saves; int npr=0; // advance over parms while (*t) { char *v; if (v=definedlist.find(t)) { l_define_saves.add(t,v); definedlist.del(t); } l_define_names.add(t,strlen(t)+1); definedlist.add(t,line.gettoken_str(npr+2)); npr++; t+=strlen(t)+1; } l_define_names.add("",1); t++; if (npr != line.getnumtokens()-2) { ERROR_MSG("!insertmacro: macro \"%s\" requires %d parameter(s), passed %d!\n", line.gettoken_str(1),npr,line.getnumtokens()-2); return PS_ERROR; } int lp=0; char str[1024]; if (m_macro_entry.find(line.gettoken_str(1),0)>=0) { ERROR_MSG("!insertmacro: macro \"%s\" already being inserted!\n",line.gettoken_str(1)); return PS_ERROR; } int npos=m_macro_entry.add(line.gettoken_str(1),0); wsprintf(str,"macro:%s",line.gettoken_str(1)); while (*t) { lp++; if (strcmp(t," ")) { int ret=process_oneline(t,str,lp); if (ret != PS_OK) { ERROR_MSG("Error in macro %s on macroline %d\n",line.gettoken_str(1),lp); return ret; } } t+=strlen(t)+1; } m_macro_entry.delbypos(npos); { char *p=(char*)l_define_names.get(); while (*p) { definedlist.del(p); char *v; if ((v=l_define_saves.find(p))) definedlist.add(p,v); p+=strlen(p); } } SCRIPT_MSG("!insertmacro: end of %s\n",line.gettoken_str(1)); } return PS_OK; // header flags /////////////////////////////////////////////////////////////////////////////// case TOK_NAME: if (build_header.common.name_ptr >= 0) { warning("Name: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_header.common.name_ptr=add_string_main(line.gettoken_str(1),0); #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT build_uninst.common.name_ptr=add_string_uninst(line.gettoken_str(1),0); #endif SCRIPT_MSG("Name: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_CAPTION: if (build_header.common.caption_ptr >= 0) { warning("Caption: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_header.common.caption_ptr=add_string_main(line.gettoken_str(1)); SCRIPT_MSG("Caption: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_ICON: SCRIPT_MSG("Icon: \"%s\"\n",line.gettoken_str(1)); try { build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); if (replace_icon(&re, IDI_ICON2, line.gettoken_str(1))) { ERROR_MSG("Error: File doesn't exist or is an invalid icon file\n"); return PS_ERROR; } free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); } catch (exception& err) { ERROR_MSG("Error while replacing icon: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #ifdef NSIS_CONFIG_COMPONENTPAGE // Changed by Amir Szekely 24th July 2002 case TOK_CHECKBITMAP: SCRIPT_MSG("CheckBitmap: \"%s\"\n",line.gettoken_str(1)); try { build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); if (update_bitmap(&re, IDB_BITMAP1, line.gettoken_str(1), 96, 16)) { ERROR_MSG("Error: File doesn't exist, is an invalid bitmap, or has the wrong size\n"); return PS_ERROR; } free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); } catch (exception& err) { ERROR_MSG("Error while replacing bitmap: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else//NSIS_CONFIG_COMPONENTPAGE case TOK_ENABLEDBITMAP: case TOK_DISABLEDBITMAP: ERROR_MSG("Error: %s specified, NSIS_CONFIG_COMPONENTPAGE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_CONFIG_COMPONENTPAGE case TOK_DIRTEXT: if (build_header.text_ptr >= 0 && line.gettoken_str(1)[0]) { warning("DirText: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_header.text_ptr=add_string_main(line.gettoken_str(1),0); if (line.getnumtokens()>2) build_header.dirsubtext_ptr=add_string_main(line.gettoken_str(2),0); if (line.getnumtokens()>3) build_header.browse_ptr=add_string_main(line.gettoken_str(3),0); SCRIPT_MSG("DirText: \"%s\" \"%s\" \"%s\"\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); #ifdef NSIS_CONFIG_COMPONENTPAGE case TOK_COMPTEXT: if (build_header.componenttext_ptr >= 0 && line.gettoken_str(1)[0]) { warning("ComponentText: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_header.componenttext_ptr=add_string_main(line.gettoken_str(1),0); if (line.getnumtokens()>2) build_header.componentsubtext_ptr[0]=add_string_main(line.gettoken_str(2),0); if (line.getnumtokens()>3) build_header.componentsubtext_ptr[1]=add_string_main(line.gettoken_str(3),0); SCRIPT_MSG("ComponentText: \"%s\" \"%s\" \"%s\"\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTTYPE: { int x; if (!stricmp(line.gettoken_str(1),"/NOCUSTOM")) { build_header.no_custom_instmode_flag=1; SCRIPT_MSG("InstType: disabling custom install type\n"); } else if (!stricmp(line.gettoken_str(1),"/COMPONENTSONLYONCUSTOM")) { build_header.no_custom_instmode_flag=2; SCRIPT_MSG("InstType: making components viewable only on custom install type\n"); } else if (!strnicmp(line.gettoken_str(1),"/CUSTOMSTRING=",14)) { build_header.custom_ptr=add_string_main(line.gettoken_str(1)+14,0); SCRIPT_MSG("InstType: setting custom text to: \"%s\"\n",line.gettoken_str(1)+14); } else if (line.gettoken_str(1)[0]=='/') PRINTHELP() else { for (x = 0; x < NSIS_MAX_INST_TYPES && build_header.install_types_ptr[x]>=0; x ++); if (x==NSIS_MAX_INST_TYPES) { ERROR_MSG("InstType: no more than %d install types allowed. %d specified\n",NSIS_MAX_INST_TYPES,NSIS_MAX_INST_TYPES+1); return PS_ERROR; } else { build_header.install_types_ptr[x] = add_string_main(line.gettoken_str(1),0); SCRIPT_MSG("InstType: %d=\"%s\"\n",x+1,line.gettoken_str(1)); } } } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else//NSIS_CONFIG_COMPONENTPAGE case TOK_COMPTEXT: case TOK_INSTTYPE: ERROR_MSG("Error: %s specified but NSIS_CONFIG_COMPONENTPAGE not defined\n",line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_CONFIG_COMPONENTPAGE #ifdef NSIS_CONFIG_LICENSEPAGE case TOK_LICENSETEXT: if (build_header.licensetext_ptr >= 0) { warning("LicenseText: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_header.licensetext_ptr=add_string_main(line.gettoken_str(1),0); if (line.getnumtokens()>2) build_header.licensebutton_ptr=add_string_main(line.gettoken_str(2),0); SCRIPT_MSG("LicenseText: \"%s\" \"%s\"\n",line.gettoken_str(1),line.gettoken_str(2)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_LICENSEDATA: if (build_header.licensedata_ptr != -1) { warning("LicenseData: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } #ifdef NSIS_CONFIG_SILENT_SUPPORT if (build_header.common.silent_install) { warning("LicenseData: SilentInstall enabled, wasting space (%s:%d)",curfilename,linecnt); } #endif { FILE *fp; int datalen; fp=fopen(line.gettoken_str(1),"rb"); if (!fp) { ERROR_MSG("LicenseData: open failed \"%s\"\n",line.gettoken_str(1)); PRINTHELP() } fseek(fp,0,SEEK_END); datalen=ftell(fp); rewind(fp); char *data=(char*)malloc(datalen+1); if (fread(data,1,datalen,fp) != datalen) { ERROR_MSG("LicenseData: can't read file.\n"); fclose(fp); return PS_ERROR; } fclose(fp); data[datalen]=0; build_header.licensedata_ptr=add_string_main(data,0); SCRIPT_MSG("LicenseData: \"%s\"\n",line.gettoken_str(1)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); // Added by Amir Szekely 30th July 2002 case TOK_LICENSEBKCOLOR: { char *p = line.gettoken_str(1); int v=strtoul(p,&p,16); build_header.license_bg=((v&0xff)<<16)|(v&0xff00)|((v&0xff0000)>>16); SCRIPT_MSG("LicenseBkColor: %06X\n",v); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else//!NSIS_CONFIG_LICENSEPAGE case TOK_LICENSETEXT: case TOK_LICENSEDATA: case TOK_LICENSEBKCOLOR: ERROR_MSG("Error: %s specified, NSIS_CONFIG_LICENSEPAGE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_CONFIG_LICENSEPAGE #ifdef NSIS_CONFIG_SILENT_SUPPORT case TOK_SILENTINST: build_header.common.silent_install=line.gettoken_enum(1,"normal\0silent\0silentlog\0"); if (build_header.common.silent_install<0) PRINTHELP() #ifndef NSIS_CONFIG_LOG if (build_header.common.silent_install == 2) { ERROR_MSG("SilentInstall: silentlog specified, no log support compiled in (use NSIS_CONFIG_LOG)\n"); return PS_ERROR; } #endif//NSIS_CONFIG_LOG SCRIPT_MSG("SilentInstall: %s\n",line.gettoken_str(1)); #ifdef NSIS_CONFIG_LICENSEPAGE if (build_header.common.silent_install && build_header.licensedata_ptr != -1) { warning("SilentInstall: LicenseData already specified. wasting space (%s:%d)",curfilename,linecnt); } #endif//NSIS_CONFIG_LICENSEPAGE return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_SILENTUNINST: #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT build_uninst.common.silent_install=line.gettoken_enum(1,"normal\0silent\0"); if (build_uninst.common.silent_install<0) PRINTHELP() SCRIPT_MSG("SilentUnInstall: %s\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_UNINSTALL_SUPPORT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif #else//!NSIS_CONFIG_SILENT_SUPPORT case TOK_SILENTINST: case TOK_SILENTUNINST: ERROR_MSG("Error: %s specified, NSIS_CONFIG_SILENT_SUPPORT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//NSIS_CONFIG_SILENT_SUPPORT case TOK_OUTFILE: strncpy(build_output_filename,line.gettoken_str(1),1024-1); SCRIPT_MSG("OutFile: \"%s\"\n",build_output_filename); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTDIR: if (build_header.install_directory_ptr >= 0) { warning("InstallDir: specified multiple times. wasting space (%s:%d)",curfilename,linecnt); } build_header.install_directory_ptr = add_string_main(line.gettoken_str(1)); SCRIPT_MSG("InstallDir: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTALLDIRREGKEY: // InstallDirRegKey { if (build_header.install_reg_key_ptr>= 0) { warning("InstallRegKey: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } int k=line.gettoken_enum(1,rootkeys[0]); if (k == -1) k=line.gettoken_enum(1,rootkeys[1]); if (k == -1) PRINTHELP() build_header.install_reg_rootkey=(int)rootkey_tab[k]; build_header.install_reg_key_ptr = add_string_main(line.gettoken_str(2),0); if (line.gettoken_str(2)[0] == '\\') warning("%s: registry path name begins with \'\\\', may cause problems (%s:%d)",line.gettoken_str(0),curfilename,linecnt); build_header.install_reg_value_ptr = add_string_main(line.gettoken_str(3),0); SCRIPT_MSG("InstallRegKey: \"%s\\%s\\%s\"\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_CRCCHECK: build_crcchk=line.gettoken_enum(1,"off\0on\0force\0"); if (build_crcchk==-1) PRINTHELP() SCRIPT_MSG("CRCCheck: %s\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTPROGRESSFLAGS: { int x; build_header.common.progress_flags=0; for (x = 1; x < line.getnumtokens(); x ++) { if (!stricmp(line.gettoken_str(x),"smooth")) build_header.common.progress_flags|=1; else if (!stricmp(line.gettoken_str(x),"colored")) build_header.common.progress_flags|=2; else PRINTHELP() } SCRIPT_MSG("InstProgressFlags: %d (smooth=%d,colored=%d)\n",build_header.common.progress_flags, build_header.common.progress_flags&1, (build_header.common.progress_flags&2)>>1); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_AUTOCLOSE: { int k=line.gettoken_enum(1,"false\0true\0"); if (k == -1) PRINTHELP() build_header.common.misc_flags&=~1; build_header.common.misc_flags|=k; SCRIPT_MSG("AutoCloseWindow: %s\n",k?"true":"false"); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_WINDOWICON: #ifdef NSIS_CONFIG_VISIBLE_SUPPORT // Changed by Amir Szekely 30th July 2002 try { int k=line.gettoken_enum(1,"on\0off\0"); if (k == -1) PRINTHELP(); SCRIPT_MSG("WindowIcon: %s\n",line.gettoken_str(1)); if (!k) return make_sure_not_in_secorfunc(line.gettoken_str(0)); build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); #define REMOVE_ICON(id) { \ BYTE* dlg = re.GetResource(RT_DIALOG, MAKEINTRESOURCE(id), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); \ if (!dlg) throw runtime_error(#id " doesn't exist!"); \ CDialogTemplate dt(dlg); \ free(dlg); \ dt.RemoveItem(IDC_ULICON); \ DialogItemTemplate* text = dt.GetItem(IDC_INTROTEXT); \ DialogItemTemplate* prog1 = dt.GetItem(IDC_PROGRESS1); \ DialogItemTemplate* prog2 = dt.GetItem(IDC_PROGRESS2); \ if (text) { \ text->sWidth += text->sX; \ text->sX = 0; \ } \ if (prog1) { \ prog1->sWidth += prog1->sX; \ prog1->sX = 0; \ } \ if (prog2) { \ prog2->sWidth += prog2->sX; \ prog2->sX = 0; \ } \ \ DWORD dwSize; \ dlg = dt.Save(dwSize); \ re.UpdateResource(RT_DIALOG, MAKEINTRESOURCE(id), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), dlg, dwSize); \ free(dlg); \ } #ifdef NSIS_CONFIG_LICENSEPAGE REMOVE_ICON(IDD_LICENSE); #endif REMOVE_ICON(IDD_DIR); #ifdef NSIS_CONFIG_COMPONENTPAGE REMOVE_ICON(IDD_SELCOM); #endif REMOVE_ICON(IDD_INSTFILES); #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT REMOVE_ICON(IDD_UNINST); #endif #ifdef NSIS_CONFIG_CRC_SUPPORT REMOVE_ICON(IDD_VERIFY); #endif free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); } catch (exception& err) { ERROR_MSG("Error while changing font: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_VISIBLE_SUPPORT not defined.\n",line.gettoken_str(0)); return PS_ERROR; #endif // NSIS_CONFIG_VISIBLE_SUPPORT case TOK_SHOWDETAILSUNINST: #ifndef NSIS_CONFIG_UNINSTALL_SUPPORT ERROR_MSG("Error: ShowUninstDetails specified but NSIS_CONFIG_UNINSTALL_SUPPORT not defined\n"); return PS_ERROR; #endif case TOK_SHOWDETAILS: { int k=line.gettoken_enum(1,"hide\0show\0nevershow\0"); if (k == -1) PRINTHELP() #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT if (which_token == TOK_SHOWDETAILSUNINST) build_uninst.common.show_details=k; else #endif build_header.common.show_details=k; SCRIPT_MSG("%s: %s\n",line.gettoken_str(0),line.gettoken_str(1)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_DIRSHOW: { int k=line.gettoken_enum(1,"show\0hide\0"); if (k == -1) PRINTHELP() build_header.common.misc_flags&=~2; build_header.common.misc_flags|=(k<<1); SCRIPT_MSG("DirShow: %s\n",k?"hide":"show"); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_ROOTDIRINST: { int k=line.gettoken_enum(1,"true\0false\0"); if (k == -1) PRINTHELP() build_header.common.misc_flags&=~8; build_header.common.misc_flags|=(k<<3); SCRIPT_MSG("AllowRootDirInstall: %s\n",k?"false":"true"); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_BGGRADIENT: #ifndef NSIS_SUPPORT_BGBG ERROR_MSG("Error: BGGradient specified but NSIS_SUPPORT_BGBG not defined\n"); return PS_ERROR; #else//NSIS_SUPPORT_BGBG if (line.getnumtokens()==1) { SCRIPT_MSG("BGGradient: default colors\n"); build_header.common.bg_color1=0; build_header.common.bg_color2=RGB(0,0,255); } else if (!stricmp(line.gettoken_str(1),"off")) { build_header.common.bg_color1=build_header.common.bg_color2=-1; SCRIPT_MSG("BGGradient: off\n"); if (line.getnumtokens()>2) PRINTHELP() } else { char *p = line.gettoken_str(1); int v1,v2,v3=-1; v1=strtoul(p,&p,16); build_header.common.bg_color1=((v1&0xff)<<16)|(v1&0xff00)|((v1&0xff0000)>>16); p=line.gettoken_str(2); v2=strtoul(p,&p,16); build_header.common.bg_color2=((v2&0xff)<<16)|(v2&0xff00)|((v2&0xff0000)>>16); p=line.gettoken_str(3); if (*p) { if (!stricmp(p,"notext")) build_header.common.bg_textcolor=-1; else { v3=strtoul(p,&p,16); build_header.common.bg_textcolor=((v3&0xff)<<16)|(v3&0xff00)|((v3&0xff0000)>>16); } } SCRIPT_MSG("BGGradient: %06X->%06X (text=%d)\n",v1,v2,v3); } #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT build_uninst.common.bg_color1=build_header.common.bg_color1; build_uninst.common.bg_color2=build_header.common.bg_color2; build_uninst.common.bg_textcolor=build_header.common.bg_textcolor; #endif//NSIS_CONFIG_UNINSTALL_SUPPORT #endif//NSIS_SUPPORT_BGBG return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTCOLORS: { char *p = line.gettoken_str(1); if (p[0]=='/') { if (stricmp(p,"/windows") || line.getnumtokens()!=2) PRINTHELP() build_header.common.lb_fg=build_header.common.lb_bg=-1; SCRIPT_MSG("InstallColors: windows default colors\n"); } else { int v1,v2; if (line.getnumtokens()!=3) PRINTHELP() v1=strtoul(p,&p,16); build_header.common.lb_fg=((v1&0xff)<<16)|(v1&0xff00)|((v1&0xff0000)>>16); p=line.gettoken_str(2); v2=strtoul(p,&p,16); build_header.common.lb_bg=((v2&0xff)<<16)|(v2&0xff00)|((v2&0xff0000)>>16); SCRIPT_MSG("InstallColors: fg=%06X bg=%06X\n",v1,v2); } #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT build_uninst.common.lb_fg=build_header.common.lb_fg; build_uninst.common.lb_bg=build_header.common.lb_bg; #endif } return make_sure_not_in_secorfunc(line.gettoken_str(0)); // Added by Amir Szekely 7th July 2002 case TOK_XPSTYLE: try { int k=line.gettoken_enum(1,"on\0off\0"); if (k == -1) PRINTHELP() SCRIPT_MSG("XPStyle: %s\n", line.gettoken_str(1)); if (k == 0) { build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); char* szXPManifest = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"><assemblyIdentity version=\"1.0.0.0\" processorArchitecture=\"X86\" name=\"Nullsoft.NSIS.exehead\" type=\"win32\"/><description>Nullsoft Install System.</description><dependency><dependentAssembly><assemblyIdentity type=\"win32\" name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\" processorArchitecture=\"X86\" publicKeyToken=\"6595b64144ccf1df\" language=\"*\" /></dependentAssembly></dependency></assembly>"; re.UpdateResource(MAKEINTRESOURCE(24), MAKEINTRESOURCE(1), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (unsigned char*)szXPManifest, lstrlen(szXPManifest)); free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); } } catch (exception& err) { ERROR_MSG("Error while adding XP style: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); // Added by Amir Szekely 28th July 2002 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT case TOK_CHANGEUI: try { HINSTANCE hUIFile = LoadLibraryEx(line.gettoken_str(1), 0, LOAD_LIBRARY_AS_DATAFILE); if (!hUIFile) { ERROR_MSG("Error: Can't find \"%s\"!\n", line.gettoken_str(1)); return PS_ERROR; } HRSRC hUIRes = FindResource(hUIFile, MAKEINTRESOURCE(IDD_INST), RT_DIALOG); if (!hUIRes) { ERROR_MSG("Error: \"%s\" doesn't contain a dialog named IDD_INST (%u)!\n", line.gettoken_str(1), IDD_INST); return PS_ERROR; } HGLOBAL hUIMem = LoadResource(hUIFile, hUIRes); if (!hUIMem) { ERROR_MSG("Error: Can't load a dialog from \"%s\"!\n", line.gettoken_str(1)); return PS_ERROR; } BYTE* pbUIData = (BYTE*)LockResource(hUIMem); if (!pbUIData) { ERROR_MSG("Error: Can't lock resource from \"%s\"!\n", line.gettoken_str(1)); return PS_ERROR; } CDialogTemplate UIDlg(pbUIData); // Search for required items #define SEARCH(x) if (!UIDlg.GetItem(IDC_BACK)) {ERROR_MSG("Error: Can't find %s (%u) in the custom UI!\n", #x, x);return PS_ERROR;} SEARCH(IDC_BACK); SEARCH(IDC_CHILDRECT); SEARCH(IDC_VERSTR); SEARCH(IDOK); SEARCH(IDCANCEL); // Search for bitmap holder (default for SetBrandingImage) DialogItemTemplate* dlgItem = 0; int i = 0; while (dlgItem = UIDlg.GetItemByIdx(i)) { if (IS_INTRESOURCE(dlgItem->szClass)) { if (dlgItem->szClass == MAKEINTRESOURCE(0x0082)) { if ((dlgItem->dwStyle & SS_BITMAP) == SS_BITMAP) { branding_image_found = true; branding_image_id = dlgItem->wId; break; } } } i++; } build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); re.UpdateResource(RT_DIALOG, IDD_INST, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), pbUIData, UIDlg.GetSize()); free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); SCRIPT_MSG("ChangeUI: %s%s\n", line.gettoken_str(1), branding_image_found?" (branding image holder found)":""); } catch (exception& err) { ERROR_MSG("Error while changing UI: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_VISIBLE_SUPPORT not defined.\n",line.gettoken_str(0)); return PS_ERROR; #endif// NSIS_CONFIG_VISIBLE_SUPPORT // Added by Amir Szekely 21st July 2002 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT case TOK_ADDBRANDINGIMAGE: try { int k=line.gettoken_enum(1,"top\0left\0"); int wh=line.gettoken_int(2); if (k == -1) PRINTHELP() CResourceEditor re(header_data_new, exeheader_size_new); BYTE* dlg = re.GetResource(RT_DIALOG, MAKEINTRESOURCE(IDD_INST), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); CDialogTemplate dt(dlg); delete [] dlg; DialogItemTemplate *childRect = dt.GetItem(IDC_CHILDRECT); DialogItemTemplate brandingCtl = {0,}; brandingCtl.dwStyle = SS_BITMAP | WS_CHILD | WS_VISIBLE; brandingCtl.sX = childRect->sX; brandingCtl.sY = childRect->sY; brandingCtl.szClass = MAKEINTRESOURCE(0x0082); brandingCtl.szTitle = ""; brandingCtl.wId = IDC_BRANDIMAGE; brandingCtl.sHeight = wh; brandingCtl.sWidth = wh; dt.PixelsToDlgUnits(brandingCtl.sWidth, brandingCtl.sHeight); if (k) { // Left dt.MoveAllAndResize(brandingCtl.sWidth + childRect->sX, 0); DialogItemTemplate *okButton = dt.GetItem(IDOK); brandingCtl.sHeight = okButton->sY + okButton->sHeight - childRect->sY; } else { // Top dt.MoveAllAndResize(0, brandingCtl.sHeight + childRect->sY); brandingCtl.sWidth = childRect->sWidth; } dt.AddItem(brandingCtl); DWORD dwDlgSize; dlg = dt.Save(dwDlgSize); re.UpdateResource(RT_DIALOG, IDD_INST, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), dlg, dwDlgSize); delete [] dlg; free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); dt.DlgUnitsToPixels(brandingCtl.sWidth, brandingCtl.sHeight); SCRIPT_MSG("AddBrandingImage: %s %ux%u\n", line.gettoken_str(1), brandingCtl.sWidth, brandingCtl.sHeight); branding_image_found = true; branding_image_id = IDC_BRANDIMAGE; } catch (exception& err) { ERROR_MSG("Error while adding image branding support: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_VISIBLE_SUPPORT not defined.\n",line.gettoken_str(0)); return PS_ERROR; #endif// NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_VISIBLE_SUPPORT case TOK_SETFONT: SCRIPT_MSG("SetFont: \"%s\" %s\n", line.gettoken_str(1), line.gettoken_str(2)); try { build_compressor_set=true; CResourceEditor re(header_data_new, exeheader_size_new); #define SET_FONT(id) { \ BYTE* dlg = re.GetResource(RT_DIALOG, MAKEINTRESOURCE(id), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); \ if (!dlg) throw runtime_error(#id " doesn't exist!"); \ CDialogTemplate td(dlg); \ free(dlg); \ td.SetFont(line.gettoken_str(1), line.gettoken_int(2)); \ DWORD dwSize; \ dlg = td.Save(dwSize); \ re.UpdateResource(RT_DIALOG, MAKEINTRESOURCE(id), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), dlg, dwSize); \ free(dlg); \ } #ifdef NSIS_CONFIG_LICENSEPAGE SET_FONT(IDD_LICENSE); #endif SET_FONT(IDD_DIR); #ifdef NSIS_CONFIG_COMPONENTPAGE SET_FONT(IDD_SELCOM); #endif SET_FONT(IDD_INST); SET_FONT(IDD_INSTFILES); #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT SET_FONT(IDD_UNINST); #endif #ifdef NSIS_CONFIG_CRC_SUPPORT SET_FONT(IDD_VERIFY); #endif free(header_data_new); header_data_new = re.Save((DWORD&)exeheader_size_new); } catch (exception& err) { ERROR_MSG("Error while changing font: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_VISIBLE_SUPPORT not defined.\n",line.gettoken_str(0)); return PS_ERROR; #endif// NSIS_CONFIG_VISIBLE_SUPPORT // Added by Amir Szekely 31st July 2002 // Ability to change compression methods from within the script case TOK_SETCOMPRESSOR: { if (build_compressor_set) { ERROR_MSG("Error: can't change compressor after data already got compressed or header already changed!\n"); return PS_ERROR; } int k=line.gettoken_enum(1,"zlib\0bzip2\0"); switch (k) { case 0: // Default is zlib... break; case 1: compressor=&bzip2_compressor; free(header_data_new); header_data_new=(unsigned char*)malloc(bzip2_exeheader_size); exeheader_size_new=bzip2_exeheader_size; exeheader_size=bzip2_exeheader_size; if (!header_data_new) { ERROR_MSG("Internal compiler error #12345: malloc(%d) failed\n",exeheader_size_new); extern void quit(); quit(); } memcpy(header_data_new,bzip2_header_data,bzip2_exeheader_size); #ifdef NSIS_BZIP2_COMPRESS_WHOLE build_compress_whole=true; #else build_compress_whole=false; #endif break; default: PRINTHELP(); } SCRIPT_MSG("SetCompressor: %s\n", line.gettoken_str(1)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); // preprocessor-ish (ifdef/ifndef/else/endif are handled one step out from here) /////////////////////////////////////////////////////////////////////////////// case TOK_P_DEFINE: if (definedlist.add(line.gettoken_str(1),line.gettoken_str(2))) { ERROR_MSG("!define: \"%s\" already defined!\n",line.gettoken_str(1)); return PS_ERROR; } SCRIPT_MSG("!define: \"%s\"=\"%s\"\n",line.gettoken_str(1),line.gettoken_str(2)); return PS_OK; case TOK_P_UNDEF: if (definedlist.del(line.gettoken_str(1))) { ERROR_MSG("!undef: \"%s\" not defined!\n",line.gettoken_str(1)); return PS_ERROR; } SCRIPT_MSG("!undef: \"%s\"\n",line.gettoken_str(1)); return PS_OK; case TOK_P_PACKEXEHEADER: strncpy(build_packname,line.gettoken_str(1),sizeof(build_packname)-1); strncpy(build_packcmd,line.gettoken_str(2),sizeof(build_packcmd)-1); SCRIPT_MSG("!packhdr: filename=\"%s\", command=\"%s\"\n", build_packname, build_packcmd); return PS_OK; case TOK_P_SYSTEMEXEC: { char *exec=line.gettoken_str(1); int comp=line.gettoken_enum(2,"<\0>\0<>\0=\0ignore\0"); if (comp == -1 && line.getnumtokens() == 3) comp=4; if (comp == -1) PRINTHELP() int success=0; int cmpv=line.gettoken_int(3,&success); if (!success && comp != 4) PRINTHELP() SCRIPT_MSG("!system: \"%s\"\n",exec); int ret=system(exec); if (comp == 0 && ret < cmpv); else if (comp == 1 && ret > cmpv); else if (comp == 2 && ret != cmpv); else if (comp == 3 && ret == cmpv); else if (comp == 4); else { ERROR_MSG("!system: returned %d, aborting\n",ret); return PS_ERROR; } SCRIPT_MSG("!system: returned %d\n",ret); } return PS_OK; case TOK_P_INCLUDE: { char *f=line.gettoken_str(1); SCRIPT_MSG("!include: \"%s\"\n",f); FILE *incfp=fopen(f,"rt"); if (!incfp) { ERROR_MSG("!include: could not open file: \"%s\"\n",f); return PS_ERROR; } static int depth; if (depth >= MAX_INCLUDEDEPTH) { ERROR_MSG("parseScript: too many levels of includes (%d max).\n",MAX_INCLUDEDEPTH); return PS_ERROR; } depth++; int lc=0; int r=parseScript(incfp,f,&lc,0); depth--; fclose(incfp); if (r != PS_EOF && r != PS_OK) { if (r == PS_ENDIF) ERROR_MSG("!endif: stray !endif\n"); if (IS_PS_ELSE(r)) ERROR_MSG("!else: stray !else\n"); ERROR_MSG("!include: error in script: \"%s\" on line %d\n",f,lc); return PS_ERROR; } SCRIPT_MSG("!include: closed: \"%s\"\n",f); } return PS_OK; case TOK_P_CD: if (!line.gettoken_str(1)[0] || !SetCurrentDirectory(line.gettoken_str(1))) { ERROR_MSG("!cd: error changing to: \"%s\"\n",line.gettoken_str(1)); return PS_ERROR; } return PS_OK; case TOK_P_ERROR: ERROR_MSG("!error: %s\n",line.gettoken_str(1)); return PS_ERROR; case TOK_P_WARNING: warning("!warning: %s (%s:%d)\n",line.gettoken_str(1),curfilename,linecnt); return PS_OK; // Added by Amir Szekely 23rd July 2002 case TOK_P_ECHO: SCRIPT_MSG("%s (%s:%d)\n", line.gettoken_str(1),curfilename,linecnt); return PS_OK; // Added by Amir Szekely 23rd July 2002 case TOK_P_VERBOSE: { extern int g_display_errors; int v=line.gettoken_int(1); display_script=v>3; display_info=v>2; display_warnings=v>1; display_errors=v>0; g_display_errors=display_errors; } return PS_OK; case TOK_UNINSTALLEXENAME: PRINTHELP() #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT case TOK_UNINSTCAPTION: if (build_uninst.common.caption_ptr >= 0) { warning("UninstCaption: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_uninst.common.caption_ptr=add_string_uninst(line.gettoken_str(1)); SCRIPT_MSG("UninstCaption: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_UNINSTICON: SCRIPT_MSG("UninstallIcon: \"%s\"\n",line.gettoken_str(1)); try { free(m_unicon_data); m_unicon_data = generate_uninstall_icon_data(line.gettoken_str(1)); if (!m_unicon_data) { ERROR_MSG("Error: File doesn't exist or is an invalid icon file\n"); return PS_ERROR; } } catch (exception& err) { ERROR_MSG("Error while replacing icon: %s\n", err.what()); return PS_ERROR; } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_UNINSTTEXT: if (build_uninst.uninstalltext_ptr >= 0) { warning("UninstallText: specified multiple times, wasting space (%s:%d)",curfilename,linecnt); } build_uninst.uninstalltext_ptr=add_string_uninst(line.gettoken_str(1),0); if (line.getnumtokens()>2) build_uninst.uninstalltext2_ptr=add_string_uninst(line.gettoken_str(2),0); SCRIPT_MSG("UninstallText: \"%s\" \"%s\"\n",line.gettoken_str(1),line.gettoken_str(2)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_UNINSTSUBCAPTION: { int s; int w=line.gettoken_int(1,&s); if (!s || w < 0 || w > 2) PRINTHELP() build_uninst.common.subcaption_ptrs[w]=add_string_uninst(line.gettoken_str(2)); SCRIPT_MSG("UninstSubCaption: page:%d, text=%s\n",w,line.gettoken_str(2)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_WRITEUNINSTALLER: if (uninstall_mode) { ERROR_MSG("WriteUninstaller only valid from install, not from uninstall.\n"); PRINTHELP() } uninstaller_writes_used++; ent.which=EW_WRITEUNINSTALLER; ent.offsets[0]=add_string_main(line.gettoken_str(1)); ent.offsets[1]=0; // uninstall section 0 ent.offsets[2]=0; if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("WriteUninstaller: \"%s\"\n",line.gettoken_str(1)); return add_entry(&ent); #else//!NSIS_CONFIG_UNINSTALL_SUPPORT case TOK_WRITEUNINSTALLER: case TOK_UNINSTCAPTION: case TOK_UNINSTICON: case TOK_UNINSTTEXT: case TOK_UNINSTSUBCAPTION: ERROR_MSG("Error: %s specified, NSIS_CONFIG_UNINSTALL_SUPPORT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif // section/function shit /////////////////////////////////////////////////////////////////////////////// case TOK_SECTION: { int a=1,ex = 0; if (!strcmp(line.gettoken_str(1),"/e")) { ex = 1; a++; } SCRIPT_MSG("Section: \"%s\"",line.gettoken_str(a)); if (line.gettoken_str(a+1)[0]) SCRIPT_MSG(" ->(%s)",line.gettoken_str(a+1)); SCRIPT_MSG("\n"); #ifndef NSIS_CONFIG_UNINSTALL_SUPPORT if (!stricmp(line.gettoken_str(a),"uninstall")) { ERROR_MSG("Error: Uninstall section declared, no NSIS_CONFIG_UNINSTALL_SUPPORT\n"); return PS_ERROR; } #endif if (line.gettoken_str(a)[0]=='-') return add_section("",curfilename,linecnt,line.gettoken_str(a+1),ex); return add_section(line.gettoken_str(a),curfilename,linecnt,line.gettoken_str(2),ex); } case TOK_SECTIONEND: SCRIPT_MSG("SectionEnd\n"); return section_end(); case TOK_SECTIONIN: { SCRIPT_MSG("SectionIn: "); int wt; for (wt = 1; wt < line.getnumtokens(); wt ++) { char *p=line.gettoken_str(wt); if (p[0]=='R' && p[1]=='O') { if (section_add_flags(DFS_SET|DFS_RO) != PS_OK) return PS_ERROR; SCRIPT_MSG("[RO] "); } else { int x=atoi(p)-1; if (x >= 0 && x < NSIS_MAX_INST_TYPES) { if (section_add_flags(1<<x) != PS_OK) return PS_ERROR; SCRIPT_MSG("[%d] ",x); } else if (x < 0) { PRINTHELP() } else { ERROR_MSG("Error: SectionIn section %d out of range 1-%d\n",x+1,NSIS_MAX_INST_TYPES); return PS_ERROR; } p++; } } SCRIPT_MSG("\n"); } return PS_OK; case TOK_SUBSECTIONEND: case TOK_SUBSECTION: { char buf[1024]; int a=1,ex = 0; if (!strcmp(line.gettoken_str(1),"/e")) { ex = 1; a++; } wsprintf(buf,"-%s",line.gettoken_str(a)); if (which_token == TOK_SUBSECTION && !line.gettoken_str(a)[0]) PRINTHELP() if (which_token == TOK_SUBSECTIONEND) { subsection_open_cnt--; if (subsection_open_cnt<0) { ERROR_MSG("SubSectionEnd: no SubSections are open\n"); return PS_ERROR; } } else subsection_open_cnt++; SCRIPT_MSG("%s %s\n",line.gettoken_str(0),line.gettoken_str(a)); return add_section(buf,curfilename,linecnt,"",ex); } case TOK_FUNCTION: if (!line.gettoken_str(1)[0]) PRINTHELP() if (line.gettoken_str(1)[0]==':' || line.gettoken_str(1)[0]=='/') { ERROR_MSG("Function: function name cannot begin with : or /.\n"); PRINTHELP() } SCRIPT_MSG("Function: \"%s\"\n",line.gettoken_str(1)); #ifndef NSIS_CONFIG_UNINSTALL_SUPPORT if (!strnicmp(line.gettoken_str(1),"un.",3)) { ERROR_MSG("Error: Uninstall function declared, no NSIS_CONFIG_UNINSTALL_SUPPORT\n"); return PS_ERROR; } #endif return add_function(line.gettoken_str(1)); case TOK_FUNCTIONEND: SCRIPT_MSG("FunctionEnd\n"); return function_end(); // flag setters /////////////////////////////////////////////////////////////////////////////// case TOK_SETDATESAVE: build_datesave=line.gettoken_enum(1,"off\0on\0"); if (build_datesave==-1) PRINTHELP() SCRIPT_MSG("SetDateSave: %s\n",line.gettoken_str(1)); return PS_OK; case TOK_SETOVERWRITE: build_overwrite=line.gettoken_enum(1,"on\0off\0try\0ifnewer\0"); if (build_overwrite==-1) PRINTHELP() SCRIPT_MSG("SetOverwrite: %s\n",line.gettoken_str(1)); return PS_OK; case TOK_SETCOMPRESS: build_compress=line.gettoken_enum(1,"off\0auto\0force\0"); if (build_compress==-1) PRINTHELP() SCRIPT_MSG("SetCompress: %s\n",line.gettoken_str(1)); return PS_OK; case TOK_DBOPTIMIZE: build_optimize_datablock=line.gettoken_enum(1,"off\0on\0"); if (build_optimize_datablock==-1) PRINTHELP() SCRIPT_MSG("SetDatablockOptimize: %s\n",line.gettoken_str(1)); return PS_OK; case TOK_ADDSIZE: { int s; int size_kb=line.gettoken_int(1,&s); if (!s) PRINTHELP() SCRIPT_MSG("AddSize: %d kb\n"); section_add_size_kb(size_kb); } return PS_OK; case TOK_SUBCAPTION: { int s; int w=line.gettoken_int(1,&s); if (!s || w < 0 || w > 4) PRINTHELP() build_header.common.subcaption_ptrs[w]=add_string_main(line.gettoken_str(2)); SCRIPT_MSG("SubCaption: page:%d, text=%s\n",w,line.gettoken_str(2)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_FILEERRORTEXT: #ifdef NSIS_SUPPORT_FILE build_header.common.fileerrtext_ptr=add_string_main(line.gettoken_str(1)); SCRIPT_MSG("FileErrorText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_SUPPORT_FILE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif case TOK_BRANDINGTEXT: build_header.common.branding_ptr=add_string_main(line.gettoken_str(1),0); SCRIPT_MSG("BrandingText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_MISCBUTTONTEXT: build_header.backbutton_ptr=add_string_main(line.gettoken_str(1),0); build_header.nextbutton_ptr=add_string_main(line.gettoken_str(2),0); build_header.common.cancelbutton_ptr=add_string_main(line.gettoken_str(3),0); build_header.common.closebutton_ptr=add_string_main(line.gettoken_str(4),0); SCRIPT_MSG("MiscButtonText: back=\"%s\" next=\"%s\" cancel=\"%s\" close=\"%s\"\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_SPACETEXTS: if (!lstrcmp(line.gettoken_str(1), "none")) { build_header.spacerequired_ptr=-2; // No space text SCRIPT_MSG("SpaceTexts: none\n"); } else { build_header.spacerequired_ptr=add_string_main(line.gettoken_str(1),0); build_header.spaceavailable_ptr=add_string_main(line.gettoken_str(2),0); SCRIPT_MSG("SpaceTexts: required=\"%s\" available=\"%s\"\n",line.gettoken_str(1),line.gettoken_str(2)); } return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_INSTBUTTONTEXT: build_header.installbutton_ptr=add_string_main(line.gettoken_str(1),0); SCRIPT_MSG("InstallButtonText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_DETAILSBUTTONTEXT: build_header.common.showdetailsbutton_ptr=add_string_main(line.gettoken_str(1),0); SCRIPT_MSG("DetailsButtonText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_COMPLETEDTEXT: build_header.common.completed_ptr=add_string_main(line.gettoken_str(1),0); SCRIPT_MSG("CompletedText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); case TOK_UNINSTBUTTONTEXT: #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT build_uninst.uninstbutton_ptr=add_string_uninst(line.gettoken_str(1),0); SCRIPT_MSG("UninstButtonText: \"%s\"\n",line.gettoken_str(1)); return make_sure_not_in_secorfunc(line.gettoken_str(0)); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_UNINSTALL_SUPPORT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif // instructions /////////////////////////////////////////////////////////////////////////////// case TOK_NOP: SCRIPT_MSG("Nop\n"); ent.which=EW_NOP; return add_entry(&ent); case TOK_GOTO: ent.which=EW_NOP; if (process_jump(line,1,&ent.offsets[0])) PRINTHELP() SCRIPT_MSG("Goto: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_SETSHELLVARCONTEXT: ent.which=EW_SETSFCONTEXT; ent.offsets[0]=line.gettoken_enum(1,"current\0all\0"); if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("SetShellVarContext: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_RET: SCRIPT_MSG("Return\n"); ent.which=EW_RET; return add_entry(&ent); case TOK_CALL: if (!line.gettoken_str(1)[0] || (line.gettoken_str(1)[0]==':' && !line.gettoken_str(1)[1] )) PRINTHELP() #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT if (uninstall_mode && strnicmp(line.gettoken_str(1),"un.",3) && (line.gettoken_enum(1,usrvars) < 0)) { ERROR_MSG("Call must be used with function names starting with \"un.\" in the uninstall section.\n"); PRINTHELP() } if (!uninstall_mode && !strnicmp(line.gettoken_str(1),"un.",3)) { ERROR_MSG("Call must not be used with functions starting with \"un.\" in the non-uninstall sections.\n"); PRINTHELP() } #endif ent.which=EW_CALL; ent.offsets[1]=0; { int v; if ((v=line.gettoken_enum(1,usrvars))>=0) { ent.offsets[0]=-v-2; } else { if (line.gettoken_str(1)[0] == ':') { ent.offsets[1]=1; ent.offsets[0]=ns_label.add(line.gettoken_str(1)+1,0); } else ent.offsets[0]=ns_func.add(line.gettoken_str(1),0); } } SCRIPT_MSG("Call \"%s\"\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_SETOUTPATH: { char *p=line.gettoken_str(1); if (*p == '-') cur_out_path[0]=0; else { if (p[0] == '\\' && p[1] != '\\') p++; strncpy(cur_out_path,p,1024-1); cur_out_path[1024-1]=0; if (*CharPrev(cur_out_path,cur_out_path+strlen(cur_out_path))=='\\') *CharPrev(cur_out_path,cur_out_path+strlen(cur_out_path))=0; // remove trailing slash } if (!cur_out_path[0]) strcpy(cur_out_path,"$INSTDIR"); SCRIPT_MSG("SetOutPath: \"%s\"\n",cur_out_path); ent.which=EW_CREATEDIR; ent.offsets[0]=add_string(cur_out_path); ent.offsets[1]=1; } return add_entry(&ent); case TOK_CREATEDIR: { char out_path[1024]; char *p=line.gettoken_str(1); if (*p == '-') out_path[0]=0; else { if (p[0] == '\\' && p[1] != '\\') p++; strncpy(out_path,p,1024-1); if (*CharPrev(out_path,out_path+strlen(out_path))=='\\') *CharPrev(out_path,out_path+strlen(out_path))=0; // remove trailing slash } if (!*out_path) PRINTHELP() SCRIPT_MSG("CreateDirectory: \"%s\"\n",out_path); ent.which=EW_CREATEDIR; ent.offsets[0]=add_string(out_path); } return add_entry(&ent); case TOK_EXEC: case TOK_EXECWAIT: #ifdef NSIS_SUPPORT_EXECUTE ent.which=EW_EXECUTE; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1] = 0; if (which_token == TOK_EXECWAIT) { ent.offsets[1]=1; ent.offsets[2]=line.gettoken_enum(2,usrvars); if (line.gettoken_str(2)[0] && ent.offsets[2]<0) PRINTHELP() } SCRIPT_MSG("%s: \"%s\" (->%s)\n",ent.offsets[1]?"ExecWait":"Exec",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); #else//!NSIS_SUPPORT_EXECUTE ERROR_MSG("Error: %s specified, NSIS_SUPPORT_EXECUTE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_EXECUTE case TOK_EXECSHELL: // this uses improvements of Andras Varga #ifdef NSIS_SUPPORT_SHELLEXECUTE ent.which=EW_SHELLEXEC; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=SW_SHOWNORMAL; if (line.getnumtokens() > 4) { int tab[3]={SW_SHOWNORMAL,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED}; int a=line.gettoken_enum(4,"SW_SHOWNORMAL\0SW_SHOWMAXIMIZED\0SW_SHOWMINIMIZED\0"); if (a < 0) PRINTHELP() ent.offsets[3]=tab[a]; } SCRIPT_MSG("ExecShell: %s: \"%s\" \"%s\" %s\n",line.gettoken_str(1),line.gettoken_str(2), line.gettoken_str(3),line.gettoken_str(4)); return add_entry(&ent); #else//!NSIS_SUPPORT_SHELLEXECUTE ERROR_MSG("Error: %s specified, NSIS_SUPPORT_SHELLEXECUTE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_SHELLEXECUTE case TOK_CALLINSTDLL: case TOK_REGDLL: case TOK_UNREGDLL: #ifndef NSIS_SUPPORT_ACTIVEXREG ERROR_MSG("%s: support not compiled in (NSIS_SUPPORT_ACTIVEXREG)\n",line.gettoken_str(0)); return PS_ERROR; #else//NSIS_SUPPORT_ACTIVEXREG ent.which=EW_REGISTERDLL; ent.offsets[0]=add_string(line.gettoken_str(1)); if (which_token == TOK_UNREGDLL) { ent.offsets[1]=add_string("DllUnregisterServer"); ent.offsets[2]=add_string("Unregistering: "); } else if (which_token == TOK_CALLINSTDLL) { ent.offsets[1] = add_string(line.gettoken_str(2)); if (ent.offsets[1]<0) PRINTHELP() ent.offsets[2]=-1; } else // register { ent.offsets[1] = add_string(line.gettoken_str(2)); if (ent.offsets[1]<0) ent.offsets[1]=add_string("DllRegisterServer"); ent.offsets[2]=add_string("Registering: "); } SCRIPT_MSG("%s: \"%s\" %s\n",line.gettoken_str(0),line.gettoken_str(1), line.gettoken_str(2)); return add_entry(&ent); #endif//NSIS_SUPPORT_ACTIVEXREG case TOK_RENAME: #ifdef NSIS_SUPPORT_RENAME { int a=1; ent.which=EW_RENAME; if (!stricmp(line.gettoken_str(1),"/REBOOTOK")) { ent.offsets[2]=1; a++; #ifndef NSIS_SUPPORT_MOVEONREBOOT ERROR_MSG("Error: /REBOOTOK specified, NSIS_SUPPORT_MOVEONREBOOT not defined\n"); PRINTHELP() #endif } else if (line.gettoken_str(1)[0]=='/') { a=line.getnumtokens(); // cause usage to go here: } if (line.getnumtokens()!=a+2) PRINTHELP() ent.offsets[0]=add_string(line.gettoken_str(a)); ent.offsets[1]=add_string(line.gettoken_str(a+1)); SCRIPT_MSG("Rename: %s%s->%s\n",ent.offsets[2]?"/REBOOTOK ":"",line.gettoken_str(a),line.gettoken_str(a+1)); } return add_entry(&ent); #else//!NSIS_SUPPORT_RENAME ERROR_MSG("Error: %s specified, NSIS_SUPPORT_RENAME not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_RENAME case TOK_MESSAGEBOX: #ifdef NSIS_SUPPORT_MESSAGEBOX { #define MBD(x) {x,#x}, struct { int id; char *str; } list[]= { MBD(MB_ABORTRETRYIGNORE) MBD(MB_OK) MBD(MB_OKCANCEL) MBD(MB_RETRYCANCEL) MBD(MB_YESNO) MBD(MB_YESNOCANCEL) MBD(MB_ICONEXCLAMATION) MBD(MB_ICONINFORMATION) MBD(MB_ICONQUESTION) MBD(MB_ICONSTOP) MBD(MB_TOPMOST) MBD(MB_SETFOREGROUND) MBD(MB_RIGHT) MBD(MB_DEFBUTTON1) MBD(MB_DEFBUTTON2) MBD(MB_DEFBUTTON3) MBD(MB_DEFBUTTON4) }; #undef MBD int r=0; int x; char *p=line.gettoken_str(1); while (*p) { char *np=p; while (*np && *np != '|') np++; if (*np) *np++=0; for (x =0 ; x < sizeof(list)/sizeof(list[0]) && strcmp(list[x].str,p); x ++); if (x < sizeof(list)/sizeof(list[0])) { r|=list[x].id; } else PRINTHELP() p=np; } ent.which=EW_MESSAGEBOX; ent.offsets[0]=r; ent.offsets[1]=add_string(line.gettoken_str(2)); int rettab[] = { 0,IDABORT,IDCANCEL,IDIGNORE,IDNO,IDOK,IDRETRY,IDYES }; const char *retstr="0\0IDABORT\0IDCANCEL\0IDIGNORE\0IDNO\0IDOK\0IDRETRY\0IDYES\0"; if (line.getnumtokens() > 3) { ent.offsets[2]=line.gettoken_enum(3,retstr); if (ent.offsets[2] < 0) PRINTHELP() ent.offsets[2] = rettab[ent.offsets[2]]; if (process_jump(line,4,&ent.offsets[3])) PRINTHELP() if (line.getnumtokens() > 5) { int v=line.gettoken_enum(5,retstr); if (v < 0) PRINTHELP() ent.offsets[2] |= rettab[v]<<16; if (process_jump(line,6,&ent.offsets[4])) PRINTHELP() } } SCRIPT_MSG("MessageBox: %d: \"%s\"",r,line.gettoken_str(2)); if (line.getnumtokens()>4) SCRIPT_MSG(" (on %s goto %s)",line.gettoken_str(3),line.gettoken_str(4)); SCRIPT_MSG("\n"); } return add_entry(&ent); #else//!NSIS_SUPPORT_MESSAGEBOX ERROR_MSG("Error: %s specified, NSIS_SUPPORT_MESSAGEBOX not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_MESSAGEBOX case TOK_CREATESHORTCUT: #ifdef NSIS_SUPPORT_CREATESHORTCUT ent.which=EW_CREATESHORTCUT; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=add_string(line.gettoken_str(4)); int s; ent.offsets[4]=line.gettoken_int(5,&s)&0xff; if (!s) { if (line.getnumtokens() > 5) { ERROR_MSG("CreateShortCut: cannot interpret icon index\n"); PRINTHELP() } ent.offsets[4]=0; } if (line.getnumtokens() > 6) { int tab[3]={SW_SHOWNORMAL,SW_SHOWMAXIMIZED,SW_SHOWMINNOACTIVE/*SW_SHOWMINIMIZED doesn't work*/}; int a=line.gettoken_enum(6,"SW_SHOWNORMAL\0SW_SHOWMAXIMIZED\0SW_SHOWMINIMIZED\0"); if (a < 0) { ERROR_MSG("CreateShortCut: unknown show mode \"%s\"\n",line.gettoken_str(6)); PRINTHELP() } ent.offsets[4]|=tab[a]<<8; } if (line.getnumtokens() > 7) { char *s=line.gettoken_str(7); if (*s) { int c=0; if (strstr(s,"ALT|")) ent.offsets[4]|=HOTKEYF_ALT << 24; if (strstr(s,"CONTROL|")) ent.offsets[4]|=HOTKEYF_CONTROL << 24; if (strstr(s,"EXT|")) ent.offsets[4]|=HOTKEYF_EXT << 24; if (strstr(s,"SHIFT|")) ent.offsets[4]|=HOTKEYF_SHIFT << 24; while (strstr(s,"|")) { s=strstr(s,"|")+1; } if ((s[0] == 'f' || s[0] == 'F') && (s[1] >= '1' && s[1] <= '9')) { c=VK_F1-1+atoi(s+1); if (atoi(s+1) < 1 || atoi(s+1) > 24) { warning("CreateShortCut: F-key \"%s\" out of range (%s:%d)\n",s,curfilename,linecnt); } } else if (s[0] >= 'a' && s[0] <= 'z' && !s[1]) c=s[0]+'A'-'a'; else if (((s[0] >= 'A' && s[0] <= 'Z') || (s[0] >= '0' && s[0] <= '9')) && !s[1]) c=s[0]; else { c=s[0]; warning("CreateShortCut: unrecognized hotkey \"%s\" (%s:%d)\n",s,curfilename,linecnt); } ent.offsets[4] |= (c) << 16; } } SCRIPT_MSG("CreateShortCut: \"%s\"->\"%s\" %s icon:%s,%d, showmode=0x%X, hotkey=0x%X\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3), line.gettoken_str(4),ent.offsets[4]&0xff,(ent.offsets[4]>>8)&0xff,ent.offsets[4]>>16); return add_entry(&ent); #else//!NSIS_SUPPORT_CREATESHORTCUT ERROR_MSG("Error: %s specified, NSIS_SUPPORT_CREATESHORTCUT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//NSIS_SUPPORT_CREATESHORTCUT #ifdef NSIS_SUPPORT_HWNDS case TOK_FINDWINDOW: ent.which=EW_FINDWINDOW; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0) PRINTHELP() ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=add_string(line.gettoken_str(4)); ent.offsets[4]=add_string(line.gettoken_str(5)); SCRIPT_MSG("FindWindow: output=%s, class=\"%s\", text=\"%s\" hwndparent=\"%s\" hwndafter=\"%s\"\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4),line.gettoken_str(5)); return add_entry(&ent); case TOK_SENDMESSAGE: ent.which=EW_SENDMESSAGE; SCRIPT_MSG("SendMessage:"); ent.offsets[0]=line.gettoken_enum(5,usrvars); if (ent.offsets[0]>=0) { SCRIPT_MSG("(->%s)",line.gettoken_str(5)); } ent.offsets[1]=add_string(line.gettoken_str(1)); ent.offsets[2]=add_string(line.gettoken_str(2)); ent.offsets[3]=add_string(line.gettoken_str(3)); ent.offsets[4]=add_string(line.gettoken_str(4)); SCRIPT_MSG("(%s,%s,%s,%s)\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); return add_entry(&ent); case TOK_ISWINDOW: ent.which=EW_ISWINDOW; ent.offsets[0]=add_string(line.gettoken_str(1)); if (process_jump(line,2,&ent.offsets[1])|| process_jump(line,3,&ent.offsets[2])) PRINTHELP() SCRIPT_MSG("IsWindow(%s): %s:%s\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return add_entry(&ent); case TOK_SETDLGITEMTEXT: ent.which=EW_SETDLGITEMTEXT; ent.offsets[0]=line.gettoken_int(1); ent.offsets[1]=add_string(line.gettoken_str(2)); SCRIPT_MSG("SetDlgItemText: item=%s text=%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); #else//!NSIS_SUPPORT_HWNDS case TOK_ISWINDOW: case TOK_SENDMESSAGE: case TOK_FINDWINDOW: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_HWNDS not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_HWNDS case TOK_DELETE: #ifdef NSIS_SUPPORT_DELETE { int a=1; ent.which=EW_DELETEFILE; if (!stricmp(line.gettoken_str(a),"/REBOOTOK")) { a++; ent.offsets[1]=1; #ifndef NSIS_SUPPORT_MOVEONREBOOT ERROR_MSG("Error: /REBOOTOK specified, NSIS_SUPPORT_MOVEONREBOOT not defined\n"); PRINTHELP() #endif } else if (line.gettoken_str(1)[0]=='/') { a=line.getnumtokens(); } if (line.getnumtokens() != a+1) PRINTHELP() ent.offsets[0]=add_string(line.gettoken_str(a)); SCRIPT_MSG("Delete: %s\"%s\"\n",ent.offsets[1]?"/REBOOTOK ":"",line.gettoken_str(a)); } return add_entry(&ent); #else//!NSIS_SUPPORT_DELETE ERROR_MSG("Error: %s specified, NSIS_SUPPORT_DELETE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_DELETE case TOK_RMDIR: #ifdef NSIS_SUPPORT_RMDIR { int a=1; ent.which=EW_RMDIR; if (!stricmp(line.gettoken_str(1),"/r")) { if (line.getnumtokens() < 3) PRINTHELP() a++; ent.offsets[1]=1; } else if (line.gettoken_str(1)[0]=='/') PRINTHELP() ent.offsets[0]=add_string(line.gettoken_str(a)); SCRIPT_MSG("RMDir: %s\"%s\"\n",ent.offsets[1]?"/r " : "",line.gettoken_str(a)); } return add_entry(&ent); #else//!NSIS_SUPPORT_RMDIR ERROR_MSG("Error: %s specified, NSIS_SUPPORT_RMDIR not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_RMDIR case TOK_FILE: #ifdef NSIS_SUPPORT_FILE { int a=1,attrib=0,rec=0; if (!stricmp(line.gettoken_str(a),"/a")) { attrib=1; a++; } if (!stricmp(line.gettoken_str(a),"/r")) { rec=1; a++; } else if (!strnicmp(line.gettoken_str(a),"/oname=",7)) { char *on=line.gettoken_str(a)+7; a++; if (!*on||line.getnumtokens()!=a+1||strstr(on,"*") || strstr(on,"?")) PRINTHELP() int tf=0; int v=do_add_file(line.gettoken_str(a), attrib, 0, linecnt,&tf,on); if (v != PS_OK) return v; if (tf > 1) PRINTHELP() if (!tf) { ERROR_MSG("File: \"%s\" -> no files found.\n",line.gettoken_str(a)); PRINTHELP() } return PS_OK; } else if (line.gettoken_str(a)[0] == '/') PRINTHELP() if (line.getnumtokens()<a+1) PRINTHELP() while (a < line.getnumtokens()) { if (line.gettoken_str(a)[0]=='/') PRINTHELP() char buf[32]; char *t=line.gettoken_str(a++); if (t[0] && CharNext(t)[0] == ':' && CharNext(t)[1] == '\\' && !CharNext(t)[2]) { strcpy(buf,"X:\\*.*"); buf[0]=t[0]; t=buf; } int tf=0; int v=do_add_file(t, attrib, rec, linecnt,&tf); if (v != PS_OK) return v; if (!tf) { ERROR_MSG("File: \"%s\" -> no files found.\n",t); PRINTHELP() } } } return PS_OK; #else//!NSIS_SUPPORT_FILE ERROR_MSG("Error: %s specified, NSIS_SUPPORT_FILE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_FILE #ifdef NSIS_SUPPORT_COPYFILES case TOK_COPYFILES: { ent.which=EW_COPYFILES; ent.offsets[2]=FOF_NOCONFIRMATION|FOF_NOCONFIRMMKDIR|FOF_NOERRORUI|FOF_SIMPLEPROGRESS; int a=1; int x; for (x = 0; x < 2; x ++) { if (!stricmp(line.gettoken_str(a),"/SILENT")) { a++; ent.offsets[2]&=~FOF_SIMPLEPROGRESS; ent.offsets[2]|=FOF_SILENT; } else if (!stricmp(line.gettoken_str(a),"/FILESONLY")) { a++; ent.offsets[2]|=FOF_FILESONLY; } else if (line.gettoken_str(a)[0]=='/') PRINTHELP() else break; } ent.offsets[0]=add_string(line.gettoken_str(a)); ent.offsets[1]=add_string(line.gettoken_str(a+1)); int s; int size_kb=line.gettoken_int(a+2,&s); if (!s && line.gettoken_str(a+2)[0]) PRINTHELP() section_add_size_kb(size_kb); SCRIPT_MSG("CopyFiles: %s\"%s\" -> \"%s\", size=%iKB\n",ent.offsets[2]?"(silent) ":"", line.gettoken_str(a),line.gettoken_str(a+1),size_kb); } return add_entry(&ent); #else//!NSIS_SUPPORT_COPYFILES case TOK_COPYFILES: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_COPYFILES not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_COPYFILES case TOK_SETFILEATTRIBUTES: { #define MBD(x) {x,#x}, struct { int id; char *str; } list[]= { MBD(FILE_ATTRIBUTE_NORMAL) MBD(FILE_ATTRIBUTE_ARCHIVE) MBD(FILE_ATTRIBUTE_HIDDEN) MBD(FILE_ATTRIBUTE_OFFLINE) MBD(FILE_ATTRIBUTE_READONLY) MBD(FILE_ATTRIBUTE_SYSTEM) MBD(FILE_ATTRIBUTE_TEMPORARY) {FILE_ATTRIBUTE_NORMAL,"NORMAL"}, {FILE_ATTRIBUTE_ARCHIVE,"ARCHIVE"}, {FILE_ATTRIBUTE_HIDDEN,"HIDDEN"}, {FILE_ATTRIBUTE_OFFLINE,"OFFLINE"}, {FILE_ATTRIBUTE_READONLY,"READONLY"}, {FILE_ATTRIBUTE_SYSTEM,"SYSTEM"}, {FILE_ATTRIBUTE_TEMPORARY,"TEMPORARY"}, {FILE_ATTRIBUTE_NORMAL,"0"}, }; #undef MBD int r=0; int x; char *p=line.gettoken_str(2); while (*p) { char *np=p; while (*np && *np != '|') np++; if (*np) *np++=0; for (x =0 ; x < sizeof(list)/sizeof(list[0]) && stricmp(list[x].str,p); x ++); if (x < sizeof(list)/sizeof(list[0])) { r|=list[x].id; } else PRINTHELP() p=np; } ent.which=EW_SETFILEATTRIBUTES; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=r; } return add_entry(&ent); case TOK_SLEEP: { ent.which=EW_SLEEP; ent.offsets[0]=add_string(line.gettoken_str(1)); SCRIPT_MSG("Sleep: %s ms\n",line.gettoken_str(1)); } return add_entry(&ent); case TOK_BRINGTOFRONT: ent.which=EW_BRINGTOFRONT; SCRIPT_MSG("BringToFront\n"); return add_entry(&ent); case TOK_HIDEWINDOW: ent.which=EW_HIDEWINDOW; SCRIPT_MSG("HideWindow\n"); return add_entry(&ent); case TOK_IFFILEEXISTS: ent.which=EW_IFFILEEXISTS; ent.offsets[0] = add_string(line.gettoken_str(1)); if (process_jump(line,2,&ent.offsets[1]) || process_jump(line,3,&ent.offsets[2])) PRINTHELP() SCRIPT_MSG("IfFileExists: \"%s\" ? %s : %s\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return add_entry(&ent); case TOK_QUIT: ent.which=EW_QUIT; SCRIPT_MSG("Quit\n"); return add_entry(&ent); case TOK_ABORT: ent.which=EW_ABORT; ent.offsets[0] = add_string(line.gettoken_str(1)); SCRIPT_MSG("Abort: \"%s\"\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_SETDETAILSVIEW: { int v=line.gettoken_enum(1,"hide\0show\0"); ent.which=EW_CHDETAILSVIEW; if (v < 0) PRINTHELP() ent.offsets[0] = v?SW_SHOWNA:SW_HIDE; ent.offsets[1] = v?SW_HIDE:SW_SHOWNA; SCRIPT_MSG("SetDetailsView: %s\n",line.gettoken_str(1)); } return add_entry(&ent); case TOK_SETDETAILSPRINT: ent.which=EW_UPDATETEXT; ent.offsets[0] = -1; ent.offsets[1] = line.gettoken_enum(1,"none\0listonly\0textonly\0both\0"); if (ent.offsets[1] < 0) PRINTHELP() if (!ent.offsets[1]) ent.offsets[1]=4; SCRIPT_MSG("SetDetailsPrint: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_SETAUTOCLOSE: ent.which=EW_SETWINDOWCLOSE; ent.offsets[0] = line.gettoken_enum(1,"false\0true\0"); if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("SetAutoClose: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_IFERRORS: ent.which=EW_IFERRORS; if (process_jump(line,1,&ent.offsets[0]) || process_jump(line,2,&ent.offsets[1])) PRINTHELP() SCRIPT_MSG("IfErrors ?%s:%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_CLEARERRORS: ent.which=EW_IFERRORS; SCRIPT_MSG("ClearErrors\n"); return add_entry(&ent); case TOK_SETERRORS: ent.which=EW_IFERRORS; ent.offsets[2]=1; SCRIPT_MSG("SetErrors\n"); return add_entry(&ent); #ifdef NSIS_SUPPORT_STROPTS case TOK_STRLEN: ent.which=EW_STRLEN; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=add_string(line.gettoken_str(2)); if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("StrLen %s \"%s\"\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_STRCPY: ent.which=EW_ASSIGNVAR; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=add_string(line.gettoken_str(4)); if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("StrCpy %s \"%s\" (%s) (%s)\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); return add_entry(&ent); case TOK_GETFUNCTIONADDR: ent.which=EW_GETFUNCTIONADDR; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=ns_func.add(line.gettoken_str(2),0); ent.offsets[2]=-1; ent.offsets[3]=-1; if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("GetFunctionAddress: %s %s",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_GETLABELADDR: ent.which=EW_GETLABELADDR; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0 || process_jump(line,2,&ent.offsets[1])) PRINTHELP() ent.offsets[2]=-1; ent.offsets[3]=-1; SCRIPT_MSG("GetLabelAddress: %s %s",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_GETCURRENTADDR: ent.which=EW_ASSIGNVAR; ent.offsets[0]=line.gettoken_enum(1,usrvars); { char buf[32]; wsprintf(buf,"%d",1+(uninstall_mode?build_uninst.code_size:build_header.common.num_entries)); ent.offsets[1]=add_string(buf); } if (ent.offsets[0] < 0) PRINTHELP() ent.offsets[2]=-1; ent.offsets[3]=-1; SCRIPT_MSG("GetCurrentAddress: %s %s",line.gettoken_str(1)); return add_entry(&ent); case TOK_STRCMP: ent.which=EW_STRCMP; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=add_string(line.gettoken_str(2)); if (process_jump(line,3,&ent.offsets[2]) || process_jump(line,4,&ent.offsets[3])) PRINTHELP() SCRIPT_MSG("StrCmp \"%s\" \"%s\" equal=%s, nonequal=%s\n",line.gettoken_str(1),line.gettoken_str(2), line.gettoken_str(3),line.gettoken_str(4)); return add_entry(&ent); case TOK_GETDLLVERSIONLOCAL: { char buf[128]; DWORD low, high; DWORD s,d; int flag=0; s=GetFileVersionInfoSize(line.gettoken_str(1),&d); if (s) { void *buf; buf=(void*)GlobalAlloc(GPTR,s); if (buf) { UINT uLen; VS_FIXEDFILEINFO *pvsf; if (GetFileVersionInfo(line.gettoken_str(1),0,s,buf) && VerQueryValue(buf,"\\",(void**)&pvsf,&uLen)) { low=pvsf->dwFileVersionLS; high=pvsf->dwFileVersionMS; flag=1; } GlobalFree(buf); } } if (!flag) { ERROR_MSG("GetDLLVersionLocal: error reading version info from \"%s\"\n",line.gettoken_str(1)); return PS_ERROR; } ent.which=EW_ASSIGNVAR; ent.offsets[0]=line.gettoken_enum(2,usrvars); wsprintf(buf,"%u",high); ent.offsets[1]=add_string(buf); ent.offsets[2]=-1; ent.offsets[3]=-1; if (ent.offsets[0]<0) PRINTHELP() add_entry(&ent); ent.offsets[0]=line.gettoken_enum(3,usrvars); wsprintf(buf,"%u",low); ent.offsets[1]=add_string(buf); ent.offsets[2]=-1; ent.offsets[3]=-1; if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("GetDLLVersionLocal: %s (%u,%u)->(%s,%s)\n", line.gettoken_str(1),high,low,line.gettoken_str(2),line.gettoken_str(3)); } return add_entry(&ent); case TOK_GETFILETIMELOCAL: { char buf[129]; DWORD high,low; int flag=0; HANDLE hFile=CreateFile(line.gettoken_str(1),0,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile != INVALID_HANDLE_VALUE) { FILETIME ft; if (GetFileTime(hFile,NULL,NULL,&ft)) { high=ft.dwHighDateTime; low=ft.dwLowDateTime; flag=1; } CloseHandle(hFile); } if (!flag) { ERROR_MSG("GetFileTimeLocal: error reading date from \"%s\"\n",line.gettoken_str(1)); return PS_ERROR; } ent.which=EW_ASSIGNVAR; ent.offsets[0]=line.gettoken_enum(2,usrvars); wsprintf(buf,"%u",high); ent.offsets[1]=add_string(buf); ent.offsets[2]=-1; ent.offsets[3]=-1; if (ent.offsets[0]<0) PRINTHELP() add_entry(&ent); ent.offsets[0]=line.gettoken_enum(3,usrvars); wsprintf(buf,"%u",low); ent.offsets[1]=add_string(buf); ent.offsets[2]=-1; ent.offsets[3]=-1; if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("GetFileTimeLocal: %s (%u,%u)->(%s,%s)\n", line.gettoken_str(1),high,low,line.gettoken_str(2),line.gettoken_str(3)); } return add_entry(&ent); #else//!NSIS_SUPPORT_STROPTS case TOK_GETDLLVERSIONLOCAL: case TOK_GETFILETIMELOCAL: case TOK_GETFUNCTIONADDR: case TOK_GETLABELADDR: case TOK_GETCURRENTADDR: case TOK_STRLEN: case TOK_STRCPY: case TOK_STRCMP: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_STROPTS not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_STROPTS #ifdef NSIS_SUPPORT_INIFILES case TOK_DELETEINISEC: case TOK_DELETEINISTR: { char *vname="<section>"; ent.which=EW_WRITEINI; ent.offsets[0]=add_string(line.gettoken_str(2)); // section name if (line.getnumtokens() > 3) { vname=line.gettoken_str(3); ent.offsets[1]=add_string(vname); // value name } else ent.offsets[1]=-1; ent.offsets[2]=-1; ent.offsets[3]=add_string(line.gettoken_str(1)); SCRIPT_MSG("DeleteINI%s: [%s] %s in %s\n",vname?"Str":"Sec", line.gettoken_str(2),vname,line.gettoken_str(1)); } return add_entry(&ent); case TOK_WRITEINISTR: ent.which=EW_WRITEINI; ent.offsets[0]=add_string(line.gettoken_str(2)); ent.offsets[1]=add_string(line.gettoken_str(3)); ent.offsets[2]=add_string(line.gettoken_str(4)); ent.offsets[3]=add_string(line.gettoken_str(1)); SCRIPT_MSG("WriteINIStr: [%s] %s=%s in %s\n", line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4),line.gettoken_str(1)); return add_entry(&ent); case TOK_READINISTR: ent.which=EW_READINISTR; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0) PRINTHELP() ent.offsets[1]=add_string(line.gettoken_str(3)); ent.offsets[2]=add_string(line.gettoken_str(4)); ent.offsets[3]=add_string(line.gettoken_str(2)); SCRIPT_MSG("ReadINIStr %s [%s]:%s from %s\n",line.gettoken_str(1),line.gettoken_str(3),line.gettoken_str(4),line.gettoken_str(2)); return add_entry(&ent); #else//!NSIS_SUPPORT_INIFILES case TOK_DELETEINISEC: case TOK_DELETEINISTR: case TOK_WRITEINISTR: case TOK_READINISTR: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_INIFILES not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_INIFILES case TOK_DETAILPRINT: ent.which=EW_UPDATETEXT; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=0; SCRIPT_MSG("DetailPrint: \"%s\"\n",line.gettoken_str(1)); return add_entry(&ent); #ifdef NSIS_SUPPORT_FNUTIL case TOK_GETTEMPFILENAME: ent.which=EW_GETTEMPFILENAME; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("GetTempFileName -> %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_GETFULLPATHNAME: { int a=0; ent.which=EW_GETFULLPATHNAME; if (line.getnumtokens()==4 && !stricmp(line.gettoken_str(1),"/SHORT")) a++; else if (line.getnumtokens()==4 || *line.gettoken_str(1)=='/') PRINTHELP() ent.offsets[0]=line.gettoken_enum(1+a,usrvars); ent.offsets[1]=add_string(line.gettoken_str(2+a)); ent.offsets[2]=!a; if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("GetFullPathName: %s->%s (%d)\n", line.gettoken_str(2+a),line.gettoken_str(1+a),a?"sfn":"lfn"); } return add_entry(&ent); case TOK_SEARCHPATH: ent.which=EW_SEARCHPATH; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0) PRINTHELP() ent.offsets[1]=add_string(line.gettoken_str(2)); SCRIPT_MSG("SearchPath %s %s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); #else case TOK_SEARCHPATH: case TOK_GETTEMPFILENAME: case TOK_GETFULLPATHNAME: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_FNUTIL not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif case TOK_GETDLLVERSION: #ifdef NSIS_SUPPORT_GETDLLVERSION ent.which=EW_GETDLLVERSION; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=line.gettoken_enum(2,usrvars); ent.offsets[2]=line.gettoken_enum(3,usrvars); if (ent.offsets[1]<0 || ent.offsets[2]<0) PRINTHELP() SCRIPT_MSG("GetDLLVersion: %s->%s,%s\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return add_entry(&ent); #else//!NSIS_SUPPORT_GETDLLVERSION ERROR_MSG("Error: %s specified, NSIS_SUPPORT_GETDLLVERSION not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_GETDLLVERSION case TOK_GETFILETIME: #ifdef NSIS_SUPPORT_GETFILETIME ent.which=EW_GETFILETIME; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=line.gettoken_enum(2,usrvars); ent.offsets[2]=line.gettoken_enum(3,usrvars); if (ent.offsets[1]<0 || ent.offsets[2]<0) PRINTHELP() SCRIPT_MSG("GetFileTime: %s->%s,%s\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return add_entry(&ent); #else//!NSIS_SUPPORT_GETFILETIME ERROR_MSG("Error: %s specified, NSIS_SUPPORT_GETFILETIME not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_GETFILETIME #ifdef NSIS_SUPPORT_INTOPTS case TOK_INTOP: ent.which=EW_INTOP; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[3]=line.gettoken_enum(3,"+\0-\0*\0/\0|\0&\0^\0~\0!\0||\0&&\0%\0"); if (ent.offsets[0] < 0 || ent.offsets[3]<0 || ((ent.offsets[3] == 7 || ent.offsets[3]==8) && line.getnumtokens()>4)) PRINTHELP() ent.offsets[1]=add_string(line.gettoken_str(2)); if (ent.offsets[3] != 7 && ent.offsets[3] != 8) ent.offsets[2]=add_string(line.gettoken_str(4)); SCRIPT_MSG("IntOp: %s=%s%s%s\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); return add_entry(&ent); case TOK_INTFMT: ent.which=EW_INTFMT; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0]<0) PRINTHELP() ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=add_string(line.gettoken_str(3)); SCRIPT_MSG("IntFmt: %s->%s (fmt:%s)\n",line.gettoken_str(3),line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_INTCMP: case TOK_INTCMPU: ent.which=(which_token == TOK_INTCMP) ? EW_INTCMP : EW_INTCMPU; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=add_string(line.gettoken_str(2)); if (process_jump(line,3,&ent.offsets[2]) || process_jump(line,4,&ent.offsets[3]) || process_jump(line,5,&ent.offsets[4])) PRINTHELP() SCRIPT_MSG("%s %s:%s equal=%s, < %s, > %s\n",line.gettoken_str(0), line.gettoken_str(1),line.gettoken_str(2), line.gettoken_str(3),line.gettoken_str(4),line.gettoken_str(5)); return add_entry(&ent); #else//!NSIS_SUPPORT_INTOPTS case TOK_INTOP: case TOK_INTCMP: case TOK_INTFMT: case TOK_INTCMPU: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_INTOPTS not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_INTOPTS #ifdef NSIS_SUPPORT_REGISTRYFUNCTIONS case TOK_READREGSTR: case TOK_READREGDWORD: { ent.which=EW_READREGSTR; ent.offsets[0]=line.gettoken_enum(1,usrvars); int k=line.gettoken_enum(2,rootkeys[0]); if (k == -1) k=line.gettoken_enum(2,rootkeys[1]); if (ent.offsets[0] < 0 || k == -1) PRINTHELP() ent.offsets[1]=(int)rootkey_tab[k]; ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=add_string(line.gettoken_str(4)); if (which_token == TOK_READREGDWORD) ent.offsets[4]=1; else ent.offsets[4]=0; if (line.gettoken_str(3)[0] == '\\') warning("%s: registry path name begins with \'\\\', may cause problems (%s:%d)",line.gettoken_str(0),curfilename,linecnt); SCRIPT_MSG("%s %s %s\\%s\\%s\n",line.gettoken_str(0), line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); } return add_entry(&ent); case TOK_DELETEREGVALUE: case TOK_DELETEREGKEY: { int a=1; if (which_token==TOK_DELETEREGKEY) { char *s=line.gettoken_str(a); if (s[0] == '/') { if (stricmp(s,"/ifempty")) PRINTHELP() a++; ent.offsets[3]=1; } } int k=line.gettoken_enum(a,rootkeys[0]); if (k == -1) k=line.gettoken_enum(a,rootkeys[1]); if (k == -1) PRINTHELP() ent.which=EW_DELREG; ent.offsets[0]=(int)rootkey_tab[k]; ent.offsets[1]=add_string(line.gettoken_str(a+1)); ent.offsets[2]=(which_token==TOK_DELETEREGKEY)?-1:add_string(line.gettoken_str(a+2)); if (line.gettoken_str(a+1)[0] == '\\') warning("%s: registry path name begins with \'\\\', may cause problems (%s:%d)",line.gettoken_str(0),curfilename,linecnt); if (which_token==TOK_DELETEREGKEY) SCRIPT_MSG("DeleteRegKey: %s\\%s\n",line.gettoken_str(a),line.gettoken_str(a+1)); else SCRIPT_MSG("DeleteRegValue: %s\\%s\\%s\n",line.gettoken_str(a),line.gettoken_str(a+1),line.gettoken_str(a+2)); } return add_entry(&ent); case TOK_WRITEREGSTR: case TOK_WRITEREGEXPANDSTR: case TOK_WRITEREGBIN: case TOK_WRITEREGDWORD: { int k=line.gettoken_enum(1,rootkeys[0]); if (k == -1) k=line.gettoken_enum(1,rootkeys[1]); if (k == -1) PRINTHELP() ent.which=EW_WRITEREG; ent.offsets[0]=(int)rootkey_tab[k]; ent.offsets[1]=add_string(line.gettoken_str(2)); if (line.gettoken_str(2)[0] == '\\') warning("%s: registry path name begins with \'\\\', may cause problems (%s:%d)",line.gettoken_str(0),curfilename,linecnt); ent.offsets[2]=add_string(line.gettoken_str(3)); if (which_token == TOK_WRITEREGSTR || which_token == TOK_WRITEREGEXPANDSTR) { SCRIPT_MSG("%s: %s\\%s\\%s=%s\n", line.gettoken_str(0),line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); ent.offsets[3]=add_string(line.gettoken_str(4)); if (which_token == TOK_WRITEREGEXPANDSTR) { ent.offsets[4]=0; } else ent.offsets[4]=1; } if (which_token == TOK_WRITEREGBIN) { char data[NSIS_MAX_STRLEN]; char *p=line.gettoken_str(4); int data_len=0; while (*p) { int c; int a,b; a=*p; if (a >= '0' && a <= '9') a-='0'; else if (a >= 'a' && a <= 'f') a-='a'-10; else if (a >= 'A' && a <= 'F') a-='A'-10; else break; b=*++p; if (b >= '0' && b <= '9') b-='0'; else if (b >= 'a' && b <= 'f') b-='a'-10; else if (b >= 'A' && b <= 'F') b-='A'-10; else break; p++; c=(a<<4)|b; if (data_len >= NSIS_MAX_STRLEN) { ERROR_MSG("WriteRegBin: %d bytes of data exceeded\n",NSIS_MAX_STRLEN); return PS_ERROR; } data[data_len++]=c; } if (*p) PRINTHELP() SCRIPT_MSG("WriteRegBin: %s\\%s\\%s=%s\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); ent.offsets[3]=add_data(data,data_len); if (ent.offsets[3] < 0) return PS_ERROR; ent.offsets[4]=3; } if (which_token == TOK_WRITEREGDWORD) { ent.offsets[3]=add_string(line.gettoken_str(4)); ent.offsets[4]=2; SCRIPT_MSG("WriteRegDWORD: %s\\%s\\%s=%s\n", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); } } return add_entry(&ent); case TOK_ENUMREGKEY: case TOK_ENUMREGVAL: { ent.which=EW_REGENUM; ent.offsets[0]=line.gettoken_enum(1,usrvars); int k=line.gettoken_enum(2,rootkeys[0]); if (k == -1) k=line.gettoken_enum(2,rootkeys[1]); if (ent.offsets[0] < 0 || k == -1) PRINTHELP() ent.offsets[1]=(int)rootkey_tab[k]; ent.offsets[2]=add_string(line.gettoken_str(3)); ent.offsets[3]=add_string(line.gettoken_str(4)); ent.offsets[4]=which_token == TOK_ENUMREGKEY; if (line.gettoken_str(3)[0] == '\\') warning("%s: registry path name begins with \'\\\', may cause problems (%s:%d)",line.gettoken_str(0),curfilename,linecnt); SCRIPT_MSG("%s %s %s\\%s\\%s\n",which_token == TOK_ENUMREGKEY ? "EnumRegKey" : "EnumRegValue", line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(4)); } return add_entry(&ent); #else//!NSIS_SUPPORT_REGISTRYFUNCTIONS case TOK_READREGSTR: case TOK_READREGDWORD: case TOK_DELETEREGVALUE: case TOK_DELETEREGKEY: case TOK_WRITEREGSTR: case TOK_WRITEREGEXPANDSTR: case TOK_WRITEREGBIN: case TOK_WRITEREGDWORD: case TOK_ENUMREGKEY: case TOK_ENUMREGVAL: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_REGISTRYFUNCTIONS not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_REGISTRYFUNCTIONS #ifdef NSIS_SUPPORT_STACK case TOK_EXCH: { int swapitem=1; int save=line.gettoken_enum(1,usrvars); ent.which=EW_PUSHPOP; if (line.gettoken_str(1)[0] && save<0) { int s=0; swapitem=line.gettoken_int(1,&s); if (!s || swapitem <= 0) PRINTHELP() } if (save>=0) { SCRIPT_MSG("Exch(%s,0)\n",line.gettoken_str(1)); ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=0; ent.offsets[2]=0; add_entry(&ent); } else SCRIPT_MSG("Exch(st(%d),0)\n",swapitem); ent.offsets[0]=0; ent.offsets[1]=0; ent.offsets[2]=swapitem; if (save>=0) { add_entry(&ent); ent.offsets[0]=save; ent.offsets[1]=1; ent.offsets[2]=0; } } return add_entry(&ent); case TOK_PUSH: ent.which=EW_PUSHPOP; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=0; SCRIPT_MSG("Push: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_POP: ent.which=EW_PUSHPOP; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=1; if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("Pop: %s\n",line.gettoken_str(1)); return add_entry(&ent); #else//!NSIS_SUPPORT_STACK case TOK_POP: case TOK_PUSH: case TOK_EXCH: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_STACK not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_STACK #ifdef NSIS_SUPPORT_ENVIRONMENT case TOK_READENVSTR: ent.which=EW_READENVSTR; ent.offsets[0]=line.gettoken_enum(1,usrvars); { ent.offsets[1]=add_string(line.gettoken_str(2)); if (ent.offsets[0] < 0 || strlen(line.gettoken_str(2))<1) PRINTHELP() } ent.offsets[2]=1; SCRIPT_MSG("ReadEnvStr: %s->%s\n",line.gettoken_str(2),line.gettoken_str(1)); return add_entry(&ent); case TOK_EXPANDENVSTRS: ent.which=EW_READENVSTR; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=0; if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("ExpandEnvStrings: %s->%s\n",line.gettoken_str(2),line.gettoken_str(1)); return add_entry(&ent); #else//!NSIS_SUPPORT_ENVIRONMENT case TOK_EXPANDENVSTRS: case TOK_READENVSTR: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_ENVIRONMENT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_ENVIRONMENT #ifdef NSIS_SUPPORT_FINDFIRST case TOK_FINDFIRST: ent.which=EW_FINDFIRST; ent.offsets[0]=add_string(line.gettoken_str(3)); // filespec ent.offsets[1]=line.gettoken_enum(2,usrvars); // out ent.offsets[2]=line.gettoken_enum(1,usrvars); // handleout if (ent.offsets[1] < 0 || ent.offsets[2] < 0) PRINTHELP() SCRIPT_MSG("FindFirst: spec=\"%s\" handle=%s output=%s\n",line.gettoken_str(3),line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_FINDNEXT: ent.which=EW_FINDNEXT; ent.offsets[0]=line.gettoken_enum(2,usrvars); ent.offsets[1]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0 || ent.offsets[1] < 0) PRINTHELP() SCRIPT_MSG("FindNext: handle=%s output=%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_FINDCLOSE: ent.which=EW_FINDCLOSE; ent.offsets[0]=line.gettoken_enum(1,usrvars); if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("FindClose: %s\n",line.gettoken_str(1)); return add_entry(&ent); #else//!NSIS_SUPPORT_FINDFIRST case TOK_FINDCLOSE: case TOK_FINDNEXT: case TOK_FINDFIRST: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_FINDFIRST not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_FINDFIRST #ifdef NSIS_SUPPORT_FILEFUNCTIONS case TOK_FILEOPEN: { ent.which=EW_FOPEN; ent.offsets[3]=line.gettoken_enum(1,usrvars); // file handle ent.offsets[0]=add_string(line.gettoken_str(2)); ent.offsets[1]=0; //openmode if (!stricmp(line.gettoken_str(3),"r")) { ent.offsets[1]=GENERIC_READ; ent.offsets[2]=OPEN_EXISTING; } else if (!stricmp(line.gettoken_str(3),"w")) { ent.offsets[1]=GENERIC_WRITE; ent.offsets[2]=CREATE_ALWAYS; } else if (!stricmp(line.gettoken_str(3),"a")) { ent.offsets[1]=GENERIC_WRITE|GENERIC_READ; ent.offsets[2]=OPEN_ALWAYS; } if (ent.offsets[3] < 0 || !ent.offsets[1]) PRINTHELP() } SCRIPT_MSG("FileOpen: %s as %s -> %s\n",line.gettoken_str(2),line.gettoken_str(3),line.gettoken_str(1)); return add_entry(&ent); case TOK_FILECLOSE: ent.which=EW_FCLOSE; ent.offsets[0]=line.gettoken_enum(1,usrvars); // file handle if (ent.offsets[0] < 0) PRINTHELP() SCRIPT_MSG("FileClose: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_FILEREAD: ent.which=EW_FGETS; ent.offsets[0]=line.gettoken_enum(1,usrvars); // file handle ent.offsets[1]=line.gettoken_enum(2,usrvars); // output string ent.offsets[2]=add_string(line.gettoken_str(3)[0]?line.gettoken_str(3):"1023"); if (ent.offsets[0]<0 || ent.offsets[1]<0) PRINTHELP() SCRIPT_MSG("FileRead: %s->%s (max:%s)\n",line.gettoken_str(1),line.gettoken_str(2),line.gettoken_str(3)); return add_entry(&ent); case TOK_FILEWRITE: ent.which=EW_FPUTS; ent.offsets[0]=line.gettoken_enum(1,usrvars); // file handle ent.offsets[1]=add_string(line.gettoken_str(2)); if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("FileWrite: %s->%s\n",line.gettoken_str(2),line.gettoken_str(1)); return add_entry(&ent); case TOK_FILEREADBYTE: ent.which=EW_FGETS; ent.offsets[0]=line.gettoken_enum(1,usrvars); // file handle ent.offsets[1]=line.gettoken_enum(2,usrvars); // output string ent.offsets[2]=add_string("1"); ent.offsets[3]=1; if (ent.offsets[0]<0 || ent.offsets[1]<0) PRINTHELP() SCRIPT_MSG("FileReadByte: %s->%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_FILEWRITEBYTE: ent.which=EW_FPUTS; ent.offsets[0]=line.gettoken_enum(1,usrvars); // file handle ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[2]=1; if (ent.offsets[0]<0) PRINTHELP() SCRIPT_MSG("FileWriteByte: %s->%s\n",line.gettoken_str(2),line.gettoken_str(1)); return add_entry(&ent); case TOK_FILESEEK: { char *modestr; int tab[3]={FILE_BEGIN,FILE_CURRENT,FILE_END}; int mode=line.gettoken_enum(3,"SET\0CUR\0END\0"); ent.which=EW_FSEEK; ent.offsets[0]=line.gettoken_enum(1,usrvars); ent.offsets[1]=add_string(line.gettoken_str(2)); ent.offsets[3]=line.gettoken_enum(4,usrvars); if (mode<0 && !line.gettoken_str(3)[0]) { mode=0; modestr="SET"; } else modestr=line.gettoken_str(3); if (mode<0 || ent.offsets[0] < 0 || (ent.offsets[3]<0 && line.gettoken_str(4)[0])) PRINTHELP() ent.offsets[2]=tab[mode]; SCRIPT_MSG("FileSeek: fp=%s, ofs=%s, mode=%s, output=%s\n", line.gettoken_str(1), line.gettoken_str(2), modestr, line.gettoken_str(4)); } return add_entry(&ent); #else//!NSIS_SUPPORT_FILEFUNCTIONS case TOK_FILEOPEN: case TOK_FILECLOSE: case TOK_FILESEEK: case TOK_FILEREAD: case TOK_FILEWRITE: case TOK_FILEREADBYTE: case TOK_FILEWRITEBYTE: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_FILEFUNCTIONS not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_FILEFUNCTIONS #ifdef NSIS_SUPPORT_REBOOT case TOK_REBOOT: ent.which=EW_REBOOT; ent.offsets[0]=0xbadf00d; SCRIPT_MSG("Reboot! (WOW)\n"); return add_entry(&ent); case TOK_IFREBOOTFLAG: ent.which=EW_IFREBOOTFLAG; if (process_jump(line,1,&ent.offsets[0]) || process_jump(line,2,&ent.offsets[1])) PRINTHELP() SCRIPT_MSG("IfRebootFlag ?%s:%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_SETREBOOTFLAG: ent.which=EW_SETREBOOTFLAG; ent.offsets[0]=line.gettoken_enum(1,"false\0true\0"); if (ent.offsets[0] < 0) PRINTHELP() return add_entry(&ent); #else//!NSIS_SUPPORT_REBOOT case TOK_REBOOT: case TOK_IFREBOOTFLAG: case TOK_SETREBOOTFLAG: ERROR_MSG("Error: %s specified, NSIS_SUPPORT_REBOOT not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_SUPPORT_REBOOT #ifdef NSIS_CONFIG_LOG case TOK_LOGSET: ent.which=EW_LOG; ent.offsets[0]=1; ent.offsets[1]=line.gettoken_enum(1,"off\0on\0"); if (ent.offsets[1]<0) PRINTHELP() SCRIPT_MSG("LogSet: %s\n",line.gettoken_str(1)); return add_entry(&ent); case TOK_LOGTEXT: ent.which=EW_LOG; ent.offsets[0]=0; ent.offsets[1]=add_string(line.gettoken_str(1)); SCRIPT_MSG("LogText \"%s\"\n",line.gettoken_str(1)); return add_entry(&ent); #else//!NSIS_CONFIG_LOG case TOK_LOGSET: case TOK_LOGTEXT: ERROR_MSG("Error: %s specified, NSIS_CONFIG_LOG not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_CONFIG_LOG #ifdef NSIS_CONFIG_COMPONENTPAGE case TOK_SECTIONSETTEXT: if (uninstall_mode) { ERROR_MSG("Error: %s called in uninstall section.\n", line.gettoken_str(0)); return PS_ERROR; } ent.which=EW_SECTIONSET; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=0; ent.offsets[2]=add_string(line.gettoken_str(2)); SCRIPT_MSG("SectionSetText: %s=%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_SECTIONGETTEXT: if (uninstall_mode) { ERROR_MSG("Error: %s called in uninstall section.\n", line.gettoken_str(0)); return PS_ERROR; } ent.which=EW_SECTIONSET; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=1; ent.offsets[2]=line.gettoken_enum(2,usrvars); if (line.gettoken_str(2)[0] && ent.offsets[2]<0) PRINTHELP() SCRIPT_MSG("SectionGetText: %s->%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_SECTIONSETFLAGS: if (uninstall_mode) { ERROR_MSG("Error: %s called in uninstall section.\n", line.gettoken_str(0)); return PS_ERROR; } ent.which=EW_SECTIONSET; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=2; ent.offsets[2]=add_string(line.gettoken_str(2)); SCRIPT_MSG("SectionSetFlags: %s->%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); case TOK_SECTIONGETFLAGS: if (uninstall_mode) { ERROR_MSG("Error: %s called in uninstall section.\n", line.gettoken_str(0)); return PS_ERROR; } ent.which=EW_SECTIONSET; ent.offsets[0]=add_string(line.gettoken_str(1)); ent.offsets[1]=3; ent.offsets[2]=line.gettoken_enum(2,usrvars); if (line.gettoken_str(2)[0] && ent.offsets[2]<0) PRINTHELP() SCRIPT_MSG("SectionGetFlags: %s->%s\n",line.gettoken_str(1),line.gettoken_str(2)); return add_entry(&ent); #else//!NSIS_CONFIG_COMPONENTPAGE case TOK_SECTIONGETTEXT: case TOK_SECTIONSETTEXT: case TOK_SECTIONSETFLAGS: case TOK_SECTIONGETFLAGS: ERROR_MSG("Error: %s specified, NSIS_CONFIG_COMPONENTPAGE not defined.\n", line.gettoken_str(0)); return PS_ERROR; #endif//!NSIS_CONFIG_COMPONENTPAGE // Added by Amir Szekely 29th July 2002 case TOK_SETBRANDINGIMAGE: #ifdef NSIS_CONFIG_VISIBLE_SUPPORT { SCRIPT_MSG("SetBrandingImage: %s\n", line.gettoken_str(1)); if (!branding_image_found) { ERROR_MSG("Error: no branding image found in choosen UI!\n"); return PS_ERROR; } ent.which=EW_SETBRANDINGIMAGE; for (int i = 1; i < line.getnumtokens(); i++) if (!strnicmp(line.gettoken_str(i),"/IMGID=",7)) ent.offsets[1]=atoi(line.gettoken_str(i)+7); else if (!stricmp(line.gettoken_str(i),"/RESIZETOFIT")) ent.offsets[2]=1; else if (!ent.offsets[0]) ent.offsets[0]=add_string(line.gettoken_str(i)); else PRINTHELP(); if (!ent.offsets[1]) ent.offsets[1]=branding_image_id; } return add_entry(&ent); #else ERROR_MSG("Error: %s specified, NSIS_CONFIG_VISIBLE_SUPPORT not defined.\n",line.gettoken_str(0)); return PS_ERROR; #endif// NSIS_CONFIG_VISIBLE_SUPPORT // end of instructions /////////////////////////////////////////////////////////////////////////////// default: break; } ERROR_MSG("Error: doCommand: Invalid token \"%s\".\n",line.gettoken_str(0)); return PS_ERROR; } int CEXEBuild::do_add_file(const char *lgss, int attrib, int recurse, int linecnt, int *total_files, const char *name_override) { char dir[1024]; char newfn[1024], *s; HANDLE h; WIN32_FIND_DATA d; strcpy(dir,lgss); s=dir+strlen(dir); while (s > dir && *s != '\\') s=CharPrev(dir,s); *s=0; h = FindFirstFile(lgss,&d); if (h != INVALID_HANDLE_VALUE) { do { if (d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (recurse && strcmp(d.cFileName,"..") && strcmp(d.cFileName,".")) { entry ent={0,}; int a; int wd_save=strlen(cur_out_path); { char *i=d.cFileName,*o=cur_out_path; while (*o) o++; if (o > cur_out_path && CharPrev(cur_out_path,o)[0] != '\\') *o++='\\'; while (*i) { char *ni=CharNext(i); if (ni-i > 1) { int l=ni-i; while (l--) { *o++=*i++; } } else { char c=*i++; *o++=c; if (c == '$') *o++='$'; } } *o=0; } (*total_files)++; ent.which=EW_CREATEDIR; ent.offsets[0]=add_string(cur_out_path); ent.offsets[1]=1; a=add_entry(&ent); if (a != PS_OK) { FindClose(h); return a; } if (attrib) { ent.which=EW_SETFILEATTRIBUTES; ent.offsets[0]=add_string(cur_out_path); ent.offsets[1]=d.dwFileAttributes; a=add_entry(&ent); if (a != PS_OK) { FindClose(h); return a; } } char spec[1024]; sprintf(spec,"%s%s%s",dir,dir[0]?"\\":"",d.cFileName); SCRIPT_MSG("File: Descending to: \"%s\" -> \"%s\"\n",spec,cur_out_path); strcat(spec,"\\*.*"); a=do_add_file(spec,attrib,recurse,linecnt,total_files); if (a != PS_OK) { FindClose(h); return a; } cur_out_path[wd_save]=0; ent.which=EW_CREATEDIR; ent.offsets[1]=1; SCRIPT_MSG("File: Returning to: \"%s\" -> \"%s\"\n",dir,cur_out_path); ent.offsets[0]=add_string(cur_out_path); a=add_entry(&ent); if (a != PS_OK) { FindClose(h); return a; } } } else { HANDLE hFile,hFileMap; DWORD len; (*total_files)++; sprintf(newfn,"%s%s%s",dir,dir[0]?"\\":"",d.cFileName); hFile=CreateFile(newfn,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile == INVALID_HANDLE_VALUE) { ERROR_MSG("File: failed opening file \"%s\"\n",newfn); return PS_ERROR; } hFileMap=NULL; len = GetFileSize(hFile, NULL); if (len && !(hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL))) { CloseHandle(hFile); ERROR_MSG("File: failed creating mmap of \"%s\"\n",newfn); return PS_ERROR; } char *filedata=NULL; if (len) { filedata=(char*)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0); if (!filedata) { if (hFileMap) CloseHandle(hFileMap); CloseHandle(hFile); ERROR_MSG("File: failed mmapping file \"%s\"\n",newfn); return PS_ERROR; } } section_add_size_kb((len+1023)/1024); if (name_override) SCRIPT_MSG("File: \"%s\"->\"%s\"",d.cFileName,name_override); else SCRIPT_MSG("File: \"%s\"",d.cFileName); if (!build_compress_whole) if (build_compress) SCRIPT_MSG(" [compress]"); fflush(stdout); char buf[1024]; int last_build_datablock_used=getcurdbsize(); entry ent={0,}; ent.which=EW_EXTRACTFILE; ent.offsets[0]=build_overwrite; if (name_override) { ent.offsets[1]=add_string(name_override); } else { char *i=d.cFileName,*o=buf; while (*i) { char c=*i++; *o++=c; if (c == '$') *o++='$'; } *o=0; ent.offsets[1]=add_string(buf); } ent.offsets[2]=add_data(filedata?filedata:"",len); if (filedata) UnmapViewOfFile(filedata); if (hFileMap) CloseHandle(hFileMap); if (ent.offsets[2] < 0) { CloseHandle(hFile); return PS_ERROR; } { DWORD s=getcurdbsize()-last_build_datablock_used; if (s) s-=4; if (s != len) SCRIPT_MSG(" %d/%d bytes\n",s,len); else SCRIPT_MSG(" %d bytes\n",len); } if (build_datesave || build_overwrite==0x3 /*ifnewer*/) { FILETIME ft; if (GetFileTime(hFile,NULL,NULL,&ft)) { ent.offsets[3]=ft.dwLowDateTime; ent.offsets[4]=ft.dwHighDateTime; } else { CloseHandle(hFile); ERROR_MSG("File: failed getting file date from \"%s\"\n",newfn); return PS_ERROR; } } else { ent.offsets[3]=0xffffffff; ent.offsets[4]=0xffffffff; } if (uninstall_mode) m_uninst_fileused++; else m_inst_fileused++; CloseHandle(hFile); int a=add_entry(&ent); if (a != PS_OK) { FindClose(h); return a; } if (attrib) { char tmp_path[1024]; ent.which=EW_SETFILEATTRIBUTES; if (name_override) { sprintf(tmp_path,"%s\\%s",cur_out_path,name_override); } else { sprintf(tmp_path,"%s\\%s",cur_out_path,buf); } ent.offsets[0]=add_string(tmp_path); ent.offsets[1]=d.dwFileAttributes; a=add_entry(&ent); if (a != PS_OK) { FindClose(h); return a; } } } } while (FindNextFile(h,&d)); FindClose(h); } return PS_OK; }
[ "(no author)@212acab6-be3b-0410-9dea-997c60f758d6" ]
(no author)@212acab6-be3b-0410-9dea-997c60f758d6
7fd2e055104adfe7d4cac9560ce8d48adeb45017
6e665dcd74541d40647ebb64e30aa60bc71e610c
/800/VPBX/pbx/op/call/CallOpConnectAckInConnect.cxx
906a3b3516b802d0ba2f2c0d791aef45630f42c6
[]
no_license
jacklee032016/pbx
b27871251a6d49285eaade2d0a9ec02032c3ec62
554149c134e50db8ea27de6a092934a51e156eb6
refs/heads/master
2020-03-24T21:52:18.653518
2018-08-04T20:01:15
2018-08-04T20:01:15
143,054,776
0
0
null
null
null
null
UTF-8
C++
false
false
2,446
cxx
/* * $Id: CallOpConnectAckInConnect.cxx,v 1.1.1.1 2006/11/30 16:26:29 lizhijie Exp $ */ #include "PbxAgent.hxx" #include "CallContainer.hxx" #include "CallOpBuilder.hxx" using namespace Assist; /* process ConnectAck in state of CONNECT. only used in the second call of console's master EndPoint */ const Sptr <PbxState> CallOpConnectAckInConnect::process( Sptr <PbxEvent> _event ) { if( checkCallMsg(_event) != CALL_CONNECT_ACK ) { return PBX_STATE_CONTINUE; } Sptr <_CallConnectAck> connAckMsg = NULL; connAckMsg.dynamicCast( isCallMsg( _event)); if( connAckMsg==0) /* not the msg handled in this operator */ { cpLog(LOG_ERR, "No CONNECT_ACK CallEvent in this callEvent"); return PBX_STATE_CONTINUE; } Sptr <EndPoint> masterEp = connAckMsg->getMasterEndPoint(); Sptr <EndPoint> slaveEp = connAckMsg->getSlaveEndPoint(); assert( masterEp != 0 && slaveEp != 0); Sptr <CallContainer> calls = PbxAgent::instance()->getScheduler()->getCallContainer(); assert( calls != 0); /* get callInfo for both end of console */ Sptr <CallInfo> firstCall = calls->findCall( masterEp->getCallId() ); if( firstCall == 0) return PBX_STATE_CONTINUE; Sptr <CallInfo> secondCall = calls->findCall( slaveEp->getCallId() ); assert(secondCall != 0); /* replace the DestEP of firstCall with DestEP in secondCall */ Sptr <EndPoint> destEp = secondCall->getDestEP(); assert(destEp!= 0); destEp->setCallId(firstCall->getCallId() ); firstCall->setDestEP( destEp ); /* replace audio channel in srcEp and dest Ep */ Sptr <EndPoint> srcEp = firstCall->getSrcEP(); assert(srcEp != 0); Sptr <AudioChannel> srcAudio = srcEp->getAudio(); assert(srcAudio != 0); Sptr <AudioChannel> destAudio = destEp->getAudio(); assert(destAudio != 0); /* mutex protected should be enhanced here , lizhijie, 2006.06.04 */ srcAudio->releaseAudioPeer();/* free connect with masterEP's audio */ srcAudio->setAudioPeer( destAudio); /* reconnect with dest's audio */ /* remove secondCall. because Slave not feedback ConnectAck for this second call, so this call is always in state of little than CONNECT */ // calls->removeCall( secondCall->getCallId() ); secondCall->setState(secondCall->findState(CALL_STATE_IDLE)); /* return CONNECT_ACK to masterEp, because of CONNECT_ACK is send with MasterEP */ sendGatewayEvent(_event); return PBX_STATE_CONTINUE; }
[ "jacklee032016@gmail.com" ]
jacklee032016@gmail.com
3cd604694ded329e5f5dc37bd96113245da71a42
050ebbbc7d5f89d340fd9f2aa534eac42d9babb7
/grupa1/koredmat/witamy.cpp
bb172bf8d500fd5c7cebe4b4029b6be0824b57e4
[]
no_license
anagorko/zpk2015
83461a25831fa4358366ec15ab915a0d9b6acdf5
0553ec55d2617f7bea588d650b94828b5f434915
refs/heads/master
2020-04-05T23:47:55.299547
2016-09-14T11:01:46
2016-09-14T11:01:46
52,429,626
0
13
null
2016-03-22T09:35:25
2016-02-24T09:19:07
C++
UTF-8
C++
false
false
88
cpp
#include<iostream> int main() { std::cout << "Witamy na pokladzie!" << std::endl; }
[ "e.lasek@student.uw.edu.pl" ]
e.lasek@student.uw.edu.pl
7ce23d55b5bc32bf1384a1a71c8773333272af08
0e5b8cd772df330e32124f524fe3778e36899f9d
/Sneks/src/Systems/Menus/EndRoundScreenSystem.cpp
47d0f5008860ed5ea419a0c55bdfab5cfd74c865
[]
no_license
findcylim/Sneks
a8a9644a34370d12fdee91fe545d39d04a6eed00
5f5a9cb1c4b4f393bb1b9da86ec99d7a294a74e1
refs/heads/master
2020-04-13T09:59:49.819473
2019-04-08T10:18:53
2019-04-08T10:18:53
163,126,719
0
0
null
null
null
null
UTF-8
C++
false
false
2,584
cpp
/* Start Header****************************************************************/ /*! \file EndRoundScreenSystem.cpp \author Primary Author : Lim Chu Yan, chuyan.lim \par email: chuyan.lim\@digipen.edu \par Course : GAM150 \par SNEKS ATTACK \par High Tea Studios \brief This file contains \par Contribution : CY - 100.00% Copyright (C) 2019 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /* End Header *****************************************************************/ #include "EndRoundScreenSystem.h" #include "../../Utility/GameStateManager.h" void EndRound_Continue(SystemManager* systemManager) { UNREFERENCED_PARAMETER(systemManager); GameStateManager::SetState(kStateCountdown); } void EndRound_Select(SystemManager* systemManager) { UNREFERENCED_PARAMETER(systemManager); GameStateManager::SetState(kStateCharacterSelection); } EndRoundScreenSystem::EndRoundScreenSystem() { } void EndRoundScreenSystem::Initialize() { auto canvas = m_po_EntityManager->NewEntity<CanvasEntity>(kEntityCanvas, "EndRoundEntity"); auto canvas_Component = canvas->GetComponent<CanvasComponent>(); //Events::EV_NEW_UI_ELEMENT endRound = //{ canvas_Component, HTVector2{ 0.5f ,0.3f } ,kCanvasBasicSprite,"EndText" ,"Countdown" ,"Snek Destroyed!","","", nullptr,{1,1,1,1},4,1 }; Events::EV_NEW_UI_ELEMENT endNextButton = { canvas_Component, HTVector2{ 0.5f ,0.6f } ,kCanvasButton,"EndNextButton" ,"UIBack" ,"Next Round","UIBack_Hover","UIBack_Click", EndRound_Continue }; Events::EV_NEW_UI_ELEMENT endSelectButton = { canvas_Component, HTVector2{ 0.5f ,0.7f } ,kCanvasButton,"EndSelectButton" ,"UIBack" ,"Character Select","UIBack_Hover","UIBack_Click", EndRound_Select }; Events::EV_NEW_UI_ELEMENT TransitonBackUIElement = { canvas_Component, HTVector2{ 0.5f , 0.5f } ,kCanvasBasicSprite,"ConfirmationBackground" ,"TransitionBack" ,"","","", nullptr }; m_po_EventManagerPtr->EmitEvent<Events::EV_NEW_UI_ELEMENT>(TransitonBackUIElement); //m_po_EventManagerPtr->EmitEvent<Events::EV_NEW_UI_ELEMENT>(pauseMenuUiElement); m_po_EventManagerPtr->EmitEvent<Events::EV_NEW_UI_ELEMENT>(endNextButton); m_po_EventManagerPtr->EmitEvent<Events::EV_NEW_UI_ELEMENT>(endSelectButton); } EndRoundScreenSystem::~EndRoundScreenSystem() { //m_po_EntityManager->AddToDeleteQueue(m_po_EntityManager->GetSpecificEntityInstance<CanvasEntity>(kEntityCanvas,"PauseMenuEntity")); } void EndRoundScreenSystem::Update(float dt) { UNREFERENCED_PARAMETER(dt); }
[ "findcylim@gmail.com" ]
findcylim@gmail.com
643da91f227832594aca8002cc9976abc0ec691c
d92e2b22d70ceb26ba95209fc026dbd74bca4185
/main.7216842138045866565.cpp
a243c24a111fb60530e5bd1c6f5dc170d1d01d02
[]
no_license
huynguy97/IP-Week6
eb3caee579f0555d8e1b10d15284964210f3aff6
44815c19137a35b5b1bd2d0860d097e1f176a676
refs/heads/master
2020-05-22T08:39:28.753865
2019-05-12T17:23:37
2019-05-12T17:23:37
186,283,097
0
0
null
null
null
null
UTF-8
C++
false
false
4,626
cpp
#include <iostream> #include <fstream> #include <cassert> using namespace std; enum Cell {Dead=0, Live}; // const char DEAD = '.' ; // const char LIVE = '*' ; // const int NO_OF_ROWS = 40 ; // const int NO_OF_COLUMNS = 60 ; // const int ROWS = NO_OF_ROWS + 2 ; // const int COLUMNS = NO_OF_COLUMNS + 2 ; // const int MAX_FILENAME_LENGTH = 80 ; // // bool enter_filename (char filename [MAX_FILENAME_LENGTH]) { // assert(true); // // cout << "Please enter a file name: "; for (int i = 0; i < MAX_FILENAME_LENGTH; i++) { filename[i] = cin.get(); if (filename[i] == '\n') { filename[i] = '\0'; return true; } } return false; } // bool read_universe_file (ifstream& inputfile, Cell universe [ROWS][COLUMNS]) { // assert(inputfile.is_open()); // // char c; int row = 1; int column = 1; while (inputfile) { inputfile.get (c); if(c == '\n') { row++; column=1; } else { if (c == '*') { universe[row][column] = Live; } else { universe[row][column] = Dead; } column++; } } } void show_universe (Cell universe [ROWS][COLUMNS]) { // assert(true); // // for (int i = 1; i < ROWS -1; i++) { for (int j = 1; j < COLUMNS -1; j++) { if(universe[i][j] == Dead) { cout << '.'; } else { cout << '*'; } } cout << endl; } } // void next_generation (Cell now [ROWS][COLUMNS], Cell next [ROWS][COLUMNS]) { // assert(true); // // for(int i = 1; i < ROWS -1; i++) { for(int j = 1; j < COLUMNS -1; j++) { Cell test = now[i][j]; int amt_of_neighbours = (now[i-1][j] == Live) + (now[i+1][j] == Live) + (now[i][j+1] == Live) + (now[i][j-1] == Live) + (now[i+1][j+1] == Live) + (now[i+1][j-1] == Live) + (now[i-1][j-1] == Live) + (now[i-1][j+1] == Live); if(test == Live) { if (amt_of_neighbours < 2) { next [i][j] = Dead; } if (amt_of_neighbours > 3) { next [i][j] = Dead; } } else if (amt_of_neighbours == 3) { next [i][j] = Live; } } } } int main () { char inputname [MAX_FILENAME_LENGTH]; enter_filename (inputname); Cell universe [ROWS] [COLUMNS] = { Dead }; ifstream inputfile; inputfile.open(inputname); // read_universe_file(inputfile, universe); show_universe(universe); cout << endl << endl; Cell copy_of_universe [ROWS] [COLUMNS] = { Dead }; for(int i = 0; i < ROWS; i++) { for(int j = 0; j < COLUMNS; j++) { copy_of_universe[i][j] = universe[i][j]; } } next_generation(copy_of_universe, universe); show_universe(universe); cout << endl << endl; }
[ "h.nguyen@student.science.ru.nl" ]
h.nguyen@student.science.ru.nl
d9f3bf282d50677c3f474ec5574d80ced58f680f
efb34a43811bae9182d19a5174467c977db18cea
/ARX/LineManageAssitant/investigation/ARXDemo/MenuLMAMain.h
33361cf1444ff9e9073e2f855fe13727b2879941
[]
no_license
omusico/Cut
6dbdbca3240da0d81121fc7ba98fa4967c59dd14
e812436ff69602f4a62cd7d5f9159672b0827e0d
refs/heads/master
2020-05-30T12:54:57.869375
2013-01-25T21:17:56
2013-01-25T21:17:56
53,396,042
1
1
null
2016-03-08T08:35:57
2016-03-08T08:35:57
null
UTF-8
C++
false
false
381
h
#pragma once #include <afxwin.h> #include "aced.h" class MenuLMAMain : public AcEdUIContext { public: MenuLMAMain(void); ~MenuLMAMain(void); virtual void* getMenuContext(const AcRxClass *pClass, const AcDbObjectIdArray& ids) ; virtual void onCommand(Adesk::UInt32 cmdIndex); virtual void OnUpdateMenu(); private: CMenu *m_pMenu; HMENU m_tempHMenu; };
[ "chgu@chgu-macpro-w7.adobenet.global.adobe.com" ]
chgu@chgu-macpro-w7.adobenet.global.adobe.com
128b9de6b9f6934888e836c8d805a193364f8933
867b972af7145dd654f42b5e1f7fb90088c6c82a
/util/main/json/QStringJson.h
cc5ce2d2789db6c894c55aa3e43467df090d39b9
[ "BSD-3-Clause" ]
permissive
haruneko/vfont
538e610c251a150c196a88cb26b4059620753b73
997e73199023eab83453d2bf1e04bfcfc16d0d10
refs/heads/master
2021-01-13T03:34:55.814697
2016-12-29T07:45:08
2016-12-29T07:45:08
77,511,198
0
0
null
null
null
null
UTF-8
C++
false
false
897
h
/** * Created by Hal@shurabaP on 2015/05/31. * This code is under The BSD 3-Clause License. * See more Licence.txt. * Copyright (c) 2015 Hal@shurabaP. All rights reserved. */ #ifndef HARUNEKO_QSTRINGJSON_H #define HARUNEKO_QSTRINGJSON_H #include <QJsonValue> #include "JsonValidator.h" namespace haruneko { namespace util { extern QJsonValue operator << (QJsonValue &json, const QString &value); extern QJsonValue operator >> (const QJsonValue &json, QString &value); template <> class JsonValidator<QString> { public: void validate(const QJsonValue &v) const throw(const JsonValidationErrorException &) { if (v.isString()) { return; } throw JsonValidationErrorException("JSON value is expected as string, but it's not."); } }; constexpr JsonValidator<QString> QStringValidator = JsonValidator<QString>(); } } #endif //HARUNEKO_QSTRINGJSON_H
[ "harunyann@hotmail.com" ]
harunyann@hotmail.com
a2c54c46074cad68a7dde89573e59ec6e1d15b31
cde4f917f4f73358ae5fc2dbc8531acf3ee89157
/src/include/Grid.h
7fdc1e3d8a35f9db1782439809a584944035c3a6
[]
no_license
hazimehh/L0Local
49fdb4ab06293a9afffe8f72f1149eef97ffe1c7
3f7341e2a4238e642c9f2f5452710e49c6308495
refs/heads/master
2020-05-22T01:03:48.854259
2019-05-11T22:31:18
2019-05-11T22:31:18
186,185,775
0
0
null
null
null
null
UTF-8
C++
false
false
718
h
#ifndef GRID_H #define GRID_H #include <set> #include "GridParams.h" #include "FitResult.h" class Grid { private: arma::mat Xscaled; arma::vec yscaled; arma::vec BetaMultiplier; arma::vec meanX; double meany; public: GridParams PG; std::vector< std::vector<double> > Lambda0; std::vector<double> Lambda12; std::vector< std::vector<unsigned int> > NnzCount; std::vector< std::vector<arma::sp_mat> > Solutions; std::vector< std::vector<double> >Intercepts; std::vector< std::vector<bool> > Converged; Grid(const arma::mat& X, const arma::vec& y, const GridParams& PG); void Fit(); }; #endif
[ "hazimeh@mit.edu" ]
hazimeh@mit.edu
01eaefbd526e5453eea03068173ae2f3f07b967c
198d7cfe684592e85482c1c41e0682bdf04db594
/Wrapped_CppPython/FEM_Mesh_Interface/Pass_1DArrayTest/Mesh_Interface.cpp
3ae09057ee21d049d8583b32caadf163ae44b067
[]
no_license
albeanth/Fctn_Src
095efd543f7d3cb37ca1e316d606171483c75bc4
590083c62cfffefadd245d5d22ec479bdd66ef25
refs/heads/master
2021-07-03T17:10:44.933143
2020-02-07T19:17:16
2020-02-07T19:17:16
76,055,698
1
0
null
2020-01-29T23:35:53
2016-12-09T17:22:41
C++
UTF-8
C++
false
false
732
cpp
#include "Mesh_Interface.h" #include <stdlib.h> using namespace std; // void GaussianIntegration::TestFun(std::vector<double> v,std::vector<double> w,int z){ // cout << "print v" << endl; // for (int i=0; i<v.size(); i++){ // cout << v[i] << endl; // } // cout << "print w" << endl; // for (int i=0; i<w.size(); i++){ // cout << w[i] << endl; // } // cout << "print z" << endl << z; // } void GaussianIntegration::ImportMeshGridInfo(std::vector<double> v,std::vector<double> w,int z){ cout << "print v" << endl; for (int i=0; i<v.size(); i++){ cout << v[i] << endl; } cout << "print w" << endl; for (int i=0; i<w.size(); i++){ cout << w[i] << endl; } cout << "print z" << endl << z; }
[ "albertia@oregonstate.edu" ]
albertia@oregonstate.edu
dbfa72128faf450128990e01a49eb1f47f1ba576
973996e18022fc176ec68876bbceb5ae54aa9cac
/Topcoder/SRM_771/a.cpp
5425064a0358aae2acbfbb6beb0f61c72335e9ad
[ "MIT" ]
permissive
Shahraaz/CP_P_S5
80bda6a39f197428bbe6952c6735fe9a17c01cb8
b068ad02d34338337e549d92a14e3b3d9e8df712
refs/heads/master
2021-08-16T11:09:59.341001
2021-06-22T05:14:10
2021-06-22T05:14:10
197,088,137
1
0
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
//Optimise #include <bits/stdc++.h> using namespace std; #define Debug #ifdef Debug #define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__); #define pc(...) PC(#__VA_ARGS__, __VA_ARGS__); template <typename T, typename U> ostream &operator<<(ostream &out, const pair<T, U> &p) { out << '[' << p.first << ", " << p.second << ']'; return out; } template <typename Arg> void PC(const char *name, Arg &&arg) { std::cerr << name << " { "; for (const auto &v : arg) cerr << v << ' '; cerr << " }\n"; } template <typename Arg1> void ZZ(const char *name, Arg1 &&arg1) { std::cerr << name << " = " << arg1 << endl; } template <typename Arg1, typename... Args> void ZZ(const char *names, Arg1 &&arg1, Args &&... args) { const char *comma = strchr(names + 1, ','); std::cerr.write(names, comma - names) << " = " << arg1; ZZ(comma, args...); } #else #define db(...) #define pc(...) #endif using ll = long long; #define f first #define s second #define pb push_back const long long mod = 1000000007; const int nax = 2e5 + 10; class BagsOfMarbles { public: int removeFewest(int desired, int bagSize, int noWhiteBags, int noBlackBags, int someWhiteBags, int someBlackBags) { int gaurenteedWhiteBalls = bagSize * noBlackBags + someWhiteBags; if (gaurenteedWhiteBalls < desired) return -1; if (desired <= bagSize * noBlackBags) return desired; return (bagSize * noBlackBags) + (desired - (bagSize * noBlackBags)) * bagSize; } }; #ifndef LOCAL <%:testing-code%> #endif #ifdef LOCAL int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t = 1; auto TimeStart = chrono::steady_clock::now(); #ifdef multitest cin >> t; #endif #ifdef TIME cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n"; #endif return 0; } #endif //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
[ "ShahraazHussain@gmail.com" ]
ShahraazHussain@gmail.com
7381abcd5a8302a056e39cbc0a8a4720fd273423
16c8f91614e7603ecff1cbbdd5e9ac92dab270dd
/lib/epd1in54_V2/epdif.cpp
4444d910f366ef747e1898a038a6ff6e10d3b777
[ "MIT" ]
permissive
Marc56K/SpotiPi3_ESP32
f37d71cb7c56fec5dd5b29702f06af9b24f7d2dc
88f7d2582edcee243e21dadd95771b5bb1fb26df
refs/heads/master
2023-04-24T15:59:31.004563
2021-05-15T20:27:34
2021-05-15T20:27:34
281,618,601
0
0
null
null
null
null
UTF-8
C++
false
false
2,135
cpp
/** * @filename : epdif.cpp * @brief : Implements EPD interface functions * Users have to implement all the functions in epdif.cpp * @author : Yehui from Waveshare * * Copyright (C) Waveshare August 10 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documnetation 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 * furished 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 OR 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. */ #include "epdif.h" #include <spi.h> EpdIf::EpdIf() { }; EpdIf::~EpdIf() { }; void EpdIf::DigitalWrite(int pin, int value) { digitalWrite(pin, value); } int EpdIf::DigitalRead(int pin) { return digitalRead(pin); } void EpdIf::DelayMs(unsigned int delaytime) { delay(delaytime); } void EpdIf::SpiTransfer(unsigned char data) { SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0)); digitalWrite(EPD_CS_PIN, LOW); SPI.transfer(data); digitalWrite(EPD_CS_PIN, HIGH); SPI.endTransaction(); } int EpdIf::IfInit(void) { pinMode(EPD_CS_PIN, OUTPUT); pinMode(EPD_RST_PIN, OUTPUT); pinMode(EPD_DC_PIN, OUTPUT); pinMode(EPD_BUSY_PIN, INPUT); SPI.begin(); return 0; }
[ "" ]
b9a5d22710da9d244b4d309d4d4395953284f497
c37be0d1ddf85325c6bd02a0c57cb1dfe2df8c36
/content/browser/renderer_host/media/service_video_capture_device_launcher_unittest.cc
36a3366ce65cc6c1f1112512abca89138a22fbd7
[ "BSD-3-Clause" ]
permissive
idofilus/chromium
0f78b085b1b4f59a5fc89d6fc0efef16beb63dcd
47d58b9c7cb40c09a7bdcdaa0feead96ace95284
refs/heads/master
2023-03-04T18:08:14.105865
2017-11-14T18:26:28
2017-11-14T18:26:28
111,206,269
0
0
null
2017-11-18T13:06:33
2017-11-18T13:06:32
null
UTF-8
C++
false
false
16,375
cc
// Copyright 2017 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 "content/browser/renderer_host/media/service_video_capture_device_launcher.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "content/browser/renderer_host/media/service_launched_video_capture_device.h" #include "content/browser/renderer_host/media/video_capture_factory_delegate.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/video_capture/public/interfaces/device_factory.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::Invoke; using testing::InvokeWithoutArgs; using testing::_; namespace content { static const std::string kStubDeviceId = "StubDevice"; static const media::VideoCaptureParams kArbitraryParams; static const base::WeakPtr<media::VideoFrameReceiver> kNullReceiver; class MockDeviceFactory : public video_capture::mojom::DeviceFactory { public: void CreateDevice(const std::string& device_id, video_capture::mojom::DeviceRequest device_request, CreateDeviceCallback callback) override { DoCreateDevice(device_id, &device_request, callback); } void GetDeviceInfos(GetDeviceInfosCallback callback) override { DoGetDeviceInfos(callback); } MOCK_METHOD1(DoGetDeviceInfos, void(GetDeviceInfosCallback& callback)); MOCK_METHOD3(DoCreateDevice, void(const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, CreateDeviceCallback& callback)); }; class MockVideoCaptureDeviceLauncherCallbacks : public VideoCaptureDeviceLauncher::Callbacks { public: void OnDeviceLaunched( std::unique_ptr<LaunchedVideoCaptureDevice> device) override { DoOnDeviceLaunched(&device); } MOCK_METHOD1(DoOnDeviceLaunched, void(std::unique_ptr<LaunchedVideoCaptureDevice>* device)); MOCK_METHOD0(OnDeviceLaunchFailed, void()); MOCK_METHOD0(OnDeviceLaunchAborted, void()); }; class ServiceVideoCaptureDeviceLauncherTest : public testing::Test { public: ServiceVideoCaptureDeviceLauncherTest() {} ~ServiceVideoCaptureDeviceLauncherTest() override {} protected: void SetUp() override { factory_binding_ = std::make_unique<mojo::Binding<video_capture::mojom::DeviceFactory>>( &mock_device_factory_, mojo::MakeRequest(&device_factory_)); launcher_ = std::make_unique<ServiceVideoCaptureDeviceLauncher>( connect_to_device_factory_cb_.Get()); launcher_has_connected_to_device_factory_ = false; launcher_has_released_device_factory_ = false; ON_CALL(connect_to_device_factory_cb_, Run(_)) .WillByDefault(Invoke( [this](std::unique_ptr<VideoCaptureFactoryDelegate>* out_factory) { launcher_has_connected_to_device_factory_ = true; *out_factory = std::make_unique<VideoCaptureFactoryDelegate>( &device_factory_, release_connection_cb_.Get()); })); ON_CALL(release_connection_cb_, Run()) .WillByDefault(InvokeWithoutArgs([this]() { launcher_has_released_device_factory_ = true; wait_for_release_connection_cb_.Quit(); })); } void TearDown() override {} void RunLaunchingDeviceIsAbortedTest( video_capture::mojom::DeviceAccessResultCode service_result_code); base::test::ScopedTaskEnvironment scoped_task_environment_; MockDeviceFactory mock_device_factory_; MockVideoCaptureDeviceLauncherCallbacks mock_callbacks_; video_capture::mojom::DeviceFactoryPtr device_factory_; std::unique_ptr<mojo::Binding<video_capture::mojom::DeviceFactory>> factory_binding_; std::unique_ptr<ServiceVideoCaptureDeviceLauncher> launcher_; base::MockCallback<base::OnceClosure> connection_lost_cb_; base::MockCallback<base::OnceClosure> done_cb_; base::MockCallback< ServiceVideoCaptureDeviceLauncher::ConnectToDeviceFactoryCB> connect_to_device_factory_cb_; base::MockCallback<base::OnceClosure> release_connection_cb_; bool launcher_has_connected_to_device_factory_; bool launcher_has_released_device_factory_; base::RunLoop wait_for_release_connection_cb_; private: DISALLOW_COPY_AND_ASSIGN(ServiceVideoCaptureDeviceLauncherTest); }; TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceSucceeds) { EXPECT_CALL(mock_device_factory_, DoCreateDevice(kStubDeviceId, _, _)) .WillOnce(Invoke([](const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory:: CreateDeviceCallback& callback) { // Note: We must keep |device_request| alive at least until we have // sent out the callback. Otherwise, |launcher_| may interpret this // as the connection having been lost before receiving the callback. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](video_capture::mojom::DeviceRequest device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback callback) { std::move(callback).Run( video_capture::mojom::DeviceAccessResultCode::SUCCESS); }, std::move(*device_request), std::move(callback))); })); EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)).Times(1); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchAborted()).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchFailed()).Times(0); EXPECT_CALL(connection_lost_cb_, Run()).Times(0); base::RunLoop wait_for_done_cb; EXPECT_CALL(done_cb_, Run()) .WillOnce(InvokeWithoutArgs( [&wait_for_done_cb]() { wait_for_done_cb.Quit(); })); // Exercise launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); wait_for_done_cb.Run(); launcher_.reset(); wait_for_release_connection_cb_.Run(); EXPECT_TRUE(launcher_has_connected_to_device_factory_); EXPECT_TRUE(launcher_has_released_device_factory_); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceIsAbortedBeforeServiceRespondsWithSuccess) { RunLaunchingDeviceIsAbortedTest( video_capture::mojom::DeviceAccessResultCode::SUCCESS); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceIsAbortedBeforeServiceRespondsWithNotFound) { RunLaunchingDeviceIsAbortedTest( video_capture::mojom::DeviceAccessResultCode::ERROR_DEVICE_NOT_FOUND); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceIsAbortedBeforeServiceRespondsWithNotInitialized) { RunLaunchingDeviceIsAbortedTest( video_capture::mojom::DeviceAccessResultCode::NOT_INITIALIZED); } void ServiceVideoCaptureDeviceLauncherTest::RunLaunchingDeviceIsAbortedTest( video_capture::mojom::DeviceAccessResultCode service_result_code) { base::RunLoop step_1_run_loop; base::RunLoop step_2_run_loop; base::OnceClosure create_device_success_answer_cb; EXPECT_CALL(mock_device_factory_, DoCreateDevice(kStubDeviceId, _, _)) .WillOnce( Invoke([&create_device_success_answer_cb, &step_1_run_loop, service_result_code]( const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback& callback) { // Prepare the callback, but save it for now instead of invoking it. create_device_success_answer_cb = base::BindOnce( [](video_capture::mojom::DeviceRequest device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback callback, video_capture::mojom::DeviceAccessResultCode service_result_code) { std::move(callback).Run(service_result_code); }, std::move(*device_request), std::move(callback), service_result_code); step_1_run_loop.Quit(); })); EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchAborted()).Times(1); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchFailed()).Times(0); EXPECT_CALL(connection_lost_cb_, Run()).Times(0); EXPECT_CALL(done_cb_, Run()).WillOnce(InvokeWithoutArgs([&step_2_run_loop]() { step_2_run_loop.Quit(); })); // Exercise launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); step_1_run_loop.Run(); launcher_->AbortLaunch(); std::move(create_device_success_answer_cb).Run(); step_2_run_loop.Run(); EXPECT_TRUE(launcher_has_connected_to_device_factory_); EXPECT_TRUE(launcher_has_released_device_factory_); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceFailsBecauseDeviceNotFound) { base::RunLoop run_loop; EXPECT_CALL(mock_device_factory_, DoCreateDevice(kStubDeviceId, _, _)) .WillOnce( Invoke([](const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback& callback) { // Note: We must keep |device_request| alive at least until we have // sent out the callback. Otherwise, |launcher_| may interpret this // as the connection having been lost before receiving the callback. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](video_capture::mojom::DeviceRequest device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback callback) { std::move(callback).Run( video_capture::mojom::DeviceAccessResultCode:: ERROR_DEVICE_NOT_FOUND); }, std::move(*device_request), std::move(callback))); })); EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchAborted()).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchFailed()).Times(1); EXPECT_CALL(connection_lost_cb_, Run()).Times(0); EXPECT_CALL(done_cb_, Run()).WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); // Exercise launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); run_loop.Run(); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceFailsBecauseFactoryIsUnbound) { base::RunLoop run_loop; EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchAborted()).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchFailed()).Times(1); EXPECT_CALL(connection_lost_cb_, Run()).Times(0); EXPECT_CALL(done_cb_, Run()).WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); // Exercise device_factory_.reset(); launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); run_loop.Run(); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, LaunchingDeviceFailsBecauseConnectionLostWhileLaunching) { base::RunLoop run_loop; video_capture::mojom::DeviceFactory::CreateDeviceCallback create_device_cb; EXPECT_CALL(mock_device_factory_, DoCreateDevice(kStubDeviceId, _, _)) .WillOnce( Invoke([&create_device_cb]( const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback& callback) { // Simulate connection lost by not invoking |callback| and releasing // |device_request|. We have to save |callback| and invoke it later // to avoid hitting a DCHECK. create_device_cb = std::move(callback); })); EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchAborted()).Times(0); EXPECT_CALL(mock_callbacks_, OnDeviceLaunchFailed()).Times(1); // Note: |connection_lost_cb_| is only meant to be called when the connection // to a successfully-launched device is lost, which is not the case here. EXPECT_CALL(connection_lost_cb_, Run()).Times(0); EXPECT_CALL(done_cb_, Run()).WillOnce(InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); // Exercise launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); run_loop.Run(); // Cut the connection to the factory, so that the outstanding // |create_device_cb| will be dropped. factory_binding_.reset(); // We have to invoke the callback, because not doing so triggers a DCHECK. const video_capture::mojom::DeviceAccessResultCode arbitrary_result_code = video_capture::mojom::DeviceAccessResultCode::SUCCESS; std::move(create_device_cb).Run(arbitrary_result_code); } TEST_F(ServiceVideoCaptureDeviceLauncherTest, ConnectionLostAfterSuccessfulLaunch) { video_capture::mojom::DeviceRequest device_request_owned_by_service; EXPECT_CALL(mock_device_factory_, DoCreateDevice(kStubDeviceId, _, _)) .WillOnce(Invoke([&device_request_owned_by_service]( const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory:: CreateDeviceCallback& callback) { // The service holds on to the |device_request|. device_request_owned_by_service = std::move(*device_request); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](video_capture::mojom::DeviceFactory::CreateDeviceCallback callback) { std::move(callback).Run( video_capture::mojom::DeviceAccessResultCode::SUCCESS); }, std::move(callback))); })); std::unique_ptr<LaunchedVideoCaptureDevice> launched_device; EXPECT_CALL(mock_callbacks_, DoOnDeviceLaunched(_)) .WillOnce( Invoke([&launched_device]( std::unique_ptr<LaunchedVideoCaptureDevice>* device) { // We must keep the launched device alive, because otherwise it will // no longer listen for connection errors. launched_device = std::move(*device); })); base::RunLoop step_1_run_loop; EXPECT_CALL(done_cb_, Run()).WillOnce(InvokeWithoutArgs([&step_1_run_loop]() { step_1_run_loop.Quit(); })); // Exercise step 1 launcher_->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, connection_lost_cb_.Get(), &mock_callbacks_, done_cb_.Get()); step_1_run_loop.Run(); base::RunLoop step_2_run_loop; EXPECT_CALL(connection_lost_cb_, Run()).WillOnce(Invoke([&step_2_run_loop]() { step_2_run_loop.Quit(); })); // Exercise step 2: The service cuts/loses the connection device_request_owned_by_service = nullptr; step_2_run_loop.Run(); launcher_.reset(); wait_for_release_connection_cb_.Run(); EXPECT_TRUE(launcher_has_connected_to_device_factory_); EXPECT_TRUE(launcher_has_released_device_factory_); } } // namespace content
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
068474616a2739a4e4c293e797346823443a23bf
b3d53587aa11c6dbe661f1c496fc98802f8d501c
/PAT/PAT (Advanced Level)/1151/main.cpp
46d4a9d72e3f8e372332fa567db892d1d4a2fb29
[]
no_license
ZhangYu-zjut/PAT_Code
1d0bd2010b2b474855b26aedf3b45241216876f6
5c376f5fcd8a69ef3d91f749dfc249c193a05d00
refs/heads/master
2022-06-06T00:22:00.697527
2020-04-28T00:36:15
2020-04-28T00:36:15
259,306,645
0
0
null
null
null
null
GB18030
C++
false
false
3,028
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ //AC!! int n,m; int in[10005],pre[10005]; struct node { int data; node* left; node* right; int layer; node* father; }N[10004]; vector<node*>ans; node* create(int prel,int prer,int inl,int inr,int layer) { if(prel>prer) { return NULL; } node* root=new node;//一定要new一个节点 root->data=pre[prel]; root->layer=layer; int i,j; for(i=inl;i<=inr;i++) { if(in[i]==pre[prel]) { break; } } int leftnum=i-inl; root->left=create(prel+1,prel+leftnum,inl,i-1,layer+1); if(root->left!=NULL)root->left->father=root; root->right=create(prel+leftnum+1,prer,i+1,inr,layer+1); if(root->right!=NULL)root->right->father=root; return root; } void inshow(node* root) { if(root==NULL) { return; } inshow(root->left); //printf("%d ",root->layer); inshow(root->right); printf("%d ",root->data); } //另一种写法 void sea(node* root,int x,int count) { if(ans.size()>0&&count==0) { ans.clear(); } count++; if(root==NULL) { return; } if(root->data==x) { ans.push_back(root); } else { sea(root->left,x,count); sea(root->right,x,count); } } void search(node* root,node* &p1,node* &p2,int x,int y) { if(root==NULL) { return; } if(root->data==x) { p1 = root; //找到后不能返回,如果返回的话,就相当于停止往下搜索 } if(root->data==y) { p2 = root; } search(root->left,p1,p2,x,y); search(root->right,p1,p2,x,y); } int main(int argc, char** argv) { freopen("test.txt","r",stdin); scanf("%d%d",&m,&n); int i,j,k; int a,b; for(i=0;i<n;i++) { scanf("%d",&in[i]); } for(i=0;i<n;i++) { scanf("%d",&pre[i]); } node* root=NULL; //root->layer=1;//这句话不能放在这里 root=create(0,n-1,0,n-1,1); //inshow(root); for(i=0;i<m;i++) { scanf("%d%d",&a,&b); node* p1=NULL; node* p2=NULL; sea(root,a,0); if(ans.size()>0)p1=ans[0]; sea(root,b,0); if(ans.size()>0)p2=ans[0]; if(p1==NULL&&p2==NULL) { printf("ERROR: %d and %d are not found.\n",a,b); continue; } if(p1==NULL&&p2!=NULL) { printf("ERROR: %d is not found.\n",a); continue; } if(p1!=NULL&&p2==NULL) { printf("ERROR: %d is not found.\n",b); continue; } if(p1!=NULL&&p2!=NULL) { int flag=0; //找到p1,p2 int maxlayer=max(p1->layer,p2->layer); while(p1->layer<p2->layer) { p2=p2->father; flag=1; } while(p1->layer>p2->layer) { p1=p1->father; flag=2; } if(p1->data==p2->data&&flag==1) { printf("%d is an ancestor of %d.\n",a,b); } else if(p1->data==p2->data&&flag==2) { printf("%d is an ancestor of %d.\n",b,a); } else { while(p1->data!=root->data&&p2->data!=root->data) { p1=p1->father; p2=p2->father; if(p1->data==p2->data) { printf("LCA of %d and %d is %d.\n",a,b,p1->data); break; } } } } } return 0; }
[ "597660653@qq.com" ]
597660653@qq.com
34922b0798ba3349da8bd528a4f208a31032a92a
38ac824e86e2b8d7083166968c2566a383d375ed
/src/util.cpp
f77b390cb7c709b55410eb1dcd481653c4f1b226
[]
no_license
moratorium08/lambda-type-verify
9ce80e6dfc2dfa40d3790c9213b81ea50ccee552
2cd4d8300616acc3199992aa574a3effad1ecd48
refs/heads/master
2020-06-27T14:51:41.449335
2017-07-25T10:02:42
2017-07-25T10:02:42
97,063,507
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
cpp
#include <cstring> #include <stdarg.h> #include <cstdlib> #include <cstdio> void panic(char *s) { printf("%s", s); exit(-1); } void _print_spaces(int space) { for (int i = 0 ; i < space; i++) { printf(" "); } } void strscpy(char *buf, int count, ...) { va_list ap; va_start(ap, count); int idx = 0; for (int i = 0; i < count; i++) { char *tmp = va_arg(ap, char*); for (int j = 0; j < strlen(tmp); j++) { buf[idx++] = tmp[j]; } } buf[idx] = 0; } char * char_alloc(int x) { char *ret = (char *)malloc(x + 1); memset(ret, x + 1, 0); return ret; } char *create_substr(char *s, int st, int ed) { char *ret = (char *)malloc(ed - st + 1); for (int i = st; i < ed; i++) { ret[i - st] = s[i]; } ret[ed - st] = 0; return ret; } int find_first_split_point(char *s, char split_c) { int l = strlen(s); int i; for (i = 0; i < l; i++) if (split_c == s[i]) break; return i; }
[ "moratorium0hiro8sanctuary@gmail.com" ]
moratorium0hiro8sanctuary@gmail.com
806aeaf77a39349dfd81575b9242999097c16fa6
963b19fc212b1cb25a754ef1c26148f711c7ad6d
/include/dive_message_factory.h
52d53dbe46fb1570bf32d1f7a4a964b866c9b2a2
[]
no_license
alexyer/dive
7b4e7ab5c66a879f9c29bc36156839e44188249c
c226cf78036f917121294f279fcdb9c02eac7d0d
refs/heads/master
2021-01-23T04:40:53.343525
2017-02-24T09:32:17
2017-02-24T13:13:56
80,371,283
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#ifndef DIVE_DIVE_MESSAGE_FACTORY_H #define DIVE_DIVE_MESSAGE_FACTORY_H #include <lib/proto/message.pb.h> using namespace dive; namespace dive { class DiveMessageFactory { public: static DiveMessage& get_ping_message(Member*); static DiveMessage& get_ack_message(Member*); private: static DiveMessage& get_message(Member*, MessageType); }; } #endif //DIVE_DIVE_MESSAGE_FACTORY_H
[ "mannavard1611@gmail.com" ]
mannavard1611@gmail.com
2044f10319ff7bd74494a6073fe6b6fc40424357
8ec26c65336cde659b2c0fff06e7694685148458
/codeforces/439/A.cpp
4a5b09a928b5a4b31dfcf7d41b798e23b5977f7a
[]
no_license
YESIMGOD/competitive-programming
d88cc7130173fb418742a2efb5891681771f0c8e
4e84360f24a9d0ad28451f6424b146907d0ef5f9
refs/heads/main
2023-06-25T08:49:45.971805
2021-01-17T09:43:16
2021-01-17T09:43:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
/* Author: saiyan_01 Problem Statement : https://codeforces.com/problemset/problem/439/A */ #include <bits/stdc++.h> using namespace std; #define ll long long #define mp make_pair #define pb push_back #define mod 1000000007 #define e "\n" #define len(x) x.size() #define gcd(a, b) __gcd(a, b) #define ste(v) v.begin(), v.end() #define stea(arr, n) arr, arr+n void solve(){ // Solve here int a, b; cin>>a>>b; int arr[a]; int sum = 0; for(int i=0;i<a;i++) { cin>>arr[i]; sum += arr[i]; } // sum -= 10; int x = b-(sum+((a-1)*10)); // cout<<x<<e; if(x<0) cout<<-1<<e; else { cout<<(b-sum)/5<<e; } } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios::sync_with_stdio(0); cout.tie(0); cin.tie(0); int t=1; // cin>>t; while(t--){ solve(); } return 0; }
[ "aditya001tomar@gmail.com" ]
aditya001tomar@gmail.com
4efa7148ed85d74522569db3a0f97d474c837abe
6b2985d7ea8b289badbeade95efe45f02409cf1b
/showdontupdatedialog.h
faf5ed74e442d026f80df3c80efe8db851a6458f
[]
no_license
feengg/SanTang
e92a3f7cca8766fe047739501d558bab3c326087
83577a464b251c96f26f75e13e7a557aa477a0ed
refs/heads/master
2021-05-18T00:18:29.374704
2020-05-03T15:02:10
2020-05-03T15:02:10
251,019,653
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
#ifndef SHOWDONTUPDATEDIALOG_H #define SHOWDONTUPDATEDIALOG_H #include <QWidget> namespace Ui { class showDontUpdateDialog; } class showDontUpdateDialog : public QWidget { Q_OBJECT public: explicit showDontUpdateDialog(QString showMsg,QWidget *parent = 0); ~showDontUpdateDialog(); private slots: void on_pushButton_clicked(); private: Ui::showDontUpdateDialog *ui; }; #endif // SHOWDONTUPDATEDIALOG_H
[ "feengg@163.com" ]
feengg@163.com
87569b23cedce688de33229716663abd696e76b8
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/068/319/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_53a.cpp
559d43f6ddf025c87cbfcce75cfaac1a036be4ce
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,451
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_53a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml Template File: sources-sink-53a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: loop * BadSink : Copy string to data using a loop * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_53 { #ifndef OMITBAD /* bad function declaration */ void badSink_b(char * data); void bad() { char * data; data = NULL; /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new char[50]; data[0] = '\0'; /* null terminate */ badSink_b(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink_b(char * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; data = NULL; /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new char[100]; data[0] = '\0'; /* null terminate */ goodG2BSink_b(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_53; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
264af9f64a6f5edeed63d954aec188b7761b2557
b4e9ff1b80ff022aaacdf2f863bc3a668898ce7f
/lime/GrotateMove/Export/macos/obj/src/lime/graphics/opengl/ext/EXT_unpack_subimage.cpp
bb2b15d0d02641d72fc366f52ee0777fe9f46957
[ "MIT" ]
permissive
TrilateralX/TrilateralSamples
c1aa206495cf6e1f4f249c87e49fa46d62544c24
9c9168c5c2fabed9222b47e738c67ec724b52aa6
refs/heads/master
2023-04-02T05:10:13.579952
2021-04-01T17:41:23
2021-04-01T17:41:23
272,706,707
1
0
null
null
null
null
UTF-8
C++
false
true
4,577
cpp
// Generated by Haxe 4.2.0-rc.1+7dc565e63 #include <hxcpp.h> #ifndef INCLUDED_lime_graphics_opengl_ext_EXT_unpack_subimage #include <lime/graphics/opengl/ext/EXT_unpack_subimage.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_379d20639afe89d4_4_new,"lime.graphics.opengl.ext.EXT_unpack_subimage","new",0xdcb8a1da,"lime.graphics.opengl.ext.EXT_unpack_subimage.new","lime/graphics/opengl/ext/EXT_unpack_subimage.hx",4,0xb36a48f8) namespace lime{ namespace graphics{ namespace opengl{ namespace ext{ void EXT_unpack_subimage_obj::__construct(){ HX_STACKFRAME(&_hx_pos_379d20639afe89d4_4_new) HXLINE( 8) this->UNPACK_SKIP_PIXELS = 3316; HXLINE( 7) this->UNPACK_SKIP_ROWS = 3315; HXLINE( 6) this->UNPACK_ROW_LENGTH = 3314; } Dynamic EXT_unpack_subimage_obj::__CreateEmpty() { return new EXT_unpack_subimage_obj; } void *EXT_unpack_subimage_obj::_hx_vtable = 0; Dynamic EXT_unpack_subimage_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< EXT_unpack_subimage_obj > _hx_result = new EXT_unpack_subimage_obj(); _hx_result->__construct(); return _hx_result; } bool EXT_unpack_subimage_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x50b59a60; } EXT_unpack_subimage_obj::EXT_unpack_subimage_obj() { } ::hx::Val EXT_unpack_subimage_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 16: if (HX_FIELD_EQ(inName,"UNPACK_SKIP_ROWS") ) { return ::hx::Val( UNPACK_SKIP_ROWS ); } break; case 17: if (HX_FIELD_EQ(inName,"UNPACK_ROW_LENGTH") ) { return ::hx::Val( UNPACK_ROW_LENGTH ); } break; case 18: if (HX_FIELD_EQ(inName,"UNPACK_SKIP_PIXELS") ) { return ::hx::Val( UNPACK_SKIP_PIXELS ); } } return super::__Field(inName,inCallProp); } ::hx::Val EXT_unpack_subimage_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 16: if (HX_FIELD_EQ(inName,"UNPACK_SKIP_ROWS") ) { UNPACK_SKIP_ROWS=inValue.Cast< int >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"UNPACK_ROW_LENGTH") ) { UNPACK_ROW_LENGTH=inValue.Cast< int >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"UNPACK_SKIP_PIXELS") ) { UNPACK_SKIP_PIXELS=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EXT_unpack_subimage_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("UNPACK_ROW_LENGTH",78,04,c5,5f)); outFields->push(HX_("UNPACK_SKIP_ROWS",0c,e6,50,4d)); outFields->push(HX_("UNPACK_SKIP_PIXELS",e0,26,60,af)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo EXT_unpack_subimage_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(EXT_unpack_subimage_obj,UNPACK_ROW_LENGTH),HX_("UNPACK_ROW_LENGTH",78,04,c5,5f)}, {::hx::fsInt,(int)offsetof(EXT_unpack_subimage_obj,UNPACK_SKIP_ROWS),HX_("UNPACK_SKIP_ROWS",0c,e6,50,4d)}, {::hx::fsInt,(int)offsetof(EXT_unpack_subimage_obj,UNPACK_SKIP_PIXELS),HX_("UNPACK_SKIP_PIXELS",e0,26,60,af)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *EXT_unpack_subimage_obj_sStaticStorageInfo = 0; #endif static ::String EXT_unpack_subimage_obj_sMemberFields[] = { HX_("UNPACK_ROW_LENGTH",78,04,c5,5f), HX_("UNPACK_SKIP_ROWS",0c,e6,50,4d), HX_("UNPACK_SKIP_PIXELS",e0,26,60,af), ::String(null()) }; ::hx::Class EXT_unpack_subimage_obj::__mClass; void EXT_unpack_subimage_obj::__register() { EXT_unpack_subimage_obj _hx_dummy; EXT_unpack_subimage_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.graphics.opengl.ext.EXT_unpack_subimage",e8,6c,60,32); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(EXT_unpack_subimage_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< EXT_unpack_subimage_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EXT_unpack_subimage_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EXT_unpack_subimage_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace graphics } // end namespace opengl } // end namespace ext
[ "none" ]
none
52a0c64fc2bf1dab5ecd63f3bbc03287215a5fb0
acd25d57f73285851713f91f0b1f87e73832dfd8
/ETriangles/app/main.cpp
1d6975cc25f1a0d3d73026394a320615f9da7751
[]
no_license
eaikao/EOpengl
0b595d8a654004bfe9c074e4796e12d14ed41116
8f581088bb68cd87d421291c374d4d96335682c4
refs/heads/master
2021-02-04T13:17:27.132941
2020-02-28T05:26:01
2020-02-28T05:26:01
243,669,538
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
cpp
#include "ETriangleWidget.h" #include <QtWidgets/QApplication> #include <gl/GL.h> #include <gl/GLU.h> #include <QString> #pragma comment(lib, "opencv_core330d.lib") #pragma comment(lib, "opencv_objdetect330d.lib") #pragma comment(lib, "opencv_video330d.lib") #pragma comment(lib, "opencv_photo330d.lib") #pragma comment(lib, "opencv_stitching330d.lib") #pragma comment(lib, "opencv_superres330d.lib") #pragma comment(lib, "opencv_videostab330d.lib") #pragma comment(lib, "opencv_calib3d330d.lib") #pragma comment(lib, "opencv_features2d330d.lib") #pragma comment(lib, "opencv_flann330d.lib") #pragma comment(lib, "opencv_highgui330d.lib") #pragma comment(lib, "opencv_imgproc330d.lib") #pragma comment(lib, "opencv_ml330d.lib") #pragma comment(lib, "opencv_videoio330d.lib") #pragma comment(lib, "opencv_shape330d.lib") #pragma comment(lib, "opencv_imgcodecs330d.lib") #pragma comment(lib, "opencv_dnn330d.lib") int main(int argc, char *argv[]) { QApplication a(argc, argv); ETriangleWidget w; w.setMinimumWidth(800); w.setMinimumHeight(600); w.show(); return a.exec(); }
[ "279712302@qq.com" ]
279712302@qq.com
c0aa9d6c7106f93e22e204f43223e19333684a23
5851526e8bf1223d1258fe7561abfd59790023e5
/Quick Sort.cpp
9b34918b15585b8be99ab369e72fac086d7276d4
[]
no_license
sumit1311singh/DS-Algo
2da99c1a3bf2fbc5cade72cce3463f63fb707aee
22515b32d543c6b2eca49726188477307327b4c9
refs/heads/main
2023-02-25T13:06:00.957428
2021-02-07T07:44:28
2021-02-07T07:44:28
336,730,416
0
0
null
null
null
null
UTF-8
C++
false
false
890
cpp
#include<bits/stdc++.h> #include<math.h> #include<string> #include <cstdio> #include <vector> #include <queue> #include <algorithm> using namespace std; typedef long long int ll; int partition(int arr[], int start, int end) { int pivot=arr[end], pIndex=start; for(int i=start; i<end; i++){ if(arr[i]<=pivot){ swap(arr[i], arr[pIndex]); pIndex++; } } swap(arr[pIndex], arr[end]); return pIndex; } void quicksort(int arr[], int start, int end) { if(start>=end) return; int pIndex = partition(arr, start, end); quicksort(arr, start, pIndex-1); quicksort(arr, pIndex+1, end); } int main() { #ifndef ONLINE_JUDGE freopen("Input.txt", "r", stdin); freopen("Output.txt", "w", stdout); #endif int n; cin>>n; int arr[n]; for(int i=0; i<n; i++) cin>>arr[i]; int start=0, end=n-1; quicksort(arr, start, end); for(int i=0; i<n; i++) cout<<arr[i]<<" "; return 0; }
[ "sumit1311singh@gamil.com" ]
sumit1311singh@gamil.com
ca0ee1ff84a9d0502ad5377b665f9724b56885a7
5fc334796d72f7975f115d815b0e0daa4d550a62
/Source/Sinister/FreeCameraPawn.h
c15667839bb9decc1f8661e2d7445475f28e9faf
[]
no_license
ninilac/Sinister
5a0496d57ae3befc32a0925462c4088c52a39e7c
e741a3b9c2b6fae798d119266d7114b2fb7ce882
refs/heads/master
2021-01-07T13:14:26.315676
2020-02-19T19:23:18
2020-02-19T19:23:18
241,705,358
0
0
null
null
null
null
UTF-8
C++
false
false
677
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/DefaultPawn.h" #include "FreeCameraPawn.generated.h" UCLASS() class SINISTER_API AFreeCameraPawn : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties AFreeCameraPawn(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; };
[ "alach987@yahoo.ca" ]
alach987@yahoo.ca
ac8a6930d41cc52fb330386ae0bb20d3718bdf62
2abad84325f6c41efbef29afd1d006223d6350d8
/NuWriter/NuWriter/NuWriterDlg.cpp
c19803240a5fb8012995b68a7e69bdd3cece8df1
[]
no_license
OpenNuvoton/NUC980_NuWriter
1252e9f29698086765a1346323505b4eb44a90c3
2fe2dcb84ef4376836163dbb1bfd4dcd9fbf4d5f
refs/heads/master
2023-07-20T04:55:42.002604
2023-07-14T10:52:09
2023-07-14T10:52:09
156,328,671
9
16
null
null
null
null
BIG5
C++
false
false
63,441
cpp
// NuWriterDlg.cpp : implementation file // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include "NuWriter.h" #include "NuWriterDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #define LOAD 1 #define SAVE 0 #define AUTO_DOWNLOAD #define RETRYCNT 5 // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CNuWriterDlg dialog DEFINE_GUID(GUID_CLASS_VCOMPORT, 0x9b2095ce, 0x99a1, 0x44d9, 0xa7, 0xc6, 0xc7, 0xcb, 0x58, 0x41, 0xfe, 0x88); //extern BOOL Auto_Detect(CString& portName,CString& tempName); extern BOOL Device_Detect(CString& portName,CString& tempName); CNuWriterDlg::CNuWriterDlg(CWnd* pParent /*=NULL*/) : CDialog(CNuWriterDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CNuWriterDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_COMBO_TYPE, m_gtype); DDX_Control(pDX, IDC_COMPORT, m_burntext); DDX_Control(pDX, IDC_TYPE, m_type); DDX_Control(pDX, IDC_STATIC_DDRFile, m_static_ddrfile); DDX_Control(pDX, IDC_RECONNECT, m_reconnect); DDX_Control(pDX, IDCANCEL, m_exit); DDX_Control(pDX, IDC_VERSION, m_version); } BEGIN_MESSAGE_MAP(CNuWriterDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_RECONNECT, &CNuWriterDlg::OnBnClickedReconnect) ON_WM_DESTROY() ON_CBN_SELCHANGE(IDC_COMBO_TYPE, &CNuWriterDlg::OnCbnSelchangeComboType) ON_WM_CTLCOLOR() ON_WM_SHOWWINDOW() END_MESSAGE_MAP() // CNuWriterDlg message handlers void CNuWriterDlg::FastMode_ProgressControl(int num, BOOL isHIDEType) { int i; CDialog* mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(isHIDEType) { for(i=0; i< 8; i++) { ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->ShowWindow(SW_HIDE); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+i)))->ShowWindow(SW_HIDE); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_DEV1+i)))->ShowWindow(SW_HIDE); } } else { for(i=0; i< num; i++) { ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->SetRange(0,100); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->SetPos(0); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+i)))->SetWindowText(_T("")); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+i)))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_DEV1+i)))->ShowWindow(SW_SHOW); } } } void CNuWriterDlg::ShowDeviceConnectState(BOOL isConnect) { COLORREF col = RGB(0xFF, 0x00, 0xFF); if(isConnect) { m_portName.Format(_T("Nuvoton VCOM")); m_reconnect.setBitmapId(IDB_RECONNECT0, col); m_reconnect.setGradient(true); m_burntext.SetWindowText(_T("Device Connected")); } else { m_portName=""; m_reconnect.setBitmapId(IDB_RECONNECT1, col); m_reconnect.setGradient(true); m_burntext.SetWindowText(_T(" Disconnected")); } } BOOL CNuWriterDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon //ShowWindow(SW_MINIMIZE); g_iDeviceNum = 0; g_iCurDevNum = 0; // TODO: Add extra initialization here envbuf=NULL; g_iDeviceNum = NucUsb.UsbDevice_Detect(); for(int i = 0; i < g_iDeviceNum; i++) { m_ExitEvent[i]=CreateEvent(NULL,TRUE,FALSE,NULL); } this->SetWindowText(PROJECT_NAME); page_idx=0; TargetChip=0; //init target chip ChipEraseWithBad=0; ChipReadWithBad=0; ChipWriteWithOOB=0; DtbEn=0; //DDRBuf=NULL; //---auto detect device ------------------------------------------------- //UsbRegisterDeviceNotification(this,OSR_DEVICE_INTERFACE,1); TCHAR exeFullPath[MAX_PATH]; memset(exeFullPath,0,MAX_PATH); int len=GetModuleFileName(NULL,exeFullPath,MAX_PATH); for(int i=len; i>0; i--) { if(exeFullPath[i]=='\\') { len=i; break; } } lstrcpy(&exeFullPath[len+1],_T("path.ini")); m_inifile.SetPath(exeFullPath); CRect rc; CString title; (GetDlgItem(IDC_TYPE))->GetWindowRect(&rc); // get the position for the subforms m_SubForms.SetCenterPos(rc); // if the subdialog needs to be centered INItoSaveOrLoad(LOAD); if(m_SelChipdlg.DoModal()==IDCANCEL) exit(0); m_gtype.AddString(_T("DDR/SRAM")); m_SubForms.CreateSubForm(IDD_SDRAM,this); // create the sub forms m_gtype.AddString(_T("SPI")); m_SubForms.CreateSubForm(IDD_SPI,this); m_gtype.AddString(_T("NAND")); m_SubForms.CreateSubForm(IDD_NAND,this); m_gtype.AddString(_T("eMMC/SD")); m_SubForms.CreateSubForm(IDD_MMC,this); m_gtype.AddString(_T("SPI NAND")); m_SubForms.CreateSubForm(IDD_SPINAND,this); m_gtype.AddString(_T("PACK")); m_SubForms.CreateSubForm(IDD_PACK,this); m_gtype.AddString(_T("Mass Production")); m_SubForms.CreateSubForm(IDD_FAST,this); m_static_ddrfile.ShowWindow(true); //------------------------------------ LPTSTR charPathName = new TCHAR[DDRFileFullPath.GetLength()+1]; _tcscpy(charPathName, DDRFileFullPath); wchar_t BmpDrive[10]; wchar_t BmpDir[256]; wchar_t BmpFName[256]; wchar_t BmpExt[256]; _wsplitpath(charPathName, BmpDrive, BmpDir, BmpFName, BmpExt); CString showddrname; CFont* pFont=m_static_ddrfile.GetFont(); LOGFONT lf; pFont->GetLogFont(&lf); int nFontSize=14; lf.lfHeight = -MulDiv(nFontSize,96,72); // 96 dpi CFont* pNewFont=new CFont; pNewFont->CreateFontIndirect(&lf); m_static_ddrfile.SetFont(pNewFont); // showddrname.Format(_T("%s%s"),BmpFName,BmpExt); // m_static_ddrfile.SetWindowText(showddrname); UpdateBufForDDR(); showddrname.Format(_T("%s%s-%s"),BmpFName,BmpExt,DDRFileVer); m_static_ddrfile.SetWindowText(showddrname); m_SubForms.ShowSubForm(); // show the first one m_gtype.SetCurSel(page_idx); m_gtype.GetWindowText(title); m_type.SetWindowText(title); m_SubForms.ShowSubForm(m_gtype.GetCurSel()); INItoSaveOrLoad(SAVE); GetDlgItem(IDC_RECONNECT)->EnableWindow(FALSE); COLORREF col = RGB(0xFF, 0x00, 0xFF); m_reconnect.setBitmapId(IDB_RECONNECT0, col); m_reconnect.setGradient(true); m_exit.setBitmapId(IDB_EXIT, col); m_exit.setGradient(true); CString tempText; if(!g_iDeviceNum) { ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); } else { ShowDeviceConnectState(1);//Connected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); } g_iCurDevNum = g_iDeviceNum; //m_burntext.SetWindowText(tempText); #ifdef AUTO_DOWNLOAD CString t_type; iDevice=0; if(!m_portName.IsEmpty()) { m_initdlg.SetData(); m_initdlg.DoModal(); if(m_initdlg.GetVersion() == _T("xxxx")) //if(!g_iDeviceNum) { ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); g_iCurDevNum -= 1; g_iDeviceNum -= 1; m_gtype.GetWindowText(t_type); if( !t_type.Compare(_T("Mass Production")) ) { FastMode_ProgressControl(8, 1); // HIDE } } else { m_version.SetWindowText(m_initdlg.GetVersion()); g_iCurDevNum = g_iDeviceNum; Sleep(FirstDelay); //GetInfo(); for(int i=0; i < NucUsb.WinUsbNumber; i++) { TRACE("Info_proc:idevice =%d\n",i); OneDeviceInfo(i); } } } #endif delete [] charPathName; delete pNewFont; return TRUE; // return TRUE unless you set the focus to a control } void CNuWriterDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CNuWriterDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CNuWriterDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CNuWriterDlg::OnBnClickedReconnect() { CDialog* mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); GetDlgItem(IDC_RECONNECT)->EnableWindow(FALSE); CString tempText; //COLORREF col = RGB(0xFF, 0x00, 0xFF); CString t_type; int i; m_gtype.GetWindowText(t_type); g_iDeviceNum = NucUsb.UsbDevice_Detect(); TRACE(_T("\n@@@@@ CNuWriterDlg::OnBnClickedReconnect, g_iDeviceNum =%d\n"), g_iDeviceNum); if(!g_iDeviceNum) { AfxMessageBox(_T("Error! No VCOM Port found.")); ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); g_iCurDevNum = 0; g_iDeviceNum = 0; if( !t_type.Compare(_T("Mass Production")) ) { FastMode_ProgressControl(8, 1); // HIDE } //AfxMessageBox(_T("Error! Please reset device and Re-connect now !!!\n")); return ; } else { ShowDeviceConnectState(1);//Connected if( !t_type.Compare(_T("Mass Production")) ) { FastMode_ProgressControl(8, 1); // HIDE } } //m_burntext.SetWindowText(tempText); //m_reconnect.setBitmapId(IDB_RECONNECT0, col); //m_reconnect.setGradient(true); #ifdef AUTO_DOWNLOAD m_initdlg.SetData(); m_initdlg.DoModal(); iDevice=0; if(m_initdlg.GetVersion() == _T("xxxx") || g_iDeviceNum == 0) { ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); g_iCurDevNum -= 1; g_iDeviceNum -= 1; if( !t_type.Compare(_T("Mass Production")) ) { FastMode_ProgressControl(8, 1); // HIDE } return; } else { m_version.SetWindowText(m_initdlg.GetVersion()); //GetInfo(); #if(1) TRACE("CNuWriterDlg::OnBnClickedReconnect:g_iDeviceNum =%d\n",g_iDeviceNum); for(i=0; i < g_iDeviceNum; i++) { OneDeviceInfo(i); } #endif g_iDeviceNum = NucUsb.WinUsbNumber; TRACE(_T("g_iDeviceNum = %d\n"), g_iDeviceNum); } #endif CString tmpstr; m_burntext.GetWindowText(tmpstr); //GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); if(m_gtype.GetCurSel()==0) /* SDRAM mode */ m_SubForms.GetSubForm(0)->PostMessage(WM_SDRAM_PROGRESS,(LPARAM)0,0); if( !t_type.Compare(_T("Mass Production")) ) { FastMode_ProgressControl(8, 1);// all HIDE FastMode_ProgressControl(g_iDeviceNum, 0);// show ((CComboBox*)mainWnd->GetDlgItem(IDC_COMBO_FAST_ID))->ResetContent(); for(i = 0; i < g_iDeviceNum; i++) { tempText.Format(_T("%d"),i); ((CComboBox*)mainWnd->GetDlgItem(IDC_COMBO_FAST_ID))->AddString(tempText); } ((CComboBox*)mainWnd->GetDlgItem(IDC_COMBO_FAST_ID))->SetCurSel(0); mainWnd->GetDlgItem(IDC_BTN_FAST_START)->EnableWindow(TRUE); } } void CNuWriterDlg::OnDestroy() { CDialog::OnDestroy(); INItoSaveOrLoad(SAVE); //TRACE(_T("CNuWriterDlg::OnDestroy() CNuWriterDlg::OnDestroy() CNuWriterDlg::OnDestroy() CNuWriterDlg::OnDestroy()")); } BYTE CNuWriterDlg::Str2Hex(CString strSource) { BYTE num; char *str; CStringA strA(strSource.GetBuffer(0)); strSource.ReleaseBuffer(); string s = strA.GetBuffer(0); const char* pc = s.c_str(); num = (int)strtol(pc, &str, 16); return num; } void CNuWriterDlg::INItoSaveOrLoad(int Flag) { if(!m_inifile.ReadFile()) //Fail return; CString idx; memset((char *)&m_info,0xff,sizeof(INFO_T)); if(Flag==LOAD) { #if 0 idx=m_inifile.GetValue(_T("DEFAULT"),_T("PAGE_IDX")); if(!idx.IsEmpty()) m_gtype.SetCurSel(_wtoi(idx)); #endif page_idx = _wtoi(m_inifile.GetValue(_T("DEFAULT"),_T("PAGE_IDX"))); TargetChip=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("CHIP"))); DDR_Idx=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("DDR"))); DDRAddress=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("DDRADDRESS"))); TimeEn=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("TimeEnable"))); Timeus=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("Timeus"))); ChipEraseWithBad=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("ChipEraseWithBad"))); ChipReadWithBad=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("ChipReadWithBad"))); ChipWriteWithOOB=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("ChipWriteWithOOB"))); DtbEn=_wtoi(m_inifile.GetValue(_T("SDRAM"),_T("DTBEN"))); FirstDelay=_wtoi(m_inifile.GetValue(_T("TARGET"),_T("FirstDelay"))); Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); //memset((char *)&m_info,0xff,sizeof(INFO_T)); m_info.SPI_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("QuadReadCmd"))); m_info.SPI_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("ReadStatusCmd"))); m_info.SPI_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("WriteStatusCmd"))); m_info.SPI_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("dummybyte"))); m_info.SPI_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("StatusValue"))); //(char*)(LPCTSTR)strSource m_info.SPINand_PageSize = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PageSize"))); m_info.SPINand_SpareArea = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("SpareArea"))); m_info.SPINand_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"))); m_info.SPINand_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); m_info.SPINand_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); m_info.SPINand_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); m_info.SPINand_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); //m_info.SPINand_ReadStatusCmd = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); //m_info.SPINand_WriteStatusCmd = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); //m_info.SPINand_dummybyte = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); //m_info.SPINand_StatusValue = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); if(Timeus==0) Timeus=5000; } else if(Flag==SAVE) { #if 0 idx.Format(_T("%d"),m_gtype.GetCurSel()); m_inifile.SetValue(_T("DEFAULT"),_T("PAGE_IDX"),idx); m_inifile.WriteFile(); #endif idx.Format(_T("%d"),TargetChip); m_inifile.SetValue(_T("TARGET"),_T("CHIP"),idx); idx.Format(_T("%d"),DDR_Idx); m_inifile.SetValue(_T("TARGET"),_T("DDR"),idx); idx.Format(_T("%d"),TimeEn); m_inifile.SetValue(_T("TARGET"),_T("TimeEnable"),idx); idx.Format(_T("%d"),Timeus); m_inifile.SetValue(_T("TARGET"),_T("Timeus"),idx); idx.Format(_T("%d"),m_gtype.GetCurSel()); m_inifile.SetValue(_T("DEFAULT"),_T("PAGE_IDX"),idx); m_inifile.WriteFile(); } } void CNuWriterDlg::UpdateBufForDDR() { LoadDDRInit(DDRFileFullPath,&DDRLen); } //char * CNuWriterDlg::LoadDDRInit(CString pathName,int *len) void CNuWriterDlg::LoadDDRInit(CString pathName,int *len) { ifstream Read; int length,tmpbuf_size; char *ptmpbuf,*ptmp,tmp[256],cvt[128]; unsigned int * puint32_t; Read.open(pathName,ios::binary | ios::in); if(!Read.is_open()) AfxMessageBox(_T("Error! Open DDR initial file error\n")); Read.seekg (0, Read.end); length=(int)Read.tellg(); ptmpbuf=(char *)malloc(sizeof(char)*length); //TRACE(_T("LoadDDRInit --> length = %d\n"), length); Read.seekg(0,Read.beg); unsigned int val=0; puint32_t=(unsigned int *)ptmpbuf; tmpbuf_size=0; while(!Read.eof()) { Read.getline(tmp,256); ptmp=strchr(tmp,'='); if(ptmp==NULL) { AfxMessageBox(_T("Error! DDR initial format error\n")); break; } strncpy(cvt,tmp,(unsigned int)ptmp-(unsigned int)tmp); cvt[(unsigned int)ptmp-(unsigned int)tmp]='\0'; val=strtoul(cvt,NULL,0); *puint32_t=val; puint32_t++; tmpbuf_size+=sizeof(unsigned int *); strncpy(cvt,++ptmp,strlen(ptmp)); cvt[strlen(ptmp)]='\0'; val=strtoul(cvt,NULL,0); *puint32_t=val; puint32_t++; tmpbuf_size+=sizeof(unsigned int *); } Read.close(); #if 0 //for test ofstream Write; Write.open("C:\\tmp.bin",ios::binary | ios::out); Write.write(ptmpbuf,tmpbuf_size); Write.close(); #endif TRACE(_T("ptmpbuf[0~3] = 0x%x 0x%x 0x%x 0x%x\n"), ptmpbuf[0], ptmpbuf[1], ptmpbuf[2], ptmpbuf[3]); if(((ptmpbuf[0]&0xff) == 0) && ((ptmpbuf[1]&0xff) == 0) && ((ptmpbuf[2]&0xff) == 0) && ((ptmpbuf[3]&0xff) == 0xB0)) { *len=(tmpbuf_size-8);// ddr version 8 byte DDRFileVer.Format(_T("V%d.0"), ptmpbuf[4]); memcpy((char *)ShareDDRBuf, ptmpbuf+8, *len); } else { *len=tmpbuf_size; DDRFileVer.Format(_T("No version")); memcpy((char *)ShareDDRBuf, ptmpbuf, *len); } free(ptmpbuf); return ; } void CNuWriterDlg::GetExeDir(CString & path) { wchar_t szDir[MAX_PATH]; GetModuleFileName(NULL,szDir,MAX_PATH); wchar_t drive[_MAX_DRIVE]; wchar_t dir[_MAX_DIR]; _wsplitpath(szDir, drive, dir, NULL,NULL); CString strPath; path.Format(_T("%s%s"), drive, dir); } HBRUSH CNuWriterDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (pWnd->GetDlgCtrlID() == IDC_COMPORT) { CString word; GetDlgItem(IDC_COMPORT)->GetWindowText(word); if(!word.Compare(_T(" Disconnected"))) pDC->SetTextColor(RGB(255,0,0)); else pDC->SetTextColor(RGB(0,0,0)); } return hbr; } void CNuWriterDlg::LoadDirINI(CString szDir,wchar_t * pext, vector<CString> &sList) // Dir 就是你要掃瞄的目錄, sList 拿來存放檔名 { //pext=".ini" WIN32_FIND_DATA filedata; // Structure for file data HANDLE filehandle; // Handle for searching CString szFileName,szFileFullPath; wchar_t filename[_MAX_FNAME]; wchar_t ext[_MAX_EXT]; //szDir = IncludeTrailingPathDelimiter(Dir); filehandle = FindFirstFile((szDir + _T("*.*")).GetBuffer(0), &filedata); if (filehandle != INVALID_HANDLE_VALUE) { do { if ((filedata.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0 || lstrcmp(filedata.cFileName, _T(".")) == 0 || lstrcmp(filedata.cFileName, _T("..")) == 0) continue; if ((filedata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { szFileFullPath = szDir + filedata.cFileName; LoadDirINI(szFileFullPath,pext,sList); } else { szFileFullPath = szDir + filedata.cFileName; _wsplitpath(szFileFullPath, NULL, NULL, filename,ext); if(lstrcmp(ext,pext)==0) { szFileName.Format(_T("%s%s"),filename,ext); sList.push_back(szFileName); } } } while (FindNextFile(filehandle, &filedata)); FindClose(filehandle); } } void CNuWriterDlg::OnCbnSelchangeComboType() { CString title; int i = 0; m_gtype.GetWindowText(title); m_type.SetWindowText(title); m_SubForms.ShowSubForm(m_gtype.GetCurSel()); CString t_type, str; //Default //m_info.Nand_uIsUserConfig = 0; //m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; //m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; m_gtype.GetWindowText(t_type); if( !t_type.Compare(_T("NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); CString tmp; unsigned int val=m_info.Nand_uPagePerBlock * m_info.Nand_uPageSize; if(val==0 || val>0x800000) { tmp.Format(_T("Alignment : N/A")); Nand_size.Format(_T("N/A")); } else { tmp.Format(_T("Alignment : 0x%x"),val); Nand_size.Format(_T("0x%x"),val); } ((CNANDDlg *)mainWnd)->m_status.SetWindowText(tmp); if(m_info.Nand_uBlockPerFlash == 1023) m_info.Nand_uBlockPerFlash = 1024; else if(m_info.Nand_uBlockPerFlash == 2047) m_info.Nand_uBlockPerFlash = 2048; else if(m_info.Nand_uBlockPerFlash == 4095) m_info.Nand_uBlockPerFlash = 4096; else if(m_info.Nand_uBlockPerFlash == 8191) m_info.Nand_uBlockPerFlash = 8192; if(((CNANDDlg *)mainWnd)->m_nandflash_check.GetCheck()!=TRUE) // Auto Detect { m_info.Nand_uIsUserConfig = 0; str.Format(_T("%d"), m_info.Nand_uBlockPerFlash); m_inifile.SetValue(_T("NAND_INFO"),_T("uBlockPerFlash"),str); m_inifile.WriteFile(); str.Format(_T("%d"), m_info.Nand_uPagePerBlock); m_inifile.SetValue(_T("NAND_INFO"),_T("uPagePerBlock"),str); m_inifile.WriteFile(); } else // User Config { m_info.Nand_uIsUserConfig = 1; m_info.Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); str.Format(_T("%d"), m_info.Nand_uBlockPerFlash); m_inifile.SetValue(_T("NAND_INFO"),_T("uBlockPerFlash"),str); m_inifile.WriteFile(); m_info.Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); str.Format(_T("%d"), m_info.Nand_uPagePerBlock); m_inifile.SetValue(_T("NAND_INFO"),_T("uPagePerBlock"),str); m_inifile.WriteFile(); } } if( !t_type.Compare(_T("SPI")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if( !t_type.Compare(_T("SPI")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CSPIDlg *)mainWnd)->m_spinor_check.GetCheck()!=TRUE) { m_info.SPI_uIsUserConfig = 0; } else { m_info.SPI_uIsUserConfig = 1; } } } if( !t_type.Compare(_T("SPI NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); CString tmp; unsigned int val= m_info.SPINand_PagePerBlock * m_info.SPINand_PageSize; if(val==0 || val>0x800000) { tmp.Format(_T("Alignment : N/A")); SPINand_size.Format(_T("N/A")); } else { tmp.Format(_T("Alignment : 0x%x"),val); SPINand_size.Format(_T("0x%x"),val); } ((CSPINandDlg *)mainWnd)->m_status.SetWindowText(tmp); if( !t_type.Compare(_T("SPI NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CSPINandDlg *)mainWnd)->m_spinandflash_check.GetCheck()!=TRUE) { m_info.SPINand_uIsUserConfig = 0; // m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); // m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); } else { m_info.SPINand_uIsUserConfig = 1; // m_info.SPINand_PageSize = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PageSize"))); // m_info.SPINand_SpareArea = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("SpareArea"))); // m_info.SPINand_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"))); // m_info.SPINand_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); // m_info.SPINand_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); // m_info.SPINand_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); // m_info.SPINand_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); // m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); // m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); } } } if( !t_type.Compare(_T("PACK")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); unsigned int val=m_info.Nand_uPagePerBlock * m_info.Nand_uPageSize; CString tmp; if(val==0 || val>0x2000000) tmp.Format(_T("Alignment : SPI(0x1000)/eMMC(0x200)/NAND(n/a)")); else tmp.Format(_T("Alignment : SPI(0x1000)/eMMC(0x200)/NAND(0x%x)"),val); ((CPACKDlg *)mainWnd)->m_status.SetWindowText(tmp); } if( !t_type.Compare(_T("eMMC")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); CString tmp; int val=m_info.EMMC_uReserved * 0x200; if(val<=0) tmp.Format(_T("Alignment : 0x200, Reserved Size : N/A"),val); else tmp.Format(_T("Alignment : 0x200, Reserved Size : 0x%x"),val); ((CMMCDlg *)mainWnd)->m_status.SetWindowText(tmp); } if( !t_type.Compare(_T("Mass Production")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(m_info.Nand_uBlockPerFlash == 1023) m_info.Nand_uBlockPerFlash = 1024; else if(m_info.Nand_uBlockPerFlash == 2047) m_info.Nand_uBlockPerFlash = 2048; else if(m_info.Nand_uBlockPerFlash == 4095) m_info.Nand_uBlockPerFlash = 4096; else if(m_info.Nand_uBlockPerFlash == 8191) m_info.Nand_uBlockPerFlash = 8192; if(((FastDlg *)mainWnd)->m_nandflashInfo_check.GetCheck()!=TRUE) // Auto Detect { m_info.Nand_uIsUserConfig = 0; str.Format(_T("%d"), m_info.Nand_uBlockPerFlash); m_inifile.SetValue(_T("NAND_INFO"),_T("uBlockPerFlash"),str); m_inifile.WriteFile(); str.Format(_T("%d"), m_info.Nand_uPagePerBlock); m_inifile.SetValue(_T("NAND_INFO"),_T("uPagePerBlock"),str); m_inifile.WriteFile(); } else // User Config { m_info.Nand_uIsUserConfig = 1; m_info.Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); str.Format(_T("%d"), m_info.Nand_uBlockPerFlash); m_inifile.SetValue(_T("NAND_INFO"),_T("uBlockPerFlash"),str); m_inifile.WriteFile(); m_info.Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); str.Format(_T("%d"), m_info.Nand_uPagePerBlock); m_inifile.SetValue(_T("NAND_INFO"),_T("uPagePerBlock"),str); m_inifile.WriteFile(); } if(((FastDlg *)mainWnd)->m_spinor_check.GetCheck()!=TRUE) { m_info.SPI_uIsUserConfig = 0; } else // User Config { m_info.SPI_uIsUserConfig = 1; } if(((FastDlg *)mainWnd)->m_spinandflashInfo_check.GetCheck()!=TRUE) { m_info.SPINand_uIsUserConfig = 0; } else // User Config { m_info.SPINand_uIsUserConfig = 1; } for(i=0; i< NucUsb.WinUsbNumber; i++) { ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+i)))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_DEV1+i)))->ShowWindow(SW_SHOW); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->SetRange(0,100); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + i))->SetPos(0); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+i)))->SetWindowText(_T("")); } } } void CNuWriterDlg::OneSelchangeComboType(int id) { CString title; m_gtype.GetWindowText(title); m_type.SetWindowText(title); m_SubForms.ShowSubForm(m_gtype.GetCurSel()); CString t_type; m_gtype.GetWindowText(t_type); if( !t_type.Compare(_T("Mass Production")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + id))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+id)))->ShowWindow(SW_SHOW); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_DEV1+id)))->ShowWindow(SW_SHOW); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + id))->SetRange(0,100); ((CProgressCtrl *)mainWnd->GetDlgItem(IDC_FAST_PROGRESS1 + id))->SetPos(0); ((CStatic *)mainWnd->GetDlgItem((IDC_STATIC_FAST_MSG1+id)))->SetWindowText(_T("")); } } int CNuWriterDlg::Read_File_Line(HANDLE hFile) { DWORD i, nBytesRead; char data_byte; BOOL bResult; for (i = 0; i < LINE_BUFF_LEN; i++) { bResult = ReadFile(hFile, (LPVOID)&data_byte, 1, &nBytesRead, NULL); if (bResult && nBytesRead == 0) { if (i == 0) { return -1; } else { _FileLineBuff[i] = 0; return 0; } } if ((data_byte == '\n') || (data_byte == '\r')) break; _FileLineBuff[i] = data_byte; } _FileLineBuff[i] = 0; while (1) { bResult = ReadFile(hFile, (LPVOID)&data_byte, 1, &nBytesRead, NULL); if (bResult && nBytesRead == 0) return 0; if ((data_byte != '\n') && (data_byte != '\r')) break; } SetFilePointer(hFile, -1, NULL, FILE_CURRENT); return 0; } void CNuWriterDlg::OnShowWindow(BOOL bShow, UINT nStatus) { CDialog::OnShowWindow(bShow, nStatus); // TODO: Add your message handler code here m_gtype.SetFocus(); } BOOL CNuWriterDlg:: Info() { BOOL bResult; bResult = NucUsb.EnableWinUsbDevice(); if(!bResult) { //AfxMessageBox(_T("CNuWriterDlg:: Info(): Device Enable error\n")); //AfxMessageBox(_T("Error! Please reset device and Re-connect now !!!\n")); return FALSE; } #if(0) bResult=NucUsb.NUC_CheckFw(0); ResetEvent(m_ExitEvent[0]); if(bResult==FALSE) { AfxMessageBox(_T("Error! Please reset device and Re-connect now !!!\n")); return FALSE; } #endif USHORT typeack; bResult=NucUsb.NUC_SetType(0,INFO,(UCHAR *)&typeack,sizeof(typeack)); if(bResult==FALSE) { NucUsb.NUC_CloseHandle(); return FALSE; } #if(1) CString t_type; m_gtype.GetWindowText(t_type); if( !t_type.Compare(_T("NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CNANDDlg *)mainWnd)->m_nandflash_check.GetCheck()!=TRUE) { m_info.Nand_uIsUserConfig = 0; m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; } else { m_info.Nand_uIsUserConfig = 1; m_info.Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); m_info.Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); } TRACE(_T("Info: BlockPerFlash =%d, PagePerBlock = %d\n"), m_info.Nand_uBlockPerFlash, m_info.Nand_uPagePerBlock); } m_gtype.GetWindowText(t_type); if( !t_type.Compare(_T("SPI NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CSPINandDlg *)mainWnd)->m_spinandflash_check.GetCheck()!=TRUE) { m_info.SPINand_uIsUserConfig = 0; // m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); // m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); } else { m_info.SPINand_uIsUserConfig = 1; // m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); // m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); m_info.SPINand_PageSize = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PageSize"))); m_info.SPINand_SpareArea = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("SpareArea"))); m_info.SPINand_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"))); m_info.SPINand_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); m_info.SPINand_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); m_info.SPINand_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); m_info.SPINand_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); } TRACE(_T("Info: BlockPerFlash =%d, PagePerBlock = %d\n"), m_info.Nand_uBlockPerFlash, m_info.Nand_uPagePerBlock); } #endif //m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; //m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; bResult=NucUsb.NUC_WritePipe(0,(UCHAR *)&m_info, sizeof(INFO_T)); if(WaitForSingleObject(m_ExitEvent, 0) != WAIT_TIMEOUT) bResult=FALSE; if(bResult!=TRUE) bResult=FALSE; bResult=NucUsb.NUC_ReadPipe(0,(UCHAR *)&m_info, sizeof(INFO_T)); if(WaitForSingleObject(m_ExitEvent, 0) != WAIT_TIMEOUT) bResult=FALSE; if(bResult!=TRUE) bResult=FALSE; NucUsb.NUC_CloseHandle(); OnCbnSelchangeComboType(); return bResult; } BOOL CNuWriterDlg::OneDeviceInfo(int id) { BOOL bResult, bRet; int count=0; CString tmp; unsigned int ack; //TRACE(_T("\n@@@@@(%d) CNuWriterDlg::OneDeviceInfo\n"), id); ResetEvent(m_ExitEvent[id]); bRet = FALSE; for(count =0; count < RETRYCNT; count++) { //TRACE(_T("@@@@@ (%d) OneDeviceInfo Retry %d\n"), id, count); bResult=NucUsb.EnableOneWinUsbDevice(id); //TRACE(_T("@@@@@ (%d) bResult %d\n\n"), id, bResult); if(!bResult) { //TRACE(_T("@@@@@ !!!!! Start (%d) bResult %d\n"), id, bResult); bResult=NucUsb.EnableOneWinUsbDevice(id); //TRACE(_T("@@@@@ !!!!! End (%d) bResult %d\n"), id, bResult); if(bResult == FALSE) { bResult =NucUsb.NUC_ResetFW(id); TRACE(_T("@@@@@ (%d) RESET NUC980 \n"), id); Sleep(100);//for Mass production if(bResult == FALSE) { TRACE(_T("@@@@@ XXXX (%d) RESET NUC980 failed\n"), id); continue; } else { bRet = TRUE; //GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); break; } Sleep(200);//for Mass production bResult = FWDownload(id); //TRACE(_T("@@@@@ (%d) FWDownload NUC980 \n"), id); Sleep(200);//for Mass production if(bResult == FALSE) { TRACE(_T("@@@@@ XXXX (%d) Download FW failed\n"), id); continue; } } else { bRet = TRUE; break; } } else { bRet = TRUE; //GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); break; } } if(bRet == FALSE) // Retry Fail { TRACE(_T("@@@@@ XXX (%d) EnableOneWinUsbDevice RETRY ERROR\n"), id); NucUsb.CloseWinUsbDevice(id); ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); //AfxMessageBox(_T("Error! Please reset device and Re-connect now !!!\n")); return FALSE; } #if(0) bResult=NucUsb.NUC_CheckFw(id); ResetEvent(m_ExitEvent[id]); if(bResult==FALSE) { AfxMessageBox(_T("Error! Please reset device and Re-connect now !!!\n")); return FALSE; } #endif USHORT typeack; bResult=NucUsb.NUC_SetType(id,INFO,(UCHAR *)&typeack,sizeof(typeack)); if(bResult==FALSE) { NucUsb.CloseWinUsbDevice(id); ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); return FALSE; } #if(1) CString t_type; m_gtype.GetWindowText(t_type); //Default m_info.Nand_uIsUserConfig = 0; m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; if( !t_type.Compare(_T("NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CNANDDlg *)mainWnd)->m_nandflash_check.GetCheck()!=TRUE) { m_info.Nand_uIsUserConfig = 0; m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; } else { m_info.Nand_uIsUserConfig = 1; m_info.Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); m_info.Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); } //TRACE(_T("OneDeviceInfo: IsUserConfig =%d, BlockPerFlash =%d, PagePerBlock = %d\n"), m_info.Nand_uIsUserConfig, m_info.Nand_uBlockPerFlash, m_info.Nand_uPagePerBlock); } if( !t_type.Compare(_T("SPI")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CSPIDlg *)mainWnd)->m_spinor_check.GetCheck()!=TRUE) { m_info.SPI_uIsUserConfig = 0; } else { m_info.SPI_uIsUserConfig = 1; m_info.SPI_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("QuadReadCmd"))); m_info.SPI_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("ReadStatusCmd"))); m_info.SPI_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("WriteStatusCmd"))); m_info.SPI_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("StatusValue"))); m_info.SPI_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("dummybyte"))); } } if( !t_type.Compare(_T("SPI NAND")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((CSPINandDlg *)mainWnd)->m_spinandflash_check.GetCheck()!=TRUE) { m_info.SPINand_uIsUserConfig = 0; // m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); // m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); } else { m_info.SPINand_uIsUserConfig = 1; m_info.SPINand_PageSize = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PageSize"))); m_info.SPINand_SpareArea = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("SpareArea"))); m_info.SPINand_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"))); m_info.SPINand_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); m_info.SPINand_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); m_info.SPINand_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); m_info.SPINand_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); } //TRACE(_T("OneDeviceInfo: IsUserConfig =%d, BlockPerFlash =%d, PagePerBlock = %d\n"), m_info.SPINand_uIsUserConfig, m_info.SPINand_BlockPerFlash, m_info.SPINand_PagePerBlock); } if( !t_type.Compare(_T("Mass Production")) ) { CDialog * mainWnd=m_SubForms.GetSubForm(m_gtype.GetCurSel()); if(((FastDlg *)mainWnd)->m_nandflashInfo_check.GetCheck()!=TRUE) // Auto Detect { m_info.Nand_uIsUserConfig = 0; m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; } else // User Config { m_info.Nand_uIsUserConfig = 1; m_info.Nand_uPagePerBlock=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uPagePerBlock"))); m_info.Nand_uBlockPerFlash=_wtoi(m_inifile.GetValue(_T("NAND_INFO"),_T("uBlockPerFlash"))); } if(((FastDlg *)mainWnd)->m_spinor_check.GetCheck()!=TRUE) { m_info.SPI_uIsUserConfig = 0; } else { m_info.SPI_uIsUserConfig = 1; m_info.SPI_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("QuadReadCmd"))); m_info.SPI_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("ReadStatusCmd"))); m_info.SPI_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("WriteStatusCmd"))); m_info.SPI_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("StatusValue"))); m_info.SPI_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPI_INFO"),_T("dummybyte"))); } if(((FastDlg *)mainWnd)->m_spinandflashInfo_check.GetCheck()!=TRUE) // Auto Detect { m_info.SPINand_uIsUserConfig = 0; } else // User Config { m_info.SPINand_uIsUserConfig = 1; m_info.SPINand_PageSize = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PageSize"))); m_info.SPINand_SpareArea = _wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("SpareArea"))); m_info.SPINand_QuadReadCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"))); m_info.SPINand_ReadStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"))); m_info.SPINand_WriteStatusCmd = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"))); m_info.SPINand_dummybyte = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("dummybyte"))); m_info.SPINand_StatusValue = Str2Hex(m_inifile.GetValue(_T("SPINAND_INFO"),_T("StatusValue"))); m_info.SPINand_BlockPerFlash=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"))); m_info.SPINand_PagePerBlock=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("PagePerBlock"))); m_info.SPINand_IsDieSelect=_wtoi(m_inifile.GetValue(_T("SPINAND_INFO"),_T("MultiChip"))); } //TRACE(_T("OneDeviceInfo: IsUserConfig =%d, BlockPerFlash =%d, PagePerBlock = %d\n"), m_info.Nand_uIsUserConfig, m_info.Nand_uBlockPerFlash, m_info.Nand_uPagePerBlock); } #endif //m_info.Nand_uPagePerBlock = Nand_uPagePerBlock; //m_info.Nand_uBlockPerFlash = Nand_uBlockPerFlash; bResult=NucUsb.NUC_WritePipe(id,(UCHAR *)&m_info, sizeof(INFO_T)); if(WaitForSingleObject(m_ExitEvent[id], 0) != WAIT_TIMEOUT) bResult=FALSE; if(bResult==FALSE) { TRACE(_T("XXXX Error NUC_WritePipe: %d.\n"), GetLastError()); //return FALSE; } Sleep(500);// Delay for emmc INFO complete bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&m_info, sizeof(INFO_T)); if(WaitForSingleObject(m_ExitEvent[id], 0) != WAIT_TIMEOUT) bResult=FALSE; if(bResult==FALSE) { TRACE(_T("XXXX Error NUC_ReadPipe: %d.\n"), GetLastError()); //return FALSE; } tmp.Format(_T("%x"),m_info.SPI_QuadReadCmd); m_inifile.SetValue(_T("SPI_INFO"),_T("QuadReadCmd"), tmp); tmp.Format(_T("%x"),m_info.SPI_ReadStatusCmd); m_inifile.SetValue(_T("SPI_INFO"),_T("ReadStatusCmd"), tmp); tmp.Format(_T("%x"),m_info.SPI_WriteStatusCmd); m_inifile.SetValue(_T("SPI_INFO"),_T("WriteStatusCmd"), tmp); tmp.Format(_T("%x"),m_info.SPI_StatusValue); m_inifile.SetValue(_T("SPI_INFO"),_T("StatusValue"), tmp); tmp.Format(_T("%x"),m_info.SPI_dummybyte); m_inifile.SetValue(_T("SPI_INFO"),_T("dummybyte"), tmp); tmp.Format(_T("%d"),m_info.SPINand_PageSize); m_inifile.SetValue(_T("SPINAND_INFO"),_T("PageSize"), tmp); tmp.Format(_T("%d"),m_info.SPINand_SpareArea); m_inifile.SetValue(_T("SPINAND_INFO"),_T("SpareArea"), tmp); tmp.Format(_T("%x"),m_info.SPINand_QuadReadCmd); m_inifile.SetValue(_T("SPINAND_INFO"),_T("QuadReadCmd"), tmp); tmp.Format(_T("%x"),m_info.SPINand_ReadStatusCmd); m_inifile.SetValue(_T("SPINAND_INFO"),_T("ReadStatusCmd"), tmp); tmp.Format(_T("%x"),m_info.SPINand_WriteStatusCmd); m_inifile.SetValue(_T("SPINAND_INFO"),_T("WriteStatusCmd"), tmp); tmp.Format(_T("%x"),m_info.SPINand_dummybyte); m_inifile.SetValue(_T("SPINAND_INFO"),_T("dummybyte"), tmp); tmp.Format(_T("%x"),m_info.SPINand_StatusValue); m_inifile.SetValue(_T("SPINAND_INFO"),_T("StatusValue"), tmp); tmp.Format(_T("%d"),m_info.SPINand_BlockPerFlash); m_inifile.SetValue(_T("SPINAND_INFO"),_T("BlockPerFlash"), tmp); tmp.Format(_T("%d"),m_info.SPINand_PagePerBlock); m_inifile.SetValue(_T("SPINAND_INFO"),_T("PagePerBlock"), tmp); tmp.Format(_T("%d"),m_info.SPINand_IsDieSelect); m_inifile.SetValue(_T("SPINAND_INFO"),_T("MultiChip"), tmp); tmp.Format(_T("%d"),m_info.SPINand_IsDieSelect); m_inifile.WriteFile(); bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); TRACE(_T("(%d) bResult=%d, ack=0x%x\n"), id, bResult, ack); if(bResult==FALSE || ack!=0x90) { bResult=FALSE; } NucUsb.CloseWinUsbDevice(id); OnCbnSelchangeComboType(); GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); if(bResult==FALSE) { ShowDeviceConnectState(0);//Disconnected } return bResult; } unsigned WINAPI CNuWriterDlg::Info_proc(void* args) { CNuWriterDlg* pThis = reinterpret_cast<CNuWriterDlg*>(args); #if(0) int time[]= {100,200,300,400,500}; for(int i=0; i<sizeof(time)/sizeof(int); i++) { //if(pThis->Info()==TRUE) break; if(pThis->g_iDeviceNum < NucUsb.WinUsbNumber) { TRACE("Info_proc:idevice =%d\n",pThis->iDevice); pThis->OneDeviceInfo(pThis->iDevice++); } Sleep(time[i]); } #else TRACE("Info_proc:: %d %d\n",pThis->g_iDeviceNum, NucUsb.WinUsbNumber); //if(pThis->g_iDeviceNum < NucUsb.WinUsbNumber) { //if(pThis->iDevice <= pThis->g_iDeviceNum) { for(int i=0; i < NucUsb.WinUsbNumber; i++) { TRACE("Info_proc:idevice =%d\n",pThis->iDevice); pThis->OneDeviceInfo(pThis->iDevice++); } #endif return 0; } void CNuWriterDlg::GetInfo() { unsigned Thread1; HANDLE hThread; hThread=(HANDLE)_beginthreadex(NULL,0,Info_proc,(void*)this,0,&Thread1); } BOOL CNuWriterDlg:: FWDownload(int id) { int i=0; TCHAR path[MAX_PATH]; GetModuleFileName(NULL, path, MAX_PATH); CString temp=path; CNuWriterDlg* mainWnd=(CNuWriterDlg*)(AfxGetApp()->m_pMainWnd); BOOL bResult=1; COLORREF col = RGB(0xFF, 0x00, 0xFF); m_reconnect.setBitmapId(IDB_RECONNECT0, col); m_reconnect.setGradient(true); m_exit.setBitmapId(IDB_EXIT, col); m_exit.setGradient(true); temp = temp.Left(temp.ReverseFind('\\') + 1); CString filename=NULL; switch(mainWnd->DDRFileName.GetAt(8)) { case '5': filename.Format(_T("%sxusb.bin"),temp); break; case '6': filename.Format(_T("%sxusb64.bin"),temp); break; case '7': filename.Format(_T("%sxusb128.bin"),temp); break; default: filename.Format(_T("%sxusb16.bin"),temp); break; }; bResult = XUSB(id, filename); if(!bResult) { ShowDeviceConnectState(0);//Disconnected GetDlgItem(IDC_RECONNECT)->EnableWindow(TRUE); NucUsb.CloseWinUsbDevice(id); } return bResult; } DWORD GetFWRamAddress(FILE* fp) { BINHEADER head; UCHAR SIGNATURE[]= {'W','B',0x5A,0xA5}; fread((CHAR*)&head,sizeof(head),1,fp); if(head.signature==*(DWORD*)SIGNATURE) { return head.address; } else return 0xFFFFFFFF; } BOOL CNuWriterDlg::DDRtoDevice(int id, char *buf,unsigned int len) { BOOL bResult; char *pbuf; unsigned int scnt,rcnt,ack; AUTOTYPEHEAD head; head.address=DDRAddress; // 0x10 head.filelen=len; // *.ini length = 384 //TRACE(_T("(%d) 0x%x, %d\n"), id, head.address, head.filelen); bResult=NucUsb.NUC_WritePipe(id,(unsigned char*)&head,sizeof(AUTOTYPEHEAD)); if(bResult==FALSE) { TRACE(_T("XXX (%d) CNuWriterDlg::DDRtoDevice error. 0x%x\n"), id, GetLastError()); goto failed; } Sleep(5); pbuf=buf; scnt=len/BUF_SIZE; rcnt=len%BUF_SIZE; while(scnt>0) { bResult=NucUsb.NUC_WritePipe(id,(UCHAR *)pbuf,BUF_SIZE); if(bResult==TRUE) { bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); if(bResult==FALSE || (int)ack==(BUF_SIZE+1)) { if(bResult==TRUE && (int)ack==(BUF_SIZE+1)) { // xub.bin is running on device NucUsb.CloseWinUsbDevice(id); return FW_CODE; } else goto failed; } } else { NucUsb.CloseWinUsbDevice(id); //TRACE(_T("(%d) DDRtoDevice scnt%d error! 0x%x\n"), id, scnt, GetLastError()); return FALSE; } scnt--; pbuf+=BUF_SIZE; } if(rcnt>0) { bResult=NucUsb.NUC_WritePipe(id,(UCHAR *)pbuf,rcnt); if(bResult==TRUE) { bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); if(bResult==FALSE || (int)ack==(BUF_SIZE+1)) { if(bResult==TRUE && (int)ack==(BUF_SIZE+1)) { // xub.bin is running on device NucUsb.CloseWinUsbDevice(id); return FW_CODE; } else goto failed; } } else { NucUsb.CloseWinUsbDevice(id); //TRACE(_T("XXX (%d) DDRtoDevice rcnt%d error! 0x%x\n"), id, rcnt, GetLastError()); return FALSE; } } bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); if(bResult==TRUE && ack==0x55AA55AA) return TRUE; failed: NucUsb.CloseWinUsbDevice(id); return FALSE; } // FW bin download BOOL CNuWriterDlg::XUSB(int id, CString& m_BinName) { BOOL bResult; CString posstr, str; CString tempstr; int count=0; FILE* fp; int pos=0; AUTOTYPEHEAD fhead; XBINHEAD xbinhead; // 16bytes for IBR using DWORD version; unsigned int total,file_len,scnt,rcnt,ack; /***********************************************/ //TRACE(_T("CNuWriterDlg::XUSB (%d), %s\n"), id, m_BinName); bResult=NucUsb.EnableOneWinUsbDevice(id); if(!bResult) { TRACE(_T("XXX (%d) NuWriterDlg.cpp XUSB Device Open error\n"),id); //AfxMessageBox(str); return FALSE; } int fw_flag[8]; fw_flag[id]=DDRtoDevice(id, ShareDDRBuf,DDRLen); if(fw_flag[id]==FALSE) { NucUsb.WinUsbNumber -= 1; NucUsb.CloseWinUsbDevice(id); return FALSE; } ULONG cbSize = 0; unsigned char* lpBuffer = new unsigned char[BUF_SIZE]; fp=_wfopen(m_BinName,_T("rb")); if(!fp) { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); AfxMessageBox(_T("Error! Bin File Open error\n")); //TRACE(_T("XXX Bin File Open error\n")); return FALSE; } fread((char*)&xbinhead,sizeof(XBINHEAD),1,fp); version=xbinhead.version; if(fw_flag[id]==FW_CODE) { fclose(fp); delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); return TRUE; } //Get File Length fseek(fp,0,SEEK_END); file_len=ftell(fp)-sizeof(XBINHEAD); fseek(fp,0,SEEK_SET); if(!file_len) { fclose(fp); delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); TRACE(_T("Error! File length is zero\n")); return FALSE; } fhead.filelen = file_len; fhead.address = GetFWRamAddress(fp);//0x8000; if(fhead.address==0xFFFFFFFF) { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); TRACE(_T("Error! Invalid Image.\n")); return FALSE; } memcpy(lpBuffer,(unsigned char*)&fhead,sizeof(fhead)); // 8 bytes bResult=NucUsb.NUC_WritePipe(id,(unsigned char*)&fhead,sizeof(fhead)); if(bResult==FALSE) { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); return FALSE; } scnt=file_len/BUF_SIZE; rcnt=file_len%BUF_SIZE; total=0; //TRACE(_T("(%d) FW scnt %d rcnt = %d\n"), id, scnt, rcnt); while(scnt>0) { fread(lpBuffer,BUF_SIZE,1,fp); bResult=NucUsb.NUC_WritePipe(id,lpBuffer,BUF_SIZE); if(bResult==TRUE) { total+=BUF_SIZE; scnt--; bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); if(bResult==FALSE || (int)ack!=BUF_SIZE) { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); if(bResult==TRUE && (int)ack==(BUF_SIZE+1)) { // xub.bin is running on device return TRUE; } else return FALSE; } } else { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); //TRACE(_T("XXX (%d) FW scnt error. 0x%x\n"), id, GetLastError()); return FALSE; } } memset(lpBuffer,0x0,BUF_SIZE); if(rcnt>0) { fread(lpBuffer,rcnt,1,fp); bResult=NucUsb.NUC_WritePipe(id,lpBuffer,BUF_SIZE); if(bResult==TRUE) { total+=rcnt; bResult=NucUsb.NUC_ReadPipe(id,(UCHAR *)&ack,4); if(bResult==FALSE) { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); return FALSE; } } else { delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); //TRACE(_T("XXX (%d) FW rcnt error. 0x%x\n"), id, GetLastError()); return FALSE; } } delete []lpBuffer; NucUsb.CloseWinUsbDevice(id); fclose(fp); return TRUE; } #define CRC32POLY 0x04c11db7 static const unsigned long crc32_table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; unsigned int CNuWriterDlg::CalculateCRC32(unsigned char * buf,unsigned int len) { #if 0 unsigned char *end; unsigned int crc=CRC32POLY; crc = ~crc; for (end = buf + len; buf < end; ++buf) crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8); return ~crc; #else unsigned int i; unsigned int crc32; unsigned char* byteBuf; crc32 = 0 ^ 0xFFFFFFFF; byteBuf = (unsigned char *) buf; for (i=0; i < len; i++) { crc32 = (crc32 >> 8) ^ crc32_table[ (crc32 ^ byteBuf[i]) & 0xFF ]; } return ( crc32 ^ 0xFFFFFFFF ); #endif } //---------------------------------------------------------------------------------------------
[ "cfli0@nuvoton.com" ]
cfli0@nuvoton.com
081b2cc83c46752aae022d8c1cbb4f80c067759e
01ebe8a41148a7dd6f34ae4794dc05910edadcb4
/flecsale/geom/shapes/test/shapes.cc
85c7ab229f1663b6a0be44e1610900a537f82dbe
[ "BSD-2-Clause" ]
permissive
tylerjereddy/flecsale
6a6a5ede1e01e25fcd9269f2a458027cf9195535
1fc0852e6315a83083d765bb857d588f4567c4fe
refs/heads/master
2021-10-11T08:25:26.180937
2017-11-15T22:57:53
2017-11-15T22:57:53
117,174,906
0
0
null
2018-01-12T01:22:38
2018-01-12T01:22:37
null
UTF-8
C++
false
false
16,231
cc
/*~-------------------------------------------------------------------------~~* * Copyright (c) 2016 Los Alamos National Laboratory, LLC * All rights reserved *~-------------------------------------------------------------------------~~*/ //////////////////////////////////////////////////////////////////////////////// /// \file /// \brief Tests related to the computational geometry for different shapes. //////////////////////////////////////////////////////////////////////////////// // user includes #include "flecsale/common/constants.h" #include "flecsale/common/types.h" #include "flecsale/geom/shapes/hexahedron.h" #include "flecsale/geom/shapes/quadrilateral.h" #include "flecsale/geom/shapes/polyhedron.h" #include "flecsale/geom/shapes/polygon.h" #include "flecsale/geom/shapes/tetrahedron.h" #include "flecsale/geom/shapes/triangle.h" #include "flecsale/math/constants.h" #include "flecsale/math/matrix.h" #include "flecsale/math/vector.h" // system includes #include<array> #include<cinchtest.h> #include<vector> // explicitly use some stuff using std::cout; using std::endl; using std::vector; using namespace flecsale; using namespace flecsale::geom::shapes; //! the real type using real_t = common::real_t; // ! the test tolerance using common::test_tolerance; //! the point type using point_2d_t = math::vector<real_t, 2>; using point_3d_t = math::vector<real_t, 3>; /////////////////////////////////////////////////////////////////////////////// //! \brief create a rotation matrix /////////////////////////////////////////////////////////////////////////////// auto rotation_matrix_y( real_t radians ) { // the trig functions auto cos = std::cos( radians ); auto sin = std::sin( radians ); // create a rotation matrix math::matrix< real_t, 3, 3 > rot; rot(0, 0) = cos; rot(0, 1) = 0; rot(0, 2) = sin; rot(1, 0) = 0; rot(1, 1) = 1; rot(1, 2) = 0; rot(2, 0) = -sin; rot(2, 1) = 0; rot(2, 2) = cos; return rot; } /////////////////////////////////////////////////////////////////////////////// //! \brief Test triangle operations //! \remark 2d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, triangle_2d) { auto pt0 = point_2d_t{0, 0}; auto pt1 = point_2d_t{1, 0}; auto pt2 = point_2d_t{0, 1}; auto area = triangle<2>::area( pt0, pt1, pt2 ); auto xc = triangle<2>::centroid( pt0, pt1, pt2 ); ASSERT_NEAR( 0.5, area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( 1./3., xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( 1./3., xc[1], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test triangle operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, triangle_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{0, 1, 0 }; // the centroid answer auto xc_ans = point_3d_t{ 1./3., 1./3., 0 }; auto n_ans = point_3d_t{ 0, 0, 0.5 }; auto area_ans = 0.5; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); // transform the coords pt0 = rot * pt0; pt1 = rot * pt1; pt2 = rot * pt2; xc_ans = rot * xc_ans; n_ans = rot * n_ans; auto area = triangle<3>::area( pt0, pt1, pt2 ); auto xc = triangle<3>::centroid( pt0, pt1, pt2 ); auto n = triangle<3>::normal( pt0, pt1, pt2 ); ASSERT_NEAR( area_ans, area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( n_ans[0], n[0], test_tolerance ) << " normal calculation wrong "; ASSERT_NEAR( n_ans[1], n[1], test_tolerance ) << " normal calculation wrong "; ASSERT_NEAR( n_ans[2], n[2], test_tolerance ) << " normal calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test quadrilateral operations //! \remark 2d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, quadrilateral_2d) { auto pt0 = point_2d_t{0, 0}; auto pt1 = point_2d_t{1, 0}; auto pt2 = point_2d_t{1, 1}; auto pt3 = point_2d_t{0, 1}; auto area = quadrilateral<2>::area( pt0, pt1, pt2, pt3 ); auto xc = quadrilateral<2>::centroid( pt0, pt1, pt2, pt3 ); ASSERT_NEAR( 1., area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( 0.5, xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( 0.5, xc[1], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test quadrilateral operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, quadrilateral_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{1, 1, 0 }; auto pt3 = point_3d_t{0, 1, 0 }; // the centroid answer auto xc_ans = point_3d_t{ 0.5, 0.5, 0 }; auto n_ans = point_3d_t{ 0, 0, 1 }; auto area_ans = 1.0; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); // transform the coords pt0 = rot * pt0; pt1 = rot * pt1; pt2 = rot * pt2; xc_ans = rot * xc_ans; n_ans = rot * n_ans; auto area = quadrilateral<3>::area( pt0, pt1, pt2, pt3 ); auto xc = quadrilateral<3>::centroid( pt0, pt1, pt2, pt3 ); auto n = quadrilateral<3>::normal( pt0, pt1, pt2, pt3 ); ASSERT_NEAR( area_ans, area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( n_ans[0], n[0], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[1], n[1], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[2], n[2], test_tolerance ) << " Normal calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test polygon operations //! \remark 2d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, polygon_2d) { auto pt0 = point_2d_t{0, 0}; auto pt1 = point_2d_t{1, 0}; auto pt2 = point_2d_t{1, 1}; auto pt3 = point_2d_t{0, 1}; auto points = std::vector<point_2d_t>{pt0, pt1, pt2, pt3}; auto area = polygon<2>::area( pt0, pt1, pt2, pt3 ); auto xc = polygon<2>::centroid( pt0, pt1, pt2, pt3 ); ASSERT_NEAR( 1., area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( 0.5, xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( 0.5, xc[1], test_tolerance ) << " Centroid calculation wrong "; area = polygon<2>::area( points ); xc = polygon<2>::centroid( points ); ASSERT_NEAR( 1., area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( 0.5, xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( 0.5, xc[1], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test polygon operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, polygon_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{1, 1, 0 }; auto pt3 = point_3d_t{0, 1, 0 }; // the centroid answer auto xc_ans = point_3d_t{ 0.5, 0.5, 0 }; auto n_ans = point_3d_t{ 0, 0, 1 }; auto area_ans = 1.0; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); // transform the coords pt0 = rot * pt0; pt1 = rot * pt1; pt2 = rot * pt2; xc_ans = rot * xc_ans; n_ans = rot * n_ans; auto points = std::vector<point_3d_t>{pt0, pt1, pt2, pt3}; auto area = polygon<3>::area( pt0, pt1, pt2, pt3 ); auto xc = polygon<3>::centroid( pt0, pt1, pt2, pt3 ); auto n = polygon<3>::normal( pt0, pt1, pt2, pt3 ); ASSERT_NEAR( area_ans, area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( n_ans[0], n[0], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[1], n[1], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[2], n[2], test_tolerance ) << " Normal calculation wrong "; area = polygon<3>::area( points ); xc = polygon<3>::centroid( points ); n = polygon<3>::normal( points ); ASSERT_NEAR( area_ans, area, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( n_ans[0], n[0], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[1], n[1], test_tolerance ) << " Normal calculation wrong "; ASSERT_NEAR( n_ans[2], n[2], test_tolerance ) << " Normal calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test tetrahedron operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, tetrahedron_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{0, 1, 0 }; auto pt3 = point_3d_t{0, 0, 1 }; // the centroid answer auto xc_ans = point_3d_t{ 1./4., 1./4., 1./4. }; auto vol_ans = 1. / 6.; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); auto vol = tetrahedron::volume( pt0, pt1, pt2, pt3 ); auto xc = tetrahedron::centroid( pt0, pt1, pt2, pt3 ); ASSERT_NEAR( vol_ans, vol, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test hexahedron operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, hexahedron_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{1, 1, 0 }; auto pt3 = point_3d_t{0, 1, 0 }; auto pt4 = point_3d_t{0, 0, 1 }; auto pt5 = point_3d_t{1, 0, 1 }; auto pt6 = point_3d_t{1, 1, 1 }; auto pt7 = point_3d_t{0, 1, 1 }; // the centroid answer auto xc_ans = point_3d_t{ 0.5, 0.5, 0.5 }; auto vol_ans = 1.; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); auto vol = hexahedron::volume( pt0, pt1, pt2, pt3, pt4, pt5, pt6, pt7 ); auto xc = hexahedron::centroid( pt0, pt1, pt2, pt3, pt4, pt5, pt6, pt7 ); ASSERT_NEAR( vol_ans, vol, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test polyhedron operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, polyhedron_3d) { // original points auto pt0 = point_3d_t{0, 0, 0 }; auto pt1 = point_3d_t{1, 0, 0 }; auto pt2 = point_3d_t{1, 1, 0 }; auto pt3 = point_3d_t{0, 1, 0 }; auto pt4 = point_3d_t{0, 0, 1 }; auto pt5 = point_3d_t{1, 0, 1 }; auto pt6 = point_3d_t{1, 1, 1 }; auto pt7 = point_3d_t{0, 1, 1 }; using polyhedron = polyhedron< point_3d_t >; polyhedron poly; poly.insert( {pt0, pt1, pt2, pt3} ); poly.insert( {pt4, pt7, pt6, pt5} ); poly.insert( {pt0, pt4, pt5, pt1} ); poly.insert( {pt1, pt5, pt6, pt2} ); poly.insert( {pt2, pt6, pt7, pt3} ); poly.insert( {pt3, pt7, pt4, pt0} ); // the centroid answer auto xc_ans = point_3d_t{ 0.5, 0.5, 0.5 }; auto vol_ans = 1.; // compute some angles auto degrees = 45; auto radians = degrees * math::pi / 180; auto rot = rotation_matrix_y( radians ); auto vol = poly.volume(); auto xc = poly.centroid(); ASSERT_NEAR( vol_ans, vol, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; } // TEST /////////////////////////////////////////////////////////////////////////////// //! \brief Test polyhedron operations //! \remark 3d version /////////////////////////////////////////////////////////////////////////////// TEST(shapes, compare_3d) { // original points auto pt0 = point_3d_t{ -0.5, -0.5, 0.25 }; auto pt1 = point_3d_t{ -0.5, -0.5, 0 }; auto pt2 = point_3d_t{ -0.5, -0.25, 0 }; auto pt3 = point_3d_t{ -0.5, -0.25, 0.25 }; auto pt4 = point_3d_t{ -0.25, -0.5, 0.25 }; auto pt5 = point_3d_t{ -0.25, -0.5, 0 }; auto pt6 = point_3d_t{ -0.25, -0.25, 0 }; auto pt7 = point_3d_t{ -0.25, -0.25, 0.25 }; // the centroid answer auto xc_ans = point_3d_t{ -0.375, -0.375, 0.125 }; auto vol_ans = 0.015625; // compute some angles auto vol = hexahedron::volume( pt0, pt1, pt2, pt3, pt4, pt5, pt6, pt7 ); auto xc = hexahedron::centroid( pt0, pt1, pt2, pt3, pt4, pt5, pt6, pt7 ); ASSERT_NEAR( vol_ans, vol, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; // now build the polyhedron pt0 = point_3d_t{ -0.5, -0.25, 0.25 }; pt1 = point_3d_t{ -0.5, -0.25, 0 }; pt2 = point_3d_t{ -0.5, -0.5, 0 }; pt3 = point_3d_t{ -0.5, -0.5, 0.25 }; pt4 = point_3d_t{ -0.25, -0.5, 0 }; pt5 = point_3d_t{ -0.25, -0.25, 0 }; pt6 = point_3d_t{ -0.25, -0.25, 0.25 }; pt7 = point_3d_t{ -0.25, -0.5, 0.25 }; using polyhedron = polyhedron< point_3d_t >; polyhedron poly; poly.insert( {pt0, pt1, pt2, pt3} ); poly.insert( {pt4, pt5, pt6, pt7} ); poly.insert( {pt2, pt4, pt7, pt3} ); poly.insert( {pt1, pt5, pt4, pt2} ); poly.insert( {pt0, pt6, pt5, pt1} ); poly.insert( {pt3, pt7, pt6, pt0} ); // compute some angles vol = poly.volume(); xc = poly.centroid(); ASSERT_NEAR( vol_ans, vol, test_tolerance ) << " Volume calculation wrong "; ASSERT_NEAR( xc_ans[0], xc[0], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[1], xc[1], test_tolerance ) << " Centroid calculation wrong "; ASSERT_NEAR( xc_ans[2], xc[2], test_tolerance ) << " Centroid calculation wrong "; }
[ "charest@lanl.gov" ]
charest@lanl.gov
ae1586782791f9e9d01f9299f9ec825d27ccbf55
8f372f74457944193b9426caccfcddaac81d79e5
/Ass-5/ass5_16CS10053_translator.h
d6a82915eab2c36955c474daec5c1c8b30145ca3
[]
no_license
vedic-partap/Compilers-lab
89f2876e9269829d1d177bb97263abad92fc673c
bee1d964d1da04a7a48cbddad5aaf954a5f83961
refs/heads/master
2020-03-23T21:59:23.056785
2019-01-10T06:25:43
2019-01-10T06:25:43
142,145,653
8
7
null
null
null
null
UTF-8
C++
false
false
3,705
h
#ifndef ASS5_16CS10053_TRANSLATOR_INCLUDED #define ASS5_16CS10053_TRANSLATOR_INCLUDED # define SIZE_OF_CHAR 1 # define SIZE_OF_INT 4 # define SIZE_OF_DOUBLE 8 # define SIZE_OF_PTR 4 // Maxsize for symbol table # define MAX_SIZE 10000 extern int c, w, flag1, flag2, line_count, temp_count, next_instr, flag_array; extern char *func_name; enum quad_data_types {DEFAULT_, PLUS, MINUS, INTO, DIV, PERCENT, U_PLUS, U_MINUS, BW_U_NOT,U_NEGATION, SL, SR, LT, LTE, GT, GTE, EQ, NEQ, BW_AND, BW_XOR, PARAM, RETURN_EXP, RETURN_, Function, BW_INOR, LOG_AND, LOG_OR, goto_LT, goto_LTE, goto_GT, goto_GTE, goto_EQ, goto_NEQ, call, EQ_BRACKET, BRACKET_EQ, U_ADDR, U_STAR, ASSIGN, GOTO_, IF_GOTO, IF_FALSE_GOTO}; enum date_types { ARRAY, PTR, FUNCTION, VOID_, CHAR_, INT_, DOUBLE_, BOOL_}; typedef struct lnode{ int index_list; struct lnode *next; }lnode; typedef struct tNode{ date_types down; int *l; struct tNode *r; }tNode; extern tNode *t; class symbol_table_fields; class symbolTable; class symbol_table_fields{ public: void *initial_value; int size; char *name; tNode *Type; int offset; symbolTable *nestedTable; void print_row(); symbol_table_fields(char * = 0 , tNode * = 0, void * = 0, int = -1, int = -1, symbolTable * = 0); void operator=(symbol_table_fields &); ~symbol_table_fields(); }; typedef struct parameter_list{ symbol_table_fields *parameter; struct parameter_list *next; }parameter_list; typedef struct fields_quad{ char *arg1; char *arg2; char *res; quad_data_types op; symbol_table_fields *arg1_loc; symbol_table_fields *arg2_loc; symbol_table_fields *res_loc; fields_quad(char * = 0, char * = 0, char * = 0, quad_data_types = DEFAULT_, symbol_table_fields * = 0, symbol_table_fields * = 0, symbol_table_fields * = 0); ~fields_quad(); void operator=(struct fields_quad &); void print_fields_quad(int); }fields_quad; typedef union attribute{ int int_data; double double_data; char char_data; }attribute; typedef struct attribute_expression{ symbol_table_fields *loc; lnode *TL; lnode *FL; lnode *NL; tNode *type; symbol_table_fields *array; symbol_table_fields *loc1; attribute val; }attribute_expression; typedef struct attribute_variable_declaration{ tNode *type; int width; char *var; }attribute_variable_declaration; typedef struct id_attr_struct{ symbol_table_fields *loc; char *var; }id_attr_struct; class symbolTable{ public: symbol_table_fields *table; int curr_length; symbolTable(unsigned int); ~symbolTable(); symbol_table_fields *lookup(char *); void insert(symbol_table_fields &); symbol_table_fields *gentemp(date_types); void print_Table(); }; class quadArray{ public: fields_quad *quad_Table; quadArray(unsigned int); ~quadArray(); void emit(fields_quad &); void print_quadArray(); void fill_dangling_goto(int,int); }; extern quadArray *quad_array; symbolTable *construct_Symbol_Table(); void print_Tree(tNode *); void print_Initial_Value(void *,tNode *); tNode *new_node(date_types ,int); tNode *merge_node(tNode *, tNode *); lnode *makelist(int); lnode *merge(lnode *, lnode *); void backpatch(lnode *, int); int typecheck(tNode *,tNode *); void conv2Bool(attribute_expression *); int compute_width(tNode *); parameter_list *make_param_list(symbol_table_fields *); parameter_list *merge_param_list(parameter_list *, parameter_list *); extern symbolTable *symbol_table; extern symbolTable *current; extern symbolTable *temp_use; #endif
[ "vedicpartap1999@gmail.com" ]
vedicpartap1999@gmail.com
1a55a91b6470b9297c33aeb6096b8550ce06b52a
8f4d355d133f27830fa9eaa039fd73ac527e848b
/Projecto_v1/Proj_v1/tangentcalculator.h
9f17f29421d1c34eaba54173d0567560bff55ca1
[]
no_license
rmcristovao/AVT_2016_1
2dd4ef932a3630bbcc3c21342c6a70a4eefab5c3
a51e735269e2a01adafc100a892f5e187a207985
refs/heads/master
2020-04-01T18:59:35.564043
2017-07-27T12:58:14
2017-07-27T12:58:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
268
h
#include <vector> #include "glm/glm.hpp" void computeTangentBasis( // inputs std::vector<glm::vec4> & vertices, std::vector<glm::vec4> & uvs, std::vector<glm::vec4> & normals, // outputs std::vector<glm::vec4> & tangents, std::vector<glm::vec4> & bitangents );
[ "slf450x@hotmail.com" ]
slf450x@hotmail.com
7f1546595e28a838c72ebace9e8890ca27034d29
1ea17fb9415957a1bedd02f121627a094620ed52
/Session 1/gaonK/3/9095.cpp
f2b7102dac94a3388c79b07e2694216847e52ced
[]
no_license
gaonK/AlgorithmStudy
e5dd261537c8ec2bb3058d4c7fd05cda599aafc5
025f09bc7b18f2c84c5db24a66548c06f86f3d0b
refs/heads/master
2021-07-09T12:38:13.777563
2019-03-07T22:29:49
2019-03-07T22:29:49
147,552,885
2
2
null
2019-03-07T22:29:50
2018-09-05T17:09:58
C++
UTF-8
C++
false
false
346
cpp
#include <iostream> using namespace std; int arr[12]; int main() { int T; cin >> T; arr[1] = 1; arr[2] = 2; arr[3] = 4; for (int i = 4; i <= 11; i++) { arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } while (T--) { int N; cin >> N; cout << arr[N] << '\n'; } return 0; }
[ "gaon.kim.dev@gmail.com" ]
gaon.kim.dev@gmail.com
ea3d92fbee3bd9b725e7eed6ea25a0b6381fc5f0
60ccc97366c43b0f83275c2c7aabd569939f8a43
/lcpfw/app/cc/app_task_graph_runner.h
7082882cf20549c40f45795e55b31769506fc30d
[]
no_license
VestasWey/mysite
d89c886c333e5aae31a04584e592bd108ead8dd3
41ea707007b688a3ef27eec55332500e369a191f
refs/heads/master
2022-12-09T10:02:19.268154
2022-10-03T03:14:16
2022-10-03T03:14:16
118,091,757
1
1
null
2022-11-26T14:29:04
2018-01-19T07:22:23
C++
UTF-8
C++
false
false
576
h
// Copyright 2015 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. #pragma once #include "base/threading/simple_thread.h" #include "cc/raster/single_thread_task_graph_runner.h" namespace cc { class AppTaskGraphRunner : public SingleThreadTaskGraphRunner { public: AppTaskGraphRunner(); AppTaskGraphRunner(const AppTaskGraphRunner&) = delete; ~AppTaskGraphRunner() override; AppTaskGraphRunner& operator=(const AppTaskGraphRunner&) = delete; }; } // namespace cc
[ "Vestas.Wey@qq.com" ]
Vestas.Wey@qq.com
28ab3dcd73d5cf658f522f04979114130c6a9263
4f8bb0eaafafaf5b857824397604538e36f86915
/课件/Code/toj3488.cpp
b8c04ad57ebc625913ebfbc7c4074d5a1a9ee2b0
[]
no_license
programmingduo/ACMsteps
c61b622131132e49c0e82ad0007227d125eb5023
9c7036a272a5fc0ff6660a263daed8f16c5bfe84
refs/heads/master
2020-04-12T05:40:56.194077
2018-05-10T03:06:08
2018-05-10T03:06:08
63,032,134
1
2
null
null
null
null
UTF-8
C++
false
false
669
cpp
#include <iostream> #include <algorithm> using namespace std; #define maxn 100004 int a[maxn]; int n,caseT; int tp; bool cmp(const int &a,const int &b) { return a > b; } int main() { int i,tmp,tmp1,tmp2,ans; while(scanf("%d",&caseT)!=EOF) { while(caseT--) { tp = 0; ans = 0; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&tmp); a[tp++] = tmp; push_heap(a,a+tp,cmp); } for(i=0;i<n-1;i++) { pop_heap(a,a+tp,cmp); tmp1 = a[tp-1]; tp--; pop_heap(a,a+tp,cmp); tmp2 = a[tp-1]; tp--; ans += tmp1 + tmp2; a[tp++] = tmp1+tmp2; push_heap(a,a+tp,cmp); } printf("%d\n",ans); } } return 0; }
[ "wuduotju@163.com" ]
wuduotju@163.com
196b043079f849f08e31cd69c78d0d3187980583
04d2ed59b185d4728e493e6186e81f538481b7d8
/Classes/MenuScenes/MainMenuScene.h
943a5a33f7c9236492d0722a77c0f9f0a7c1ba5d
[]
no_license
kolesnykovVladyslav/NinjaWars
182b9f9dd14386ba869dc395de718626e69a2c46
d173fa5eed61bf864b4a21204d0d64f2046b62cc
refs/heads/master
2020-03-24T19:19:03.433867
2019-06-21T17:04:41
2019-06-21T17:04:41
142,918,901
0
0
null
null
null
null
UTF-8
C++
false
false
1,685
h
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 __MAIN_MENU_SCENE_H__ #define __MAIN_MENU_SCENE_H__ #include "cocos2d.h" class MainMenuScene : public cocos2d::Scene { public: static cocos2d::Scene* createScene(); virtual bool init(); // implement the "static create()" method manually CREATE_FUNC(MainMenuScene); private: void goToSinglePlayerMenuScene(cocos2d::Ref *sender); }; #endif // __MAIN_MENU_SCENE_H__
[ "vlad.kolesnykov@gmail.com" ]
vlad.kolesnykov@gmail.com
354afc701c8697f5585e8b27e6446a5417f33ba1
06bd96cc95eed2b4230e477dba259dc9d32a0fa8
/source/HIS/app/communication/SoftSwitch/SwitchPortInner.cpp
d676c4c3155e49a9aa7377722f1ae4bb70c49dac
[]
no_license
venkatarajasekhar/ISAP300
2e7ed8e92b7e9c0446212bcafb2998f354521bc7
c6ba1a7fd4bb636ef088a632539e0094f8ba3130
refs/heads/master
2020-06-26T18:19:08.032681
2016-09-21T04:34:44
2016-09-21T04:34:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,868
cpp
/* * SwitchPortInner.cpp * * Created on: 2013-6-25 * Author: Administrator */ #include "SwitchPortInner.h" #include "PriPacket.h" //#include "DCCChannelSnd.h" //#include "DCCChannelRcv.h" #include <string.h> #include <iostream> #include "DeviceComponent.h" #include "DeviceAttribute.h" #include "NMPort.h" uint32 SwitchPortInner::pSnBase = 255; SwitchPortInner::SwitchPortInner() : SwitchPort(pSnBase--) { // TODO Auto-generated constructor stub } SwitchPortInner::SwitchPortInner(uint32 sn) : SwitchPort(sn) { } SwitchPortInner::~SwitchPortInner() { // TODO Auto-generated destructor stub } int SwitchPortInner::outputPacket(PriPacket& pkg) { uint32 sn = pkg.getPrivateTag().sn; uint16 priLen = pkg.getPriLen(); ch[0] = sn>>24; ch[1] = sn>>16; ch[2] = sn>>8; ch[3] = sn>>0; uint16 len = 0; uint8* stdd = pkg.getStdStream(&len); if( stdd == 0 || len < 20 ) { return -1; } memcpy( ch+4, stdd, len); std::map<uint32, NMPort*>::iterator it = nmport.begin(); while( it != nmport.end() ) { if( pkg.getRcvNMPort()->getUID() != it->second->getUID() ) { //只发送非本管理接口收到的包 it->second->sendData(ch, priLen); } ++it; } return 1; } //void SwitchPortInner::addDcc(DCCChannelRcv* ch) { // dccRcv.insert(std::pair<uint32, DCCChannelRcv*>( ch->getUID(), ch)); // ch->setInnerPort(this); //} // //void SwitchPortInner::addDcc(DCCChannelSnd* ch) { // dccSnd.insert( std::pair<uint32, DCCChannelSnd*>( ch->getUID(), ch) ); // ch->setInnerPort(this); //} // //void SwitchPortInner::removeDcc(DCCChannelRcv* ch) { // ch->setInnerPort(0); // dccRcv.erase(ch->getUID()); //} //void SwitchPortInner::removeDcc(DCCChannelSnd* ch) { // ch->setInnerPort(0); // dccSnd.erase(ch->getUID()); //} void SwitchPortInner::addNmPort(NMPort* p) { nmport.insert(std::pair<uint32, NMPort*>(p->getUID(), p)); p->setInnerPort(this); } void SwitchPortInner::removePort(NMPort* p) { p->setInnerPort(0); nmport.erase(p->getUID()); } bool SwitchPortInner::ifDropThePacket(PriPacket& pkt) { uint16 len = 0; uint8* databuf = pkt.getStdStream(&len); if( databuf == 0 ) { return true; } uint16 frameType = ((databuf[12] << 8) | databuf[13]); if( frameType == 0x0806 ) { uint8* ip = databuf + 38; //arp request dest ip address uint8 remoteIP[4]; DeviceComponent::getDeviceAttribute().getProtectMCUIP(remoteIP); if( memcmp(ip, remoteIP, 4) == 0 ) { return true; } ip = databuf + 28; //arp request src ip address if( memcmp(ip, remoteIP, 4) == 0 ) { return true; } } return false; }
[ "momo_nono@163.com" ]
momo_nono@163.com
95f5864612ed7dd4d3e51615d8721478c6badaa8
e54731e92f3964e5f00116d6b58d0c5733c76e92
/newview/trackball.cpp
dd5a64a20c84e86fe84736c37089b6fbef0a686a
[]
no_license
lidan233/render
daa2da01d273d790178e216cd641aa16aac911ff
ea596c366af2509a8be92551911c366d0c0e2176
refs/heads/master
2023-01-03T11:06:45.388323
2020-11-03T07:32:30
2020-11-03T07:32:30
309,422,900
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
// // Created by MQ on 2020/8/24. // #include "trackball.h" void trackball::drag_update(int x, int y) { if(_dragged) { _drag_start_position.x = x; _drag_start_position.y = y ; } } void trackball::drag_end() { if(_dragged) { drag_update(0.0f,0.0f) ; _dragged = false ; } } glm::vec2 trackball::direction(int x, int y) { glm::ivec2 drag_end_position(x-_center_position.x,y-_center_position.y) ; glm::vec2 v(drag_end_position.x - _drag_start_position.x,drag_end_position.y-_drag_start_position.y) ; v.y = -v.y ; return glm::normalize(v) ; }
[ "2016735055@qq.com" ]
2016735055@qq.com
f98edaf45e64a69c8a9ee9fbba61e87a966c9de7
ba68c2eaefa2e30dbd145f898eaf98e314f492af
/src/Subrecords/ScriptCollection.hpp
114419caf8a8288680d4e77d912d7db8d1a4c32f
[ "Apache-2.0" ]
permissive
AWildErin/ESx-Reader
2aae30386c66441e2124657d40adaf663ebd535e
fa7887c934141f7b0a956417392f2b618165cc34
refs/heads/master
2023-03-16T22:53:44.060605
2015-07-16T11:16:57
2015-07-16T11:16:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
hpp
/* * File: ScriptCollection.hpp * Author: Koncord <koncord at rwa.su> * * Created on 10 Апрель 2015 г., 21:24 */ #ifndef SCRIPTCOLLECTION_HPP #define SCRIPTCOLLECTION_HPP #include "../Types.hpp" #include "../debug_macros.hpp" #pragma pack(push, 1) struct Script { todo(rename structures) std::vector<uint8_t> compiled; std::string source; std::vector<formid> globRefs; // ACTI, DOOR, STAT, FURN, CREA, SPEL, NPC_, CONT, ARMO, // AMMO, MISC, WEAP, IMAD, BOOK, KEYM, ALCH, LIGH, QUST, PLYR, // PACK, LVLI, ECZN, EXPL, FLST, IDLM, PMIS, FACT, ACHR, REFR, ACRE, // GLOB, DIAL, CELL, SOUN, MGEF, WTHR, CLAS, EFSH, RACE, LVLC, CSTY, // WRLD, SCPT, IMGS, MESG, MSTT, MUSC, NOTE, PERK, PGRE, PROJ, LVLN, // WATR, ENCH, TREE, TERM, HAIR, EYES, ADDN or NULL record. std::vector<uint32_t> locRefs; struct LocalVariable { struct SLSD { uint32_t index; uint8_t unused[12]; bool isLongOrShort; uint8_t unused1[7]; }data; std::string name; }; std::vector<LocalVariable> localVariables; struct SCHR { uint8_t unused[4]; uint32_t refCount; uint32_t compiledSize; uint32_t variableCount; uint16_t type; bool enabled; uint8_t unused1; } main; enum TYPE { Object = 0, Quest, Effect = 0x100 }; }; #pragma pack(pop) typedef std::vector<Script> Scripts; #endif /* SCRIPTCOLLECTION_HPP */
[ "koncord@rwa.su" ]
koncord@rwa.su
194f677c545c67a5333e7c7461ac36c02bd16cb3
8cbf974f7eb4ce96ec4b3f1bad8d4358ccd24d63
/arduino-1.6.4/libraries/ros_lib/mongodb_store_msgs/StringPair.h
cf0f79dcd9264c871d7796f35d87afe06feca575
[]
no_license
Amahmoud1994/Arduino
9d846c0907bf57bacfbe05cf1b9e460197fe59c5
d4f40f0657fa24df476f27591f6c105488f30221
refs/heads/master
2021-01-13T00:50:25.960068
2015-09-16T19:08:17
2015-09-16T19:08:17
36,795,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,873
h
#ifndef _ROS_mongodb_store_msgs_StringPair_h #define _ROS_mongodb_store_msgs_StringPair_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace mongodb_store_msgs { class StringPair : public ros::Msg { public: char * first; char * second; virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_first = strlen( (const char*) this->first); memcpy(outbuffer + offset, &length_first, sizeof(uint32_t)); offset += 4; memcpy(outbuffer + offset, this->first, length_first); offset += length_first; uint32_t length_second = strlen( (const char*) this->second); memcpy(outbuffer + offset, &length_second, sizeof(uint32_t)); offset += 4; memcpy(outbuffer + offset, this->second, length_second); offset += length_second; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_first; memcpy(&length_first, (inbuffer + offset), sizeof(uint32_t)); offset += 4; for(unsigned int k= offset; k< offset+length_first; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_first-1]=0; this->first = (char *)(inbuffer + offset-1); offset += length_first; uint32_t length_second; memcpy(&length_second, (inbuffer + offset), sizeof(uint32_t)); offset += 4; for(unsigned int k= offset; k< offset+length_second; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_second-1]=0; this->second = (char *)(inbuffer + offset-1); offset += length_second; return offset; } const char * getType(){ return "mongodb_store_msgs/StringPair"; }; const char * getMD5(){ return "c0d0db6e21f3fc1eb068f9cc22ba8beb"; }; }; } #endif
[ "ros@ubuntu.(none)" ]
ros@ubuntu.(none)
35c02837fdcb6089b100f99d7185418d342dd9c8
8f00d8868b5fbb786a96c2679ec78ebb6d2856cb
/Hackerrank/HR-Huns.cpp
a78d923e3dc8cee0b3e2c7000f88ed28aaaeb111
[]
no_license
LearnerMN/Algorithm-Problems
59af7a5b133c7ffb8bd97ef327216c30cd65801b
9d61f2135b0a7a339c1b78330e49ae1468e405a8
refs/heads/master
2023-05-11T03:36:56.720269
2023-04-30T02:01:46
2023-04-30T02:01:46
44,692,956
1
0
null
null
null
null
UTF-8
C++
false
false
1,631
cpp
//https://www.hackerrank.com/contests/open-cup-mongolia-2014/challenges/khuns/submissions/code/1211376 #include <iostream> //#include <cstdio> #include <climits> #include <stack> #include <vector> #include <algorithm> #define ull unsigned long long using namespace std; vector<string> v; bool used[151][151]; int R,C; int upDot(){ int c=0; for (int i=1; i<=C; i++){ if (v[1][i]=='.' || v[1][i]=='D'){ c++; } } return c; } int downDot(){ int c=0; for (int i=1; i<=C; i++){ if (v[R][i]=='.' || v[R][i]=='D'){ c++; } } return c; } int leftDot(){ int c=0; for (int i=1; i<=R; i++){ if (v[i][1]=='.' || v[i][1]=='D'){ c++; } } return c; } int rightDot(){ int c=0; for (int i=1; i<=R; i++){ if (v[i][C]=='.' || v[i][C]=='D'){ c++; } } return c; } bool up(int x,int y){ return v[x-1][y]=='.'; } bool down(int x,int y){ return v[x+1][y]=='.'; } bool left(int x,int y){ return v[x][y-1]=='.'; } bool right(int x,int y){ return v[x][y+1]=='.'; } int main(){ int u=0,l=0,d=0,r=0; string st; cin>>R>>C; string str = ""; for (int i=0; i<C+2; i++){ str += "."; } v.push_back(str); for (int i=0; i<R; i++){ cin>>st; st = "." + st + "."; v.push_back(st); } v.push_back(str); for (int i=1; i<=R; i++){ for (int k=1; k<=C; k++){ if (v[i][k]=='D'){ if (up(i,k)) u++; if (down(i,k)) d++; if (left(i,k)) l++; if (right(i,k)) r++; } } } cout<<min(r,rightDot()) + min(l,leftDot()) + min(d,downDot()) + min(u,upDot())<<endl; //cout<<u<<" "<<d<<" "<<l<<" "<<r<<endl; return 0; } /* 7 8 XXX..XXX XXX..XXX .....XXX XXX..XXX XDDDD.XX XDDDD... XXXXXXXX */
[ "LearnerMN@gmail.com" ]
LearnerMN@gmail.com
d9d9129e7152343f37061954716c3a0e1bb6c923
3f5adb4c6b734468b2dd682aba0237ef6c63facf
/demo/testBasic.h
7f43cd5bd6ffcd9d27e4524128a24e70738e16cb
[]
no_license
renzhe20092584/cocoCpp
50b7337544cec17ec265d83649e1926d88e050be
7c2b501a4264be4eabab80f79f28e08b4319246c
refs/heads/master
2016-09-10T22:45:21.044254
2014-08-11T08:28:52
2014-08-11T08:28:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
#ifndef _TEST_BASIC_H_ #define _TEST_BASIC_H_ #include "cocos2d.h" #include "VisibleRect.h" USING_NS_CC; class TestScene : public Scene { public: TestScene(bool bPortrait = false, bool physics = false); virtual void onEnter() override; virtual void runThisTest() = 0; }; #define CL(__className__) [](){ return __className__::create();} #define CLN(__className__) [](){ auto obj = new __className__(); obj->autorelease(); return obj; } #endif
[ "252327412@qq.com" ]
252327412@qq.com
deaaa78cc291d3e19ca0ce00d225252e3a8a3ecf
b83d9b18fb92174e18c0f43784f080bc7c3bfd27
/Source/PathFind/Private/GridGraph.cpp
b8d088b6ff29bacb45b6ac9ff774b4f0230ad6e3
[ "MIT" ]
permissive
arttu94/UE-PathFind
f4d6b71d4c5c25b3952cb6432e5d7f30840c2036
9e0c20114fdb31c1fce5007bb5d4f634f808de45
refs/heads/master
2020-12-21T00:57:54.013197
2020-12-15T22:32:04
2020-12-15T22:32:04
236,259,749
0
0
null
null
null
null
UTF-8
C++
false
false
3,791
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "GridGraph.h" #include "Engine/World.h" #include "PathNode.h" #include "Containers/Queue.h" #include "GraphSearch.h" #include "Engine.h" // Sets default values AGridGraph::AGridGraph() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; SquareSize = 0; bAllowDiagonalMovement = false; } // Called when the game starts or when spawned void AGridGraph::BeginPlay() { Super::BeginPlay(); CreateGrid(); //TODO: change this if (SquareSize > 15) { Start = Grid[0][3]; Finish = Grid[11][13]; } Finish->SetNodeType(EPathNodeType::PN_Finish); Finish->UpdateNodeType(); Start->SetNodeType(EPathNodeType::PN_Start); Start->UpdateNodeType(); //UGraphSearch::BreadthFirstSearch(Start); } void AGridGraph::CreateGrid() { for (int8 x = 0; x < SquareSize; x++) { Grid.Add(TArray<APathNode*>()); for (int8 y = 0; y < SquareSize; y++) { if (NodeBlueprintClass) { FActorSpawnParameters SpawnParams; Grid[x].Add(GetWorld()->SpawnActor<APathNode>(NodeBlueprintClass, SpawnParams)); /*if (x == 0 || x == 19 || y == 0 || y == 19) Grid[x][y]->SetNodeType(EPathNodeType::PN_Closed); else Grid[x][y]->SetNodeType(EPathNodeType::PN_Open);*/ Grid[x][y]->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform); Grid[x][y]->SetNodeType(EPathNodeType::PN_Open); Grid[x][y]->SetActorLocation(FVector(x * 100, y * -100, 0.f)); Grid[x][y]->UpdateNodeType(); Grid[x][y]->SetNodeWeight(1); Grid[x][y]->Graph = this; Grid[x][y]->SetGraphLocation(FGraphLocation(x, y)); } } } for (size_t x = 0; x < SquareSize; x++) { for (size_t y = 0; y < SquareSize; y++) { //Grid[x][y]->Neighbours = TArray<APathNode*>(); if (Grid[x][y]->GetNodeType() != EPathNodeType::PN_Closed) { if (y < SquareSize - 1) { Grid[x][y]->AddNeighbourNode(Grid[x][y + 1]); if (bAllowDiagonalMovement && x < SquareSize - 1) Grid[x][y]->AddNeighbourNode(Grid[x + 1][y + 1]); } if (x < SquareSize - 1) { Grid[x][y]->AddNeighbourNode(Grid[x + 1][y]); if (bAllowDiagonalMovement && y > 0) Grid[x][y]->AddNeighbourNode(Grid[x + 1][y - 1]); } if (y > 0) { Grid[x][y]->AddNeighbourNode(Grid[x][y - 1]); if (bAllowDiagonalMovement && x > 0) Grid[x][y]->AddNeighbourNode(Grid[x - 1][y - 1]); } if (x > 0) { Grid[x][y]->AddNeighbourNode(Grid[x - 1][y]); if (bAllowDiagonalMovement && y < SquareSize - 1) Grid[x][y]->AddNeighbourNode(Grid[x - 1][y + 1]); } } } } } void AGridGraph::ClearGraphNodes() { for (auto nodeArray : Grid) { for (auto node : nodeArray) { node->SetCameFrom(nullptr); //node->SetCostSoFar(0); } } } void AGridGraph::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { GEngine->AddOnScreenDebugMessage(0, 1.0f, FColor::Blue, "some property changed"); /* SquareSize = FMath::Clamp(SquareSize, 0, 100); if (Grid.Num() == 0) { if (SquareSize < 0) { return; } else { CreateGrid(); } } else { for (auto nodeArray : Grid) { for (auto node : nodeArray) { node->Destroy(); } } Grid.Empty(); CreateGrid(); } */ } void AGridGraph::BeginDestroy() { GEngine->AddOnScreenDebugMessage(0, 1.0f, FColor::Blue, "grid begin destroy called"); /* for (auto nodeArray : Grid) { for (auto node : nodeArray) { node->Destroy(); //GetWorld()->DestroyActor(node); } } Grid.Empty(); */ Super::BeginDestroy(); } // Called every frame //void AGridGraph::Tick(float DeltaTime) //{ // Super::Tick(DeltaTime); // //}
[ "arttu.gz94@hotmail.com" ]
arttu.gz94@hotmail.com
4a695c79e759221c91e29ada7638b6b7bbf20027
72f9348e3ced8105ecaaab3c23e0a7b19316bc70
/SDK/PUBG_ABP_Weapon_SCAR_functions.cpp
3f59263763d8847529e4852bf88f6ed2982263c2
[]
no_license
Kepa2012/cuckg_sdk
0737f29c7cea0c0bd08a65a46d008bdf5b6d4d4a
17aa2d8fdedc8e5665f420f85f8c6733bd1b1ae3
refs/heads/master
2021-09-09T06:16:06.258818
2018-03-14T05:04:26
2018-03-14T05:04:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,770
cpp
// PlayerUnknown's Battlegrounds (3.5.7.7) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_ABP_Weapon_SCAR_parameters.hpp" namespace PUBG { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.Handle_Fire // (Public, BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::Handle_Fire() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125699); UABP_Weapon_SCAR_C_Handle_Fire_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.BlueprintUpdateAnimation // (Event, Public, BlueprintEvent) // Parameters: // float* DeltaTimeX (Parm, ZeroConstructor, IsPlainOldData) void UABP_Weapon_SCAR_C::BlueprintUpdateAnimation(float* DeltaTimeX) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125697); UABP_Weapon_SCAR_C_BlueprintUpdateAnimation_Params params; params.DeltaTimeX = DeltaTimeX; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.BlueprintInitializeAnimation // (Event, Public, BlueprintEvent) void UABP_Weapon_SCAR_C::BlueprintInitializeAnimation() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125696); UABP_Weapon_SCAR_C_BlueprintInitializeAnimation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.WeaponFire_Event_1 // (BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::WeaponFire_Event_1() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125695); UABP_Weapon_SCAR_C_WeaponFire_Event_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.Reload1_Event_1 // (BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::Reload1_Event_1() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125694); UABP_Weapon_SCAR_C_Reload1_Event_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_09887E094E8FB8C6610C919B75736092 // (BlueprintEvent) void UABP_Weapon_SCAR_C::EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_09887E094E8FB8C6610C919B75736092() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125693); UABP_Weapon_SCAR_C_EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_09887E094E8FB8C6610C919B75736092_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.Reload2_Event_1 // (BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::Reload2_Event_1() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125692); UABP_Weapon_SCAR_C_Reload2_Event_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.FireSelect_Event_1 // (BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::FireSelect_Event_1() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125691); UABP_Weapon_SCAR_C_FireSelect_Event_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_4B9A8FC14E38A93E912DC482DEE75372 // (BlueprintEvent) void UABP_Weapon_SCAR_C::EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_4B9A8FC14E38A93E912DC482DEE75372() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125690); UABP_Weapon_SCAR_C_EvaluateGraphExposedInputs_ExecuteUbergraph_ABP_Weapon_SCAR_AnimGraphNode_ModifyBone_4B9A8FC14E38A93E912DC482DEE75372_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.CancelReload_Event_1 // (BlueprintCallable, BlueprintEvent) void UABP_Weapon_SCAR_C::CancelReload_Event_1() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125689); UABP_Weapon_SCAR_C_CancelReload_Event_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ABP_Weapon_SCAR.ABP_Weapon_SCAR_C.ExecuteUbergraph_ABP_Weapon_SCAR // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UABP_Weapon_SCAR_C::ExecuteUbergraph_ABP_Weapon_SCAR(int EntryPoint) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(125663); UABP_Weapon_SCAR_C_ExecuteUbergraph_ABP_Weapon_SCAR_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "roger@bitcoin.com" ]
roger@bitcoin.com
6af577314781a5d914d1bb18b1b4cd540810ffeb
23e28faf06342112da759de1355acd706d735800
/summit_xl_pad/src/summit_xl_pad_csl.cpp
ea071781455bde765318f05f1590ae16c8bf0526
[]
no_license
dtbinh/summit_csl
9923dda0e09c662a4ea3aff843b6c1f120694e2d
f24c89f1dad9ef7527bdcf7c3de19bae4f7082cb
refs/heads/master
2022-03-21T23:02:37.265857
2019-12-02T08:34:34
2019-12-02T08:34:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,729
cpp
/* * summit_xl_pad * Copyright (c) 2012, Robotnik Automation, SLL * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Robotnik Automation, SLL. 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. * * \author Robotnik Automation, SLL * \brief Allows to use a pad with the roboy controller, sending the messages received from the joystick device */ #include <ros/ros.h> #include <sensor_msgs/Joy.h> #include <geometry_msgs/Twist.h> #include <robotnik_msgs/ptz.h> // Not yet catkinized 9/2013 // #include <sound_play/sound_play.h> #include <unistd.h> #include <robotnik_msgs/set_mode.h> #include <robotnik_msgs/set_digital_output.h> #include <robotnik_msgs/ptz.h> #include <robotnik_msgs/home.h> #include <diagnostic_updater/diagnostic_updater.h> #include <diagnostic_updater/publisher.h> #define DEFAULT_NUM_OF_BUTTONS 16 #define DEFAULT_AXIS_LINEAR_X 1 #define DEFAULT_AXIS_LINEAR_Y 0 #define DEFAULT_AXIS_ANGULAR 2 #define DEFAULT_AXIS_LINEAR_Z 3 #define DEFAULT_SCALE_LINEAR 1.0 #define DEFAULT_SCALE_ANGULAR 2.0 #define DEFAULT_SCALE_LINEAR_Z 1.0 //Used only with ps4 #define AXIS_PTZ_TILT_UP 0 #define AXIS_PTZ_TILT_DOWN 1 #define AXIS_PTZ_PAN_LEFT 2 #define AXIS_PTZ_PAN_RIGHT 3 //////////////////////////////////////////////////////////////////////// // NOTE: // // This configuration is made for a THRUSTMASTER T-Wireless 3in1 Joy // // please feel free to modify to adapt for your own joystick. // // // class SummitXLPad { public: SummitXLPad(); void Update(); private: void padCallback(const sensor_msgs::Joy::ConstPtr& joy); ros::NodeHandle nh_; ros::NodeHandle pnh_; int linear_x_, linear_y_, linear_z_, angular_; double l_scale_, a_scale_, l_scale_z_; //! It will publish into command velocity (for the robot) and the ptz_state (for the pantilt) ros::Publisher vel_pub_, ptz_pub_; //! It will be suscribed to the joystick ros::Subscriber pad_sub_; //! Name of the topic where it will be publishing the velocity std::string cmd_topic_vel_; //! Name of the service where it will be modifying the digital outputs std::string cmd_service_io_; //! Name of the topic where it will be publishing the pant-tilt values std::string cmd_topic_ptz_; double current_vel; //! Pad type std::string pad_type_; //! Number of the DEADMAN button int dead_man_button_; //! Number of the button for increase or decrease the speed max of the joystick int speed_up_button_, speed_down_button_; int button_output_1_, button_output_2_; int output_1_, output_2_; bool bOutput1, bOutput2; //! button to change kinematic mode int button_kinematic_mode_; //! kinematic mode int kinematic_mode_; //! Service to modify the kinematic mode ros::ServiceClient setKinematicMode; //! Name of the service to change the mode std::string cmd_set_mode_; //! button to start the homing service int button_home_; //! Service to start homing ros::ServiceClient doHome; //! Name of the service to do the homing std::string cmd_home_; //! buttons to the pan-tilt-zoom camera int ptz_tilt_up_, ptz_tilt_down_, ptz_pan_right_, ptz_pan_left_; int ptz_zoom_wide_, ptz_zoom_tele_; //! Service to modify the digital outputs ros::ServiceClient set_digital_outputs_client_; //! Number of buttons of the joystick int num_of_buttons_; //! Pointer to a vector for controlling the event when pushing the buttons bool bRegisteredButtonEvent[DEFAULT_NUM_OF_BUTTONS]; //! Pointer to a vector for controlling the event when pushing directional arrows (UNDER AXES ON PX4!) bool bRegisteredDirectionalArrows[4]; // DIAGNOSTICS //! Diagnostic to control the frequency of the published command velocity topic diagnostic_updater::HeaderlessTopicDiagnostic *pub_command_freq; //! Diagnostic to control the reception frequency of the subscribed joy topic diagnostic_updater::HeaderlessTopicDiagnostic *sus_joy_freq; //! General status diagnostic updater diagnostic_updater::Updater updater_pad; //! Diagnostics min freq double min_freq_command, min_freq_joy; // //! Diagnostics max freq double max_freq_command, max_freq_joy; // //! Flag to enable/disable the communication with the publishers topics bool bEnable; //! Flag to track the first reading without the deadman's button pressed. bool last_command_; //! Client of the sound play service // sound_play::SoundClient sc; //! Pan & tilt increment (degrees) double pan_increment_, tilt_increment_; //! Zoom increment (steps) int zoom_increment_; //! Add a dead zone to the joystick that controls scissor and robot rotation (only useful for xWam) std::string joystick_dead_zone_; //! Flag to enable the ptz control via axes bool ptz_control_by_axes_; }; SummitXLPad::SummitXLPad(): linear_x_(1), linear_y_(0), angular_(2), linear_z_(3), pnh_("~") { current_vel = 0.1; //JOYSTICK PAD TYPE pnh_.param<std::string>("pad_type",pad_type_,"ps3"); // pnh_.param("num_of_buttons", num_of_buttons_, DEFAULT_NUM_OF_BUTTONS); // MOTION CONF pnh_.param("axis_linear_x", linear_x_, DEFAULT_AXIS_LINEAR_X); pnh_.param("axis_linear_y", linear_y_, DEFAULT_AXIS_LINEAR_Y); pnh_.param("axis_linear_z", linear_z_, DEFAULT_AXIS_LINEAR_Z); pnh_.param("axis_angular", angular_, DEFAULT_AXIS_ANGULAR); pnh_.param("scale_angular", a_scale_, DEFAULT_SCALE_ANGULAR); pnh_.param("scale_linear", l_scale_, DEFAULT_SCALE_LINEAR); pnh_.param("scale_linear_z", l_scale_z_, DEFAULT_SCALE_LINEAR_Z); pnh_.param("cmd_topic_vel", cmd_topic_vel_, cmd_topic_vel_); pnh_.param("button_dead_man", dead_man_button_, dead_man_button_); pnh_.param("button_speed_up", speed_up_button_, speed_up_button_); //4 Thrustmaster pnh_.param("button_speed_down", speed_down_button_, speed_down_button_); //5 Thrustmaster pnh_.param<std::string>("joystick_dead_zone", joystick_dead_zone_, "true"); // DIGITAL OUTPUTS CONF pnh_.param("cmd_service_io", cmd_service_io_, cmd_service_io_); pnh_.param("button_output_1", button_output_1_, button_output_1_); pnh_.param("button_output_2", button_output_2_, button_output_2_); pnh_.param("output_1", output_1_, output_1_); pnh_.param("output_2", output_2_, output_2_); // PANTILT-ZOOM CONF pnh_.param("cmd_topic_ptz", cmd_topic_ptz_, cmd_topic_ptz_); pnh_.param("button_ptz_tilt_up", ptz_tilt_up_, ptz_tilt_up_); pnh_.param("button_ptz_tilt_down", ptz_tilt_down_, ptz_tilt_down_); pnh_.param("button_ptz_pan_right", ptz_pan_right_, ptz_pan_right_); pnh_.param("button_ptz_pan_left", ptz_pan_left_, ptz_pan_left_); pnh_.param("button_ptz_zoom_wide", ptz_zoom_wide_, ptz_zoom_wide_); pnh_.param("button_ptz_zoom_tele", ptz_zoom_tele_, ptz_zoom_tele_); pnh_.param("button_home", button_home_, button_home_); pnh_.param("pan_increment", pan_increment_, 0.09); pnh_.param("tilt_increment", tilt_increment_, 0.09); pnh_.param("zoom_increment", zoom_increment_, 200); // KINEMATIC MODE pnh_.param("button_kinematic_mode", button_kinematic_mode_, button_kinematic_mode_); pnh_.param("cmd_service_set_mode", cmd_set_mode_, cmd_set_mode_); pnh_.param("cmd_service_home", cmd_home_, std::string("home")); kinematic_mode_ = 1; ROS_INFO("SummitXLPad num_of_buttons_ = %d, zoom = %d, %d", num_of_buttons_, ptz_zoom_wide_, ptz_zoom_tele_); for(int i = 0; i < num_of_buttons_; i++){ bRegisteredButtonEvent[i] = false; ROS_INFO("bREG %d", i); } for(int i = 0; i < 3; i++){ bRegisteredDirectionalArrows[i] = false; } /*ROS_INFO("Service I/O = [%s]", cmd_service_io_.c_str()); ROS_INFO("Topic PTZ = [%s]", cmd_topic_ptz_.c_str()); ROS_INFO("Service I/O = [%s]", cmd_topic_vel_.c_str()); ROS_INFO("Axis linear = %d", linear_); ROS_INFO("Axis angular = %d", angular_); ROS_INFO("Scale angular = %d", a_scale_); ROS_INFO("Deadman button = %d", dead_man_button_); ROS_INFO("OUTPUT1 button %d", button_output_1_); ROS_INFO("OUTPUT2 button %d", button_output_2_); ROS_INFO("OUTPUT1 button %d", button_output_1_); ROS_INFO("OUTPUT2 button %d", button_output_2_);*/ // Publish through the node handle Twist type messages to the guardian_controller/command topic vel_pub_ = nh_.advertise<geometry_msgs::Twist>(cmd_topic_vel_, 1); // Publishes msgs for the pant-tilt cam ptz_pub_ = nh_.advertise<robotnik_msgs::ptz>(cmd_topic_ptz_, 1); // Listen through the node handle sensor_msgs::Joy messages from joystick // (these are the references that we will sent to summit_xl_controller/command) pad_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &SummitXLPad::padCallback, this); // Request service to activate / deactivate digital I/O set_digital_outputs_client_ = nh_.serviceClient<robotnik_msgs::set_digital_output>(cmd_service_io_); bOutput1 = bOutput2 = false; // Request service to set kinematic mode setKinematicMode = nh_.serviceClient<robotnik_msgs::set_mode>(cmd_set_mode_); // Request service to start homing doHome = nh_.serviceClient<robotnik_msgs::home>(cmd_home_); // Diagnostics updater_pad.setHardwareID("None"); // Topics freq control min_freq_command = min_freq_joy = 5.0; max_freq_command = max_freq_joy = 50.0; sus_joy_freq = new diagnostic_updater::HeaderlessTopicDiagnostic("/joy", updater_pad, diagnostic_updater::FrequencyStatusParam(&min_freq_joy, &max_freq_joy, 0.1, 10)); pub_command_freq = new diagnostic_updater::HeaderlessTopicDiagnostic(cmd_topic_vel_.c_str(), updater_pad, diagnostic_updater::FrequencyStatusParam(&min_freq_command, &max_freq_command, 0.1, 10)); bEnable = false; // Communication flag disabled by default last_command_ = true; if(pad_type_=="ps4" || pad_type_=="logitechf710") ptz_control_by_axes_ = true; else ptz_control_by_axes_ = false; } /* * \brief Updates the diagnostic component. Diagnostics * */ void SummitXLPad::Update(){ updater_pad.update(); } void SummitXLPad::padCallback(const sensor_msgs::Joy::ConstPtr& joy) { geometry_msgs::Twist vel; robotnik_msgs::ptz ptz; bool ptzEvent = false; //TODO added by me bool in_use = false; vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0; vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; bEnable = (joy->buttons[dead_man_button_] == 1); // Actions dependant on dead-man button if (joy->buttons[dead_man_button_] == 1) { //ROS_ERROR("SummitXLPad::padCallback: DEADMAN button %d", dead_man_button_); //Set the current velocity level if ( joy->buttons[speed_down_button_] == 1 ){ if(!bRegisteredButtonEvent[speed_down_button_]) if(current_vel > 0.1){ current_vel = current_vel - 0.1; bRegisteredButtonEvent[speed_down_button_] = true; ROS_INFO("Velocity: %f%%", current_vel*100.0); char buf[50]="\0"; int percent = (int) (current_vel*100.0); sprintf(buf," %d percent", percent); // sc.say(buf); } }else{ bRegisteredButtonEvent[speed_down_button_] = false; } //ROS_ERROR("SummitXLPad::padCallback: Passed SPEED DOWN button %d", speed_down_button_); if (joy->buttons[speed_up_button_] == 1){ if(!bRegisteredButtonEvent[speed_up_button_]) if(current_vel < 0.9){ current_vel = current_vel + 0.1; bRegisteredButtonEvent[speed_up_button_] = true; ROS_INFO("Velocity: %f%%", current_vel*100.0); char buf[50]="\0"; int percent = (int) (current_vel*100.0); sprintf(buf," %d percent", percent); // sc.say(buf); } }else{ bRegisteredButtonEvent[speed_up_button_] = false; } //ROS_ERROR("SummitXLPad::padCallback: Passed SPEED UP button %d", speed_up_button_); vel.linear.x = current_vel*l_scale_*joy->axes[linear_x_]; if (kinematic_mode_ == 2) vel.linear.y = current_vel*l_scale_*joy->axes[linear_y_]; else vel.linear.y = 0.0; //ROS_ERROR("SummitXLPad::padCallback: Passed linear axes"); if(joystick_dead_zone_=="true") { // limit scissor movement or robot turning (they are in the same joystick) if(joy->axes[angular_] == 1.0 || joy->axes[angular_] == -1.0) // if robot turning { // Same angular velocity for the three axis vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]); vel.linear.z = 0.0; } else if (joy->axes[linear_z_] == 1.0 || joy->axes[linear_z_] == -1.0) // if scissor moving { vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement // limit robot turn vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; } else { // Same angular velocity for the three axis vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]); vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement } } else // no dead zone { vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]); vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]); vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; } //ROS_ERROR("SummitXLPad::padCallback: Passed joystick deadzone ifelse"); // LIGHTS if (joy->buttons[button_output_1_] == 1) { if(!bRegisteredButtonEvent[button_output_1_]){ //ROS_INFO("SummitXLPad::padCallback: OUTPUT1 button %d", button_output_1_); robotnik_msgs::set_digital_output write_do_srv; write_do_srv.request.output = output_1_; bOutput1=!bOutput1; write_do_srv.request.value = bOutput1; if(bEnable){ set_digital_outputs_client_.call( write_do_srv ); bRegisteredButtonEvent[button_output_1_] = true; } } }else{ bRegisteredButtonEvent[button_output_1_] = false; } if (joy->buttons[button_output_2_] == 1) { if(!bRegisteredButtonEvent[button_output_2_]){ //ROS_INFO("SummitXLPad::padCallback: OUTPUT2 button %d", button_output_2_); robotnik_msgs::set_digital_output write_do_srv; write_do_srv.request.output = output_2_; bOutput2=!bOutput2; write_do_srv.request.value = bOutput2; if(bEnable){ set_digital_outputs_client_.call( write_do_srv ); bRegisteredButtonEvent[button_output_2_] = true; } } }else{ bRegisteredButtonEvent[button_output_2_] = false; } //ROS_ERROR("SummitXLPad::padCallback: Passed LIGHTS"); // HOMING SERVICE if (joy->buttons[button_home_] == 1) { if (!bRegisteredButtonEvent[button_home_]) { robotnik_msgs::home home_srv; home_srv.request.request = true; if (bEnable) { ROS_INFO("SummitXLPad::padCallback - Home"); doHome.call( home_srv ); bRegisteredButtonEvent[button_home_] = true; } } // Use this button also to block robot motion while moving the scissor vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; vel.linear.x = 0.0; vel.linear.y = 0.0; } else { bRegisteredButtonEvent[button_home_]=false; } //ROS_ERROR("SummitXLPad::padCallback: Passed HOME BUTTON"); // PTZ ptz.pan = ptz.tilt = ptz.zoom = 0.0; ptz.relative = true; if(ptz_control_by_axes_) { if (joy->axes[ptz_tilt_up_] == -1.0) { if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP]){ ptz.tilt = tilt_increment_; //ROS_INFO("SummitXLPad::padCallback: TILT UP"); bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = true; ptzEvent = true; } }else{ bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = false; } if (joy->axes[ptz_tilt_down_] == 1.0) { if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN]){ ptz.tilt = -tilt_increment_; //ROS_INFO("SummitXLPad::padCallback: TILT DOWN"); bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = true; ptzEvent = true; } }else{ bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = false; } if (joy->axes[ptz_pan_left_] == -1.0) { if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT]){ ptz.pan = -pan_increment_; //ROS_INFO("SummitXLPad::padCallback: PAN LEFT"); bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = true; ptzEvent = true; } }else{ bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = false; } if (joy->axes[ptz_pan_right_] == 1.0) { if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT]){ ptz.pan = pan_increment_; //ROS_INFO("SummitXLPad::padCallback: PAN RIGHT"); bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = true; ptzEvent = true; } }else{ bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = false; } }else{ //ROS_ERROR("SummitXLPad::padCallback: INSIDE ELSE PTZ PAD_TYPE"); // TILT-MOVEMENTS (RELATIVE POS) if (joy->buttons[ptz_tilt_up_] == 1) { if(!bRegisteredButtonEvent[ptz_tilt_up_]){ ptz.tilt = tilt_increment_; //ROS_INFO("SummitXLPad::padCallback: TILT UP"); bRegisteredButtonEvent[ptz_tilt_up_] = true; ptzEvent = true; } }else { bRegisteredButtonEvent[ptz_tilt_up_] = false; } if (joy->buttons[ptz_tilt_down_] == 1) { if(!bRegisteredButtonEvent[ptz_tilt_down_]){ ptz.tilt = -tilt_increment_; //ROS_INFO("SummitXLPad::padCallback: TILT DOWN"); bRegisteredButtonEvent[ptz_tilt_down_] = true; ptzEvent = true; } }else{ bRegisteredButtonEvent[ptz_tilt_down_] = false; } // PAN-MOVEMENTS (RELATIVE POS) if (joy->buttons[ptz_pan_left_] == 1) { if(!bRegisteredButtonEvent[ptz_pan_left_]){ ptz.pan = -pan_increment_; //ROS_INFO("SummitXLPad::padCallback: PAN LEFT"); bRegisteredButtonEvent[ptz_pan_left_] = true; ptzEvent = true; } }else{ bRegisteredButtonEvent[ptz_pan_left_] = false; } if (joy->buttons[ptz_pan_right_] == 1) { if(!bRegisteredButtonEvent[ptz_pan_right_]){ ptz.pan = pan_increment_; //ROS_INFO("SummitXLPad::padCallback: PAN RIGHT"); bRegisteredButtonEvent[ptz_pan_right_] = true; ptzEvent = true; } }else{ bRegisteredButtonEvent[ptz_pan_right_] = false; } } // ZOOM Settings (RELATIVE) if (joy->buttons[ptz_zoom_wide_] == 1) { if(!bRegisteredButtonEvent[ptz_zoom_wide_]){ ptz.zoom = -zoom_increment_; //ROS_INFO("SummitXLPad::padCallback: ZOOM WIDe"); bRegisteredButtonEvent[ptz_zoom_wide_] = true; ptzEvent = true; } }else{ bRegisteredButtonEvent[ptz_zoom_wide_] = false; } if (joy->buttons[ptz_zoom_tele_] == 1) { if(!bRegisteredButtonEvent[ptz_zoom_tele_]){ ptz.zoom = zoom_increment_; //ROS_INFO("SummitXLPad::padCallback: ZOOM TELE"); bRegisteredButtonEvent[ptz_zoom_tele_] = true; ptzEvent = true; } }else{ bRegisteredButtonEvent[ptz_zoom_tele_] = false; } if (joy->buttons[button_kinematic_mode_] == 1) { if(!bRegisteredButtonEvent[button_kinematic_mode_]){ // Define mode (inc) - still coupled kinematic_mode_ += 1; if (kinematic_mode_ > 2) kinematic_mode_ = 1; ROS_INFO("SummitXLJoy::joyCallback: Kinematic Mode %d ", kinematic_mode_); // Call service robotnik_msgs::set_mode set_mode_srv; set_mode_srv.request.mode = kinematic_mode_; setKinematicMode.call( set_mode_srv ); bRegisteredButtonEvent[button_kinematic_mode_] = true; } }else{ bRegisteredButtonEvent[button_kinematic_mode_] = false; } //ROS_ERROR("SummitXLPad::padCallback: Passed SPHERE CAM and KINEMATIC MODE"); } else { vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0; } sus_joy_freq->tick(); // Ticks the reception of joy events // Publish // Only publishes if it's enabled if(bEnable){ if (ptzEvent) ptz_pub_.publish(ptz); vel_pub_.publish(vel); pub_command_freq->tick(); last_command_ = true; //TODO added by me in_use = true; } // if(!bEnable && last_command_){ // if (ptzEvent) ptz_pub_.publish(ptz); // // vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; // vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0; // vel_pub_.publish(vel); // pub_command_freq->tick(); // last_command_ = false; // } if(!bEnable){ if (ptzEvent) ptz_pub_.publish(ptz); //TODO added by me if (in_use) { vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0; vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0; vel_pub_.publish(vel); pub_command_freq->tick(); last_command_ = false; in_use = false; } } } int main(int argc, char** argv) { ros::init(argc, argv, "summit_xl_pad"); SummitXLPad summit_xl_pad; ros::Rate r(50.0); while( ros::ok() ){ // UPDATING DIAGNOSTICS summit_xl_pad.Update(); ros::spinOnce(); r.sleep(); } }
[ "logotm@gmail.com" ]
logotm@gmail.com
ac36ee18a770f1760065d23ba2422e550cc994d7
1222fafc421e1a9fc2956aa2fb5532c1535bdef7
/src/gradmanager.h
92906e3263f1b35b4e0868771762c119be4885b5
[]
no_license
MhYao2014/AssVec-ADMM-MPI
9b4a8c93ea963ba3a681f9551c3d2cb796c8fcd1
e6d53b3b5b15f0cd2bee0eb69b8651366dd5f2db
refs/heads/master
2020-12-08T14:49:15.551184
2020-04-19T12:43:41
2020-04-19T12:43:41
233,009,193
0
0
null
null
null
null
UTF-8
C++
false
false
644
h
// // Created by mhyao on 2020/3/25. // #ifndef ASSVEC_ADMM_MPI_GRADMANAGER_H #define ASSVEC_ADMM_MPI_GRADMANAGER_H #include "vector.h" #include <random> class GradManager { public: std::minstd_rand rng; long long inId; long long inDictId; long long TotalToken; int parallelNum; int repeatTime; Vector inputGrad; Vector inputVec; Vector inputVecBackUp; Vector outputGrad; Vector outputVec; Vector outputVecBackUp; std::vector<long long> outIdCount; double lossSG; double lr; GradManager(int dim, int seed); void setLr(double lr); }; #endif
[ "yaopeizhang1@yeah.net" ]
yaopeizhang1@yeah.net
56fd6ca8dc98a22b184224ed3ae74bf768b75d55
7bad194abb98dac6a3d27176b712da4c5e7f0757
/PriorityQueue/CallCenter.h
69826d3ae926d4be48710ebdc442f8286c9686d6
[]
no_license
uck16m1997/CppDataStructures
0e9f8362ec9e722a2da62aef0b59733bd946fc5f
d152581b4fd22f529fe0ca435489b6e153f49f0d
refs/heads/master
2020-06-15T04:34:15.461178
2019-07-04T09:01:43
2019-07-04T09:01:43
195,204,532
2
0
null
null
null
null
UTF-8
C++
false
false
1,086
h
#ifndef CALLCENTER_H #define CALLCENTER_H #include "PriorityQueue.h" class CallCenter { public: CallCenter();//constructor assigns variables to their initial values void AcceptCall(Call c);//ads the call to the waiting list void UpdateCenter();/*increments the time variable if there are no calls ongoin but there the waitlist not empty takes the call from waitlist to an ongoing call and stores their wait time and priority infos if there is an call ongoing then checks if the call equal to the answer time if it is closes the call and increases the numberof calls answered*/ bool CenterDone(); // returns true if there are no call in the waitlist or ongoing else returns false void DisplayResults();//displays the simulation results void DisplayStatus();//displays the current status of the simulation private: PriorityQueue pQueue; Call curCall; int numOfAnsCalls; int totalTime; int waitTime; double waitP1; double waitP2; double waitP3; int numOfP1; int numOfP2; int numOfP3; int openTime; }; #endif
[ "noreply@github.com" ]
noreply@github.com
24f21a7d2b516e1e35a40114719c656e04fd75cd
be87ba1d9433f0bdceaa92d8441054693949e449
/pest++/yamr/network_package.cpp
ccd8116ecca69e5c5ce92a2490d4c132d38cb097
[]
no_license
odellus/pestpp
278fa6e58e7a8ac18e8d46ab1a90595ba14c30bf
8194c0677f1fa26806897d855573f60656a33a1f
refs/heads/master
2021-01-24T17:28:50.279053
2014-04-05T00:59:51
2014-04-05T00:59:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,568
cpp
#include <memory> #include <sstream> #include <cstring> #include "network_package.h" #include "network_wrapper.h" #include <cassert> using namespace std; //Static Memeber Initialization int NetPackage::last_group_id = 0; //Static Methods int NetPackage::get_new_group_id() { return ++last_group_id; } //Non static methods NetPackage::NetPackage(PackType _type, int _group, int _run_id, const string &desc_str) : type(_type), group(_group), run_id(_run_id) { memset(desc, '\0', DESC_LEN); strncpy(desc, desc_str.c_str(), DESC_LEN-1); data_len = 1; } void NetPackage::reset(PackType _type, int _group, int _run_id, const string &_desc) { type = _type; group = _group; run_id = _run_id; memset(desc, '\0', DESC_LEN); strncpy(desc, _desc.c_str(), DESC_LEN-1); data.clear(); } int NetPackage::send(int sockfd, const void *data, unsigned long data_len_l) { int n; unsigned long buf_sz = 0; //calculate the size of buffer buf_sz = sizeof(buf_sz); buf_sz += sizeof(type); buf_sz += sizeof(group); buf_sz += sizeof(run_id); buf_sz += sizeof(desc); buf_sz += data_len_l; //pack information into buffer //unique_ptr<char[]> buf(new char[buf_sz]); vector<char> buf; buf.resize(buf_sz, '\0'); size_t i_start = 0; w_memcpy_s(&buf[i_start], buf_sz-i_start, &buf_sz, sizeof(buf_sz)); i_start += sizeof(buf_sz); w_memcpy_s(&buf[i_start], buf_sz-i_start, &type, sizeof(type)); i_start += sizeof(type); w_memcpy_s(&buf[i_start], buf_sz-i_start, &group, sizeof(group)); i_start += sizeof(group); w_memcpy_s(&buf[i_start], buf_sz-i_start, &run_id, sizeof(run_id)); i_start += sizeof(run_id); w_memcpy_s(&buf[i_start], buf_sz-i_start, desc, sizeof(desc)); i_start += sizeof(desc); if (data_len_l > 0) { w_memcpy_s(&buf[i_start], buf_sz-i_start, data, data_len_l); i_start += data_len_l; } if (i_start!=buf_sz) { cerr << "NetPackage::send error: could ony send" << i_start << " out of " << buf_sz << "bytes" << endl; } assert (i_start==buf_sz); n = w_sendall(sockfd, buf.data(), &buf_sz); return n; // return 0 on sucess or -1 on failure } int NetPackage::recv(int sockfd) { int n; unsigned long header_sz = 0; unsigned long buf_sz = 0; size_t i_start = 0; //get header (ie size, seq_id, id and name) header_sz = sizeof(buf_sz) + sizeof(type) + sizeof(group) + sizeof(run_id) + sizeof(desc); vector<char> header_buf; header_buf.resize(header_sz, '\0'); n = w_recvall(sockfd, &header_buf[0], &header_sz); if(n>0) { assert(header_sz==header_buf.size()); i_start = 0; w_memcpy_s(&buf_sz, sizeof(buf_sz), &header_buf[i_start], sizeof(buf_sz)); i_start += sizeof(buf_sz); w_memcpy_s(&type, sizeof(type), &header_buf[i_start], sizeof(type)); i_start += sizeof(type); w_memcpy_s(&group, sizeof(group), &header_buf[i_start], sizeof(group)); i_start += sizeof(group); w_memcpy_s(&run_id, sizeof(run_id), &header_buf[i_start], sizeof(run_id)); i_start += sizeof(run_id); w_memcpy_s(&desc, sizeof(desc), &header_buf[i_start], sizeof(desc)); i_start += sizeof(desc); desc[DESC_LEN-1] = '\0'; //get data data_len = buf_sz - i_start; data.resize(data_len, '\0'); if (data_len > 0) { n = w_recvall(sockfd, &data[0], &data_len); assert(data_len==buf_sz-header_sz); } } if (n> 1) {n=1;} return n; // -1 on failure, 0 on a close connection or 1 on success } void NetPackage::print_header(std::ostream &fout) { fout << "NetPackage: type = " << int(type) <<", group = " << group << ", run_id = " << run_id << ", description = " << desc << ", data package size = " << data.size() << endl; }
[ "dwelter1@bellsouth.net" ]
dwelter1@bellsouth.net
91634b2f88b1181e85938862bb895ef421eb5ca7
17deea08baa3ab70fcfb14d9821eac9143a78181
/MonoTest/Label.cpp
880197a3b7e61d17ed0fe8f6efe811a094dee347
[]
no_license
OSM-Made/Mono-Test
09ea9e7b47648b2a61f7b7bd1edbf683317a79db
2cfcbd7e8ea11d389bee29a2973a782e4c563f29
refs/heads/master
2023-04-26T01:09:01.838086
2021-05-11T00:22:01
2021-05-11T00:22:01
364,706,842
10
3
null
null
null
null
UTF-8
C++
false
false
2,451
cpp
#include "Common.h" #include "UI.h" #include "Widget.h" #include "Label.h" void Label::Set_Location(float X, float Y) { Mono::Set_Property(Label_Class, Instance, "X", X); Mono::Set_Property(Label_Class, Instance, "Y", Y); } void Label::Set_Text(const char* Text) { Mono::Set_Property(Label_Class, Instance, "Text", Mono::New_String(Text)); } void Label::Set_Font(int Size, FontStyle Style, FontWeight Weight) { Mono::Set_Property_Invoke(Label_Class, Instance, "Font", UI::Drawing::IUFont(Size, Style, Weight)); } void Label::Set_Alignment(VerticalAlignment Vertical_Align, HorizontalAlignment Horizontal_Align) { Mono::Set_Property(Label_Class, Instance, "VerticalAlignment", Vertical_Align); Mono::Set_Property(Label_Class, Instance, "HorizontalAlignment", Horizontal_Align); } void Label::Set_Colour(float R, float G, float B, float A) { Mono::Set_Property_Invoke(Label_Class, Instance, "TextColor", NewUIColor(R, G, B, A)); } float Label::Get_Text_Width() { return Mono::Invoke<float>(Mono::App_exe, Label_Class, Instance, "GetTextWidth"); } float Label::Get_Text_Height() { return Mono::Invoke<float>(Mono::App_exe, Label_Class, Instance, "GetTextHeight"); } Label::Label(const char* Name) { Label_Class = Mono::Get_Class(Mono::Highlevel_UI2, "Sce.PlayStation.HighLevel.UI2", "Label"); //Allocates memory for our new instance of a class. Instance = Mono::New_Object(Label_Class); //Call Constructor. mono_runtime_object_init(Instance); //Set Panel Name Mono::Set_Property(Label_Class, Instance, "Name", Mono::New_String(Name)); } Label::Label(const char* Name, float X, float Y, const char* Text, int Size, FontStyle Style, FontWeight Weight, VerticalAlignment Vertical_Align, HorizontalAlignment Horizontal_Align, float R, float G, float B, float A) { Label_Class = Mono::Get_Class(Mono::Highlevel_UI2, "Sce.PlayStation.HighLevel.UI2", "Label"); //Allocates memory for our new instance of a class. Instance = Mono::New_Object(Label_Class); //Call Constructor. mono_runtime_object_init(Instance); //Set Panel Name Mono::Set_Property(Label_Class, Instance, "Name", Mono::New_String(Name)); //Set Values Set_Location(X, Y); Set_Text(Text); Set_Font(Size, Style, Weight); Set_Alignment(Vertical_Align, Horizontal_Align); Set_Colour(R, G, B, A); Mono::Set_Property(Label_Class, Instance, "FitWidthToText", true); Mono::Set_Property(Label_Class, Instance, "FitHeightToText", true); } Label::~Label() { }
[ "oldskoolmodz@gmail.com" ]
oldskoolmodz@gmail.com
778f3fd444849277e75d91451811948512775887
ba4db75b9d1f08c6334bf7b621783759cd3209c7
/src_main/hammer/ToolSphere.h
43c1198d93ee290e6328b4301c2a5c1ff7802f2a
[]
no_license
equalent/source-2007
a27326c6eb1e63899e3b77da57f23b79637060c0
d07be8d02519ff5c902e1eb6430e028e1b302c8b
refs/heads/master
2020-03-28T22:46:44.606988
2017-03-27T18:05:57
2017-03-27T18:05:57
149,257,460
2
0
null
2018-09-18T08:52:10
2018-09-18T08:52:09
null
WINDOWS-1252
C++
false
false
956
h
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef TOOLSPHERE_H #define TOOLSPHERE_H #ifdef _WIN32 #pragma once #endif #include "ToolInterface.h" class CMapSphere; class CToolSphere : public CBaseTool { public: CToolSphere(); void Attach(CMapSphere *pShere); // // CBaseTool implementation. // virtual ToolID_t GetToolID(void) { return TOOL_SPHERE; } virtual bool OnLMouseDown2D(CMapView2D *pView, UINT nFlags, const Vector2D &vPoint); virtual bool OnLMouseUp2D(CMapView2D *pView, UINT nFlags, const Vector2D &vPoint); virtual bool OnMouseMove2D(CMapView2D *pView, UINT nFlags, const Vector2D &vPoint); //virtual void RenderTool2D(CRender2D *pRender); private: CMapSphere *m_pSphere; }; #endif // TOOLSPHERE_H
[ "sean@csnxs.uk" ]
sean@csnxs.uk
19076b9fa7215402a1a8f933159f01f595376836
ae956d4076e4fc03b632a8c0e987e9ea5ca89f56
/SDK/TBP_OC_NOS_M_OU_09_classes.h
3bbfb474ca1ccdd765d6911880a5eb8fc2a59f3c
[]
no_license
BrownBison/Bloodhunt-BASE
5c79c00917fcd43c4e1932bee3b94e85c89b6bc7
8ae1104b748dd4b294609717142404066b6bc1e6
refs/heads/main
2023-08-07T12:04:49.234272
2021-10-02T15:13:42
2021-10-02T15:13:42
638,649,990
1
0
null
2023-05-09T20:02:24
2023-05-09T20:02:23
null
UTF-8
C++
false
false
772
h
#pragma once // Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass TBP_OC_NOS_M_OU_09.TBP_OC_NOS_M_OU_09_C // 0x0000 (FullSize[0x02A0] - InheritedSize[0x02A0]) class UTBP_OC_NOS_M_OU_09_C : public UTigerCharacterOutfitConfiguration { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass TBP_OC_NOS_M_OU_09.TBP_OC_NOS_M_OU_09_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "69031575+leoireo@users.noreply.github.com" ]
69031575+leoireo@users.noreply.github.com
51f4bb413fc777690019bfd1eabeb8f96e6b8f84
aa7eca0eeccc7c71678a90fc04c02dce9f47ec46
/Codes_13TeV/LimitTool_HiggsCombine/HiggsAnalysis_modified/CombinedLimit/interface/MultiDimFit.h
e856bef25735b536876d8a46d51811a4991353b8
[]
no_license
rockybala/Analyses_codes
86c055ebe45b8ec96ed7bcddc5dd9c559d643523
cc727a3414bef37d2e2110b66a4cbab8ba2bacf2
refs/heads/master
2021-09-15T10:25:33.040778
2018-05-30T11:50:42
2018-05-30T11:50:42
133,632,693
0
2
null
null
null
null
UTF-8
C++
false
false
3,203
h
#ifndef HiggsAnalysis_CombinedLimit_MultiDimFit_h #define HiggsAnalysis_CombinedLimit_MultiDimFit_h /** \class MultiDimFit * * Do a ML fit with multiple POI * * \author Giovanni Petrucciani (UCSD) * * */ #include "HiggsAnalysis/CombinedLimit/interface/FitterAlgoBase.h" #include <RooRealVar.h> #include <vector> class MultiDimFit : public FitterAlgoBase { public: MultiDimFit() ; virtual const std::string & name() const { static const std::string name("MultiDimFit"); return name; } virtual void applyOptions(const boost::program_options::variables_map &vm) ; protected: virtual bool runSpecific(RooWorkspace *w, RooStats::ModelConfig *mc_s, RooStats::ModelConfig *mc_b, RooAbsData &data, double &limit, double &limitErr, const double *hint); enum Algo { None, Singles, Cross, Grid, RandomPoints, Contour2D, Stitch2D, FixedPoint, Impact }; static Algo algo_; enum GridType { G1x1, G3x3 }; static GridType gridType_; static std::vector<std::string> poi_; static std::vector<RooRealVar*> poiVars_; static std::vector<float> poiVals_; static RooArgList poiList_; static unsigned int nOtherFloatingPoi_; // keep a count of other POIs that we're ignoring, for proper chisquare normalization static float deltaNLL_; // options static unsigned int points_, firstPoint_, lastPoint_; static bool floatOtherPOIs_; static bool squareDistPoiStep_; static bool skipInitialFit_; static bool fastScan_; static bool hasMaxDeltaNLLForProf_; static bool loadedSnapshot_, savingSnapshot_; static float maxDeltaNLLForProf_; static float autoRange_; static bool startFromPreFit_; static std::string fixedPointPOIs_; static std::string saveSpecifiedFuncs_; static std::string saveSpecifiedNuis_; static std::string saveSpecifiedIndex_; static std::vector<std::string> specifiedFuncNames_; static std::vector<RooAbsReal*> specifiedFunc_; static std::vector<float> specifiedFuncVals_; static RooArgList specifiedFuncList_; static std::vector<std::string> specifiedCatNames_; static std::vector<RooCategory*> specifiedCat_; static std::vector<int> specifiedCatVals_; static RooArgList specifiedCatList_; static std::vector<std::string> specifiedNuis_; static std::vector<RooRealVar *> specifiedVars_; static std::vector<float> specifiedVals_; static RooArgList specifiedList_; static bool saveInactivePOI_; // initialize variables void initOnce(RooWorkspace *w, RooStats::ModelConfig *mc_s) ; // variables void doSingles(RooFitResult &res) ; void doGrid(RooWorkspace *w, RooAbsReal &nll) ; void doRandomPoints(RooWorkspace *w, RooAbsReal &nll) ; void doFixedPoint(RooWorkspace *w, RooAbsReal &nll) ; void doContour2D(RooWorkspace *w, RooAbsReal &nll) ; void doStitch2D(RooWorkspace *w, RooAbsReal &nll) ; void doImpact(RooFitResult &res, RooAbsReal &nll) ; // utilities /// for each RooRealVar, set a range 'box' from the PL profiling all other parameters void doBox(RooAbsReal &nll, double cl, const char *name="box", bool commitPoints=true) ; }; #endif
[ "rgarg@cern.ch" ]
rgarg@cern.ch
ca499d346f0f73547113b4538bc41bff589ebc3b
303cb679fdcd8a436dbd373f98da679eefefae01
/3rdParty/Breakpad/src/tools/windows/symupload/symupload.cc
7e3029326d5cd684c1727ec51d4ef9f2f572faf9
[ "BSD-3-Clause", "LicenseRef-scancode-unicode-mappings", "MIT" ]
permissive
rohmer/LVGL_UI_Creator
d812a66ca8e3f8a736b02f074d6fbb324560b881
8ff044064819be0ab52eee89642956a3cc81564b
refs/heads/Dev
2023-02-16T01:25:33.247640
2023-02-09T16:58:50
2023-02-09T16:58:50
209,129,978
37
17
MIT
2023-02-09T16:58:51
2019-09-17T18:35:36
C
UTF-8
C++
false
false
13,113
cc
// Copyright (c) 2006, Google Inc. // 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 Google Inc. 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. // Tool to upload an exe/dll and its associated symbols to an HTTP server. // The PDB file is located automatically, using the path embedded in the // executable. The upload is sent as a multipart/form-data POST request, // with the following parameters: // code_file: the basename of the module, e.g. "app.exe" // debug_file: the basename of the debugging file, e.g. "app.pdb" // debug_identifier: the debug file's identifier, usually consisting of // the guid and age embedded in the pdb, e.g. // "11111111BBBB3333DDDD555555555555F" // product: the HTTP-friendly product name, e.g. "MyApp" // version: the file version of the module, e.g. "1.2.3.4" // os: the operating system that the module was built for, always // "windows" in this implementation. // cpu: the CPU that the module was built for, typically "x86". // symbol_file: the contents of the breakpad-format symbol file #include <windows.h> #include <dbghelp.h> #include <wininet.h> #include <cstdio> #include <map> #include <string> #include <vector> #include "common/windows/string_utils-inl.h" #include "common/windows/http_upload.h" #include "common/windows/pdb_source_line_writer.h" #include "common/windows/symbol_collector_client.h" using std::string; using std::wstring; using std::vector; using std::map; using google_breakpad::HTTPUpload; using google_breakpad::SymbolCollectorClient; using google_breakpad::SymbolStatus; using google_breakpad::UploadUrlResponse; using google_breakpad::CompleteUploadResult; using google_breakpad::PDBModuleInfo; using google_breakpad::PDBSourceLineWriter; using google_breakpad::WindowsStringUtils; // Extracts the file version information for the given filename, // as a string, for example, "1.2.3.4". Returns true on success. static bool GetFileVersionString(const wchar_t *filename, wstring *version) { DWORD handle; DWORD version_size = GetFileVersionInfoSize(filename, &handle); if (version_size < sizeof(VS_FIXEDFILEINFO)) { return false; } vector<char> version_info(version_size); if (!GetFileVersionInfo(filename, handle, version_size, &version_info[0])) { return false; } void *file_info_buffer = NULL; unsigned int file_info_length; if (!VerQueryValue(&version_info[0], L"\\", &file_info_buffer, &file_info_length)) { return false; } // The maximum value of each version component is 65535 (0xffff), // so the max length is 24, including the terminating null. wchar_t ver_string[24]; VS_FIXEDFILEINFO *file_info = reinterpret_cast<VS_FIXEDFILEINFO*>(file_info_buffer); swprintf(ver_string, sizeof(ver_string) / sizeof(ver_string[0]), L"%d.%d.%d.%d", file_info->dwFileVersionMS >> 16, file_info->dwFileVersionMS & 0xffff, file_info->dwFileVersionLS >> 16, file_info->dwFileVersionLS & 0xffff); // remove when VC++7.1 is no longer supported ver_string[sizeof(ver_string) / sizeof(ver_string[0]) - 1] = L'\0'; *version = ver_string; return true; } // Creates a new temporary file and writes the symbol data from the given // exe/dll file to it. Returns the path to the temp file in temp_file_path // and information about the pdb in pdb_info. static bool DumpSymbolsToTempFile(const wchar_t *file, wstring *temp_file_path, PDBModuleInfo *pdb_info) { google_breakpad::PDBSourceLineWriter writer; // Use EXE_FILE to get information out of the exe/dll in addition to the // pdb. The name and version number of the exe/dll are of value, and // there's no way to locate an exe/dll given a pdb. if (!writer.Open(file, PDBSourceLineWriter::EXE_FILE)) { return false; } wchar_t temp_path[_MAX_PATH]; if (GetTempPath(_MAX_PATH, temp_path) == 0) { return false; } wchar_t temp_filename[_MAX_PATH]; if (GetTempFileName(temp_path, L"sym", 0, temp_filename) == 0) { return false; } FILE *temp_file = NULL; #if _MSC_VER >= 1400 // MSVC 2005/8 if (_wfopen_s(&temp_file, temp_filename, L"w") != 0) #else // _MSC_VER >= 1400 // _wfopen_s was introduced in MSVC8. Use _wfopen for earlier environments. // Don't use it with MSVC8 and later, because it's deprecated. if (!(temp_file = _wfopen(temp_filename, L"w"))) #endif // _MSC_VER >= 1400 { return false; } bool success = writer.WriteSymbols(temp_file); fclose(temp_file); if (!success) { _wunlink(temp_filename); return false; } *temp_file_path = temp_filename; return writer.GetModuleInfo(pdb_info); } static bool DoSymUploadV2( const wchar_t* api_url, const wchar_t* api_key, const wstring& debug_file, const wstring& debug_id, const wstring& symbol_file, bool force) { wstring url(api_url); wstring key(api_key); if (!force) { SymbolStatus symbolStatus = SymbolCollectorClient::CheckSymbolStatus( url, key, debug_file, debug_id); if (symbolStatus == SymbolStatus::Found) { wprintf(L"Symbol file already exists, upload aborted." L" Use \"-f\" to overwrite.\n"); return true; } else if (symbolStatus == SymbolStatus::Unknown) { wprintf(L"Failed to get check for existing symbol.\n"); return false; } } UploadUrlResponse uploadUrlResponse; if (!SymbolCollectorClient::CreateUploadUrl( url, key, &uploadUrlResponse)) { wprintf(L"Failed to create upload URL.\n"); return false; } wstring signed_url = uploadUrlResponse.upload_url; wstring upload_key = uploadUrlResponse.upload_key; wstring response; int response_code; bool success = HTTPUpload::SendPutRequest( signed_url, symbol_file, /* timeout = */ NULL, &response, &response_code); if (!success) { wprintf(L"Failed to send symbol file.\n"); wprintf(L"Response code: %ld\n", response_code); wprintf(L"Response:\n"); wprintf(L"%s\n", response.c_str()); return false; } else if (response_code == 0) { wprintf(L"Failed to send symbol file: No response code\n"); return false; } else if (response_code != 200) { wprintf(L"Failed to send symbol file: Response code %ld\n", response_code); wprintf(L"Response:\n"); wprintf(L"%s\n", response.c_str()); return false; } CompleteUploadResult completeUploadResult = SymbolCollectorClient::CompleteUpload( url, key, upload_key, debug_file, debug_id); if (completeUploadResult == CompleteUploadResult::Error) { wprintf(L"Failed to complete upload.\n"); return false; } else if (completeUploadResult == CompleteUploadResult::DuplicateData) { wprintf(L"Uploaded file checksum matched existing file checksum," L" no change necessary.\n"); } else { wprintf(L"Successfully sent the symbol file.\n"); } return true; } __declspec(noreturn) void printUsageAndExit() { wprintf(L"Usage:\n\n" L" symupload [--timeout NN] [--product product_name] ^\n" L" <file.exe|file.dll> <symbol upload URL> ^\n" L" [...<symbol upload URLs>]\n\n"); wprintf(L" - Timeout is in milliseconds, or can be 0 to be unlimited.\n"); wprintf(L" - product_name is an HTTP-friendly product name. It must only\n" L" contain an ascii subset: alphanumeric and punctuation.\n" L" This string is case-sensitive.\n\n"); wprintf(L"Example:\n\n" L" symupload.exe --timeout 0 --product Chrome ^\n" L" chrome.dll http://no.free.symbol.server.for.you\n"); wprintf(L"\n"); wprintf(L"sym-upload-v2 usage:\n" L" symupload -p [-f] <file.exe|file.dll> <API-URL> <API-key>\n"); wprintf(L"\n"); wprintf(L"sym_upload_v2 Options:\n"); wprintf(L" <API-URL> is the sym_upload_v2 API URL.\n"); wprintf(L" <API-key> is a secret used to authenticate with the API.\n"); wprintf(L" -p:\t Use sym_upload_v2 protocol.\n"); wprintf(L" -f:\t Force symbol upload if already exists.\n"); exit(0); } int wmain(int argc, wchar_t *argv[]) { const wchar_t *module; const wchar_t *product = nullptr; int timeout = -1; int currentarg = 1; bool use_sym_upload_v2 = false; bool force = false; const wchar_t* api_url = nullptr; const wchar_t* api_key = nullptr; while (argc > currentarg + 1) { if (!wcscmp(L"--timeout", argv[currentarg])) { timeout = _wtoi(argv[currentarg + 1]); currentarg += 2; continue; } if (!wcscmp(L"--product", argv[currentarg])) { product = argv[currentarg + 1]; currentarg += 2; continue; } if (!wcscmp(L"-p", argv[currentarg])) { use_sym_upload_v2 = true; ++currentarg; continue; } if (!wcscmp(L"-f", argv[currentarg])) { force = true; ++currentarg; continue; } break; } if (argc >= currentarg + 2) module = argv[currentarg++]; else printUsageAndExit(); wstring symbol_file; PDBModuleInfo pdb_info; if (!DumpSymbolsToTempFile(module, &symbol_file, &pdb_info)) { fwprintf(stderr, L"Could not get symbol data from %s\n", module); return 1; } wstring code_file = WindowsStringUtils::GetBaseName(wstring(module)); wstring file_version; // Don't make a missing version a hard error. Issue a warning, and let the // server decide whether to reject files without versions. if (!GetFileVersionString(module, &file_version)) { fwprintf(stderr, L"Warning: Could not get file version for %s\n", module); } bool success = true; if (use_sym_upload_v2) { if (argc >= currentarg + 2) { api_url = argv[currentarg++]; api_key = argv[currentarg++]; success = DoSymUploadV2( api_url, api_key, pdb_info.debug_file, pdb_info.debug_identifier, symbol_file, force); } else { printUsageAndExit(); } } else { map<wstring, wstring> parameters; parameters[L"code_file"] = code_file; parameters[L"debug_file"] = pdb_info.debug_file; parameters[L"debug_identifier"] = pdb_info.debug_identifier; parameters[L"os"] = L"windows"; // This version of symupload is Windows-only parameters[L"cpu"] = pdb_info.cpu; map<wstring, wstring> files; files[L"symbol_file"] = symbol_file; if (!file_version.empty()) { parameters[L"version"] = file_version; } // Don't make a missing product name a hard error. Issue a warning and let // the server decide whether to reject files without product name. if (product) { parameters[L"product"] = product; } else { fwprintf( stderr, L"Warning: No product name (flag --product) was specified for %s\n", module); } while (currentarg < argc) { int response_code; if (!HTTPUpload::SendMultipartPostRequest(argv[currentarg], parameters, files, timeout == -1 ? NULL : &timeout, nullptr, &response_code)) { success = false; fwprintf(stderr, L"Symbol file upload to %s failed. Response code = %ld\n", argv[currentarg], response_code); } currentarg++; } } _wunlink(symbol_file.c_str()); if (success) { wprintf(L"Uploaded breakpad symbols for windows-%s/%s/%s (%s %s)\n", pdb_info.cpu.c_str(), pdb_info.debug_file.c_str(), pdb_info.debug_identifier.c_str(), code_file.c_str(), file_version.c_str()); } return success ? 0 : 1; }
[ "rohmerpi@bitbucket.org" ]
rohmerpi@bitbucket.org
07990e36dc77844e59887394dfb1566dbf31678f
c7d98beb689410cbba2c712a01c25863f267b5dc
/src/util.h
2db4513289eb19f9cf5d124333c2f503872bd886
[]
no_license
ml4ai/hamlet_experiment_py2
2b8d5b21e9c3c62bc17409da4971869aaf13f705
2d49f797d0ee0baa0447e0965468e7c15e796bb7
refs/heads/master
2021-03-27T11:41:43.494446
2017-11-06T14:31:18
2017-11-06T14:31:18
61,496,702
0
1
null
null
null
null
UTF-8
C++
false
false
10,255
h
/* $Id: util.h 21509 2017-07-21 17:39:13Z cdawson $ */ #ifndef UTIL_H_ #define UTIL_H_ /*! * @file util.h * * @author Colin Dawson */ #include <l_cpp/l_stdio_wrap.h> #include <l_cpp/l_util.h> #include <l_cpp/l_int_matrix.h> #include <l_cpp/l_index.h> #include <m_cpp/m_matrix.h> #include <gsl_cpp/gsl_rng.h> #include <third_party/rtnorm.hpp> #include <third_party/underflow_utils.h> #include <prob_cpp/prob_util.h> #include <prob_cpp/prob_distribution.h> #include <prob_cpp/prob_sample.h> #include <boost/random.hpp> #include <boost/bind.hpp> #include <boost/unordered_map.hpp> //need to include boost algorithm string #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <fstream> //include for the macro #include <boost/preprocessor/seq.hpp> //end change #include <map> #include <cmath> #ifdef DEBUGGING #define PM(condition, msg) \ do \ { \ if (condition) \ { \ printf(msg); \ } \ } \ while(0) #define PMWP(condition, msg, params) \ do \ { \ if (condition) \ { \ printf(msg, \ BOOST_PP_SEQ_ENUM(params)); \ } \ } \ while(0) #else #define PM(condition, msg) #define PMWP(condition, msg, params) #endif #define NULL_SHAPE -1.0 #define NULL_RATE -1.0 #define NULL_CONC -1.0 #define NULL_BETA_PARAM -1.0 #define NULL_STRING "" class HMM_base; class HDP_HMM_LT; class State_model; class Emission_model; class Transition_model; struct Transition_prior_parameters; class Transition_prior; struct Dynamics_parameters; class Dynamics_model; class Similarity_model; typedef kjb::Matrix Mean_matrix; typedef kjb::Vector Mean_vector; typedef kjb::Vector Scale_vector; typedef boost::shared_ptr<Transition_prior> Transition_prior_ptr; typedef boost::shared_ptr<State_model> State_model_ptr; typedef boost::shared_ptr<Emission_model> Emission_model_ptr; typedef boost::shared_ptr<Similarity_model> Similarity_model_ptr; typedef boost::shared_ptr<Dynamics_model> Dynamics_model_ptr; typedef boost::shared_ptr<const Transition_prior> Transition_prior_const_ptr; typedef boost::shared_ptr<const State_model> State_model_const_ptr; typedef boost::shared_ptr<const Emission_model> Emission_model_const_ptr; typedef boost::shared_ptr<const Similarity_model> Similarity_model_const_ptr; typedef boost::shared_ptr<const Dynamics_model> Dynamics_model_const_ptr; typedef std::vector<Mean_matrix> Mean_matrix_list; /// Variable types typedef double Prob; typedef double Conc; typedef int Count; typedef double Cts_duration; typedef double Distance; typedef size_t Dsct_duration; typedef int State_indicator; typedef size_t Time_index; typedef std::vector<Time_index> Time_set; typedef kjb::Matrix State_matrix; typedef kjb::Vector State_type; typedef State_matrix::Value_type Coordinate; typedef kjb::Int_vector State_sequence; typedef kjb::Vector Prob_vector; typedef kjb::Const_matrix_vector_view Const_prob_row_view; typedef kjb::Matrix_vector_view Prob_row_view; typedef kjb::Matrix Prob_matrix; typedef std::vector<Count> Count_vector; typedef kjb::Int_matrix Count_matrix; typedef kjb::Int_matrix Binary_matrix; typedef kjb::Int_vector Binary_vector; typedef std::vector<Cts_duration> Time_array; typedef kjb::Vector Likelihood_vector; typedef kjb::Matrix Likelihood_matrix; typedef kjb::Matrix Distance_matrix; typedef boost::unordered_map<State_indicator, Time_set> Partition_map; typedef std::vector<State_sequence> State_sequence_list; typedef kjb::Int_vector T_list; typedef std::vector<State_matrix> State_matrix_list; typedef std::vector<Partition_map> Partition_map_list; /// Distribution types // typedef boost::gamma_distribution<> Gamma_dist; // typedef boost::poisson_distribution<> Poisson_dist; // typedef boost::bernoulli_distribution<> Bernoulli_dist; typedef kjb::Gamma_distribution Gamma_dist; typedef kjb::Poisson_distribution Poisson_dist; typedef kjb::Bernoulli_distribution Bernoulli_dist; typedef kjb::Beta_distribution Beta_dist; typedef kjb::Normal_distribution Normal_dist; typedef Gamma_dist Conc_dist; typedef Gamma_dist Rate_dist; typedef Gamma_dist Precision_dist; typedef Gamma_dist Dur_dist; typedef Poisson_dist Count_dist; /* void score_binary_states( const std::string& results_path, const std::string& ground_truth_path, const std::string& label, const State_matrix& state_matrix ); */ void score_binary_states( const std::string& results_path, const std::string& ground_truth_path, const std::string& label, const State_matrix_list& state_matrix_list ); void add_binary_gt_eval_header(const std::string& results_path); inline double log_of_one_more_than(const double& u) { return LogOnePlusX(u); } inline double log_normalize_by(const double& x, const double& logmax) {return x - logmax;} template<class InputIt> void log_normalize_vector_in_place(InputIt first, InputIt last) { const double total_mass = kjb::log_sum(first, last); std::transform(first, last, first, boost::bind(log_normalize_by, _1, total_mass)); } void threshold_a_double( double& x, const std::string& write_path, const std::string& message ); /** * @brief create a matrix whose rows are binary representations of ints from 0 to 2^(num_cols - 1) * * Noticeable lag starts to happen when num_cols is >= about 20 */ Binary_matrix generate_matrix_of_binary_range(const size_t& num_cols); template<class InputIt, class OutputIt> void sample_log_from_dirichlet_posterior_with_symmetric_prior( const double& prior_weight_per_value, const InputIt params_update_first, const InputIt params_update_last, const OutputIt d_first, const OutputIt d_last, const std::string& write_path ) { OutputIt oit = d_first; double val; for(InputIt it = params_update_first; it != params_update_last; ++it, ++oit) { double shape = prior_weight_per_value + (*it); threshold_a_double(shape, write_path, "beta"); Gamma_dist r_gamma(shape, 1.0); val = log(kjb::sample(r_gamma)); // (*oit) = val < thresh ? thresh : val; (*oit) = val; } log_normalize_vector_in_place(d_first, d_last); } void sample_mv_normal_vectors_from_row_means( kjb::Matrix& result, const kjb::Matrix& means, const kjb::Matrix& cov ); template<typename T> std::ostream& operator<<(std::ostream& os, std::vector<T> d) { for (typename std::vector<T>::const_iterator d_it = d.begin(); d_it != d.end(); ++d_it) { os << *d_it << " "; } return os; } template<typename T> std::ostream& operator<<(std::ostream& os, std::vector<std::vector<T> > d) { os << "[" << std::endl; for (typename std::vector<std::vector<T> >::const_iterator r_it = d.begin(); r_it != d.end(); ++r_it) { os << "("; for(typename std::vector<T>::const_iterator e_it = (*r_it).begin(); e_it != (*r_it).end(); ++e_it) { os << *e_it << ", "; } os << ")" << std::endl; } os << "]"; return os; } //new function to input a vector from a file template<typename T> T input_to_value( const std::string& write_path, const std::string& file_name, const std::string& name) { //input data std::string iteration_input; std::vector <std::string> input_vector; std::ifstream input_file((write_path + file_name).c_str()); while (getline(input_file, iteration_input)) { input_vector.push_back(iteration_input); } input_file.close(); //find iteration number std::vector<std::string> split_vector; T data_value; for (std::vector<std::string>::reverse_iterator rit = input_vector.rbegin(); rit != input_vector.rend(); ++rit) { boost::split(split_vector, *rit, boost::is_any_of(" ")); if (split_vector[0] == name) { data_value = boost::lexical_cast<T>(split_vector[1]); break; } } return data_value; } template<typename T> std::vector<T> input_to_vector( const std::string& write_path, const std::string& file_name, const std::string& name) { //input data std::string iteration_input; std::vector <std::string> input_vector; std::ifstream input_file((write_path + file_name).c_str()); while (getline(input_file, iteration_input)) { input_vector.push_back(iteration_input); } input_file.close(); //find iteration number std::vector<std::string> split_vector; std::vector<T> data_vector; for (std::vector<std::string>::reverse_iterator rit = input_vector.rbegin(); rit != input_vector.rend(); ++rit) { boost::split(split_vector, *rit, boost::is_any_of(" ")); if (split_vector[0] == name) { for (std::vector<std::string>::iterator it = std::next(split_vector.begin()); it != split_vector.end(); ++it) { try{ data_vector.push_back(boost::lexical_cast<T>(*it)); } catch(boost::bad_lexical_cast &){ continue; } } break; } } return data_vector; } /* /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ */ static gsl_rng* gnu_rng; void initialize_gnu_rng(const unsigned long int& seed); double sample_left_truncated_normal(double lower); double sample_right_truncated_normal(double upper); int create_directory_if_nonexistent(const std::string& dir_name); int empty_directory(const std::string& dir_name); #endif
[ "cdawson@oberlin.edu" ]
cdawson@oberlin.edu
f512eb03f0045d54b6ed858c6a61dfece2ef260c
751fe73c7a0188dfe27c9fe78c0410b137db91fb
/media_components/src/NvCodec10/Utils/NvCodecUtils.h
661c23d9536b52c00a362b668111a0d4a076b214
[]
no_license
longshadian/estl
0b1380e9dacfc4e193e1bb19401de28dd135fedf
3dba7a84abc8dbf999ababa977279e929a0a6623
refs/heads/master
2021-07-09T19:29:06.402311
2021-04-05T14:16:21
2021-04-05T14:16:21
12,356,617
3
1
null
null
null
null
UTF-8
C++
false
false
14,665
h
/* * Copyright 2017-2020 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ //--------------------------------------------------------------------------- //! \file NvCodecUtils.h //! \brief Miscellaneous classes and error checking functions. //! //! Used by Transcode/Encode samples apps for reading input files, mutithreading, performance measurement or colorspace conversion while decoding. //--------------------------------------------------------------------------- #pragma once #include <iomanip> #include <chrono> #include <sys/stat.h> #include <assert.h> #include <stdint.h> #include <string.h> #include "Logger.h" #include <ios> #include <sstream> #include <thread> #include <list> #include <condition_variable> extern simplelogger::Logger *logger; #ifdef __cuda_cuda_h__ inline bool check(CUresult e, int iLine, const char *szFile) { if (e != CUDA_SUCCESS) { const char *szErrName = NULL; cuGetErrorName(e, &szErrName); LOG(FATAL) << "CUDA driver API error " << szErrName << " at line " << iLine << " in file " << szFile; return false; } return true; } #endif #ifdef __CUDA_RUNTIME_H__ inline bool check(cudaError_t e, int iLine, const char *szFile) { if (e != cudaSuccess) { LOG(FATAL) << "CUDA runtime API error " << cudaGetErrorName(e) << " at line " << iLine << " in file " << szFile; return false; } return true; } #endif #ifdef _NV_ENCODEAPI_H_ inline bool check(NVENCSTATUS e, int iLine, const char *szFile) { const char *aszErrName[] = { "NV_ENC_SUCCESS", "NV_ENC_ERR_NO_ENCODE_DEVICE", "NV_ENC_ERR_UNSUPPORTED_DEVICE", "NV_ENC_ERR_INVALID_ENCODERDEVICE", "NV_ENC_ERR_INVALID_DEVICE", "NV_ENC_ERR_DEVICE_NOT_EXIST", "NV_ENC_ERR_INVALID_PTR", "NV_ENC_ERR_INVALID_EVENT", "NV_ENC_ERR_INVALID_PARAM", "NV_ENC_ERR_INVALID_CALL", "NV_ENC_ERR_OUT_OF_MEMORY", "NV_ENC_ERR_ENCODER_NOT_INITIALIZED", "NV_ENC_ERR_UNSUPPORTED_PARAM", "NV_ENC_ERR_LOCK_BUSY", "NV_ENC_ERR_NOT_ENOUGH_BUFFER", "NV_ENC_ERR_INVALID_VERSION", "NV_ENC_ERR_MAP_FAILED", "NV_ENC_ERR_NEED_MORE_INPUT", "NV_ENC_ERR_ENCODER_BUSY", "NV_ENC_ERR_EVENT_NOT_REGISTERD", "NV_ENC_ERR_GENERIC", "NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY", "NV_ENC_ERR_UNIMPLEMENTED", "NV_ENC_ERR_RESOURCE_REGISTER_FAILED", "NV_ENC_ERR_RESOURCE_NOT_REGISTERED", "NV_ENC_ERR_RESOURCE_NOT_MAPPED", }; if (e != NV_ENC_SUCCESS) { LOG(FATAL) << "NVENC error " << aszErrName[e] << " at line " << iLine << " in file " << szFile; return false; } return true; } #endif #ifdef _WINERROR_ inline bool check(HRESULT e, int iLine, const char *szFile) { if (e != S_OK) { std::stringstream stream; stream << std::hex << std::uppercase << e; LOG(FATAL) << "HRESULT error 0x" << stream.str() << " at line " << iLine << " in file " << szFile; return false; } return true; } #endif #if defined(__gl_h_) || defined(__GL_H__) inline bool check(GLenum e, int iLine, const char *szFile) { if (e != 0) { LOG(ERROR) << "GLenum error " << e << " at line " << iLine << " in file " << szFile; return false; } return true; } #endif inline bool check(int e, int iLine, const char *szFile) { if (e < 0) { LOG(ERROR) << "General error " << e << " at line " << iLine << " in file " << szFile; return false; } return true; } #define ck(call) check(call, __LINE__, __FILE__) /** * @brief Wrapper class around std::thread */ class NvThread { public: NvThread() = default; NvThread(const NvThread&) = delete; NvThread& operator=(const NvThread& other) = delete; NvThread(std::thread&& thread) : t(std::move(thread)) { } NvThread(NvThread&& thread) : t(std::move(thread.t)) { } NvThread& operator=(NvThread&& other) { t = std::move(other.t); return *this; } ~NvThread() { join(); } void join() { if (t.joinable()) { t.join(); } } private: std::thread t; }; #ifndef _WIN32 #define _stricmp strcasecmp #define _stat64 stat64 #endif /** * @brief Utility class to allocate buffer memory. Helps avoid I/O during the encode/decode loop in case of performance tests. */ class BufferedFileReader { public: /** * @brief Constructor function to allocate appropriate memory and copy file contents into it */ BufferedFileReader(const char *szFileName, bool bPartial = false) { struct _stat64 st; if (_stat64(szFileName, &st) != 0) { return; } nSize = st.st_size; while (nSize) { try { pBuf = new uint8_t[(size_t)nSize]; if (nSize != st.st_size) { LOG(WARNING) << "File is too large - only " << std::setprecision(4) << 100.0 * nSize / st.st_size << "% is loaded"; } break; } catch(std::bad_alloc) { if (!bPartial) { LOG(ERROR) << "Failed to allocate memory in BufferedReader"; return; } nSize = (uint32_t)(nSize * 0.9); } } std::ifstream fpIn(szFileName, std::ifstream::in | std::ifstream::binary); if (!fpIn) { LOG(ERROR) << "Unable to open input file: " << szFileName; return; } std::streamsize nRead = fpIn.read(reinterpret_cast<char*>(pBuf), nSize).gcount(); fpIn.close(); assert(nRead == nSize); } ~BufferedFileReader() { if (pBuf) { delete[] pBuf; } } bool GetBuffer(uint8_t **ppBuf, uint64_t *pnSize) { if (!pBuf) { return false; } *ppBuf = pBuf; *pnSize = nSize; return true; } private: uint8_t *pBuf = NULL; uint64_t nSize = 0; }; /** * @brief Template class to facilitate color space conversion */ template<typename T> class YuvConverter { public: YuvConverter(int nWidth, int nHeight) : nWidth(nWidth), nHeight(nHeight) { pQuad = new T[nWidth * nHeight / 4]; } ~YuvConverter() { delete pQuad; } void PlanarToUVInterleaved(T *pFrame, int nPitch = 0) { if (nPitch == 0) { nPitch = nWidth; } T *puv = pFrame + nPitch * nHeight; if (nPitch == nWidth) { memcpy(pQuad, puv, nWidth * nHeight / 4 * sizeof(T)); } else { for (int i = 0; i < nHeight / 2; i++) { memcpy(pQuad + nWidth / 2 * i, puv + nPitch / 2 * i, nWidth / 2 * sizeof(T)); } } T *pv = puv + (nPitch / 2) * (nHeight / 2); for (int y = 0; y < nHeight / 2; y++) { for (int x = 0; x < nWidth / 2; x++) { puv[y * nPitch + x * 2] = pQuad[y * nWidth / 2 + x]; puv[y * nPitch + x * 2 + 1] = pv[y * nPitch / 2 + x]; } } } void UVInterleavedToPlanar(T *pFrame, int nPitch = 0) { if (nPitch == 0) { nPitch = nWidth; } T *puv = pFrame + nPitch * nHeight, *pu = puv, *pv = puv + nPitch * nHeight / 4; for (int y = 0; y < nHeight / 2; y++) { for (int x = 0; x < nWidth / 2; x++) { pu[y * nPitch / 2 + x] = puv[y * nPitch + x * 2]; pQuad[y * nWidth / 2 + x] = puv[y * nPitch + x * 2 + 1]; } } if (nPitch == nWidth) { memcpy(pv, pQuad, nWidth * nHeight / 4 * sizeof(T)); } else { for (int i = 0; i < nHeight / 2; i++) { memcpy(pv + nPitch / 2 * i, pQuad + nWidth / 2 * i, nWidth / 2 * sizeof(T)); } } } private: T *pQuad; int nWidth, nHeight; }; /** * @brief Utility class to measure elapsed time in seconds between the block of executed code */ class StopWatch { public: void Start() { t0 = std::chrono::high_resolution_clock::now(); } double Stop() { return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch() - t0.time_since_epoch()).count() / 1.0e9; } private: std::chrono::high_resolution_clock::time_point t0; }; template<typename T> class ConcurrentQueue { public: ConcurrentQueue() {} ConcurrentQueue(size_t size) : maxSize(size) {} ConcurrentQueue(const ConcurrentQueue&) = delete; ConcurrentQueue& operator=(const ConcurrentQueue&) = delete; void setSize(size_t s) { maxSize = s; } void push_back(const T& value) { // Do not use a std::lock_guard here. We will need to explicitly // unlock before notify_one as the other waiting thread will // automatically try to acquire mutex once it wakes up // (which will happen on notify_one) std::unique_lock<std::mutex> lock(m_mutex); auto wasEmpty = m_List.empty(); while (full()) { m_cond.wait(lock); } m_List.push_back(value); if (wasEmpty && !m_List.empty()) { lock.unlock(); m_cond.notify_one(); } } T pop_front() { std::unique_lock<std::mutex> lock(m_mutex); while (m_List.empty()) { m_cond.wait(lock); } auto wasFull = full(); T data = std::move(m_List.front()); m_List.pop_front(); if (wasFull && !full()) { lock.unlock(); m_cond.notify_one(); } return data; } T front() { std::unique_lock<std::mutex> lock(m_mutex); while (m_List.empty()) { m_cond.wait(lock); } return m_List.front(); } size_t size() { std::unique_lock<std::mutex> lock(m_mutex); return m_List.size(); } bool empty() { std::unique_lock<std::mutex> lock(m_mutex); return m_List.empty(); } void clear() { std::unique_lock<std::mutex> lock(m_mutex); m_List.clear(); } private: bool full() { if (m_List.size() == maxSize) return true; return false; } private: std::list<T> m_List; std::mutex m_mutex; std::condition_variable m_cond; size_t maxSize; }; inline void CheckInputFile(const char *szInFilePath) { std::ifstream fpIn(szInFilePath, std::ios::in | std::ios::binary); if (fpIn.fail()) { std::ostringstream err; err << "Unable to open input file: " << szInFilePath << std::endl; throw std::invalid_argument(err.str()); } } inline void ValidateResolution(int nWidth, int nHeight) { if (nWidth <= 0 || nHeight <= 0) { std::ostringstream err; err << "Please specify positive non zero resolution as -s WxH. Current resolution is " << nWidth << "x" << nHeight << std::endl; throw std::invalid_argument(err.str()); } } template <class COLOR32> void Nv12ToColor32(uint8_t *dpNv12, int nNv12Pitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR64> void Nv12ToColor64(uint8_t *dpNv12, int nNv12Pitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR32> void P016ToColor32(uint8_t *dpP016, int nP016Pitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 4); template <class COLOR64> void P016ToColor64(uint8_t *dpP016, int nP016Pitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 4); template <class COLOR32> void YUV444ToColor32(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR64> void YUV444ToColor64(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR32> void YUV444P16ToColor32(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 4); template <class COLOR64> void YUV444P16ToColor64(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgra, int nBgraPitch, int nWidth, int nHeight, int iMatrix = 4); template <class COLOR32> void Nv12ToColorPlanar(uint8_t *dpNv12, int nNv12Pitch, uint8_t *dpBgrp, int nBgrpPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR32> void P016ToColorPlanar(uint8_t *dpP016, int nP016Pitch, uint8_t *dpBgrp, int nBgrpPitch, int nWidth, int nHeight, int iMatrix = 4); template <class COLOR32> void YUV444ToColorPlanar(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgrp, int nBgrpPitch, int nWidth, int nHeight, int iMatrix = 0); template <class COLOR32> void YUV444P16ToColorPlanar(uint8_t *dpYUV444, int nPitch, uint8_t *dpBgrp, int nBgrpPitch, int nWidth, int nHeight, int iMatrix = 4); void Bgra64ToP016(uint8_t *dpBgra, int nBgraPitch, uint8_t *dpP016, int nP016Pitch, int nWidth, int nHeight, int iMatrix = 4); void ConvertUInt8ToUInt16(uint8_t *dpUInt8, uint16_t *dpUInt16, int nSrcPitch, int nDestPitch, int nWidth, int nHeight); void ConvertUInt16ToUInt8(uint16_t *dpUInt16, uint8_t *dpUInt8, int nSrcPitch, int nDestPitch, int nWidth, int nHeight); void ResizeNv12(unsigned char *dpDstNv12, int nDstPitch, int nDstWidth, int nDstHeight, unsigned char *dpSrcNv12, int nSrcPitch, int nSrcWidth, int nSrcHeight, unsigned char *dpDstNv12UV = nullptr); void ResizeP016(unsigned char *dpDstP016, int nDstPitch, int nDstWidth, int nDstHeight, unsigned char *dpSrcP016, int nSrcPitch, int nSrcWidth, int nSrcHeight, unsigned char *dpDstP016UV = nullptr); void ScaleYUV420(unsigned char *dpDstY, unsigned char* dpDstU, unsigned char* dpDstV, int nDstPitch, int nDstChromaPitch, int nDstWidth, int nDstHeight, unsigned char *dpSrcY, unsigned char* dpSrcU, unsigned char* dpSrcV, int nSrcPitch, int nSrcChromaPitch, int nSrcWidth, int nSrcHeight, bool bSemiplanar); void Nv12ToBgr(uint8_t* dpNv12, int nNv12Pitch, uint8_t* dpBgrp, int nBgrpPitch, int nWidth, int nHeight, int iMatrix = 0); #ifdef __cuda_cuda_h__ void ComputeCRC(uint8_t *pBuffer, uint32_t *crcValue, CUstream_st *outputCUStream); #endif
[ "guangyuanchen001@163.com" ]
guangyuanchen001@163.com
a9bcb30a04cb2eaa6ede69d1126f5b9be4c3a924
f5c383c6dcb154930eda6c254a19386dd8d980d8
/CURDPROD.cpp
21912e3a37d588f7427404dac368bb0d51c2b147
[]
no_license
riyadhrazzaq/spoj-solutions
e5e2768297d342a968da5acbb9e88ab112fdddfb
484f2cdb17f46c7f05644dcaf9a19a386e8cd6ee
refs/heads/master
2020-03-29T06:15:41.276084
2016-11-21T05:54:08
2016-11-21T05:54:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
#include<cstdio> #include<iostream> #include<string> #include<cstdlib> #include<queue> #include<stack> #include<utility> #include<string> #include<cstring> #include<set> #include<cmath> #include<vector> #include<fstream> #include<map> #include<list> #include<algorithm> #define SIZE 10000 typedef long long int LLD; typedef unsigned long long int LLU; using namespace std; LLD arr[SIZE]; LLD findQuantity(LLD x, LLD n){ LLD result = 0; for(int i=0;i<n;i++) result += (x / arr[i]); return result; } LLD binarySearch(LLD lo, LLD hi, LLD n, LLD m){ while(hi > lo){ LLD mi = (lo + hi) / 2; LLD quantity = findQuantity(mi, n); if(quantity >= m) hi = mi; else if(quantity < m) lo = mi + 1; } return hi; } int main(){ LLD t, n, m, lo = 1, hi; scanf("%lld", &t); while(t--){ scanf("%lld%lld", &n, &m); hi = 0; for(int i=0;i<n;i++){ scanf("%lld", &arr[i]); hi = max(hi, arr[i] * m); } printf("%lld\n", binarySearch(lo, hi, n, m)); } return 0; }
[ "jiteshjs99@gmail.com" ]
jiteshjs99@gmail.com
17f68b5972af1e79973a89cb07a15a9f6975fa08
4ab90879599e2d3f30fe63707b7ec0eac2cb8fa9
/tensorflow/compiler/xla/mlir_hlo/deallocation/utils/util.cc
1831bd44b69fca5c6a4c372cf73b93cca9b4e6cd
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
Romyull-Islam/tensorflow
030fbe090174c368639b945274f5965072bf17df
3e2405541f8be5db4bb1594fd3520a369bcfb211
refs/heads/master
2023-02-17T02:03:28.580789
2023-02-10T17:19:58
2023-02-10T17:26:52
150,025,165
0
0
Apache-2.0
2018-09-23T20:59:59
2018-09-23T20:59:59
null
UTF-8
C++
false
false
3,617
cc
/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "deallocation/utils/util.h" #include <optional> #include "mlir/Dialect/SCF/IR/SCF.h" namespace mlir { namespace deallocation { SmallVector<RegionEdge> getSuccessorRegions(RegionBranchOpInterface op, std::optional<unsigned> index) { SmallVector<RegionEdge> edges; if (index && op->getRegion(*index).empty()) { return edges; } SmallVector<RegionSuccessor> successors; op.getSuccessorRegions(index, successors); for (const auto& successor : successors) { auto& edge = edges.emplace_back(); edge.predecessorRegionIndex = index; edge.predecessorOp = index ? op->getRegion(*index).front().getTerminator() : op.getOperation(); edge.predecessorOperandIndex = edge.predecessorOp->getNumOperands() - successor.getSuccessorInputs().size(); if (successor.isParent()) { edge.successorRegionIndex = std::nullopt; edge.successorOpOrRegion = op.getOperation(); edge.successorValueIndex = 0; } else { edge.successorRegionIndex = successor.getSuccessor()->getRegionNumber(); edge.successorOpOrRegion = successor.getSuccessor(); edge.successorValueIndex = llvm::isa<scf::ForOp>(op) ? 1 : 0; } } return edges; } SmallVector<RegionEdge> getPredecessorRegions(RegionBranchOpInterface op, std::optional<unsigned> index) { SmallVector<RegionEdge> result; auto checkPredecessor = [&](std::optional<unsigned> possiblePredecessor) { for (const auto& successor : getSuccessorRegions(op, possiblePredecessor)) { if (successor.successorRegionIndex == index) { result.push_back(successor); } } }; checkPredecessor(std::nullopt); for (unsigned i = 0; i < op->getNumRegions(); ++i) { checkPredecessor(i); } return result; } RegionBranchOpInterface moveRegionsToNewOpButKeepOldOp( RegionBranchOpInterface op) { OpBuilder b(op); RegionBranchOpInterface newOp; if (llvm::isa<scf::ForOp>(op)) { newOp = b.create<scf::ForOp>(op.getLoc(), op->getOperands()[0], op->getOperands()[1], op->getOperands()[2], op->getOperands().drop_front(3)); } else if (llvm::isa<scf::WhileOp>(op)) { newOp = b.create<scf::WhileOp>(op.getLoc(), TypeRange{op->getOperands()}, op->getOperands()); } else if (llvm::isa<scf::IfOp>(op)) { newOp = b.create<scf::IfOp>( op.getLoc(), TypeRange{op->getRegion(0).front().getTerminator()->getOperands()}, op->getOperands()[0], op->getNumRegions() > 1); } else { llvm_unreachable("unsupported"); } for (auto [oldRegion, newRegion] : llvm::zip(op->getRegions(), newOp->getRegions())) { newRegion.takeBody(oldRegion); } return newOp; } } // namespace deallocation } // namespace mlir
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
c9307df28fd0066c1142ce014089306619b41af1
8a5ae995f94de81eec9658bffa4102f216df4481
/cpp/oke/figura.h
ad4431b601b7c00bea8d9728a928496160b2be44
[]
no_license
maciej-brochocki/recruitment
2d3d7701f1563c288a4d3939108fcadd6909c222
891aa24d496f6bb88cebe7915c56bd2614d738cc
refs/heads/master
2021-01-17T07:23:05.507116
2017-12-20T20:47:13
2017-12-20T20:47:13
83,703,682
0
0
null
null
null
null
UTF-8
C++
false
false
637
h
// figura.h: interface for the figura class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_FIGURA_H__C5E3A844_E3E2_4B76_B7D4_0AEB97C600B3__INCLUDED_) #define AFX_FIGURA_H__C5E3A844_E3E2_4B76_B7D4_0AEB97C600B3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class figura { public: virtual void rysuj(CWnd* okno); void dolacz(figura* fig); figura(int x1, int y1, int x2, int y2); virtual ~figura(); protected: figura* m_fNext; int m_iY2; int m_iX2; int m_iY1; int m_iX1; }; #endif // !defined(AFX_FIGURA_H__C5E3A844_E3E2_4B76_B7D4_0AEB97C600B3__INCLUDED_)
[ "maciej.brochocki@bestideas.pl" ]
maciej.brochocki@bestideas.pl
de5e54afe66151cfa3fe4bd2dd1a0d5ace9b987f
c43b0d1e041d004d1fa8e1469f57b62d4d4bea88
/sdk/lib/fuzzing/cpp/fuzz_input.cc
f737303b12aa0b104f364826ee3899da0616f711
[ "BSD-3-Clause" ]
permissive
ZVNexus/fuchsia
75122894e09c79f26af828d6132202796febf3f3
c5610ad15208208c98693618a79c705af935270c
refs/heads/master
2023-01-12T10:48:06.597690
2019-07-04T05:09:11
2019-07-04T05:09:11
195,169,207
0
0
BSD-3-Clause
2023-01-05T20:35:36
2019-07-04T04:34:33
C++
UTF-8
C++
false
false
680
cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fuzz_input.h" #include <cstddef> #include <cstdint> #include <string.h> namespace fuzzing { const uint8_t* FuzzInput::TakeBytes(size_t size) { if (remaining_ < size) { return nullptr; } const uint8_t* out = data_; data_ += size; remaining_ -= size; return out; } bool FuzzInput::CopyBytes(uint8_t* out, size_t size) { if (remaining_ < size || !out) { return false; } memcpy(out, data_, size); data_ += size; remaining_ -= size; return true; } } // namespace fuzzing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
01f6d169715189ecdc34cddfc67e7815f0b7cbff
dccd1058e723b6617148824dc0243dbec4c9bd48
/codeforces/922B.cpp
d4d21371277cf5e56b48acfac48f61d092fe2343
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
773
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} int main(){ int n; cin >>n; int ans = 0; for(int a=1; a<=n; ++a)for(int b=a; b<=n; ++b){ int c = a^b; if(b<=c && c<=n && c<a+b){ // printf(" %d %d %d\n", a,b,c); ++ans; } } cout << ans << endl; return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
70b6b7feaa068688eb76f66464f83e4bc62ffdd6
e934b8587ecfab8ed0bdba34533c8c115977803d
/test/integration/worker/job/tool/SendInitRenderDataWorkerTool.re
8bdaa4dc4f91431144408e395a84791bb83515c5
[ "MIT" ]
permissive
III-three/Wonder.js
2d9d37e9db31e95a0b82c822597bfad21e354379
460d39cbfa1da7633300cc18c4a05787c0279c7d
refs/heads/master
2022-05-30T21:55:38.505054
2020-04-29T13:57:33
2020-04-29T13:57:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
re
let buildInitRenderData = ( ~isDebug=true, ~viewportData=Sinon.matchAny, ~workerDetectData=Sinon.matchAny, ~browserDetectData=Sinon.matchAny, ~textureData=Sinon.matchAny, ~imguiData=Sinon.matchAny, ~meshRendererData=Sinon.matchAny, ~geometryData=Sinon.matchAny, (), ) => { "operateType": "INIT_RENDER", "canvas": Sinon.matchAny, "contextConfig": Sinon.matchAny, "bufferData": Sinon.matchAny, "instanceBufferData": Sinon.matchAny, "isDebug": isDebug, "viewportData": viewportData, "gpuData": Sinon.matchAny, "memoryData": Sinon.matchAny, "renderConfigData": Sinon.matchAny, "workerDetectData": workerDetectData, "browserDetectData": browserDetectData, "textureData": textureData, "imguiData": imguiData, "transformData": Sinon.matchAny, "basicMaterialData": Sinon.matchAny, "lightMaterialData": Sinon.matchAny, "meshRendererData": Sinon.matchAny, "geometryData": geometryData, "directionLightData": Sinon.matchAny, "pointLightData": Sinon.matchAny, "sourceInstanceData": Sinon.matchAny, };
[ "395976266@qq.com" ]
395976266@qq.com
23c63960c8d6a361396c3557144d8d28b44dcf40
409ded07b81a09fe0edbcad475d63a4ab584659f
/TCC/Problem.cpp
10549ba93e112189e1a5aed4b0c43f8a475dfd44
[]
no_license
junior003/TCC
afaa63470f5484f75fe9926d2af3f9a413922c91
1e6124ea90490929dbf1cebdd9f1aa8e813735b3
refs/heads/master
2022-05-25T23:34:02.299367
2019-11-11T03:27:23
2019-11-11T03:27:23
209,185,835
0
0
null
null
null
null
UTF-8
C++
false
false
10,286
cpp
#include "Problem.h" #include "ISolution.h" #include "Methods.h" #include <math.h> float Problem::obj2(ISolution* s,float d)//trocar distancia para distancia por veiculo e descobrir o valor correto { float SUM_freshness = 0; float distance =0; float arrive_time=0; float Total_demand = 0; int i, j,k; for (i = 0; i < s->get_num_vehicles_in_S(); i++) { //cout <<endl << "veiculo " << i << ":"<<endl; distance = euclidian_distance( origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, 0)).get_X(), cons.at(s->get_client_id_on_route(i, 0)).get_Y() ); Total_demand += cons.at(s->get_client_id_on_route(i, 0)).get_demand(); arrive_time = cons.at(s->get_client_id_on_route(i, 0)).get_initial_T(); SUM_freshness += calc_beta(arrive_time) *cons.at(s->get_client_id_on_route(i, 0)).get_demand(); for ( j = 0, k = 1; j < s->get_route_size(i) - 1; j++, k++) { distance = euclidian_distance( cons.at(s->get_client_id_on_route(i, j)).get_X(), cons.at(s->get_client_id_on_route(i, j)).get_Y(), cons.at(s->get_client_id_on_route(i, k)).get_X(), cons.at(s->get_client_id_on_route(i, k)).get_Y() ); arrive_time = calc_arrival_time_of_vehicle(arrive_time, cons.at(s->get_client_id_on_route(i, j)).get_id(), distance); //analisar esta parte //if (arrive_time < cons.at(s->get_client_id_on_route(i, k)).get_initial_T()) //{ //espera o cliente abrir //arrive_time += cons.at(s->get_client_id_on_route(i, k)).get_initial_T() - arrive_time; //} Total_demand += cons.at(s->get_client_id_on_route(i, k)).get_demand(); SUM_freshness += calc_beta(arrive_time) *cons.at(s->get_client_id_on_route(i, k)).get_demand(); ; } Total_demand += cons.at(s->get_client_id_on_route(i, j)).get_demand(); distance = euclidian_distance(origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, j)).get_X(), cons.at(s->get_client_id_on_route(i, j)).get_Y()); arrive_time = calc_arrival_time_of_vehicle(arrive_time, cons.at(s->get_client_id_on_route(i, j)).get_id(), distance); SUM_freshness += calc_beta(arrive_time) *cons.at(s->get_client_id_on_route(i, j)).get_demand(); ; } //cout << "SOMA FRESH:" << SUM_freshness << endl; //cout << "Total_demand:" << Total_demand; s->set_obj2_freshness(SUM_freshness / Total_demand); s->set_inv_obj2_freshness(); return SUM_freshness/Total_demand; } bool Problem::constraint_vehicle_capacity(ISolution s) { float SUM_demand=0; for (int i = 0; i < num_vehicle; i++) { SUM_demand = 0; for (int j = 0; j < s.get_route_size(i); j++) { //cout << "demand for client:" << cons.at(s.get_client_id_on_route(i, j)).get_demand(); SUM_demand += cons.at(s.get_client_id_on_route(i,j)).get_demand(); } //cout << "[" << SUM_demand << "." << capacity << "]"; if (SUM_demand <= capacity) { continue; } else { return false; } } return true; } bool Problem::constraint_curr_freshness(ISolution s) { float SUM_freshness = 1; for (int i = 0; i < num_vehicle; i++) { for (int j = 0; j < s.get_route_size(i); j++)//ta errado { SUM_freshness -= 0.0001; } if (SUM_freshness >= product_freshness) { continue; } else { break; } } if (SUM_freshness >= product_freshness) { return true; } return false; } float Problem::euclidian_distance(int x1, int y1, int x2, int y2) { return sqrt(pow(x2-x1,2)+pow(y2-y1,2)); } float Problem::calc_arrival_time_of_vehicle(float past_time,int c, float dist) { //casos seja o primeiro cliente nao ha tempo de servico nem tempo de chegada if (past_time == 0) { return dist/velocity_vehicle ; } else { return past_time + cons.at(c).get_service_T() + ((dist)/(velocity_vehicle/3.6)) ; } } float Problem::calc_transport_cost(float dist) { return (dist * transport_cost_per_KM); } Problem::Problem() { } Problem::Problem(int num_v, int cap, int num_c, int cost_v, float prod_fresh) { set_num_vehicle(num_v); set_capacity(cap); set_num_clients(num_c); set_fixed_cost_vehicle(cost_v); set_product_freshness(prod_fresh); } void Problem::set_capacity(int c) { capacity = c; } void Problem::set_num_clients(int c) { num_consumers = c; } void Problem::add_client(Client * c) { cons.push_back(*c); } void Problem::set_product_freshness(float pf ) { product_freshness = pf; } int Problem::get_capacity() { return capacity; } int Problem::get_num_clients() { return num_consumers; } Client * Problem::get_client(int pos) { return &cons.at(pos); } float Problem::get_fixed_cost_vehicle() { return cost_vehicle; } float Problem::get_velocity_vehicle() { return velocity_vehicle; } float Problem::get_transportation_cost_per_KM() { return transport_cost_per_KM; } float Problem::get_product_freshness() { return product_freshness; } void Problem::set_num_vehicle(int v) { num_vehicle = v; } void Problem::set_weight(int w1, int w2, int w3) { w_1 = w1; w_2 = w2; w_3 = w3; } void Problem::set_fixed_cost_vehicle(float c) { cost_vehicle = c; } void Problem::set_velocity_vehicle(float v) { velocity_vehicle = v; } void Problem::set_transportation_cost_per_KM(float tcpk) { transport_cost_per_KM = tcpk; } int Problem::get_num_vehicle() { return num_vehicle; } float Problem::obj1(ISolution* s) { int i = 0, j = 0, k = 0; float SUM_time_vehicle_cost = 0; float SUM_cost_vehicle=0; float SUM_cost_early_arrive = 0; float SUM_cost_due_arrive = 0; float SUM_lost_product = 0; float Total_distance_traveled=0; float distance_by_vehicle = 0; float arrive_time=0; int early_pen=0; int due_pen = 0; int dist_temp = 0; for (i = 0; i < s->get_num_vehicles_in_S(); i++) { SUM_cost_vehicle += cost_vehicle; } for (i = 0; i < s->get_num_vehicles_in_S(); i++) { //distancia de origem ate 1o cliente distance_by_vehicle += euclidian_distance(origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, 0)).get_X(), cons.at(s->get_client_id_on_route(i, 0)).get_Y()); //Abordagens de calculo do tempo de chegada no primeiro cliente: //1 - O primeiro veiculo chega no tempo inicial do primeiro cliente arrive_time = cons.at(s->get_client_id_on_route(i, 0)).get_initial_T(); dist_temp = euclidian_distance(origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, 0)).get_X(), cons.at(s->get_client_id_on_route(i, 0)).get_Y()); //2 - calculo normal como nos outros clientes //arrive_time += calc_time_vehicle(0, cons.at(s->get_client_id_on_route(i, 0)).get_id(), dist_temp); //cout << "<" << cons.at(s->get_client_id_on_route(i, 0)).get_initial_T() << "'" << arrive_time << "'" << cons.at(s->get_client_id_on_route(i, 0)).get_due_T() << ">"; if (arrive_time < cons.at(s->get_client_id_on_route(i, 0)).get_initial_T()) { early_pen++; //SUM_cost_early_arrive += w_1 * (cons.at(s->get_client_id_on_route(i, 0)).get_initial_T() - arrive_time);//**** arrive_time += (cons.at(s->get_client_id_on_route(i, 0)).get_initial_T() - arrive_time); } else if (arrive_time > cons.at(s->get_client_id_on_route(i, 0)).get_due_T()) { due_pen++; //Abordagem similar ao early: //SUM_cost_due_arrive += w_2 * (arrive_time -cons.at(s->get_client_id_on_route(i, 0)).get_due_T()); arrive_time += (cons.at(s->get_client_id_on_route(i, 0)).get_initial_T() - arrive_time); } SUM_lost_product += calc_phi(distance_by_vehicle / velocity_vehicle)*cons.at(s->get_client_id_on_route(i, 0)).get_demand(); //Demais clientes for (j = 0, k = 1; j < s->get_route_size(i)-1; j++, k++) { distance_by_vehicle += euclidian_distance( cons.at(s->get_client_id_on_route(i, j)).get_X(), cons.at(s->get_client_id_on_route(i, j)).get_Y(), cons.at(s->get_client_id_on_route(i, k)).get_X(), cons.at(s->get_client_id_on_route(i, k)).get_Y() ); dist_temp = euclidian_distance(cons.at(s->get_client_id_on_route(i, j)).get_X(), cons.at(s->get_client_id_on_route(i, j)).get_Y(), cons.at(s->get_client_id_on_route(i, k)).get_X(), cons.at(s->get_client_id_on_route(i, k)).get_Y()); //Janela de tempo arrive_time = calc_arrival_time_of_vehicle(arrive_time,cons.at(s->get_client_id_on_route(i, j)).get_id(),dist_temp); //cout << "<" << cons.at(s->get_client_id_on_route(i, k)).get_initial_T() << "'" << arrive_time << "'" << cons.at(s->get_client_id_on_route(i, k)).get_due_T() << ">"; if (arrive_time < cons.at(s->get_client_id_on_route(i, k)).get_initial_T()) { early_pen++; //int dist_temp = euclidian_distance(origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, k)).get_X(), cons.at(s->get_client_id_on_route(i, k)).get_Y()); //SUM_cost_early_arrive += w_1 * (cons.at(s->get_client_id_on_route(i, k)).get_initial_T() - arrive_time);//**** //arrive_time += (cons.at(s->get_client_id_on_route(i, 0)).get_initial_T() - arrive_time); arrive_time += (cons.at(s->get_client_id_on_route(i, k)).get_initial_T() - arrive_time); } else if (arrive_time > cons.at(s->get_client_id_on_route(i, k)).get_due_T()) { due_pen++; //SUM_cost_due_arrive += w_2 * (arrive_time - cons.at(s->get_client_id_on_route(i, k)).get_due_T());//**** } SUM_lost_product += calc_phi(distance_by_vehicle / velocity_vehicle)*cons.at(s->get_client_id_on_route(i, j)).get_demand(); } //calculo do ultimo de volta a origem distance_by_vehicle += euclidian_distance(origin.get_X(), origin.get_Y(), cons.at(s->get_client_id_on_route(i, j)).get_X(), cons.at(s->get_client_id_on_route(i, j)).get_Y()); //calculo do custo do transporte e tempo percorrido SUM_time_vehicle_cost += distance_by_vehicle*transport_cost_per_KM; Total_distance_traveled += distance_by_vehicle; SUM_lost_product += calc_phi(distance_by_vehicle / velocity_vehicle)*cons.at(s->get_client_id_on_route(i, j)).get_demand(); distance_by_vehicle = 0; } s->set_obj1_cost(SUM_time_vehicle_cost + early_pen * w_1 + due_pen * w_2 + SUM_cost_vehicle + SUM_lost_product * w_3); s->set_dist_travel(Total_distance_traveled); //SUM_cost_early_arrive + SUM_cost_due_arrive return SUM_time_vehicle_cost + early_pen*w_1 + due_pen*w_2 +SUM_cost_vehicle + SUM_lost_product*w_3; }
[ "jojuvi3@gmail.com" ]
jojuvi3@gmail.com
7cdb7bc9b07190f6a5225158371de3d6b671a6bb
c3e13411632c328741306bd5ede06320a5a4a9ae
/MainWindow/MainWindow.h
1df6bb342a8afeafd26949ed6046f290deaa9088
[]
no_license
Lezh1k/SoundManager
8a08d17b905cb552284419b8fca89c4f1839d8ec
4363e436503152d65404db92bd0eaeef0e4c51dd
refs/heads/master
2020-04-28T07:29:09.258544
2015-04-26T06:48:53
2015-04-26T06:48:53
28,269,429
0
0
null
null
null
null
UTF-8
C++
false
false
599
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "WaveFile/WaveFileErrors.h" #include "WaveFile/WaveFile.h" #include "WaveFile/WavFileChannelVisualizer.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; CWavFile *m_wavFile; void ResetWavFile(const std::string& fileName); private slots: void MnuFileExit_Clicked(void); void MnuFileOpen_Clicked(void); }; #endif // MAINWINDOW_H
[ "lezh1k.vohrer@gmail.com" ]
lezh1k.vohrer@gmail.com
bbbc034148923e1cf026b516b0875f7cab6f3198
b20353e26e471ed53a391ee02ea616305a63bbb0
/trunk/engine/tools/MapEditor/MapEditorEngine/CMapEditApp.h
5758e7bb557900967b98a2be4f4ae213c9eca04c
[]
no_license
trancx/ybtx
61de88ef4b2f577e486aba09c9b5b014a8399732
608db61c1b5e110785639d560351269c1444e4c4
refs/heads/master
2022-12-17T05:53:50.650153
2020-09-19T12:10:09
2020-09-19T12:10:09
291,492,104
0
0
null
2020-08-30T15:00:16
2020-08-30T15:00:15
null
GB18030
C++
false
false
1,679
h
#pragma once #include "TSingleton.h" #include "ExsertStructDB.h" namespace sqr_tools { class CEditDataScene; class CEditContext; class CMapContext; } namespace MapEditor { class CMapMgr; } using namespace MapEditor; namespace sqr { class CTerrainMesh; class COperator; class CWaterOperator; class CMapEditApp : public Singleton<CMapEditApp> { public: static bool NEWOLD; CMapEditApp(); virtual ~CMapEditApp(); private: COperator* m_pOperator; CWaterOperator* m_pWaterOperator; CTerrainMesh* m_pTerrainMesh; CTerrainMesh* m_pTransformTerrainMesh;//扩充,分割,移动后的terrainMesh CEditDataScene* m_pDataScene; CEditContext* m_pRenderScene; public: void SetTransformTerrainMesh(CTerrainMesh * pTerrainMesh); void SetTerrainMesh(CTerrainMesh * pTerrainMesh); CTerrainMesh* GetEditingMesh(); CTerrainMesh* GetTransformEditingMesh(); COperator * GetOperator(); CWaterOperator* GetWaterOperator(); CTerrainMesh* GetTerrain(); CTerrainMesh* GetWater(); CEditDataScene* GetDataScene(void); CEditContext* GetRenderScene(void); bool InitNewRenderScene(); void SetEditingMesh(sqr::EEDIT_MESH e); bool GetIsEditingWater(); string savelog; bool m_bSave; EEDIT_MESH m_eEditMesh; // 标志是地表还是水 public://新增加 CMapMgr* GetMapMgr(); CMapMgr* m_Map; void SetRenderScene(CEditContext* cont); }; inline void CMapEditApp::SetEditingMesh(sqr::EEDIT_MESH e) { m_eEditMesh = e; } inline bool CMapEditApp::GetIsEditingWater() { return m_eEditMesh == sqr::EEM_WATER; } }
[ "CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee" ]
CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee
6d077c832b05aa43510ab8b736d12fa9791d435a
6c0a11f53eff7b31ee0c493524e69b003b5938d7
/src.gfx/Compositor/OgreCompositorNode.h
0328e27d6abf9ae1b6e9dc8f818dbe9baa29b690
[]
no_license
yangfengzzz/Sisy
d2a8a6c34cd24f2eb9ab11bf99c76c68032ccc25
1f9637bcdc31905a4fb28fe2b9446c1ed279a923
refs/heads/master
2023-02-02T20:16:19.307627
2020-03-26T02:03:15
2020-03-26T02:03:15
322,533,099
1
0
null
null
null
null
UTF-8
C++
false
false
15,488
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 __CompositorNode_H__ #define __CompositorNode_H__ #include "OgreHeaderPrefix.h" #include "OgreCompositorCommon.h" #include "OgreCompositorChannel.h" #include "OgreCompositorNamedBuffer.h" #include "OgreResourceTransition.h" #include "OgreIdString.h" #include "OgreId.h" namespace Ogre{ class CompositorNodeDef; /** \addtogroup Core * @{ */ /** \addtogroup Effects * @{ */ struct BoundUav; /** Compositor nodes are the core subject of compositing. This is an instantiation. All const, shared parameters are in the definition (CompositorNodeDef) and we assume they don't change throughout the lifetime of our instance. @par The textures in mLocalTextures are managed by us and we're responsible for freeing them when they're no longer needed. @par Before nodes can be used, they have to be connected between each other, followed by a call to routeOutputs() Connections must be done in a very specific order, so let the manager take care of solving the dependencies. Basically the problem is that if the chain is like this: A -> B -> C; if we connect node B to C first, then there's a chance of giving null pointers to C instead of the valid ones that belong to A. @par To solve this problem, we first start with nodes that have no input, and then continue with those who have all of their input set; then repeat until there are no nodes to be processed. If there's still nodes with input left open; then those nodes can't be activated and the workspace is invalid. @par No Node can be valid if it has disconnected input channels left. Nodes can have no input because they either use passes that don't need it (eg. scene pass) or use global textures as means for sharing their work Similarly, Nodes may have no output because they use global textures. @par Nodes with feedback loops are not supported and may or may not work. A feedback loop is when A's output is used in B, B to C, then C is plugged back into A. @par It's possible to assign the same output to two different input channels, though it could work very unintuitively... (because two textures that may be intended to be hard copies are actually sharing the same memory) @remarks We own the local textures, so it's our job to destroy them @author Matias N. Goldberg @version 1.0 */ class _OgreExport CompositorNode : public CompositorInstAlloc, public IdObject { protected: /// Unique name across the same workspace IdString mName; bool mEnabled; /// Must be <= mInTextures.size(). Tracks how many pointers are not null in mInTextures size_t mNumConnectedInputs; CompositorChannelVec mInTextures; CompositorChannelVec mLocalTextures; /// Contains pointers that are ither in mInTextures or mLocalTextures CompositorChannelVec mOutTextures; size_t mNumConnectedBufferInputs; CompositorNamedBufferVec mBuffers; CompositorPassVec mPasses; /// Nodes we're connected to. If we destroy our local textures, we need to inform them CompositorNodeVec mConnectedNodes; CompositorWorkspace *mWorkspace; RenderSystem *mRenderSystem; /// Used to create/destroy MRTs /** Fills mOutTextures with the pointers from mInTextures & mLocalTextures according to CompositorNodeDef::mOutChannelMapping. Call this immediately after modifying mInTextures or mLocalTextures */ void routeOutputs(); /** Disconnects this node's output from all nodes we send our textures to. We only disconnect local textures. @remarks Textures that we got from our input channel and then pass it to the output channel are left untouched. This allows for some node to be plugged back & forth without making much mess and leaving everything else working. */ void disconnectOutput(); /// Makes global buffers visible to our passes. Must be done last in case /// there's an input/local buffer with the same name as a global buffer /// (local scope prevails over global scope) void populateGlobalBuffers(void); /** Called right after we create a pass. Derived classes may want to do something with it @param pass Newly created pass to toy with. */ virtual void postInitializePass( CompositorPass *pass ) {} public: /** The Id must be unique across all engine so we can create unique named textures. The name is only unique across the workspace */ CompositorNode( IdType id, IdString name, const CompositorNodeDef *definition, CompositorWorkspace *workspace, RenderSystem *renderSys, TextureGpu *finalTarget ); virtual ~CompositorNode(); void destroyAllPasses(void); IdString getName(void) const { return mName; } const CompositorNodeDef* getDefinition() const { return mDefinition; } RenderSystem* getRenderSystem(void) const { return mRenderSystem; } /** Enables or disables all instances of this node @remarks Note that we just won't execute our passes. It's your job to change the channel connections accordingly if you have to. A disabled node won't complain when its connections are incomplete in a workspace. @par This function is useful frequently toggling a compositor effect without having to recreate any API resource (which often would involve stalls). */ void setEnabled( bool bEnabled ); /// Returns if this instance is enabled. @See setEnabled bool getEnabled(void) const { return mEnabled; } /** Connects this node (let's call it node 'A') to node 'B', mapping the output channel from A into the input channel from B (buffer version) @param outChannelA Output to use from node A. @param inChannelB Input to connect the output from A. */ void connectBufferTo( size_t outChannelA, CompositorNode *nodeB, size_t inChannelB ); /** Connects this node (let's call it node 'A') to node 'B', mapping the output channel from A into the input channel from B (texture version) @param outChannelA Output to use from node A. @param inChannelB Input to connect the output from A. */ void connectTo( size_t outChannelA, CompositorNode *nodeB, size_t inChannelB ); /** Connects (injects) an external RT into the given channel. Usually used for the "connect_output" / "connect_external" directive for the RenderWindow. @param externalTexture The Textures associated with the RT. Can be empty (eg. RenderWindow) but could cause crashes/exceptions if tried to use in PASS_QUAD passes. @param inChannelA In which channel number to inject to. */ void connectExternalRT( TextureGpu *externalTexture, size_t inChannelA ); /** Connects (injects) an external buffer into the given channel. Usually used for the 'connect_buffer_external' directive. @param buffer The buffer. @param inChannelA In which channel number to inject to. */ void connectExternalBuffer( UavBufferPacked *buffer, size_t inChannelA ); bool areAllInputsConnected() const; const CompositorChannelVec& getInputChannel() const { return mInTextures; } const CompositorChannelVec& getLocalTextures() const { return mLocalTextures; } /** Returns the texture pointer of a texture based on it's name & mrt index. @remarks The texture name must have been registered with CompositorNodeDef::addTextureSourceName @param textureName The name of the texture. This name may only be valid at node scope. It can refer to an input texture, a local texture, or a global one. If the global texture wasn't registered with addTextureSourceName, it will fail. @return Null if not found (or global texture not registered). The texture otherwise */ TextureGpu* getDefinedTexture( IdString textureName ) const; /** Returns the buffer pointer of a buffer based on it's name. @remarks The buffer may come from a local buffer, an input buffer, or global (workspace). @param bufferName The name of the buffer. This name may only be valid at node scope. It can refer to an input buffer, a local buffer, or a global one. If a local or input buffer has the same name as a global one, the global one is ignored. @return Regular: The buffer. Throws if buffer wasn't found. No throw version: Null if not found. The buffer otherwise */ UavBufferPacked* getDefinedBuffer( IdString bufferName ) const; UavBufferPacked* getDefinedBufferNoThrow( IdString bufferName ) const; /** Creates all passes based on our definition @remarks Call this function after connecting all channels (at least our input) otherwise we may bind null pointer RTs to the passes (and then crash) @See connectTo and @see connectFinalRT */ void createPasses(void); const CompositorPassVec& _getPasses() const { return mPasses; } /** Calling this function every frame will cause us to execute all our passes (ie. render) @param lodCamera LOD Camera to be used by our passes. Pointer can be null, and note however passes can ignore this hint and use their own camera pointer for LOD (this parameter is mostly used for syncing shadow mapping). */ void _update( const Camera *lodCamera, SceneManager *sceneManager ); /// Overrides a resource with the given layout if it's already in outResourcesLayout static void fillResourcesLayout( ResourceLayoutMap &outResourcesLayout, const CompositorChannelVec &compositorChannels, ResourceLayout::Layout layout ); /// Only inits a resource with the given layout if it wasn't already in outResourcesLayout static void initResourcesLayout( ResourceLayoutMap &outResourcesLayout, const CompositorChannelVec &compositorChannels, ResourceLayout::Layout layout ); /// Only inits a resource with the given layout if it wasn't already in outResourcesLayout static void initResourcesLayout( ResourceLayoutMap &outResourcesLayout, const CompositorNamedBufferVec &buffers, ResourceLayout::Layout layout ); /// @see CompositorPass::_placeBarriersAndEmulateUavExecution void _placeBarriersAndEmulateUavExecution( BoundUav boundUavs[64], ResourceAccessMap &uavsAccess, ResourceLayoutMap &resourcesLayout ); /// @see CompositorPass::_removeAllBarriers void _removeAllBarriers(void); /// Places a resource transition in our last pass to the given RenderTarget. /// Usually needed to ensure the final 'RenderWindow' is still a RenderTarget /// after the workspace is finished. void _setFinalTargetAsRenderTarget( ResourceLayoutMap::iterator finalTargetCurrentLayout ); /** Call this function when you're replacing the textures from oldChannel with the ones in newChannel. Useful when recreating textures (i.e. resolution changed) @param oldBuffer The old textures that are going to be removed. Pointers in it must be still valid @param newBuffer The new replacement textures */ void notifyRecreated( const UavBufferPacked *oldBuffer, UavBufferPacked *newBuffer ); void notifyRecreated( TextureGpu *channel ); /** Call this function when caller has destroyed a RenderTarget in which the callee may have a reference to that pointer, so that we can clean it up. @param channel Channel containing the pointer about to be destroyed (must still be valid) */ void notifyDestroyed( TextureGpu *channel ); void notifyDestroyed( const UavBufferPacked *buffer ); /** Internal Use. Called when connections are all being zero'ed. We rely our caller is doing this to all nodes, hence we do not notify our @mConnectedNodes nodes. Failing to clear them too may leave dangling pointers or graphical glitches @remarks Destroys all of our passes. */ void _notifyCleared(void); /** Called by CompositorManager2 when (i.e.) the RenderWindow was resized, thus our RTs that depend on their resolution need to be recreated. @remarks We inform all connected nodes and passes related to us of RenderTargets/Textures that may have been recreated (pointers could become danlging otherwise). @par This is divided in two steps: recreateResizableTextures01 & recreateResizableTextures02 since in some cases in RenderPassDescriptor, setting up MRT and depth textures requires all textures to be up to date, otherwise validation errors would occur since we'll have partial data (e.g. MRT 0 is 1024x768 while MRT 1 is 800x600) @param finalTarget The Final Target (i.e. RenderWindow) from which we'll base our local textures' resolution. */ virtual void finalTargetResized01( const TextureGpu *finalTarget ); virtual void finalTargetResized02( const TextureGpu *finalTarget ); /// @copydoc CompositorWorkspace::resetAllNumPassesLeft void resetAllNumPassesLeft(void); /// @copydoc CompositorPassDef::getPassNumber size_t getPassNumber( CompositorPass *pass ) const; /// Returns our parent workspace CompositorWorkspace* getWorkspace(void) { return mWorkspace; } /// Returns our parent workspace const CompositorWorkspace* getWorkspace(void) const { return mWorkspace; } private: CompositorNodeDef const *mDefinition; }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
[ "yangfengzzz@hotmail.com" ]
yangfengzzz@hotmail.com
4a5d7906b3864d8732bcb1a9b19cc0d058c0ec6b
62fcc682afbc9197b3c4b9a8e2cafd70ff8ec4b1
/Lab07/Derived.h
79762caad5b9da0b9532f8cbedb9a45d85a29def
[]
no_license
miguellane/165-Object-Oriented-Programming
7f5d851874c2698b36c88a2d1ce3f19320aa93e4
8a1e31e649c5d35ae91deec78ff8bb27b3b9ac79
refs/heads/master
2021-01-20T00:45:55.126644
2017-10-14T00:03:09
2017-10-14T00:03:09
89,170,525
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
#ifndef LA6_ADTD_h #define LA6_ADTD_h #include <iostream> #include "ADT.h" class Derived : public ADT { public: void doSomething(){ std::cout << "I did something"<< std::endl; } void doSomethingElse(){ std::cout << "I did something else"<< std::endl; } void dontDoThis(){ } }; #endif
[ "noreply@github.com" ]
noreply@github.com
268d1004875910615e7b75e357bca3698ba77c89
8ae0c3dbb6c2e9991e9f56b58fbdec5b09ef3d20
/Gameboard.cpp
0a832fb8c5d8f371814360f2424140af4bac6850
[]
no_license
dlevi326/Checkers-AI
91201639b537337b8551c08c0952e42f11a854d9
74048a3d182fb84bb5a94ba757f209d972c7a48e
refs/heads/master
2020-03-29T22:49:20.545854
2018-11-08T19:56:32
2018-11-08T19:56:32
150,442,103
0
0
null
null
null
null
UTF-8
C++
false
false
3,204
cpp
#include <iostream> #include <vector> #include <string> #include <fstream> #include "Gameboard.h" using namespace std; int defArray[8][8] = {{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1,-1,-1,-1}}; Gameboard::Gameboard(int size){ //blankGame = " - "; //player1Game = " X "; //player2Game = " O "; //types[5] = {{" - "," x "," o "," X "," O "}}; blankGame = " - "; player1GameReg = " o "; // o player2GameReg = " x "; // x player1GameKing = " 0 "; // O player2GameKing = " Z "; // X string blank = blankGame; string player1 = player1GameKing; string player2 = player2GameKing; string arr[8][8] = {{player1,blank,player1,blank,player1,blank,player1,blank},{blank,player1,blank,player1,blank,player1,blank,player1},{player1,blank,player1,blank,player1,blank,player1,blank}, {blank,blank,blank,blank,blank,blank,blank,blank},{blank,blank,blank,blank,blank,blank,blank,blank}, {blank,player2,blank,player2,blank,player2,blank,player2},{player2,blank,player2,blank,player2,blank,player2,blank},{blank,player2,blank,player2,blank,player2,blank,player2}}; for(int i=0;i<size;i++){ vector<Square> v; for(int j=0;j<size;j++){ Square s(arr[i][j],i,j); if(arr[i][j]==player1GameKing || arr[i][j]==player2GameKing){ s.isKing = true; } else{ s.isKing = false; } v.push_back(s); } board.push_back(v); } } void Gameboard::load_board(Gameboard& g,string file){ ifstream inFile; inFile.open(file); if (!inFile) { cerr << "Unable to open file datafile.txt"; exit(1); // call system to stop } string line; string x; int ind1=0; int ind2=0; while ( getline (inFile,line) ) { if(line=="") break; for(int i=0;i<line.length();i++){ int num = (int) line[i]- '0'; //ind1 = 0; //ind2 = 0; switch(num){ case 0: g.board[ind1][ind2].type = g.blankGame; g.board[ind1][ind2].isKing = false; ind2++; break; //case 1: case 2: g.board[ind1][ind2].type = g.player1GameReg; g.board[ind1][ind2].isKing = false; ind2++; break; //case 2: case 4: g.board[ind1][ind2].type = g.player1GameKing; g.board[ind1][ind2].isKing = true; ind2++; break; //case 3: case 1: g.board[ind1][ind2].type = g.player2GameReg; g.board[ind1][ind2].isKing = false; ind2++; break; case 3: g.board[ind1][ind2].type = g.player2GameKing; g.board[ind1][ind2].isKing = true; ind2++; break; default: // May take out /*g.board[ind1][ind2].type = g.blankGame; g.board[ind1][ind2].isKing = false; ind2++; break;*/ continue; } } ind2 = 0; ind1++; //cout << line << '\n'; } inFile.close(); /*for(int i=0;i<8;i++){ for(int j=0;j<8;j++){ cout<<g.board[i][j].type; } cout<<endl; }*/ } Gameboard::Square::Square(string t ,int i,int j){ type = t; isKing = false; coords = make_pair(i,j); }
[ "dlevi623@gmail.com" ]
dlevi623@gmail.com
61e04e663ecb9c48fa7c6bf844ff983bbc01c195
e40cadbf02bf7d75bdf1a2c7dda6242c1b883e49
/examples/sunspot/adaptivitySS.cpp
1beb2421232cae0f0a4fd5377994ecfb423a5140
[]
no_license
jan-kotek/mhdeal
abd151a2dea9dae81fba64fbd3ab6a3323ee4bea
4ec5ce745e40006abe38ec8e72948d9d4ef3eefc
refs/heads/master
2023-04-19T05:32:08.663992
2022-12-20T10:20:57
2022-12-20T10:20:57
336,401,602
0
0
null
null
null
null
UTF-8
C++
false
false
15,728
cpp
#include "adaptivitySS.h" template <int dim> AdaptivitySS<dim>::AdaptivitySS(Parameters<dim>& parameters, MPI_Comm& mpi_communicator) : Adaptivity<dim>(parameters, mpi_communicator), last_time_step(0), adaptivity_step(0), mag(dim + 2) { } template <int dim> void AdaptivitySS<dim>::calculate_jumps(TrilinosWrappers::MPI::Vector& solution, const DoFHandler<dim>& dof_handler, const Mapping<dim>& mapping, Vector<double>& gradient_indicator) { FEValuesExtractors::Scalar scalars[dim]; scalars[0].component = 0; scalars[1].component = 4; const QGauss<dim - 1> face_quadrature(1); UpdateFlags face_update_flags = UpdateFlags(update_values | update_JxW_values | update_gradients); FEFaceValues<dim> fe_v_face(mapping, dof_handler.get_fe(), face_quadrature, face_update_flags); FESubfaceValues<dim> fe_v_subface(mapping, dof_handler.get_fe(), face_quadrature, face_update_flags); FEFaceValues<dim> fe_v_face_neighbor(mapping, dof_handler.get_fe(), face_quadrature, update_values | update_gradients); int n_quadrature_points_face = face_quadrature.get_points().size(); int dofs_per_cell = dof_handler.get_fe().dofs_per_cell; this->dof_indices.resize(dofs_per_cell); this->dof_indices_neighbor.resize(dofs_per_cell); for (unsigned int i = 0; i < dofs_per_cell; ++i) { const unsigned int component_i = dof_handler.get_fe().system_to_base_index(i).first.first; is_primitive[i] = dof_handler.get_fe().is_primitive(i); if (is_primitive[i]) component_ii[i] = dof_handler.get_fe().system_to_component_index(i).first; else component_ii[i] = 999; } for (typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) { if (!cell->is_locally_owned()) continue; Point<dim> jump; Point<dim> area; cell->get_dof_indices(this->dof_indices); for (unsigned int face_no = 0; face_no < GeometryInfo<dim>::faces_per_cell; ++face_no) { typename DoFHandler<dim>::face_iterator face = cell->face(face_no); if (!face->at_boundary()) { Assert(cell->neighbor(face_no).state() == IteratorState::valid, ExcInternalError()); typename DoFHandler<dim>::cell_iterator neighbor = cell->neighbor(face_no); std::vector<double> u(n_quadrature_points_face); std::vector<double> u_neighbor(n_quadrature_points_face); std::vector<std::array<std::array<double, dim>, dim> > u_mag; std::vector<std::array<std::array<double, dim>, dim> > u_neighbor_mag; u_mag.resize(n_quadrature_points_face); u_neighbor_mag.resize(n_quadrature_points_face); if (face->has_children()) { unsigned int neighbor2 = cell->neighbor_face_no(face_no); for (unsigned int subface_no = 0; subface_no < face->number_of_children(); ++subface_no) { typename DoFHandler<dim>::cell_iterator neighbor_child = cell->neighbor_child_on_subface(face_no, subface_no); Assert(!neighbor_child->has_children(), ExcInternalError()); fe_v_subface.reinit(cell, face_no, subface_no); fe_v_face_neighbor.reinit(neighbor_child, neighbor2); neighbor_child->get_dof_indices(dof_indices_neighbor); const std::vector<double> &JxW = fe_v_subface.get_JxW_values(); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) area[face_no / 2] += JxW[x]; if (this->parameters.polynomial_order_dg == 0) { for (int scalar_i = 0; scalar_i < 2; scalar_i++) { fe_v_subface[scalars[scalar_i]].get_function_values(solution, u); fe_v_face_neighbor[scalars[scalar_i]].get_function_values(solution, u_neighbor); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) jump[face_no / 2] += std::fabs(u[x] - u_neighbor[x]) * JxW[x]; } } else { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] = u_neighbor_mag[q][d][e] = 0.; for (unsigned int i = 0; i < dofs_per_cell; ++i) { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { // Plus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_subface[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] += solution(this->dof_indices[i]) * fe_v_grad[d][e]; } else if(component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices[i]) * fe_v_subface.shape_grad(i, q)[d]; // Minus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_face_neighbor[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_neighbor_mag[q][d][e] += solution(this->dof_indices_neighbor[i]) * fe_v_grad[d][e]; } else if (component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_neighbor_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices_neighbor[i]) * fe_v_face_neighbor.shape_grad(i, q)[d]; } } for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { std::array<double, dim> curl_ = { u_mag[q][2][1] - u_mag[q][1][2], u_mag[q][0][2] - u_mag[q][2][0], u_mag[q][1][0] - u_mag[q][0][1] }; u[q] = curl_[0] * curl_[0] + curl_[1] * curl_[1] + curl_[2] * curl_[2]; std::array<double, dim> curl_neighbor_ = { u_neighbor_mag[q][2][1] - u_neighbor_mag[q][1][2], u_neighbor_mag[q][0][2] - u_neighbor_mag[q][2][0], u_neighbor_mag[q][1][0] - u_neighbor_mag[q][0][1] }; u_neighbor[q] = curl_neighbor_[0] * curl_neighbor_[0] + curl_neighbor_[1] * curl_neighbor_[1] + curl_neighbor_[2] * curl_neighbor_[2]; jump[face_no / 2] += std::fabs(u[q] - u_neighbor[q]) * JxW[q]; } } } } else { if (!cell->neighbor_is_coarser(face_no)) { unsigned int neighbor2 = cell->neighbor_of_neighbor(face_no); fe_v_face.reinit(cell, face_no); fe_v_face_neighbor.reinit(neighbor, neighbor2); neighbor->get_dof_indices(dof_indices_neighbor); const std::vector<double> &JxW = fe_v_face.get_JxW_values(); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) area[face_no / 2] += JxW[x]; if (this->parameters.polynomial_order_dg == 0) { for (int scalar_i = 0; scalar_i < 2; scalar_i++) { fe_v_face[scalars[scalar_i]].get_function_values(solution, u); fe_v_face_neighbor[scalars[scalar_i]].get_function_values(solution, u_neighbor); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) jump[face_no / 2] += std::fabs(u[x] - u_neighbor[x]) * JxW[x]; } } else { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] = u_neighbor_mag[q][d][e] = 0.; for (unsigned int i = 0; i < dofs_per_cell; ++i) { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { // Plus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_face[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] += solution(this->dof_indices[i]) * fe_v_grad[d][e]; } else if (component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices[i]) * fe_v_face.shape_grad(i, q)[d]; // Minus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_face_neighbor[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_neighbor_mag[q][d][e] += solution(this->dof_indices_neighbor[i]) * fe_v_grad[d][e]; } else if (component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_neighbor_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices_neighbor[i]) * fe_v_face_neighbor.shape_grad(i, q)[d]; } } for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { std::array<double, dim> curl_ = { u_mag[q][2][1] - u_mag[q][1][2], u_mag[q][0][2] - u_mag[q][2][0], u_mag[q][1][0] - u_mag[q][0][1] }; u[q] = curl_[0] * curl_[0] + curl_[1] * curl_[1] + curl_[2] * curl_[2]; std::array<double, dim> curl_neighbor_ = { u_neighbor_mag[q][2][1] - u_neighbor_mag[q][1][2], u_neighbor_mag[q][0][2] - u_neighbor_mag[q][2][0], u_neighbor_mag[q][1][0] - u_neighbor_mag[q][0][1] }; u_neighbor[q] = curl_neighbor_[0] * curl_neighbor_[0] + curl_neighbor_[1] * curl_neighbor_[1] + curl_neighbor_[2] * curl_neighbor_[2]; jump[face_no / 2] += std::fabs(u[q] - u_neighbor[q]) * JxW[q]; } } } else //i.e. neighbor is coarser than cell { std::pair<unsigned int, unsigned int> neighbor_face_subface = cell->neighbor_of_coarser_neighbor(face_no); Assert(neighbor_face_subface.first < GeometryInfo<dim>::faces_per_cell, ExcInternalError()); Assert(neighbor_face_subface.second < neighbor->face(neighbor_face_subface.first)->number_of_children(), ExcInternalError()); Assert(neighbor->neighbor_child_on_subface(neighbor_face_subface.first, neighbor_face_subface.second) == cell, ExcInternalError()); fe_v_face.reinit(cell, face_no); fe_v_subface.reinit(neighbor, neighbor_face_subface.first, neighbor_face_subface.second); neighbor->get_dof_indices(dof_indices_neighbor); const std::vector<double> &JxW = fe_v_face.get_JxW_values(); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) area[face_no / 2] += JxW[x]; if (this->parameters.polynomial_order_dg == 0) { for (int scalar_i = 0; scalar_i < 2; scalar_i++) { fe_v_face[scalars[scalar_i]].get_function_values(solution, u); fe_v_subface[scalars[scalar_i]].get_function_values(solution, u_neighbor); for (unsigned int x = 0; x < n_quadrature_points_face; ++x) jump[face_no / 2] += std::fabs(u[x] - u_neighbor[x]) * JxW[x]; } } else { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] = u_neighbor_mag[q][d][e] = 0.; for (unsigned int i = 0; i < dofs_per_cell; ++i) { for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { // Plus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_face[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_mag[q][d][e] += solution(this->dof_indices[i]) * fe_v_grad[d][e]; } else if (component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices[i]) * fe_v_face.shape_grad(i, q)[d]; // Minus if (!is_primitive[i]) { Tensor<2, dim> fe_v_grad = fe_v_subface[mag].gradient(i, q); for (int d = 0; d < dim; d++) for (int e = 0; e < dim; e++) u_neighbor_mag[q][d][e] += solution(this->dof_indices_neighbor[i]) * fe_v_grad[d][e]; } else if (component_ii[i] >= 5) for (int d = 0; d < dim; d++) u_neighbor_mag[q][component_ii[i] - 5][d] += solution(this->dof_indices_neighbor[i]) * fe_v_subface.shape_grad(i, q)[d]; } } for (unsigned int q = 0; q < n_quadrature_points_face; ++q) { std::array<double, dim> curl_ = { u_mag[q][2][1] - u_mag[q][1][2], u_mag[q][0][2] - u_mag[q][2][0], u_mag[q][1][0] - u_mag[q][0][1] }; u[q] = curl_[0] * curl_[0] + curl_[1] * curl_[1] + curl_[2] * curl_[2]; std::array<double, dim> curl_neighbor_ = { u_neighbor_mag[q][2][1] - u_neighbor_mag[q][1][2], u_neighbor_mag[q][0][2] - u_neighbor_mag[q][2][0], u_neighbor_mag[q][1][0] - u_neighbor_mag[q][0][1] }; u_neighbor[q] = curl_neighbor_[0] * curl_neighbor_[0] + curl_neighbor_[1] * curl_neighbor_[1] + curl_neighbor_[2] * curl_neighbor_[2]; jump[face_no / 2] += std::fabs(u[q] - u_neighbor[q]) * JxW[q]; } } } } } } double average_jumps[dim]; double sum_of_average_jumps = 0.; for (unsigned int i = 0; i < dim; ++i) { average_jumps[i] = jump(i) / area(i); sum_of_average_jumps += average_jumps[i]; } for (int i = 0; i < this->parameters.volume_factor; i++) sum_of_average_jumps *= cell->diameter(); gradient_indicator(cell->active_cell_index()) = sum_of_average_jumps; } } template <int dim> bool AdaptivitySS<dim>::refine_mesh(int time_step, double time, TrilinosWrappers::MPI::Vector& solution, const DoFHandler<dim>& dof_handler, #ifdef HAVE_MPI parallel::distributed::Triangulation<dim>& triangulation #else Triangulation<dim>& triangulation #endif , const Mapping<dim>& mapping) { if (time_step % this->parameters.refine_every_nth_time_step) return false; if (++adaptivity_step > (time_step == 0 ? this->parameters.perform_n_initial_refinements : 1)) { adaptivity_step = 0; return false; } Vector<double> gradient_indicator(triangulation.n_active_cells()); calculate_jumps(solution, dof_handler, mapping, gradient_indicator); int max_calls_ = this->parameters.max_cells + (int)std::floor(time * this->parameters.max_cells * this->parameters.time_interval_max_cells_multiplicator / this->parameters.final_time); GridRefinement::refine_and_coarsen_fixed_fraction(triangulation, gradient_indicator, this->parameters.refine_threshold, this->parameters.coarsen_threshold, max_calls_); triangulation.prepare_coarsening_and_refinement(); return true; } template class AdaptivitySS<3>;
[ "jankotek@email.cz" ]
jankotek@email.cz
fa5ac04265106a0df144d966e6c42dd1a4bd876c
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14776/function14776_schedule_24/function14776_schedule_24.cpp
30e46a7b3b46271948ab151c9a6e6affdb7826f3
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14776_schedule_24"); constant c0("c0", 128), c1("c1", 1024), c2("c2", 512); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i100("i100", 1, c0 - 1), i101("i101", 1, c1 - 1), i102("i102", 1, c2 - 1), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); input input0("input0", {i0, i1, i2}, p_int32); computation comp0("comp0", {i100, i101, i102}, (input0(i100, i101, i102) - input0(i100 + 1, i101, i102) + input0(i100 - 1, i101, i102))); comp0.tile(i100, i101, i102, 64, 32, 32, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf00("buf00", {128, 1024, 512}, p_int32, a_input); buffer buf0("buf0", {128, 1024, 512}, p_int32, a_output); input0.store_in(&buf00); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf0}, "../data/programs/function14776/function14776_schedule_24/function14776_schedule_24.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
d7fe704b9a32274b9e9d42e13f23d4d50c636b8d
70c296a4f5c4387ad9a6bfe6e5c59bc23430485c
/cosfile.cpp
83cf466602d326556da8538b9bfa3ca1b3d6290e
[ "MIT" ]
permissive
rda-dattore/util
3e7ff63ac74ceae356e938b62d4ff8d71e00b517
5a28b748f64db991e62be58c25513041017c21ee
refs/heads/master
2021-11-21T13:23:05.070229
2021-07-30T20:33:10
2021-07-30T20:33:10
101,075,360
0
0
null
2020-03-05T00:18:08
2017-08-22T15:01:30
C++
UTF-8
C++
false
false
4,445
cpp
#include <iostream> #include <iomanip> #include <string> #include <list> #include <regex> #include <bfstream.hpp> #include <strutils.hpp> #include <utils.hpp> #include <myerror.hpp> struct Args { Args() : files(),verbose(false) {} std::list<std::string> files; bool verbose; } args; std::string myerror=""; std::string mywarning=""; void parse_args(int argc,char **argv) { auto unix_args=unixutils::unix_args_string(argc,argv,'!'); auto sp=strutils::split(unix_args,"!"); for (size_t n=0; n < sp.size(); ++n) { if (sp[n] == "-v") { args.verbose=true; } else if (std::regex_search(sp[n],std::regex("^-"))) { std::cerr << "Error: invalid flag " << sp[n] << std::endl; exit(1); } else { args.files.push_back(sp[n]); } } } int main(int argc,char **argv) { if (argc < 2) { std::cerr << "usage: " << argv[0] << " [-v] files" << std::endl; std::cerr << std::endl; std::cerr << "function: " << argv[0] << " provides information about a COS-blocked dataset(s)" << std::endl; std::cerr << std::endl; std::cerr << "options:" << std::endl; std::cerr << " -v provides additional information about the record sizes in the" << std::endl; std::cerr << " dataset(s)" << std::endl; exit(1); } parse_args(argc,argv); int BUF_LEN=0; std::unique_ptr<unsigned char []> buf; auto eof_recs=0; int eof_min=0x7fffffff,eof_max=0; size_t type[]={0,0}; for (const auto& file : args.files) { // open the COS-blocked dataset icstream istream; if (!istream.open(file.c_str())) { std::cerr << "Error opening " << file << std::endl; exit(1); } double eof_bytes=0.; auto eof_num=0; long long eod_bytes=0; auto eod_recs=0; auto eod_min=0x7fffffff; auto eod_max=0; auto last_written=false; std::cout << "\nProcessing dataset: " << file << std::endl; // read to the end of the COS-blocked dataset int num_bytes; while ( (num_bytes=istream.peek()) != craystream::eod) { if (num_bytes == bfstream::error) { std::cerr << "\nRead error on record " << eof_recs+1 << " - may not be COS-blocked" << std::endl; exit(1); } auto last_len=-1; // read the current file do { if (num_bytes > BUF_LEN) { BUF_LEN=num_bytes; buf.reset(new unsigned char[BUF_LEN]); } istream.read(buf.get(),BUF_LEN); // handle a double EOF if (num_bytes == craystream::eof) { eof_min=0; break; } ++eof_recs; ++eod_recs; eof_bytes+=num_bytes; eod_bytes+=num_bytes; if (num_bytes < eof_min) eof_min=num_bytes; if (num_bytes > eof_max) eof_max=num_bytes; if (num_bytes < eod_min) eod_min=num_bytes; if (num_bytes > eod_max) eod_max=num_bytes; last_written=false; if (args.verbose && num_bytes != last_len) { if (last_len == -1) { std::cout << "\n Rec# Bytes" << std::endl; } std::cout << " " << std::setw(7) << eof_recs << " " << std::setw(7) << num_bytes << std::endl; last_written=true; } last_len=num_bytes; for (int n=0; n < num_bytes; ++n) { if (buf[n] < 0x20 || buf[n] > 0x7e) { ++type[0]; } else { ++type[1]; } } } while ( (num_bytes=istream.peek()) != craystream::eof); num_bytes=istream.read(buf.get(),BUF_LEN); if (args.verbose && eof_recs > 0 && !last_written) { std::cout << " " << std::setw(7) << eof_recs << " " << std::setw(7) << last_len << std::endl; } // summarize for the current file std::cout << " EOF " << ++eof_num << ": Recs=" << eof_recs << " Min=" << eof_min << " Max=" << eof_max << " Avg="; if (eof_recs > 0) { std::cout << lroundf(eof_bytes/eof_recs); } else { std::cout << "0"; } std::cout << " Bytes=" << static_cast<long long>(eof_bytes) << std::endl; if (eof_bytes > 0) { if (type[0] == 0) { std::cout << " Type=ASCII" << std::endl; } else { if (type[1] == 0) { std::cout << " Type=Binary" << std::endl; } else { type[0]=type[0]*100./eof_bytes; type[1]=100-type[0]; std::cout << " Type=Binary or mixed -- Binary= " << type[0] << "% ASCII= " << type[1] << "%" << std::endl; } } } std::cout << std::endl; // reset eof_bytes=0; eof_recs=0; eof_min=0x7fffffff; eof_max=0; type[0]=type[1]=0; } istream.close(); // summarize for the dataset std::cout << " EOD. Min=" << eod_min << " Max=" << eod_max << " Records=" << eod_recs << " Bytes=" << eod_bytes << std::endl; } return 0; }
[ "dattore@ucar.edu" ]
dattore@ucar.edu
92b37755ebb66294455d900a926240b374ef97e6
b97c1b35c0e6350c49bac6b3b489652584977d01
/src/NmarBdSbm.cpp
595bee9446d39749ce7e16cbb50cbd0c7ba745ee
[]
no_license
minghao2016/greed
42f8e104381744ce719b2cb614652608182419f9
0cc68aac7fed229db1d8e4dbdeb0b16e0b466e2c
refs/heads/master
2023-04-20T07:28:53.538857
2021-05-11T10:22:58
2021-05-11T10:22:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,468
cpp
// [[Rcpp::depends(RcppArmadillo)]] #include "gicl_tools.h" #include "MergeMat.h" #include "IclModel.h" #include "MissSbm.h" #include "NmarBdSbm.h" using namespace Rcpp; double NmarBdSbm::icl_emiss(const List & obs_stats){ arma::vec counts =as<arma::vec>(obs_stats["counts"]); arma::mat edges_counts =as<arma::mat>(obs_stats["x_counts"]); arma::mat obs_counts =as<arma::mat>(obs_stats["x_counts_obs"]); arma::mat cmat = lgamma(a0+edges_counts)+lgamma(obs_counts-edges_counts+b0)+lgamma(a0+b0); cmat = cmat - lgamma(a0) - lgamma(b0) - lgamma(obs_counts+a0+b0); arma::mat matcount = counts*counts.t(); arma::mat cmatobs = lgamma(a0obs+obs_counts)+lgamma(matcount-obs_counts+b0obs)+lgamma(a0obs+b0obs); cmatobs = cmatobs - lgamma(a0obs) - lgamma(b0obs) - lgamma(matcount+a0obs+b0obs); double icl_emiss=accu(cmat+cmatobs); return icl_emiss; } double NmarBdSbm::icl_emiss(const List & obs_stats,int oldcl,int newcl){ arma::vec counts =as<arma::vec>(obs_stats["counts"]); arma::mat edges_counts =as<arma::mat>(obs_stats["x_counts"]); arma::mat obs_counts =as<arma::mat>(obs_stats["x_counts_obs"]); arma::mat si = submatcross(oldcl,newcl,counts.n_rows); double icl_emiss = 0; int k = 0; int l = 0; int cc = 0; for (arma::uword i = 0;i<si.n_rows;++i){ k=si(i,0); l=si(i,1); if(counts(k)*counts(l)!=0){ cc = obs_counts(k,l); icl_emiss += lgamma(a0+edges_counts(k,l))+lgamma(b0+cc-edges_counts(k,l))+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc); cc = counts(k)*counts(l); icl_emiss += lgamma(a0obs+obs_counts(k,l))+lgamma(b0obs+cc-obs_counts(k,l))+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc); } } return icl_emiss; } double NmarBdSbm::delta_merge_correction(int k,int l,int obk,int obl,const List & old_stats){ // here old refers to the stats before the fusion between obk and obl //Rcout << obk << "---- " << obl << std::endl; int a,b,ao,bo,lo; double icl_cor = 0; int cc, cc_old; double oxc,xc; arma::vec old_counts =as<arma::vec>(old_stats["counts"]); arma::mat old_x_counts =as<arma::mat>(old_stats["x_counts"]); arma::mat old_obs_counts =as<arma::mat>(old_stats["x_counts_obs"]); cc = counts(k)*counts(l); arma::uvec kl; kl << k << l << arma::endr; arma::uvec mkl; mkl << obk << obl << arma::endr; if(l>=obk){ lo=l+1; }else{ lo=l; } for(int i=0;i<2;i++){ for (int j=0;j<2;j++){ a = kl(i); b = mkl(j); if(b>=obk){ b=b-1; } // new stats no fusion k/l if(j==1){ cc = x_counts_obs(a,b); icl_cor -= lgamma(a0+x_counts(a,b))+lgamma(b0+cc-x_counts(a,b))+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc); cc = counts(a)*counts(b); icl_cor -= lgamma(a0obs+x_counts_obs(a,b))+lgamma(b0obs+cc-x_counts_obs(a,b))+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc); cc = x_counts_obs(b,a); icl_cor -= lgamma(a0+x_counts(b,a))+lgamma(b0+cc-x_counts(b,a))+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc); cc = counts(a)*counts(b); icl_cor -= lgamma(a0obs+x_counts_obs(b,a))+lgamma(b0obs+cc-x_counts_obs(b,a))+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc); } // new stats fusion k/l if((j==1) & (i==0)){ cc = x_counts_obs(k,b)+x_counts_obs(l,b); xc = x_counts(k,b)+x_counts(l,b); icl_cor += lgamma(a0+xc)+lgamma(b0+cc-xc)+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc); cc = (counts(k)+counts(l))*counts(b); xc = x_counts_obs(k,b)+x_counts_obs(l,b); icl_cor += lgamma(a0obs+xc)+lgamma(b0obs+cc-xc)+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc); cc = x_counts_obs(b,k)+x_counts_obs(b,l); xc = x_counts(b,k)+x_counts(b,l); icl_cor += lgamma(a0+xc)+lgamma(b0+cc-xc)+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc); cc = (counts(k)+counts(l))*counts(b); xc = x_counts_obs(b,k)+x_counts_obs(b,l); icl_cor += lgamma(a0obs+xc)+lgamma(b0obs+cc-xc)+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc); } // handling matrix sizes differences ao = kl(i); bo = mkl(j); if(ao>=obk){ ao=ao+1; } // old stats no fusion k/l cc_old = old_obs_counts(ao,bo); icl_cor += lgamma(a0+old_x_counts(ao,bo))+lgamma(b0+cc_old-old_x_counts(ao,bo))+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc_old); cc_old = old_counts(ao)*old_counts(bo); icl_cor += lgamma(a0obs+old_obs_counts(ao,bo))+lgamma(b0+cc_old-old_obs_counts(ao,bo))+lgamma(a0obs+b0)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc_old); cc_old = old_obs_counts(bo,ao); icl_cor += lgamma(a0+old_x_counts(bo,ao))+lgamma(b0+cc_old-old_x_counts(bo,ao))+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc_old); cc_old = old_counts(ao)*old_counts(bo); icl_cor += lgamma(a0obs+old_obs_counts(bo,ao))+lgamma(b0+cc_old-old_obs_counts(bo,ao))+lgamma(a0obs+b0)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc_old); // old stats fusion k/l if(i==0){ cc_old = old_obs_counts(ao,bo)+old_obs_counts(lo,bo); oxc = old_x_counts(ao,bo)+old_x_counts(lo,bo); icl_cor -= lgamma(a0+oxc)+lgamma(b0+cc_old-oxc)+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc_old); cc_old = (old_counts(ao)+old_counts(lo))*old_counts(bo); oxc = old_obs_counts(ao,bo)+old_obs_counts(lo,bo); icl_cor -= lgamma(a0obs+oxc)+lgamma(b0obs+cc_old-oxc)+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc_old); cc_old = old_obs_counts(bo,ao)+old_obs_counts(bo,lo); oxc = old_x_counts(bo,ao)+old_x_counts(bo,lo); icl_cor -= lgamma(a0+oxc)+lgamma(b0+cc_old-oxc)+lgamma(a0+b0)-lgamma(a0)-lgamma(b0)-lgamma(a0+b0+cc_old); cc_old = (old_counts(ao)+old_counts(lo))*old_counts(bo); oxc = old_obs_counts(bo,ao)+old_obs_counts(bo,lo); icl_cor -= lgamma(a0obs+oxc)+lgamma(b0obs+cc_old-oxc)+lgamma(a0obs+b0obs)-lgamma(a0obs)-lgamma(b0obs)-lgamma(a0obs+b0obs+cc_old); } } } return icl_cor; }
[ "etienne.come@gmail.com" ]
etienne.come@gmail.com
3914a4a608c8fb3781a1d304fe432a46f05fe6f4
7ff6b06a07b17d0d580db60943296124ec35f144
/src/fftTool.h
b99c1ad331d278eeff1486d0a55ee0d4188c9e93
[]
no_license
Hislocked/ECO_HC
6addaef3a1a18228860889279c67688cb1fc8d6b
73786eb218f9c1f4f73f24ef9aabb793c0ef5921
refs/heads/master
2020-07-12T12:55:10.519135
2019-08-29T01:15:25
2019-08-29T01:15:25
204,824,186
0
0
null
2019-08-28T09:45:07
2019-08-28T01:45:07
null
UTF-8
C++
false
false
2,045
h
#ifndef FFTTOOL_H #define FFTTOOL_H #include <opencv2/features2d/features2d.hpp> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" namespace FFTTools { // Previous declarations, to avoid warnings cv::Mat fftd(const cv::Mat& img_org, bool backwards = false); cv::Mat fftr(const cv::Mat& img_org); cv::Mat real(cv::Mat img); cv::Mat imag(cv::Mat img); cv::Mat magnitude(cv::Mat img); cv::Mat complexMultiplication(cv::Mat a, cv::Mat b); float sum_conj(cv::Mat a, cv::Mat b); cv::Mat complexDivision(cv::Mat a, cv::Mat b); cv::Mat complexDivisionreal(cv::Mat a, cv::Mat b); cv::Mat complexbsxfun(cv::Mat a, cv::Mat b); cv::Mat eng(cv::Mat img); void rearrange(cv::Mat &img); void normalizedLogTransform(cv::Mat &img); //***** add by tanfeiyang **** 2017.8.15 cv::Mat fftshift(const cv::Mat& org_img, bool rowshift = true, bool colshift = true, bool reverse = 0); cv::Mat mat_conj(const cv::Mat org); float mat_sum(cv::Mat org); //** just for single channel float *** cv::Mat cmat_multi(const cv::Mat&a, const cv::Mat& b); //** the mulitiplciation of two complex matrix cv::Mat real2complx(const cv::Mat& x); inline bool SizeCompare(cv::Size& a, cv::Size& b) //** extra function for STL { return a.height < b.height; } inline void rot90(cv::Mat &matImage, int rotflag){ //matrix ration by tanfeiyang 1=CW, 2=CCW, 3=180 if (rotflag == 1){ transpose(matImage, matImage); flip(matImage, matImage, 1); //transpose+flip(1)=CW } else if (rotflag == 2) { transpose(matImage, matImage); flip(matImage, matImage, 0); //transpose+flip(0)=CCW } else if (rotflag == 3){ flip(matImage, matImage, -1); //flip(-1)=180 } else if (rotflag != 0){ //if not 0,1,2,3: assert("Unknown rotation flag"); } } //*** roa cv::Mat conv_complex(cv::Mat _a, cv::Mat _b, bool valid = 0); //*** impliment matlab c = convn(a,b) no matter of real of complex, It can work } #endif
[ "492585385@qq.com" ]
492585385@qq.com
cb01b4719ab8caca0c915202b378cd651a3ad67f
d0bb25d43b9f299a3ace313d4f8805750c4f0751
/GameProject/main.cpp
8cde4969b9c04a43fe962ae06bbc32831b4961a6
[]
no_license
KillianMcCabe/OpenGL-Game
1eb272aee14a86482b2129f22d7d9097aef90f89
c2ce196a3c4c76090c97d14e9755df9679ef1b76
refs/heads/master
2021-01-01T05:31:32.982178
2014-12-08T00:27:45
2014-12-08T00:27:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,944
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <SFML/Window.hpp> #include <SFML/Audio.hpp> #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <iostream> #include <vector> #define STB_IMAGE_IMPLEMENTATION #include "text.h" #include "object.h" #include "camera.hpp" #include "utilities.h" #include "wizard.h" #include "crow.h" #include "venom.h" #include "fountain.h" #include "tree.h" #include "house.h" #include "projectile.h" #include "ObjectManager.h" // files to use for font. change path here const char* atlas_image = "freemono.png"; const char* atlas_meta = "freemono.meta"; // Globals GLFWwindow* window = NULL; bool game_over = false; bool game_win = false; Wizard wizard; Venom venom; House house; int crow_shot_count; // // dimensions of the window drawing surface int gl_width = 1024; int gl_height = 768; glm::mat4 P, V, M; const float flash_rate = 0.35; const float flash_length = 0.1; float flash_time = 0.0; using namespace glm; #define MAIN_TITLE "OpenGL 4.0 - Mountains demo" int main () { const GLubyte* renderer; const GLubyte* version; sf::Music music; if (!music.openFromFile("assets/audio/SpookyScarySkeletons.ogg")) return -1; // error music.setVolume(20); bool music_playing = false; double time_since_music_start = 0.0; //music.play(); // // Start OpenGL using helper libraries // -------------------------------------------------------------------------- if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); */ window = glfwCreateWindow (gl_width, gl_height, "Hello Spooky", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: opening OS window\n"); return 1; } glfwMakeContextCurrent (window); glewExperimental = GL_TRUE; glewInit (); glfwSetCursorPos(window, gl_width/2, gl_height/2); //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); //GLuint simple_shader_programme = load_shaders("simple.vert", "simple.frag"); //GLuint simple_shader_programme = load_shaders("fog_shader.vert", "fog_shader.frag"); GLuint simple_shader_programme = load_shaders("fog_shader_to_texture.vert", "fog_shader_to_texture.frag"); GLuint quad_shader = load_shaders("quad.vert", "quad.frag"); GLuint game_over_screen_texture = load_texture("assets/game_over_screen.jpg"); // Get uniform locations int M_loc = glGetUniformLocation (simple_shader_programme, "M"); assert (M_loc > -1); int V_loc = glGetUniformLocation (simple_shader_programme, "V"); assert (V_loc > -1); int P_loc = glGetUniformLocation (simple_shader_programme, "P"); assert (P_loc > -1); int light_pos_loc = glGetUniformLocation (simple_shader_programme, "light_pos"); assert (light_pos_loc > -1); int effect_loc = glGetUniformLocation (quad_shader, "effect"); assert (effect_loc > -1); glUseProgram (simple_shader_programme); // Pass light position to shader vec3 light_pos = vec3(8.0, 5.0, -8.5); glUniform3f(light_pos_loc, light_pos[0], light_pos[1], light_pos[2]); // // Start rendering // -------------------------------------------------------------------------- // tell GL to only draw onto a pixel if the fragment is closer to the viewer //glEnable (GL_DEPTH_TEST); // enable depth-testing //glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" //glDisable(GL_CULL_FACE); ObjectManager objects = ObjectManager(); Tree::init(simple_shader_programme); House::init(simple_shader_programme); objects.generateTerrain(); // add grass to scene Object ground = Object("assets/ground.obj", "assets/grass_tex.png"); // add trees to scene //objects.add(Tree(simple_shader_programme, -3.0, 0.0, 3.0)); //objects.add(Tree(simple_shader_programme, 3.0, 0.0, 3.0)); // add crow objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); objects.add(Crow(simple_shader_programme, rand_int(-100, 100), 2.5, rand_int(0, 100))); //objects.add(Venom(simple_shader_programme, rand_int(-5, 5), 0, rand_int(-5, 5))); wizard = Wizard(simple_shader_programme); //objects.setPlayer(wizard); venom = Venom(simple_shader_programme, rand_int(-5, 5), 0, rand_int(-5, 5)); Fountain fountain = Fountain(); assert (init_text_rendering (atlas_image, atlas_meta, gl_width, gl_height)); int crow_count_text_id = add_text ( "Crows shot: ", -0.95f, -0.8f, 50.0f, 1.0f, 1.0f, 1.0f, 1.0f); int leaving_area_text_id = add_text ( "", -0.6f, 0.8f, 50.0f, 1.0f, 1.0f, 1.0f, 1.0f); int venom_dead_text_id = add_text ( "", -0.4f, 0.5f, 50.0f, 1.0f, 1.0f, 1.0f, 1.0f); focus_camera_on(vec3(0, 0, 0), gl_width, gl_height); V = getViewMatrix(); P = getProjectionMatrix(); // // create vao for rendering image // // The fullscreen quad's FBO static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; GLfloat tex_uvs[] = { 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f }; GLuint quad_vertexbuffer; GLuint uvs_vbo; GLuint quad_vao; glGenBuffers(1, &quad_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); glGenBuffers (1, &uvs_vbo); glBindBuffer (GL_ARRAY_BUFFER, uvs_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (tex_uvs), tex_uvs, GL_STATIC_DRAW); glGenVertexArrays (1, &quad_vao); glBindVertexArray (quad_vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); glBindBuffer (GL_ARRAY_BUFFER, uvs_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // ----------- Render to frame buffer start ------------------- // GLuint renderedTexture; glGenTextures(1, &renderedTexture); glBindTexture(GL_TEXTURE_2D, renderedTexture); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, gl_width, gl_height, 0,GL_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GLuint depthrenderbuffer; glGenRenderbuffers(1, &depthrenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, gl_width, gl_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderedTexture, 0); glDrawBuffer(GL_NONE); // Always check that our framebuffer is ok if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return false; // Set the list of draw buffers. GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0}; glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers // ----------- Render to frame buffer end ------------------- char tmp[256]; vec3 wiz_pos; double lastTime = glfwGetTime(); double currentTime; float r, g, b; bool sound_was_pressed = false; while (!glfwWindowShouldClose (window)) { if (glfwGetKey(window, GLFW_KEY_ESCAPE)== GLFW_PRESS) { music.stop(); glfwSetWindowShouldClose(window, GL_TRUE); } if (glfwGetKey(window, GLFW_KEY_M) == GLFW_RELEASE && sound_was_pressed) { if (music_playing & time_since_music_start >0.5 ) { music.stop(); music_playing = false; } else { music.play(); music_playing = true; time_since_music_start = 0.0; } } if (glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS) { sound_was_pressed = true; } else { sound_was_pressed = false; } currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); // Render to Framebuffer glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0,0,gl_width,gl_height); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.5, 0.5, 0.5, 1);//gray color, same as fog color if (game_over) { // Use our shader glUseProgram(quad_shader); // Bind our texture textures GLuint texLoc = glGetUniformLocation(quad_shader, "input_texture"); assert(texLoc != -1); glUniform1i(texLoc, 0); glUniform4f(effect_loc, 0.0, 0.0, 0.0, 0.0); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, game_over_screen_texture); // select vao glBindVertexArray (quad_vao); glDrawArrays(GL_TRIANGLES, 0, 6); if (glfwGetKey(window, GLFW_KEY_SPACE)== GLFW_PRESS) { game_over = false; venom = Venom(simple_shader_programme, rand_int(-5, 5), 0, rand_int(-5, 5)); wizard = Wizard(simple_shader_programme); ObjectManager::crow_shot_count = 0; objects.refresh(); } } else { focus_camera_on(objects.getPlayerPos(), gl_width, gl_height); V = getViewMatrix(); P = getProjectionMatrix(); glUniformMatrix4fv (V_loc, 1, GL_FALSE, &V[0][0]); glUniformMatrix4fv (P_loc, 1, GL_FALSE, &P[0][0]); light_pos = objects.getLanternPos(); glUniform3f(light_pos_loc, light_pos[0], light_pos[1], light_pos[2]); glUseProgram (simple_shader_programme); ground.draw(mat4(1.0), M_loc); //fountain.draw(deltaTime, V, P, light_pos); objects.update(deltaTime); objects.draw(V, P, light_pos); wiz_pos = wizard.get_pos(); if (wiz_pos.x > 80 || wiz_pos.x < -80 || wiz_pos.z > 80 || wiz_pos.z < -80) { sprintf (tmp, "Warning: You are leaving the forest, turn back."); update_text (leaving_area_text_id, tmp); } else { sprintf (tmp, ""); update_text (leaving_area_text_id, tmp); } if (venom.dead) { sprintf (tmp, "Venom has fallen to the crows."); update_text (venom_dead_text_id, tmp); } else if (venom.home) { sprintf (tmp, "Venom has safely made it home!"); update_text (venom_dead_text_id, tmp); } else { sprintf (tmp, ""); update_text (venom_dead_text_id, tmp); } sprintf (tmp, "Crows shot: %d\n", ObjectManager::crow_shot_count); update_text (crow_count_text_id, tmp); draw_texts(); //if (glfwGetKey(window, GLFW_KEY_SPACE)== GLFW_PRESS) { // game_over = false; // venom = Venom(simple_shader_programme, rand_int(-5, 5), 0, rand_int(-5, 5)); // wizard = Wizard(simple_shader_programme); // ObjectManager::crow_shot_count = 0; // //objects.refresh(); TODO //} } // Render to window glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0,0,gl_width,gl_height); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(quad_shader); GLuint texLoc = glGetUniformLocation(quad_shader, "input_texture"); assert(texLoc != -1); glUniform1i(texLoc, 0); if (music_playing) { if (time_since_music_start > 7.5 && flash_time > flash_rate ) { glUniform4f(effect_loc, r, g, b, 0.0); if (flash_time > flash_rate + flash_length) { flash_time -= flash_rate + flash_length; } } else { r = RandomFloat(0.0, 0.8); g = RandomFloat(0.0, 0.8); b = RandomFloat(0.0, 0.8); glUniform4f(effect_loc, 0, 0, 0, 0.0); } flash_time += deltaTime; time_since_music_start += deltaTime; } glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderedTexture); glBindVertexArray (quad_vao); glDrawArrays(GL_TRIANGLES, 0, 6); lastTime = currentTime; /* this just updates window events and keyboard input events (not used yet) */ glfwPollEvents (); /* swaps the buffer that we are drawing to, and the one currently displayed on the window */ glfwSwapBuffers (window); } return 0; }
[ "killianparker93@gmail.com" ]
killianparker93@gmail.com
9042f5690d149c07e7123f869c470c4a392e5401
478fc63a73a7816070e64c701575a785f6ec76a9
/include/caffe/layers/pairwise_avg_layer.hpp
56a37d8c25e9afc12371f09c9012ba61f258df25
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
sarojraizan/caffe
cf6ad0690018c3116c67d262f76dc47aa5f38848
cec841637c2a585f3667612a073c005e5e922040
refs/heads/master
2021-01-18T03:22:43.708132
2016-11-02T09:13:03
2016-11-02T09:13:03
35,623,677
0
0
null
2016-07-28T12:49:32
2015-05-14T16:52:46
C++
UTF-8
C++
false
false
1,950
hpp
#ifndef CAFFE_PAIRWISEAVG_LAYER_HPP_ #define CAFFE_PAIRWISEAVG_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/eltwise_layer.hpp" #include "caffe/layers/pooling_layer.hpp" #include "caffe/layers/power_layer.hpp" #include "caffe/layers/split_layer.hpp" namespace caffe { /** * @brief Extract pairwise averages of neighbouring pixels in a single channel. * * TODO(dox): thorough documentation for Forward, Backward, and proto params. */ template <typename Dtype> class PairwiseAvgLayer : public Layer<Dtype> { public: explicit PairwiseAvgLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "PairwiseAvg"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); int num; int channels; int height; int width; }; } // namespace caffe #endif // CAFFE_PAIRWISEAVG_LAYER_HPP_
[ "sarojraizan@gmail.com" ]
sarojraizan@gmail.com
29d62fe55f5b0e414eb78ab14ae7d4ddce00d448
00dc96bd9cb12b018897929ffd7c7b1484c0b8f9
/samples/10/10-destructor4.cpp
54157637c68e8cfb41b3a90f4a37ba1b0de4235e
[]
no_license
taroyabuki/cppbook2
b6521002933ef49f0bc29f8c26395894ce4ecc04
571fdddb320c7b0547aac592ffc30766b26d8193
refs/heads/master
2022-12-22T02:48:34.801844
2022-12-15T14:32:40
2022-12-15T14:32:40
81,698,520
12
3
null
2019-06-04T03:26:39
2017-02-12T02:46:16
Shell
UTF-8
C++
false
false
606
cpp
#include <iostream> #include <string> #include <memory> using namespace std; struct A { ~A() { cout << "Aオブジェクトは解体された\n"; } }; struct Person { string name; shared_ptr<A> pA; //Aオブジェクトをフリーストアに構築するコンストラクタ Person(const string& newName) : name(newName), pA(new A) {} //Aオブジェクトを解体するデストラクタ ~Person() { //delete pA;//不要 cout << name << "は解体された\n"; } }; int main() { Person a1("Taro"); auto pA2 = make_shared<Person>("Jiro"); //delete pA2;//不要 }
[ "taro.yabuki@it-chiba.ac.jp" ]
taro.yabuki@it-chiba.ac.jp
625e669eb8cdd441c682630ecc24444ce9ffcf8f
8ba20f5826a76d274ee44cfc42017c264f943d05
/McSim/PTS.h
8684247ad2c59125a17adba46466b4276a54cb6c
[]
no_license
lidonggit/McSimA-_NVM
a1ddbb85ce0e556f9c843ffc6e88b748af02ce3f
5d8d7976819a983a03410fbb6feeb8106128f1d9
refs/heads/master
2021-01-01T16:19:11.372070
2013-09-24T15:44:16
2013-09-24T15:44:16
12,116,819
3
0
null
null
null
null
UTF-8
C++
false
false
5,793
h
/* * Copyright (c) 2010 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Jung Ho Ahn */ #ifndef __PTS_H__ #define __PTS_H__ #include <list> #include <map> #include <queue> #include <stack> #include <vector> #include <string> #include <stdlib.h> #include <stdint.h> typedef uint8_t UINT8; //LINUX HOSTS typedef uint16_t UINT16; typedef uint32_t UINT32; typedef uint64_t UINT64; typedef int8_t INT8; typedef int16_t INT16; typedef int32_t INT32; typedef int64_t INT64; #if defined(TARGET_IA32) typedef UINT32 ADDRINT; typedef INT32 ADDRDELTA; #elif defined(TARGET_IPF) || defined(TARGET_IA32E) typedef UINT64 ADDRINT; typedef INT64 ADDRDELTA; #else #error "xxx" #endif #include <assert.h> #if defined(NDEBUG) #define ASSERTX(a) #else #define ASSERTX(a) if (!a) { std::cout << __FILE__ << ", line: " << __LINE__ << std::endl; assert(a); } #endif // please refer to 'xed-category-enu.h'. //const uint32_t XED_CATEGORY_X87_ALU = 36; //const uint32_t XED_CATEGORY_CALL = 5; const uint32_t instr_batch_size = 32; enum pts_msg_type { pts_constructor, pts_destructor, pts_resume_simulation, pts_add_instruction, pts_set_stack_n_size, pts_set_active, pts_get_num_hthreads, pts_get_param_uint64, pts_get_param_bool, pts_get_curr_time, pts_invalid, #ifdef MALLOC_INTERCEPT pts_add_heap_mem, pts_free_heap_mem, pts_update_heap_mem_for_hpl, #endif }; struct PTSInstr { uint32_t hthreadid_; uint64_t curr_time_; uint64_t waddr; UINT32 wlen; uint64_t raddr; uint64_t raddr2; UINT32 rlen; uint64_t ip; uint32_t category; bool isbranch; bool isbranchtaken; bool islock; bool isunlock; bool isbarrier; uint32_t rr0; uint32_t rr1; uint32_t rr2; uint32_t rr3; uint32_t rw0; uint32_t rw1; uint32_t rw2; uint32_t rw3; }; typedef union { PTSInstr instr[instr_batch_size]; char str[1024]; } instr_n_str; struct PTSMessage { pts_msg_type type; bool bool_val; uint32_t uint32_t_val; uint64_t uint64_t_val; ADDRINT stack_val; //ADDRINT stacksize_val; ADDRINT memsize_val; instr_n_str val; }; using namespace std; namespace PinPthread { class McSim; #ifdef MALLOC_INTERCEPT #define STRING_NAME_LENGTH 1024 struct HeapMemRec { uint64_t start_address; uint64_t end_address; bool avail_flag; //whether the heap mem is freed. char rtn_name[STRING_NAME_LENGTH]; //where the heap mem is allocated char lib_name[STRING_NAME_LENGTH]; //where the heap mem is allocated }; #endif class PthreadTimingSimulator { public: PthreadTimingSimulator(const string & mdfile); PthreadTimingSimulator(int port_num) { } ~PthreadTimingSimulator(); pair<uint32_t, uint64_t> resume_simulation(bool must_switch); bool add_instruction( uint32_t hthreadid_, uint64_t curr_time_, uint64_t waddr, UINT32 wlen, uint64_t raddr, uint64_t raddr2, UINT32 rlen, uint64_t ip, uint32_t category, bool isbranch, bool isbranchtaken, bool islock, bool isunlock, bool isbarrier, uint32_t rr0, uint32_t rr1, uint32_t rr2, uint32_t rr3, uint32_t rw0, uint32_t rw1, uint32_t rw2, uint32_t rw3 ); // return value -- whether we have to resume simulation void set_stack_n_size(int32_t pth_id, ADDRINT stack, ADDRINT stacksize); void set_active(int32_t pth_id, bool is_active); uint32_t get_num_hthreads() const; uint64_t get_param_uint64(const string & idx_, uint64_t def_value) const; bool get_param_bool(const string & idx_, bool def_value) const; string get_param_str(const string & idx_) const; uint64_t get_curr_time() const; #ifdef MALLOC_INTERCEPT void add_heap_mem(uint64_t addr, int heap_size); void free_heap_mem(uint64_t addr); //HeapMemRec * search_heap_mem(uint64_t addr); #ifdef APP_HPL void update_heap_mem_for_hpl(uint64_t addr, int size); #endif #endif std::map<string, string> params; std::vector<string> trace_files; McSim * mcsim; }; } #endif //__PTS_H__
[ "dol@dmz02.ftpn.ornl.gov" ]
dol@dmz02.ftpn.ornl.gov
d560b56656985318457bfb369fbf816762d601da
4fd9f29b20e26b7cc80d748abd8f1dcd94fbbfdd
/Software rasterizer/Lukas Hermanns/SoftPixelEngine/sources/RenderSystem/Direct3D9/spDirect3D9Shader.hpp
c53d0eece7220b8dc48913f513385505b2fe32cd
[ "Zlib" ]
permissive
Kochise/3dglrtvr
53208109ca50e53d8380bed0ebdcb7682a2e9438
dcc2bf847ca26cd6bbd5644190096c27432b542a
refs/heads/master
2021-12-28T03:24:51.116120
2021-08-02T18:55:21
2021-08-02T18:55:21
77,951,439
8
5
null
null
null
null
UTF-8
C++
false
false
3,750
hpp
/* * Direct3D9 shader header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_DIRECT3D9_SHADER_H__ #define __SP_DIRECT3D9_SHADER_H__ #include "Base/spStandard.hpp" #if defined(SP_COMPILE_WITH_DIRECT3D9) #include "RenderSystem/Direct3D9/spDirect3D9ShaderTable.hpp" #if defined(SP_PLATFORM_WINDOWS) # include <d3d9.h> # include <d3dx9shader.h> #endif namespace sp { namespace video { class SP_EXPORT Direct3D9Shader : public Shader { public: Direct3D9Shader(ShaderTable* Table, const EShaderTypes Type, const EShaderVersions Version); ~Direct3D9Shader(); /* Shader compilation */ bool compile(const std::vector<io::stringc> &ShaderBuffer, const io::stringc &EntryPoint = ""); /* Set the constants (by number) */ bool setConstant(s32 Number, const EConstantTypes Type, const f32 Value); bool setConstant(s32 Number, const EConstantTypes Type, const f32* Buffer, s32 Count); bool setConstant(s32 Number, const EConstantTypes Type, const dim::vector3df &Position); bool setConstant(s32 Number, const EConstantTypes Type, const video::color &Color); bool setConstant(s32 Number, const EConstantTypes Type, const dim::matrix4f &Matrix); /* Set the constants (by name) */ bool setConstant(const io::stringc &Name, const f32 Value); bool setConstant(const io::stringc &Name, const f32* Buffer, s32 Count); bool setConstant(const io::stringc &Name, const s32 Value); bool setConstant(const io::stringc &Name, const s32* Buffer, s32 Count); bool setConstant(const io::stringc &Name, const dim::vector3df &Position); bool setConstant(const io::stringc &Name, const dim::vector4df &Position); bool setConstant(const io::stringc &Name, const video::color &Color); bool setConstant(const io::stringc &Name, const dim::matrix4f &Matrix); /* Set the constants for assembly shaders */ bool setConstant(const f32* Buffer, s32 StartRegister, s32 ConstAmount); private: friend class Direct3D9ShaderTable; /* Functions */ bool compileHLSL(const c8* ProgramBuffer, const c8* EntryPoint, const c8* TargetName); bool compileProgram(const c8* ProgramBuffer); void createProgramString(const std::vector<io::stringc> &ShaderBuffer, c8* &ProgramBuffer); HRESULT d3dAssembleShader( LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs ); HRESULT d3dCompileShader( LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable ); bool setupShaderConstants(); /* Members */ IDirect3DDevice9* pD3D9Device_; IDirect3DVertexShader9* VertexShaderObject_; IDirect3DPixelShader9* PixelShaderObject_; ID3DXConstantTable* ConstantTable_; }; } // /namespace scene } // /namespace sp #endif #endif // ================================================================================
[ "noreply@github.com" ]
noreply@github.com