blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
992d4686707951168a4c1d01a36f9f9e0f287285
5e1ae0c5e8f26339759b43e6627771edcf7d16ce
/external/chromium_org/content/renderer/history_serialization.cc
cf85496de3c7441a0d420da02bb21cd117d12925
[ "BSD-3-Clause" ]
permissive
guoyanjun0313/cb40_6735
d303eec21051633ee52230704a1dfd0f3c579cc0
fc5aa800555da17f2c2c3f75f95f772ff67b40c0
refs/heads/master
2022-12-28T16:44:38.678552
2018-04-18T03:00:31
2018-04-18T03:00:31
null
0
0
null
null
null
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 "content/renderer/history_serialization.h" #include "content/common/page_state_serialization.h" #include "content/public/common/page_state.h" #include "content/renderer/history_entry.h" #include "third_party/WebKit/public/platform/WebFloatPoint.h" #include "third_party/WebKit/public/platform/WebHTTPBody.h" #include "third_party/WebKit/public/platform/WebPoint.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebSerializedScriptValue.h" using blink::WebHTTPBody; using blink::WebHistoryItem; using blink::WebSerializedScriptValue; using blink::WebString; using blink::WebVector; namespace content { namespace { void ToNullableString16Vector(const WebVector<WebString>& input, std::vector<base::NullableString16>* output) { output->reserve(input.size()); for (size_t i = 0; i < input.size(); ++i) output->push_back(input[i]); } void ToExplodedHttpBodyElement(const WebHTTPBody::Element& input, ExplodedHttpBodyElement* output) { switch (input.type) { case WebHTTPBody::Element::TypeData: output->data.assign(input.data.data(), input.data.size()); break; case WebHTTPBody::Element::TypeFile: output->file_path = input.filePath; output->file_start = input.fileStart; output->file_length = input.fileLength; output->file_modification_time = input.modificationTime; break; case WebHTTPBody::Element::TypeFileSystemURL: output->filesystem_url = input.fileSystemURL; output->file_start = input.fileStart; output->file_length = input.fileLength; output->file_modification_time = input.modificationTime; break; case WebHTTPBody::Element::TypeBlob: output->blob_uuid = input.blobUUID.utf8(); break; } } void AppendHTTPBodyElement(const ExplodedHttpBodyElement& element, WebHTTPBody* http_body) { switch (element.type) { case WebHTTPBody::Element::TypeData: http_body->appendData(element.data); break; case WebHTTPBody::Element::TypeFile: http_body->appendFileRange( element.file_path, element.file_start, element.file_length, element.file_modification_time); break; case WebHTTPBody::Element::TypeFileSystemURL: http_body->appendFileSystemURLRange( element.filesystem_url, element.file_start, element.file_length, element.file_modification_time); break; case WebHTTPBody::Element::TypeBlob: http_body->appendBlob(WebString::fromUTF8(element.blob_uuid)); break; } } void GenerateFrameStateFromItem(const WebHistoryItem& item, ExplodedFrameState* state) { state->url_string = item.urlString(); state->referrer = item.referrer(); state->referrer_policy = item.referrerPolicy(); state->target = item.target(); if (!item.stateObject().isNull()) state->state_object = item.stateObject().toString(); state->pinch_viewport_scroll_offset = item.pinchViewportScrollOffset(); state->scroll_offset = item.scrollOffset(); state->item_sequence_number = item.itemSequenceNumber(); state->document_sequence_number = item.documentSequenceNumber(); state->frame_sequence_number = item.frameSequenceNumber(); state->page_scale_factor = item.pageScaleFactor(); /// M: Support text-reflow in chromium state->text_wrap_width = item.textWrapWidth(); ToNullableString16Vector(item.documentState(), &state->document_state); state->http_body.http_content_type = item.httpContentType(); const WebHTTPBody& http_body = item.httpBody(); state->http_body.is_null = http_body.isNull(); if (!state->http_body.is_null) { state->http_body.identifier = http_body.identifier(); state->http_body.elements.resize(http_body.elementCount()); for (size_t i = 0; i < http_body.elementCount(); ++i) { WebHTTPBody::Element element; http_body.elementAt(i, element); ToExplodedHttpBodyElement(element, &state->http_body.elements[i]); } state->http_body.contains_passwords = http_body.containsPasswordData(); } } void RecursivelyGenerateFrameState(HistoryEntry::HistoryNode* node, ExplodedFrameState* state) { GenerateFrameStateFromItem(node->item(), state); std::vector<HistoryEntry::HistoryNode*>& children = node->children(); state->children.resize(children.size()); for (size_t i = 0; i < children.size(); ++i) RecursivelyGenerateFrameState(children[i], &state->children[i]); } void RecursivelyGenerateHistoryItem(const ExplodedFrameState& state, HistoryEntry::HistoryNode* node) { WebHistoryItem item; item.initialize(); item.setURLString(state.url_string); item.setReferrer(state.referrer, state.referrer_policy); item.setTarget(state.target); if (!state.state_object.is_null()) { item.setStateObject( WebSerializedScriptValue::fromString(state.state_object)); } item.setDocumentState(state.document_state); item.setPinchViewportScrollOffset(state.pinch_viewport_scroll_offset); item.setScrollOffset(state.scroll_offset); item.setPageScaleFactor(state.page_scale_factor); /// M: Support text-reflow in chromium item.setTextWrapWidth(state.text_wrap_width); // These values are generated at WebHistoryItem construction time, and we // only want to override those new values with old values if the old values // are defined. A value of 0 means undefined in this context. if (state.item_sequence_number) item.setItemSequenceNumber(state.item_sequence_number); if (state.document_sequence_number) item.setDocumentSequenceNumber(state.document_sequence_number); if (state.frame_sequence_number) item.setFrameSequenceNumber(state.frame_sequence_number); item.setHTTPContentType(state.http_body.http_content_type); if (!state.http_body.is_null) { WebHTTPBody http_body; http_body.initialize(); http_body.setIdentifier(state.http_body.identifier); for (size_t i = 0; i < state.http_body.elements.size(); ++i) AppendHTTPBodyElement(state.http_body.elements[i], &http_body); item.setHTTPBody(http_body); } node->set_item(item); for (size_t i = 0; i < state.children.size(); ++i) RecursivelyGenerateHistoryItem(state.children[i], node->AddChild()); } } // namespace PageState HistoryEntryToPageState(HistoryEntry* entry) { ExplodedPageState state; ToNullableString16Vector(entry->root().getReferencedFilePaths(), &state.referenced_files); RecursivelyGenerateFrameState(entry->root_history_node(), &state.top); std::string encoded_data; if (!EncodePageState(state, &encoded_data)) return PageState(); return PageState::CreateFromEncodedData(encoded_data); } PageState SingleHistoryItemToPageState(const WebHistoryItem& item) { ExplodedPageState state; ToNullableString16Vector(item.getReferencedFilePaths(), &state.referenced_files); GenerateFrameStateFromItem(item, &state.top); std::string encoded_data; if (!EncodePageState(state, &encoded_data)) return PageState(); return PageState::CreateFromEncodedData(encoded_data); } scoped_ptr<HistoryEntry> PageStateToHistoryEntry(const PageState& page_state) { ExplodedPageState state; if (!DecodePageState(page_state.ToEncodedData(), &state)) return scoped_ptr<HistoryEntry>(); scoped_ptr<HistoryEntry> entry(new HistoryEntry()); RecursivelyGenerateHistoryItem(state.top, entry->root_history_node()); return entry.Pass(); } } // namespace content
[ "liuyiping@t-road.cn" ]
liuyiping@t-road.cn
6b0abafe70af21017e2521960b1ef9a285061405
5af80813298c3a2da7f7e3e28adb1b9bcc433878
/gameplay/src/Curve.h
05e9a246ee572af18300197eefa4dcf24b9e12b1
[]
no_license
damonyan1985/SkCanvas
c250ad47bdd0fa072ca859c6b1242dede2045f95
731ae8abb540382da2e156e8d93373c4563017ea
refs/heads/master
2021-09-10T20:03:51.927207
2018-03-23T02:02:10
2018-03-23T02:02:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,129
h
#ifndef CURVE_H_ #define CURVE_H_ #include "Ref.h" namespace gameplay { /** * Defines an n-dimensional curve. */ class Curve : public Ref { friend class AnimationTarget; friend class Animation; friend class AnimationClip; friend class AnimationController; friend class MeshSkin; public: /** * Types of interpolation. * * Defines how the points in the curve are connected. * * Note: InterpolationType::BEZIER requires control points and InterpolationType::HERMITE requires tangents. */ enum InterpolationType { /** * Bezier Interpolation. * * Requires that two control points are set for each segment. */ BEZIER, /** * B-Spline Interpolation. * * Uses the points as control points, and the curve is guaranteed to only pass through the * first and last point. */ BSPLINE, /** * Flat Interpolation. * * A form of Hermite interpolation that generates flat tangents for you. The tangents have a value equal to 0. */ FLAT, /** * Hermite Interpolation. * * Requires that two tangents for each segment. */ HERMITE, /** * Linear Interpolation. */ LINEAR, /** * Smooth Interpolation. * * A form of Hermite interpolation that generates tangents for each segment based on the points prior to and after the segment. */ SMOOTH, /** * Discrete Interpolation. */ STEP, /** * Quadratic-In Interpolation. */ QUADRATIC_IN, /** * Quadratic-Out Interpolation. */ QUADRATIC_OUT, /** * Quadratic-In-Out Interpolation. */ QUADRATIC_IN_OUT, /** * Quadratic-Out-In Interpolation. */ QUADRATIC_OUT_IN, /** * Cubic-In Interpolation. */ CUBIC_IN, /** * Cubic-Out Interpolation. */ CUBIC_OUT, /** * Cubic-In-Out Interpolation. */ CUBIC_IN_OUT, /** * Cubic-Out-In Interpolation. */ CUBIC_OUT_IN, /** * Quartic-In Interpolation. */ QUARTIC_IN, /** * Quartic-Out Interpolation. */ QUARTIC_OUT, /** * Quartic-In-Out Interpolation. */ QUARTIC_IN_OUT, /** * Quartic-Out-In Interpolation. */ QUARTIC_OUT_IN, /** * Quintic-In Interpolation. */ QUINTIC_IN, /** * Quintic-Out Interpolation. */ QUINTIC_OUT, /** * Quintic-In-Out Interpolation. */ QUINTIC_IN_OUT, /** * Quintic-Out-In Interpolation. */ QUINTIC_OUT_IN, /** * Sine-In Interpolation. */ SINE_IN, /** * Sine-Out Interpolation. */ SINE_OUT, /** * Sine-In-Out Interpolation. */ SINE_IN_OUT, /** * Sine-Out-In Interpolation. */ SINE_OUT_IN, /** * Exponential-In Interpolation. */ EXPONENTIAL_IN, /** * Exponential-Out Interpolation. */ EXPONENTIAL_OUT, /** * Exponential-In-Out Interpolation. */ EXPONENTIAL_IN_OUT, /** * Exponential-Out-In Interpolation. */ EXPONENTIAL_OUT_IN, /** * Circular-In Interpolation. */ CIRCULAR_IN, /** * Circular-Out Interpolation. */ CIRCULAR_OUT, /** * Circular-In-Out Interpolation. */ CIRCULAR_IN_OUT, /** * Circular-Out-In Interpolation. */ CIRCULAR_OUT_IN, /** * Elastic-In Interpolation. */ ELASTIC_IN, /** * Elastic-Out Interpolation. */ ELASTIC_OUT, /** * Elastic-In-Out Interpolation. */ ELASTIC_IN_OUT, /** * Elastic-Out-In Interpolation. */ ELASTIC_OUT_IN, /** * Overshoot-In Interpolation. */ OVERSHOOT_IN, /** * Overshoot-Out Interpolation. */ OVERSHOOT_OUT, /** * Overshoot-In-Out Interpolation. */ OVERSHOOT_IN_OUT, /** * Overshoot-Out-In Interpolation. */ OVERSHOOT_OUT_IN, /** * Bounce-In Interpolation. */ BOUNCE_IN, /** * Bounce-Out Interpolation. */ BOUNCE_OUT, /** * Bounce-In-Out Interpolation. */ BOUNCE_IN_OUT, /** * Bounce-Out-In Interpolation. */ BOUNCE_OUT_IN }; /** * Creates a new curve. * * @param pointCount The number of points in the curve. * @param componentCount The number of float component values per key value. * @script{create} */ static Curve* create(unsigned int pointCount, unsigned int componentCount); /** * Gets the number of points in the curve. * * @return The number of points in the curve. */ unsigned int getPointCount() const; /** * Gets the number of float component values per points. * * @return The number of float component values per point. */ unsigned int getComponentCount() const; /** * Returns the start time for the curve. * * @return The curve's start time. */ float getStartTime() const; /** * Returns the end time for the curve. * * @return The curve's end time. */ float getEndTime() const; /** * Sets the given point values on the curve. * * @param index The index of the point. * @param time The time for the key. * @param value The point to add. * @param type The curve interpolation type. */ void setPoint(unsigned int index, float time, float* value, InterpolationType type); /** * Sets the given point on the curve for the specified index and the specified parameters. * * @param index The index of the point. * @param time The time of the point within the curve. * @param value The value of the point to copy the data from. * @param type The curve interpolation type. * @param inValue The tangent approaching the point. * @param outValue The tangent leaving the point. */ void setPoint(unsigned int index, float time, float* value, InterpolationType type, float* inValue, float* outValue); /** * Sets the tangents for a point on the curve specified by the index. * * @param index The index of the point. * @param type The interpolation type. * @param type The curve interpolation type. * @param inValue The tangent approaching the point. * @param outValue The tangent leaving the point. */ void setTangent(unsigned int index, InterpolationType type, float* inValue, float* outValue); /** * Gets the time at a specified point. * * @param index The index of the point. * * @return The time for a key point. */ float getPointTime(unsigned int index) const; /** * Gets the interpolation type at the specified point * * @param index The index of the point. * * @return The interpolation type at the specified index. */ InterpolationType getPointInterpolation(unsigned int index) const; /** * Gets the values and in/out tangent value at a spedified point. * * @param index The index of the point. * @param value The value at the specified index. Ignored if NULL. * @param inValue The tangent inValue at the specified index. Ignored if NULL. * @param outValue The tangent outValue at the specified index. Ignored if NULL. */ void getPointValues(unsigned int index, float* value, float* inValue, float* outValue) const; /** * Evaluates the curve at the given position value. * * Time should generally be specified as a value between 0.0 - 1.0, inclusive. * A value outside this range can also be specified to perform an interpolation * between the two end points of the curve. This can be useful for smoothly * interpolating a repeat of the curve. * * @param time The position to evaluate the curve at. * @param dst The evaluated value of the curve at the given time. */ void evaluate(float time, float* dst) const; /** * Evaluates the curve at the given position value (between 0.0 and 1.0 inclusive) * within the specified subregion of the curve. * * This method is useful for evaluating sub sections of the curve. A common use for * this is when evaluating individual animation clips that are positioned within a * larger animation curve. This method also allows looping to occur between the * end points of curve sub regions, with optional blending/interpolation between * the end points (using the loopBlendTime parameter). * * Time should generally be specified as a value between 0.0 - 1.0, inclusive. * A value outside this range can also be specified to perform an interpolation * between the two end points of the curve. This can be useful for smoothly * interpolating a repeat of the curve. * * @param time The position within the subregion of the curve to evaluate the curve at. * A time of zero represents the start of the subregion, with a time of one * representing the end of the subregion. * @param startTime Start time for the subregion (between 0.0 - 1.0). * @param endTime End time for the subregion (between 0.0 - 1.0). * @param loopBlendTime Time (in milliseconds) to blend between the end points of the curve * for looping purposes when time is outside the range 0-1. A value of zero here * disables curve looping. * @param dst The evaluated value of the curve at the given time. */ void evaluate(float time, float startTime, float endTime, float loopBlendTime, float* dst) const; /** * Linear interpolation function. */ static float lerp(float t, float from, float to); private: /** * Defines a single point within a curve. */ class Point { public: /** The time of the point within the curve. */ float time; /** The value of the point. */ float* value; /** The value of the tangent when approaching this point (from the previous point in the curve). */ float* inValue; /** The value of the tangent when leaving this point (towards the next point in the curve). */ float* outValue; /** The type of interpolation to use between this point and the next point. */ InterpolationType type; /** * Constructor. */ Point(); /** * Destructor. */ ~Point(); /** * Hidden copy assignment operator. */ Point& operator=(const Point&); }; /** * Constructor. */ Curve(); /** * Constructs a new curve and the specified parameters. * * @param pointCount The number of points in the curve. * @param componentCount The number of float component values per key value. */ Curve(unsigned int pointCount, unsigned int componentCount); /** * Constructor. */ Curve(const Curve& copy); /** * Destructor. */ ~Curve(); /** * Hidden copy assignment operator. */ Curve& operator=(const Curve&); /** * Bezier interpolation function. */ void interpolateBezier(float s, Point* from, Point* to, float* dst) const; /** * Bspline interpolation function. */ void interpolateBSpline(float s, Point* c0, Point* c1, Point* c2, Point* c3, float* dst) const; /** * Hermite interpolation function. */ void interpolateHermite(float s, Point* from, Point* to, float* dst) const; /** * Hermite interpolation function. */ void interpolateHermiteFlat(float s, Point* from, Point* to, float* dst) const; /** * Hermite interpolation function. */ void interpolateHermiteSmooth(float s, unsigned int index, Point* from, Point* to, float* dst) const; /** * Linear interpolation function. */ void interpolateLinear(float s, Point* from, Point* to, float* dst) const; /** * Quaternion interpolation function. */ void interpolateQuaternion(float s, float* from, float* to, float* dst) const; /** * Determines the current keyframe to interpolate from based on the specified time. */ int determineIndex(float time, unsigned int min, unsigned int max) const; /** * Sets the offset for the beginning of a Quaternion piece of data within the curve's value span at the specified * index. The next four components of data starting at the given index will be interpolated as a Quaternion. * This function will assert an error if the given index is greater than the component size subtracted by the four components required * to store a quaternion. * * @param index The index of the Quaternion rotation data. */ void setQuaternionOffset(unsigned int index); /** * Gets the InterpolationType value for the given string ID * * @param interpolationId The string representation of the InterpolationType * @return the InterpolationType value; -1 if the string does not represent an InterpolationType. */ static int getInterpolationType(const char* interpolationId); unsigned int _pointCount; // Number of points on the curve. unsigned int _componentCount; // Number of components on the curve. unsigned int _componentSize; // The component size (in bytes). unsigned int* _quaternionOffset; // Offset for the rotation component. Point* _points; // The points on the curve. }; } #endif
[ "hgl868@126.com" ]
hgl868@126.com
ab03962226e64a1f96942896d9ef8e71bce76df4
b8e8c8c95d9a196260d4b08e86b4750bb07a1a10
/ZSJ-Project/Project3/CODETEST/test/Priority-Queue-Test/fib_heap(pass correctness).h
c604cbfa2306011fb4572d6d9b663f009f5ee02c
[]
no_license
Randyzhang98/Weikang-s-Data-House
69d1817757eb33bed5747d518ced0a48a8618104
1e8781c5967ff46084b98c4c9fdcc633cccce76f
refs/heads/master
2020-04-06T09:14:33.993428
2018-12-19T07:57:43
2018-12-19T07:57:43
157,334,186
0
0
null
null
null
null
UTF-8
C++
false
false
7,009
h
#ifndef FIB_HEAP_H #define FIB_HEAP_H #include <algorithm> #include <cmath> #include <list> #include <iostream> #include "priority_queue.h" // OVERVIEW: A specialized version of the 'heap' ADT implemented as a // Fibonacci heap. template<typename TYPE, typename COMP = std::less<TYPE> > class fib_heap: public priority_queue<TYPE, COMP> { public: typedef unsigned size_type; // EFFECTS: Construct an empty heap with an optional comparison functor. // See test_heap.cpp for more details on functor. // MODIFIES: this // RUNTIME: O(1) fib_heap(COMP comp = COMP()); // EFFECTS: Deconstruct the heap with no memory leak. // MODIFIES: this // RUNTIME: O(n) ~fib_heap(); // EFFECTS: Add a new element to the heap. // MODIFIES: this // RUNTIME: O(1) virtual void enqueue(const TYPE &val); // EFFECTS: Remove and return the smallest element from the heap. // REQUIRES: The heap is not empty. // MODIFIES: this // RUNTIME: Amortized O(log(n)) virtual TYPE dequeue_min(); // EFFECTS: Return the smallest element of the heap. // REQUIRES: The heap is not empty. // RUNTIME: O(1) virtual const TYPE &get_min() const; // EFFECTS: Get the number of elements in the heap. // RUNTIME: O(1) virtual size_type size() const; // EFFECTS: Return true if the heap is empty. // RUNTIME: O(1) virtual bool empty() const; private: // Note: compare is a functor object COMP compare; private: // Add any additional member functions or data you require here. // You may want to define a strcut/class to represent nodes in the heap and a // pointer to the min node in the heap. struct node_t { TYPE value; unsigned degree = 0; std::list<node_t*> children; }; typename std::list<node_t*>::iterator min; std::list<node_t*> root; const double phi = 1.618; unsigned n = 0; void destructor(node_t *target); void consolidate(); void Fib_Heap_Link(decltype(min) &target, decltype(min) &source); void print_root() const { //std::cout << "root is : "; for (auto p = root.begin(); p != root.end(); p++) { //std::cout << (*p)->value << "." << (*p)->degree << " ; "; } //std::cout << std::endl; } void print_A(std::vector<typename std::list<node_t*>::iterator> A) { //std::cout << "A is : "; for (int i = 0; i < A.size(); i++) { //std::cout << (*A[i]) -> value << "," << (*A[i])->degree<< " ; "; } //std::cout << std::endl; } }; // Add the definitions of the member functions here. Please refer to // binary_heap.h for the syntax. template<typename TYPE, typename COMP> fib_heap<TYPE, COMP> :: fib_heap(COMP comp) { //std::cout<< "fib_heap()" << std::endl; compare = comp; n = 0; min = root.end(); } template<typename TYPE, typename COMP> fib_heap<TYPE, COMP> :: ~fib_heap() { //std::cout<< "!!!!!!!~~~~()" << std::endl; for (auto p = root.begin(); p != root.end(); p++) { destructor(*p); } } template<typename TYPE, typename COMP> void fib_heap<TYPE, COMP> :: destructor(node_t *target) { //std::cout<< "destructor()" << std::endl; if (target->children.empty()) delete target; else { for (auto p = target->children.begin(); p != target->children.end(); p++) { destructor(*p); } } } template<typename TYPE, typename COMP> void fib_heap<TYPE, COMP> :: enqueue(const TYPE &val) { //std::cout<< "enqueue()" << std::endl; node_t* input = new node_t; input->degree = 0; input->value = val; root.push_front(input); if (min == root.end()) { min = root.begin(); } else if (compare(val, (*min)->value)) min = root.begin(); n++; //std::cout<< "here min's value is " << (*min) -> value << std::endl; //print_root(); } template<typename TYPE, typename COMP> TYPE fib_heap<TYPE, COMP> :: dequeue_min() { //std::cout<< "deque()" << std::endl; TYPE result = (*min)->value; decltype(min) z = min; if (z != root.end()) { n--; for (auto p = (*z)->children.begin(); p != (*z)->children.end(); p++) { root.push_front(*p); } min = root.erase(min); if (n == 0) min = root.end(); else consolidate(); } //std::cout<< "result is " << result << std::endl; return result; } template<typename TYPE, typename COMP> void fib_heap<TYPE, COMP> :: consolidate() { //std::cout<< "consolidate()" << std::endl; unsigned N = n; N = (unsigned) log(N) / log(phi); std::vector<typename std::list<node_t*>::iterator> A(N+2, root.end()); typename std::list<node_t*>::iterator new_temp; for (auto p = root.begin(); p != root.end(); p = new_temp ) { ////std::cout << "170" << std::endl; ////std::cout << "here p's value is " << (*p) -> value << std::endl; ////std::cout << "172" << std::endl; print_root(); ////std::cout<< "here min's value is " << (*min) -> value << std::endl; auto x = p; unsigned d = (*x)->degree; new_temp = std::next(p,1); //std::cout<< "here N is " << N << std::endl; while (A[d] != root.end()) { auto y = A[d]; if (compare( (*y)->value, (*x)->value) ) swap(x,y); Fib_Heap_Link(x,y); //std::cout<< "here d is " << d << std::endl; A[d] = root.end(); d++; if (d >= N+1) break; //std::cout<< "here d is " << d << std::endl; print_root(); //print_A(A); } //std::cout<< "here" << std::endl; A[d] = x; print_root(); //std::cout<< "here" << std::endl; min = root.end(); for (unsigned i = 0; i < N+2; i++) { //std::cout<< "here min loop i = " << i << std::endl; if (A[i] != root.end()) { // //std::cout<< "here min loop i = " << i << std::endl; if (min == root.end()) min = A[i]; else if (compare((*A[i])->value, (*min)->value)) min = A[i]; } } //std::cout<< "here min's value is " << (*min) -> value << std::endl; //p = std::next(p, 1); } } template<typename TYPE, typename COMP> void fib_heap<TYPE, COMP> :: Fib_Heap_Link(decltype(min) &target, decltype(min) &source) { //std::cout<< "Fib+Heap+link()" << std::endl; node_t *t = *source; root.erase(source); (*target)->children.push_front(t); ////std::cout<< "here" << std::endl; ((*target)->degree)++; } template<typename TYPE, typename COMP> const TYPE &fib_heap<TYPE, COMP>::get_min() const { //std::cout<< "get_min()" << std::endl; return (*min)->value; } template<typename TYPE, typename COMP> unsigned int fib_heap<TYPE, COMP>::size() const { //std::cout<< "size()" << std::endl; return this->n; } template<typename TYPE, typename COMP> bool fib_heap<TYPE, COMP>::empty() const { //std::cout<< "empty()" << std::endl; return (this->n == 0); } #endif //FIB_HEAP_H
[ "601981285@qq.com" ]
601981285@qq.com
684a75d016cfce04fb684f65448940837d646b47
7305ca85b0b585d8178f013c2a417deb3ddcd498
/src/backend/spin/camera_device_spin.hpp
04cc58654bbee0d792e6f6b2a66da05dbec5c2c3
[ "Apache-2.0" ]
permissive
rozmar/bias
de00b2b1cfe888487b89480646d5f0516cb7284a
3881370bb46fdc8976c04ec033cdfb240d1a26da
refs/heads/master
2022-11-13T19:08:46.643239
2020-03-13T17:55:44
2020-03-13T17:55:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,392
hpp
#ifdef WITH_SPIN #ifndef BIAS_CAMERA_DEVICE_SPIN_HPP #define BIAS_CAMERA_DEVICE_SPIN_HPP #include <map> #include <string> #include <functional> #include <opencv2/core/core.hpp> #include "utils.hpp" #include "camera_device.hpp" #include "camera_info_spin.hpp" #include "property.hpp" #include "SpinnakerC.h" #include "node_map_spin.hpp" namespace bias { class CameraDevice_spin : public CameraDevice { public: CameraDevice_spin(); explicit CameraDevice_spin(Guid guid); virtual ~CameraDevice_spin(); virtual CameraLib getCameraLib(); virtual void connect(); virtual void disconnect(); virtual void startCapture(); virtual void stopCapture(); virtual cv::Mat grabImage(); virtual void grabImage(cv::Mat &image); virtual bool isColor(); virtual bool isSupported(VideoMode vidMode, FrameRate frmRate); virtual bool isSupported(ImageMode imgMode); virtual unsigned int getNumberOfImageMode(); virtual VideoMode getVideoMode(); virtual FrameRate getFrameRate(); virtual ImageMode getImageMode(); virtual VideoModeList getAllowedVideoModes(); virtual FrameRateList getAllowedFrameRates(VideoMode vidMode); virtual ImageModeList getAllowedImageModes(); virtual PropertyInfo getPropertyInfo(PropertyType propType); virtual Property getProperty(PropertyType propType); virtual void setProperty(Property prop); //virtual void setFormat7ImageMode(ImageMode imgMode); // TO DO // virtual Format7Settings getFormat7Settings(); virtual Format7Info getFormat7Info(ImageMode imgMode); virtual bool validateFormat7Settings(Format7Settings settings); virtual void setFormat7Configuration(Format7Settings settings, float percentSpeed); virtual PixelFormatList getListOfSupportedPixelFormats(ImageMode imgMode); virtual void setTriggerInternal(); virtual void setTriggerExternal(); virtual TriggerType getTriggerType(); virtual std::string getVendorName(); virtual std::string getModelName(); virtual TimeStamp getImageTimeStamp(); virtual std::string toString(); virtual void printGuid(); virtual void printInfo(); void develExpProps(); // Constants // -------------------------------------------------------- // Artificial shutter limits to make GUI more usable. static constexpr double MinAllowedShutterUs = 100.0; static constexpr double MaxAllowedShutterUs = 200000.0; // Number of times auto mode is set to "once". Seems to need to be called // more than once in order to reach a stable value. static constexpr int AutoOnePushSetCount = 10; private: spinSystem hSystem_ = nullptr; spinCamera hCamera_ = nullptr; spinNodeMapHandle hNodeMapCamera_ = nullptr; spinNodeMapHandle hNodeMapTLDevice_ = nullptr; NodeMapCamera_spin nodeMapCamera_; NodeMapTLDevice_spin nodeMapTLDevice_; CameraInfo_spin cameraInfo_; TimeStamp timeStamp_ = {0,0}; int64_t timeStamp_ns_ = 0; bool imageOK_ = false; spinImage hSpinImage_ = nullptr; TriggerType triggerType_ = TRIGGER_TYPE_UNSPECIFIED; bool grabImageCommon(std::string &errMsg); bool releaseSpinImage(spinImage &hImage); bool destroySpinImage(spinImage &hImage); void setupTimeStamping(); void updateTimeStamp(); // Get Property Info methods static std::map<PropertyType, std::function<PropertyInfo(CameraDevice_spin*)>> getPropertyInfoDispatchMap_; PropertyInfo getPropertyInfoBrightness(); PropertyInfo getPropertyInfoGamma(); PropertyInfo getPropertyInfoShutter(); PropertyInfo getPropertyInfoGain(); PropertyInfo getPropertyInfoTriggerDelay(); PropertyInfo getPropertyInfoFrameRate(); PropertyInfo getPropertyInfoTemperature(); PropertyInfo getPropertyInfoTriggerMode(); // Get property methods static std::map<PropertyType, std::function<Property(CameraDevice_spin*)>> getPropertyDispatchMap_; Property getPropertyBrightness(); Property getPropertyGamma(); Property getPropertyShutter(); Property getPropertyGain(); Property getPropertyTriggerDelay(); Property getPropertyFrameRate(); Property getPropertyTemperature(); Property getPropertyTriggerMode(); // Set Property methods bool isPropertySettable(PropertyType propType, std::string &msg); static std::map<PropertyType, std::function<void(CameraDevice_spin*,Property)>> setPropertyDispatchMap_; void setPropertyBrightness(Property prop); void setPropertyGamma(Property prop); void setPropertyShutter(Property prop); void setPropertyGain(Property prop); void setPropertyTriggerDelay(Property prop); void setPropertyFrameRate(Property prop); void setPropertyTemperature(Property prop); void setPropertyTriggerMode(Property prop); PixelFormat getPixelFormat(); bool isSupportedPixelFormat(PixelFormat pixelFormat, ImageMode imgMode); // spin get methods // --------------- std::vector<spinPixelFormatEnums> getSupportedPixelFormats_spin(); spinPixelFormatEnums getPixelFormat_spin(); }; typedef std::shared_ptr<CameraDevice_spin> CameraDevicePtr_spin; } #endif // #ifndef BIAS_CAMERA_DEVICE_SPIN_HPP #endif // #ifdef WITH_SPIN
[ "will@iorodeo.com" ]
will@iorodeo.com
549af41db9a65d7fe1acf52e5054a2bf629b70d4
21da454a8f032d6ad63ca9460656c1e04440310e
/test/utest/StringTest.cpp
85fb41c510728e6ec167722582db6d8c20583906
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
3,030
cpp
#include "StringTest.h" #include <wcpp/lang/wscUUID.h> #include <wcpp/lang/wscSystem.h> #include <wcpp/lang/wscLong.h> #include <wcpp/lang/wscThrowable.h> StringTest::StringTest(void) { } StringTest::~StringTest(void) { } ws_result StringTest::doTest(void) { trace( "========================================\n" ); trace( "case:StringTest - begin\n" ); test_wsString(); test_wsLong_ToString(); test_wscUUID_ToString(); trace( "case:StringTest - end\n" ); trace( "========================================\n" ); return ws_result( WS_RLT_SUCCESS ); } void StringTest::test_wscUUID_ToString(void) { trace( " -------------------------------- \n" ); trace( "func:test_wscUUID_ToString - begin\n" ); { ws_ptr<wsiString> str1, str2; wscUUID::ToString( wsiObject::sIID.uuid, &str1 ); ws_uuid uuid; wscUUID::ParseUUID( str1, uuid ); wscUUID::ToString( uuid, &str2 ); trace( "wsiObject::sIID : " ); trace( "{3F45A92B-A7D5-4d93-946C-373E56A8C17B}" ); trace( "\n" ); trace( "wsiObject::sIID ToString : " ); trace( str1->GetBuffer() ); trace( "\n" ); trace( "wsiObject::sIID ParseUUID : " ); trace( str2->GetBuffer() ); trace( "\n" ); } ws_ptr<wsiString> str1,str2; wscUUID::ToString( wsiSystem::sIID.uuid, &str1 ); ws_uuid uuid; wscUUID::ParseUUID( str2, uuid ); wscUUID::ToString( uuid, &str2 ); trace( "wsiSystem::sIID : " ); trace( "{FAC4AD98-7554-4561-AF17-9A5ADB66AD30}" ); trace( "\n" ); trace( "wsiSystem::sIID ToString : " ); trace( str1->GetBuffer() ); trace( "\n" ); trace( "wsiSystem::sIID ParseUUID : " ); trace( str2->GetBuffer() ); trace( "\n" ); trace( "func:test_wscUUID_ToString - end\n" ); trace( " -------------------------------- \n" ); } void StringTest::test_wsLong_ToString(void) { trace( " -------------------------------- \n" ); trace( "func:test_wsLong_ToString - begin\n" ); const int len = 8; ws_long values[len] = { -1, 0, 1, 2147483647, -2147483647, 2147483647, // -2147483648, }; ws_ptr<wsiString> str; trace( "ws_long [wsString]\n" ); for (int i=0; i<len; i++) { wscLong::ToString( values[i], &str ); trace( values[i] ); trace( " [" ); trace( str->GetBuffer() ); trace( "]\n" ); } trace( "func:test_wsLong_ToString - end\n" ); trace( " -------------------------------- \n" ); } void StringTest::test_wsString(void) { trace( " -------------------------------- \n" ); trace( "func:test_wsString - begin\n" ); ws_str str1; ws_str str2( static_cast<wsiString*>(WS_NULL) ); ws_str str3( "" ); ws_str str4( "hello" ); str1 = str4; str2 = str4; str3 = str4; str4 = ""; str3 = str4; str4.SetString( 0, 0 ); str3 = "abcdefg hijk lmn opq rst uvw xyz"; str4 = "hp"; trace( "func:test_wsString - end\n" ); trace( " -------------------------------- \n" ); }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8
fba0b2fab53e2a4e75d1cfd1cfbe49c3aa1c53b5
637efca09ccbce88aab2ec75dcaff0a331d2fd5d
/Source.cpp
92faf17e0309c133ba2543981e84ea614e380dba
[]
no_license
shar-rahman/trieProject
24812f15f2838929261c8045c0fbc5f4ba3dbdbb
b8ae31be48d5e459ff15dd9c276e8c69934478b4
refs/heads/master
2020-04-26T10:48:51.167168
2019-03-20T00:05:36
2019-03-20T00:05:36
173,497,162
0
0
null
null
null
null
UTF-8
C++
false
false
4,401
cpp
#include "Trie.h" #include "stdlib.h" #include <iostream> #include <string> #include <fstream> #include <windows.h> using namespace std; void mainMenuPrint(); void searchMethod(Trie* trie); void insertMethod(Trie* trie); void addDefinition(Trie* trie); void printMethod(Trie* trie); void print(TrieNode* root, char word[], int level); ifstream inputFile; ofstream outputFile; int main() { string file; string toInsert; string search; int choice; int count = 0; Trie* dictionary = new Trie(); cout << "Enter the name of the text file: " << endl; cin >> file; inputFile.open(file + ".txt"); while (getline(inputFile, toInsert, '\n') && !inputFile.eof()) { cout << "Entered: " << toInsert << endl; count++; dictionary->insert(toInsert); } cout << "Read in: " << count << " words." << endl; cout << "\n" << endl; system("pause"); while (1) { mainMenuPrint(); cin >> choice; cin.clear(); if (choice == 1) searchMethod(dictionary); if (choice == 2) insertMethod(dictionary); if (choice == 3) addDefinition(dictionary); if (choice == 4) break; if (choice == 5) printMethod(dictionary); else { cout << "Try again.\n"; } } cout << "Exiting...\n\n\n\n"; system("pause"); return 0; } void addDefinition(Trie* trie) { cout << flush; system("CLS"); int choice; string definition, wordType, word; string listOfTypes[4] = { "verb", "noun", "adj", "adverb" }; cout << "~\tBlank entry to exit." << endl; cin.ignore(); while (1) { cout << "~\tEnter word to add definition & word type for > "; getline(cin, word, '\n'); if (word == "") return; else if (trie->searchWord2(word)) { cout << "~\tEnter definition > "; getline(cin, definition, '\n'); cout << "\n\n~\t Word Types" << endl; cout << "~\t==============" << endl; cout << "~\t1. Verb\n~\t2. Noun\n~\t3. Adjective\n~\t4. Adverb\n"; cout << "\nEnter choice > "; cin >> choice; if (choice == 1) trie->setDef(word, definition, listOfTypes[0]); if (choice == 2) trie->setDef(word, definition, listOfTypes[1]); if (choice == 3) trie->setDef(word, definition, listOfTypes[2]); if (choice == 4) trie->setDef(word, definition, listOfTypes[3]); cin.ignore(); } else cout << "~\tWord not found.\n\n"; } } void searchMethod(Trie* trie) { cout << flush; system("CLS"); string search; cout << "~\tSearch method selected." << endl; cin.ignore(); while (1) { cout << "~\tEnter Word > "; getline(cin, search, '\n'); if (search == "\n" || search == " " || search == "") { cout << "asdf"; break; } else { if (trie->searchWord(search)) { cout << "\n\t~~~~~~~~~~~~~~~~~" << endl; } else cout << "~\tWord not found!" << endl << endl; } } return; } void insertMethod(Trie* trie) { cout << flush; system("CLS"); string toInsert; cout << "*\tInsert Selected" << endl; cout << "*\t=================" << endl; cout << "*\tEnter a word to insert.\n*\tPress enter with a blank entry to exit.\n" << endl; cin.ignore(); while (1) { cin.clear(); cout << " Word Entry > "; getline(cin, toInsert, '\n'); if (toInsert == "") break; else { cout << "*\t "; for (size_t i = 0; i < toInsert.length(); i++, Sleep(25)) cout << "^"; trie->insert(toInsert); cout << "\n*\tWord inserted.\n" << endl; } } return; } void printMethod(Trie* trie) { cout << flush; system("CLS"); cout << "\nHere is the trie printed in order of input: \n" << endl; char arr[1000]; print(trie->getRoot(), arr, 0); } void print(TrieNode* root, char word[], int level) { if (root->wordMarker()) { word[level] = '\0'; cout << word << endl; } int x; for (x = 0; x < root->children().size(); x++) { if (root->children()[x]) { word[level] = root->children()[x]->getChar(); print(root->children()[x], word, level + 1); } } } void mainMenuPrint() { cout << flush; system("CLS"); cout << "\n\n\t Trie Main Menu" << endl; cout << "\t =================" << endl; cout << "\t 1. Search" << endl; cout << "\t 2. Insert" << endl; cout << "\t 3. Add Definition" << endl; cout << "\t 4. Exit" << endl; cout << "\n\n Enter Choice > "; }
[ "noreply@github.com" ]
shar-rahman.noreply@github.com
975bd7b456ba6c0ca4d5b0b1726cdd25775b60c1
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/asio/windows/stream_handle.hpp
82ecf20793b7d0a3e0f7d6ca533cfd1d56ff3bb6
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,863
hpp
// // windows/stream_handle.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_WINDOWS_STREAM_HANDLE_HPP #define BOOST_ASIO_WINDOWS_STREAM_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/windows/overlapped_handle.hpp> #if defined(BOOST_ASIO_HAS_WINDOWS_STREAM_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #if defined(BOOST_ASIO_ENABLE_OLD_SERVICES) # include <boost/asio/windows/basic_stream_handle.hpp> #endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace windows { #if defined(BOOST_ASIO_ENABLE_OLD_SERVICES) // Typedef for the typical usage of a stream-oriented handle. typedef basic_stream_handle<> stream_handle; #else // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) /// Provides stream-oriented handle functionality. /** * The windows::stream_handle class provides asynchronous and blocking * stream-oriented handle functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ class stream_handle : public overlapped_handle { public: /// Construct a stream_handle without opening it. /** * This constructor creates a stream handle without opening it. The handle * needs to be opened and then connected or accepted before data can be sent * or received on it. * * @param io_context The io_context object that the stream handle will use to * dispatch handlers for any asynchronous operations performed on the handle. */ explicit stream_handle(boost::asio::io_context& io_context) : overlapped_handle(io_context) { } /// Construct a stream_handle on an existing native handle. /** * This constructor creates a stream handle object to hold an existing native * handle. * * @param io_context The io_context object that the stream handle will use to * dispatch handlers for any asynchronous operations performed on the handle. * * @param handle The new underlying handle implementation. * * @throws boost::system::system_error Thrown on failure. */ stream_handle(boost::asio::io_context& io_context, const native_handle_type& handle) : overlapped_handle(io_context, handle) { } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a stream_handle from another. /** * This constructor moves a stream handle from one object to another. * * @param other The other stream_handle object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c stream_handle(io_context&) constructor. */ stream_handle(stream_handle&& other) : overlapped_handle(std::move(other)) { } /// Move-assign a stream_handle from another. /** * This assignment operator moves a stream handle from one object to * another. * * @param other The other stream_handle object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c stream_handle(io_context&) constructor. */ stream_handle& operator=(stream_handle&& other) { overlapped_handle::operator=(std::move(other)); return *this; } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Write some data to the handle. /** * This function is used to write data to the stream handle. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the handle. * * @returns The number of bytes written. * * @throws boost::system::system_error Thrown on failure. An error code of * boost::asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.write_some(boost::asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { boost::system::error_code ec; std::size_t s = this->get_service().write_some( this->get_implementation(), buffers, ec); boost::asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the handle. /** * This function is used to write data to the stream handle. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the handle. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) { return this->get_service().write_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream handle. * The function call always returns immediately. * * @param buffers One or more data buffers to be written to the handle. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * boost::asio::io_context::post(). * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.async_write_some(boost::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (boost::system::error_code, std::size_t)) async_write_some(const ConstBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. BOOST_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; boost::asio::async_completion<WriteHandler, void (boost::system::error_code, std::size_t)> init(handler); this->get_service().async_write_some( this->get_implementation(), buffers, init.completion_handler); return init.result.get(); } /// Read some data from the handle. /** * This function is used to read data from the stream handle. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws boost::system::system_error Thrown on failure. An error code of * boost::asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.read_some(boost::asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { boost::system::error_code ec; std::size_t s = this->get_service().read_some( this->get_implementation(), buffers, ec); boost::asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the handle. /** * This function is used to read data from the stream handle. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) { return this->get_service().read_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream handle. * The function call always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * boost::asio::io_context::post(). * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.async_read_some(boost::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read_some(const MutableBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. BOOST_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; boost::asio::async_completion<ReadHandler, void (boost::system::error_code, std::size_t)> init(handler); this->get_service().async_read_some( this->get_implementation(), buffers, init.completion_handler); return init.result.get(); } }; #endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) } // namespace windows } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_WINDOWS_STREAM_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_WINDOWS_STREAM_HANDLE_HPP
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
837693d8f02cf7203b4412d14f7244a1f60014a0
f4482b0859df9c7a6b932422c385442a248a4ba8
/b2/parser/output_buffer.hpp
e856665c9f5be33d367e4ea3648188c57d115497
[]
no_license
mrdooz/tano
e86e3540a8ad4aeb967ff2297f3c44f2537ab619
4fd1112e7590aca0b86a00b4b865f5ebe0453191
refs/heads/master
2021-03-12T19:53:59.096866
2015-10-27T13:41:21
2015-10-27T13:41:21
29,353,711
0
2
null
null
null
null
UTF-8
C++
false
false
249
hpp
#pragma once namespace parser { struct OutputBuffer { OutputBuffer(); void EnsureCapacity(size_t required); char* Cur(); void Advance(size_t distance); size_t _ofs; size_t _capacity; std::vector<char> _buf; }; }
[ "magnus.osterlind@gmail.com" ]
magnus.osterlind@gmail.com
58914bab23efa98c8bab567972ebce90792eafe5
90312ba1088363f12408b9869d89e31d6ad658e5
/mbr_partition_table/src/cpp_stl_98/mbr_partition_table.cpp
1453b49e293a143821a1a4d469d229237fde90dc
[ "ISC" ]
permissive
Tosyk/formats-kaitai-io.github.io
c3e9d0df4deae557f5ac4d36290c7052be4c16bb
1faec646734b93815d39bc638ead4bc9a37eca3e
refs/heads/master
2023-07-29T07:22:10.818349
2021-09-12T11:41:45
2021-09-12T11:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,350
cpp
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild #include "mbr_partition_table.h" #include "kaitai/exceptions.h" mbr_partition_table_t::mbr_partition_table_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, mbr_partition_table_t* p__root) : kaitai::kstruct(p__io) { m__parent = p__parent; m__root = this; m_partitions = 0; try { _read(); } catch(...) { _clean_up(); throw; } } void mbr_partition_table_t::_read() { m_bootstrap_code = m__io->read_bytes(446); int l_partitions = 4; m_partitions = new std::vector<partition_entry_t*>(); m_partitions->reserve(l_partitions); for (int i = 0; i < l_partitions; i++) { m_partitions->push_back(new partition_entry_t(m__io, this, m__root)); } m_boot_signature = m__io->read_bytes(2); if (!(boot_signature() == std::string("\x55\xAA", 2))) { throw kaitai::validation_not_equal_error<std::string>(std::string("\x55\xAA", 2), boot_signature(), _io(), std::string("/seq/2")); } } mbr_partition_table_t::~mbr_partition_table_t() { _clean_up(); } void mbr_partition_table_t::_clean_up() { if (m_partitions) { for (std::vector<partition_entry_t*>::iterator it = m_partitions->begin(); it != m_partitions->end(); ++it) { delete *it; } delete m_partitions; m_partitions = 0; } } mbr_partition_table_t::partition_entry_t::partition_entry_t(kaitai::kstream* p__io, mbr_partition_table_t* p__parent, mbr_partition_table_t* p__root) : kaitai::kstruct(p__io) { m__parent = p__parent; m__root = p__root; m_chs_start = 0; m_chs_end = 0; try { _read(); } catch(...) { _clean_up(); throw; } } void mbr_partition_table_t::partition_entry_t::_read() { m_status = m__io->read_u1(); m_chs_start = new chs_t(m__io, this, m__root); m_partition_type = m__io->read_u1(); m_chs_end = new chs_t(m__io, this, m__root); m_lba_start = m__io->read_u4le(); m_num_sectors = m__io->read_u4le(); } mbr_partition_table_t::partition_entry_t::~partition_entry_t() { _clean_up(); } void mbr_partition_table_t::partition_entry_t::_clean_up() { if (m_chs_start) { delete m_chs_start; m_chs_start = 0; } if (m_chs_end) { delete m_chs_end; m_chs_end = 0; } } mbr_partition_table_t::chs_t::chs_t(kaitai::kstream* p__io, mbr_partition_table_t::partition_entry_t* p__parent, mbr_partition_table_t* p__root) : kaitai::kstruct(p__io) { m__parent = p__parent; m__root = p__root; f_sector = false; f_cylinder = false; try { _read(); } catch(...) { _clean_up(); throw; } } void mbr_partition_table_t::chs_t::_read() { m_head = m__io->read_u1(); m_b2 = m__io->read_u1(); m_b3 = m__io->read_u1(); } mbr_partition_table_t::chs_t::~chs_t() { _clean_up(); } void mbr_partition_table_t::chs_t::_clean_up() { } int32_t mbr_partition_table_t::chs_t::sector() { if (f_sector) return m_sector; m_sector = (b2() & 63); f_sector = true; return m_sector; } int32_t mbr_partition_table_t::chs_t::cylinder() { if (f_cylinder) return m_cylinder; m_cylinder = (b3() + ((b2() & 192) << 2)); f_cylinder = true; return m_cylinder; }
[ "kaitai-bot@kaitai.io" ]
kaitai-bot@kaitai.io
9e774e8c0747fd872618b8bf28567a387b0cc5d8
c45511f1d650751d4f3aa685fde49eb6baa24a08
/tests/core_tests/chain_switch_1.h
c084faeba2cf5ad709d949f50ccf3fb6a7d9f44e
[ "BSD-3-Clause" ]
permissive
cutcoin/cutcoin
41a64eb853d209868b2f37bd7675e833fcdb6c7b
2cec00c3b98b7d67a43cd9310271e1de05309c40
refs/heads/master
2023-09-03T17:23:14.797983
2021-04-06T17:26:12
2021-04-06T17:26:12
162,971,729
9
5
null
null
null
null
UTF-8
C++
false
false
2,673
h
// Copyright (c) 2018-2021, CUT coin // Copyright (c) 2014-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include "chaingen.h" /************************************************************************/ /* */ /************************************************************************/ class gen_chain_switch_1 : public test_chain_unit_base { public: gen_chain_switch_1(); bool generate(std::vector<test_event_entry>& events) const; bool check_split_not_switched(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry>& events); bool check_split_switched(cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry>& events); private: std::vector<cryptonote::block> m_chain_1; cryptonote::account_base m_recipient_account_1; cryptonote::account_base m_recipient_account_2; cryptonote::account_base m_recipient_account_3; cryptonote::account_base m_recipient_account_4; std::vector<cryptonote::transaction> m_tx_pool; };
[ "info@cutcoin.org" ]
info@cutcoin.org
fa8ac62a3d5e8a7a32556561bda1a367e9dc784f
2e30c9c3554509b1c83a4bfb1195d91262828bc9
/sumOfArray.cpp
53442947f327fc904fb174d36db7bcd51147cd5d
[]
no_license
ChristinaChyi/lab04_ronak45
f3494ba6abb7c02ee6a09f991d3ed262fe1294a4
8b854e0d7c939947d4f7d1dbd525fde67c96c1b8
refs/heads/master
2020-04-24T01:12:37.206030
2019-02-18T03:28:44
2019-02-18T03:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
#include "arrayFuncs.h" #include <cstdlib> #include <iostream> int sumOfArray(int a[], int size) { if (size < 1) { std::cerr << "ERROR: sumOfArray called with size < 1" << std::endl; exit(1); } int result=a[0]; for (int i=1; i<size; i++) { result += a[i]; } return result; }
[ "rsparikh@cs.ucsb.edu" ]
rsparikh@cs.ucsb.edu
8ed3177ddde259defe8e40437cd82d4fe6040577
17fb61a3a2fdda085941c2ba8d04daaf8397d2a5
/test/libponyc/badpony.cc
fb7a7d0f56c7923f179729859f30a28e0dc133ae
[ "BSD-2-Clause" ]
permissive
shlomif/ponyc
3553a42aa63fc7700f8469715b3c4470fcbda8f3
545e403b3d4e2fcb572575940f2b377c7d391146
refs/heads/master
2020-12-24T16:16:24.254052
2015-08-25T09:57:39
2015-08-25T09:57:39
41,370,048
1
0
null
2015-08-25T15:02:24
2015-08-25T15:02:24
null
UTF-8
C++
false
false
1,668
cc
#include <gtest/gtest.h> #include <platform.h> #include "util.h" /** Pony code that parses, but is erroneous. Typically type check errors and * things used in invalid contexts. * * We build all the way up to and including code gen and check that we do not * assert, segfault, etc but that the build fails and at least one error is * reported. * * There is definite potential for overlap with other tests but this is also a * suitable location for tests which don't obviously belong anywhere else. */ class BadPonyTest : public PassTest { protected: void test(const char* src) { DO(test_error(src, "ir")); ASSERT_NE(0, get_error_count()); } }; // Cases from reported issues TEST_F(BadPonyTest, DontCareInFieldType) { // From issue #207 const char* src = "class Abc\n" " var _test1: (_)"; DO(test(src)); } TEST_F(BadPonyTest, ClassInOtherClassProvidesList) { // From issue #218 const char* src = "class Named\n" "class Dog is Named\n" "actor Main\n" " new create(env: Env) =>\n" " None"; DO(test(src)); } TEST_F(BadPonyTest, TypeParamMissingForTypeInProvidesList) { // From issue #219 const char* src = "trait Bar[A]\n" " fun bar(a: A) =>\n" " None\n" "trait Foo is Bar // here also should be a type argument, like Bar[U8]\n" " fun foo() =>\n" " None\n" "actor Main\n" " new create(env: Env) =>\n" " None"; DO(test(src)); } TEST_F(BadPonyTest, DontCareInIntLiteralType) { // From issue #222 const char* src = "actor Main\n" " new create(env: Env) =>\n" " let crashme: (_, I32) = (4, 4)"; DO(test(src)); }
[ "andrew@causality.io" ]
andrew@causality.io
b69a1980f8e21cb9f1aff842e75e786e54196a5c
184d28d5aa0c74573eaf52d7a90c10e4b2ac9cd1
/source/Memory/Finalizer.cpp
58ac29f3dfdf09526b5cd80fed31e9fab2c75ab3
[ "MIT" ]
permissive
kurocha/memory
8ce792f23dcf5ce9ca6183449000ddcaa07da079
57e4fd53202f17764f7fe6cf04ac77d343bae2a5
refs/heads/master
2020-12-10T03:26:20.912305
2019-09-22T11:02:10
2019-09-22T11:02:10
95,565,544
1
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
// // Finalizer.cpp // File file is part of the "Memory" project and released under the MIT License. // // Created by Samuel Williams on 27/6/2017. // Copyright, 2017, by Samuel Williams. All rights reserved. // #include "Finalizer.hpp" namespace Memory { Finalizer::~Finalizer() { } void Finalizer::List::insert(Finalizer * finalizer) { Node * node = new Node; node->finalizer = finalizer; node->next = head; head = node; } bool Finalizer::List::erase(Finalizer * finalizer) { Node ** previous = &head; Node * current = head; // It may be possible to improve upon this approach since it is a linear scan. while (current) { if (current->finalizer == finalizer) { *previous = current->next; delete current; return true; } previous = &(current->next); current = current->next; } return false; } void Finalizer::List::finalize(Object * object) { Node * current = head; while (current) { if (current->finalizer) current->finalizer->finalize(object); Node * next = current->next; delete current; current = next; } } }
[ "samuel.williams@oriontransfer.co.nz" ]
samuel.williams@oriontransfer.co.nz
c657fcd3e7e0f04e509e37930508fec3c4e7efe8
0e9394230899fd0df0c891a83131883f4451bcb9
/include/boost/simd/constant/definition/oneosqrt5.hpp
be7bc770213d7aa2084fd475e4229585ee747d02
[ "BSL-1.0" ]
permissive
WillowOfTheBorder/boost.simd
f75764485424490302291fbe9856d10eb55cdbf6
561316cc54bdc6353ca78f3b6d7e9120acd11144
refs/heads/master
2022-05-02T07:07:29.560118
2016-04-21T12:53:10
2016-04-21T12:53:10
59,155,554
1
0
null
null
null
null
UTF-8
C++
false
false
1,526
hpp
//================================================================================================== /*! @file @copyright 2012-2015 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_CONSTANT_DEFINITION_ONEOSQRT5_HPP_INCLUDED #define BOOST_SIMD_CONSTANT_DEFINITION_ONEOSQRT5_HPP_INCLUDED #include <boost/simd/config.hpp> #include <boost/simd/detail/brigand.hpp> #include <boost/simd/detail/dispatch.hpp> #include <boost/simd/detail/constant_traits.hpp> #include <boost/dispatch/function/make_callable.hpp> #include <boost/dispatch/hierarchy/functions.hpp> #include <boost/dispatch/as.hpp> namespace boost { namespace simd { namespace tag { struct oneosqrt5_ : boost::dispatch::constant_value_<oneosqrt5_> { BOOST_DISPATCH_MAKE_CALLABLE(ext,oneosqrt5_,boost::dispatch::constant_value_<oneosqrt5_>); BOOST_SIMD_REGISTER_CONSTANT(0, 0x3ee4f92eUL, 0x3fdc9f25c5bfedd9ULL); }; } namespace ext { BOOST_DISPATCH_FUNCTION_DECLARATION(tag,oneosqrt5_); } namespace detail { BOOST_DISPATCH_CALLABLE_DEFINITION(tag::oneosqrt5_,oneosqrt5); } template<typename T> BOOST_FORCEINLINE auto Oneosqrt5() BOOST_NOEXCEPT_DECLTYPE(detail::oneosqrt5( boost::dispatch::as_<T>{})) { return detail::oneosqrt5( boost::dispatch::as_<T>{} ); } } } #endif
[ "charly.chevalier@numscale.com" ]
charly.chevalier@numscale.com
3b83201b1e766fb0faca0c4659ad2ef8654e9f3b
3517125aebbd8b01f40c41a08d8345e251f4ce19
/server_config.ino
45928be1f3e3d26e82dd53889d5ccd841a1a5754
[]
no_license
jasoncwilley/simple_node_webserver
d8bfb588f2a184d830d68dbb2c8a7777ebc67525
416ccbdab413f733603c658021d8f60b20ae5976
refs/heads/main
2023-04-02T21:08:43.841008
2021-03-26T01:57:22
2021-03-26T01:57:22
351,600,617
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
ino
// ESP8266 and ESP32 boards are utilezed in the project // Not all Libs are compatible with both boards // This if statemtn will allow us to control whether or not to // import the ESP32 or ESP8266 lib version #ifdef ESP8266 #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #elif defined(ESP32) #include <WiFi.h> #include <ESPmDNS.h> #else #error "Board not found" #endif #include "/home/userone/Arduino/simple_node_webserver/index.h" #include <ESPAsyncWebServer.h> AsyncWebServer server(80); // server port 80 void notFound(AsyncWebServerRequest *request) { request->send(404", "text/plain", "Are you lost? The page you requested ws Not Found") } void setup(void) // Begin setup() { Serial.begin(115200); // Begin communiction on Serial 115200 Serial.println("Creating wifi network"); delay(2000); // SSID and Password for the ESP32 Access Point const char* ssid = "smelly_packets"; const char* password = ""; // Access Point is left insecure WiFi.softAP(ssid, password); //Create INSECURE Access Point Serial.println("Intializing wifi network"); delay(2000); Serial.println("Access Point configured..."); Serial.println(ssid); //Return Access Point SSID in Serial Serial.println("has been created at"); Serial.println(WiFi.softAPIP()); //Return Access Point IP address in Serial if (MDNS.begin("ESP")) { //home.local/ Serial.println("MDNS responder started"); } server.on("/", [](AsyncWebServerRequest * request) // Webserver created at home.local return helo world { String index = INDEX_page; // Reads the HTML code from defined in index.h request->send(200, "text/html", index); // Displays code from index.h }); server.on("/page1", HTTP_GET, [](AsyncWebServerRequest * request) { String message = "Hello world, we meet again..."; request->send(200, "text/plain", message); }); server.onNotFound(notFound); // run notFound function if GET returns 404 server.begin(); // starts webserver } // End setup() void loop(void) { }
[ "jason.c.willey@gmail.com" ]
jason.c.willey@gmail.com
71a8b362d946858d64300331909c1bcfc7a0b45a
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/chrome/app/mash/mash_runner.h
813daa0eb00aa96a845772a1074b647b251fd3fa
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
1,027
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_APP_MASH_MASH_RUNNER_H_ #define CHROME_APP_MASH_MASH_RUNNER_H_ #include <memory> #include "base/macros.h" #include "services/service_manager/public/interfaces/service.mojom.h" namespace service_manager { class ServiceContext; } // Responsible for running mash, both child and main processes. class MashRunner { public: MashRunner(); ~MashRunner(); // Returns 0 if the process was initialized correctly, or error code on // failure. int Run(); private: void RunMain(); // Returns 0 if the child process was initialized correctly, or error code on // failure. int RunChild(); void StartChildApp(service_manager::mojom::ServiceRequest service_request); std::unique_ptr<service_manager::ServiceContext> context_; DISALLOW_COPY_AND_ASSIGN(MashRunner); }; int MashMain(); #endif // CHROME_APP_MASH_MASH_RUNNER_H_
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
41731244e0e963dd024db7e53e1725ba85589a88
32cf94c304c2c832595a28b49c7d9e0361d50950
/test/dump/swdbgbk_src/chap25/PdbFairy/PdbMaster.cpp
2f3d3e0f6cb3c4259e33c3bfda90d62113aba8da
[ "MIT" ]
permissive
oudream/ccxx
11d3cd9c044c5f413ebc0735548f102a6f583114
26cecfb02e861ce6b821b33350493bac4793e997
refs/heads/master
2023-01-29T11:20:12.210439
2023-01-12T06:49:23
2023-01-12T06:49:23
47,005,127
46
11
MIT
2020-10-17T02:24:06
2015-11-28T01:05:30
C
UTF-8
C++
false
false
18,207
cpp
// PdbMaster.cpp: implementation of the CPdbMaster class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "PdbFairy.h" #include "PdbMaster.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CPdbMaster::CPdbMaster() { m_hFileHandle=INVALID_HANDLE_VALUE; m_nSignatureLength=0; m_pPdbHeader=NULL; m_nRootStreamOffset=0; } CPdbMaster::~CPdbMaster() { Cleanup(); } // ----------------------------------------------------------------- /*PPDB_HEADER PdbLoad (PWORD pwPath, PBOOL pfInvalid) { HANDLE hf; DWORD dData, dRead; PPDB_HEADER pph = NULL; *pfInvalid = FALSE; if ((hf = CreateFile (pwPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)) != INVALID_HANDLE_VALUE) { dData = GetFileSize (hf, NULL); if ((dData != INVALID_FILE_SIZE) && dData && ((pph = malloc (dData)) != NULL)) { if ((!ReadFile (hf, pph, dData, &dRead, NULL)) || (dData != dRead) || (*pfInvalid = !PdbValid (pph, dData))) { free (pph); pph = NULL; } } CloseHandle (hf); } return pph; } // ----------------------------------------------------------------- BOOL PdbSave (PWORD pwTarget, PVOID pData, DWORD dData) { HANDLE hf; DWORD dWritten; BOOL fOk = FALSE; printf (L"\r\nSaving \"%s\"... ", pwTarget); if ((hf = CreateFile (pwTarget, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN | FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { fOk = WriteFile (hf, pData, dData, &dWritten, NULL) && (dData == dWritten); CloseHandle (hf); } printf (fOk ? L"%lu bytes\r\n" : L"ERROR\r\n", dData); return fOk; } // ----------------------------------------------------------------- DWORD PdbLimit (PPDB_HEADER pph) { return ((DWORD) pph->wStartPage - 1) * pph->dPageSize * 8 * pph->dPageSize; } // ----------------------------------------------------------------- DWORD PdbPages (PPDB_HEADER pph, DWORD dBytes) { return (dBytes ? (((dBytes-1) / pph->dPageSize) + 1) : 0); } // ----------------------------------------------------------------- PVOID PdbRead (PPDB_HEADER pph, DWORD dBytes, PWORD pwPages) { DWORD i, j; DWORD dPages = PdbPages (pph, dBytes); PVOID pPages = malloc (dPages * pph->dPageSize); if (pPages != NULL) { for (i = 0; i < dPages; i++) { j = pwPages [i]; CopyMemory ((PBYTE) pPages + (i * pph->dPageSize), (PBYTE) pph + (j * pph->dPageSize), pph->dPageSize); } } return pPages; } // ----------------------------------------------------------------- PPDB_ROOT PdbRoot (PPDB_HEADER pph, PDWORD pdBytes) { DWORD dBytes, i, n; PPDB_ROOT ppr = NULL; if ((ppr = PdbRead (pph, PDB_ROOT_, pph->awRootPages)) != NULL) { dBytes = PDB_ROOT__ ((DWORD) ppr->wCount); free (ppr); if ((ppr = PdbRead (pph, dBytes, pph->awRootPages)) != NULL) { for (n = i = 0; i < (DWORD) ppr->wCount; i++) { n += PdbPages (pph, ppr->aStreams [i].dStreamSize); } dBytes += n * sizeof (WORD); free (ppr); ppr = PdbRead (pph, dBytes, pph->awRootPages); } } *pdBytes = (ppr != NULL ? dBytes : 0); return ppr; } // ----------------------------------------------------------------- PVOID PdbStream (PPDB_HEADER pph, PPDB_ROOT ppr, DWORD dStream, PDWORD pdBytes) { DWORD dBytes, i; PWORD pwPages; PVOID pPages = NULL; if (dStream < (DWORD) ppr->wCount) { pwPages = (PWORD) ((PBYTE) ppr + PDB_ROOT__ ((DWORD) ppr->wCount)); for (i = 0; i < dStream; i++) { pwPages += PdbPages (pph, ppr->aStreams [i].dStreamSize); } dBytes = ppr->aStreams [dStream].dStreamSize; pPages = PdbRead (pph, dBytes, pwPages); } *pdBytes = (pPages != NULL ? dBytes : 0); return pPages; } // ----------------------------------------------------------------- VOID PdbInfo (PWORD pwPath, PPDB_HEADER pph, PPDB_ROOT ppr) { DWORD dFileLimit, dFileBytes, dFilePages, dStreams; DWORD dDataBytes, dDataPages, dRootBytes, dRootPages, i, n; PWORD pwFile; WORD awPath [MAX_PATH]; dFileLimit = PdbLimit (pph); dFilePages = pph->wFilePages; dFileBytes = dFilePages * pph->dPageSize; dStreams = ppr->wCount; dDataBytes = 0; dDataPages = 0; for (i = 0; i < dStreams; i++) { dDataBytes += ppr->aStreams [i].dStreamSize ; dDataPages += PdbPages (pph, ppr->aStreams [i].dStreamSize); } dRootBytes = PDB_ROOT__(dStreams) + (dDataPages * sizeof(WORD)); dRootPages = PdbPages (pph, dRootBytes); n = GetFullPathName (pwPath, MAX_PATH, awPath, &pwFile); if ((!n) || (n >= MAX_PATH)) { lstrcpyn (awPath, pwPath, MAX_PATH); } printf (L"\r\n" L"Properties of \"%s\":\r\n" L"\r\n" L"%13lu byte%s maximum size\r\n" L"%13lu byte%s allocated\r\n" L"%13lu byte%s used by %lu data stream%s\r\n" L"%13lu byte%s used by the root stream\r\n" L"%13lu byte%s per page\r\n" L"%13lu page%s allocated\r\n" L"%13lu page%s used by %lu data stream%s\r\n" L"%13lu page%s used by the root stream\r\n", awPath, COUNT (dFileLimit, L" ", L"s"), COUNT (dFileBytes, L" ", L"s"), COUNT (dDataBytes, L" ", L"s"), COUNT (dStreams, L"", L"s"), COUNT (dRootBytes, L" ", L"s"), COUNT (pph->dPageSize, L" ", L"s"), COUNT (dFilePages, L" ", L"s"), COUNT (dDataPages, L" ", L"s"), COUNT (dStreams, L"", L"s"), COUNT (dRootPages, L" ", L"s")); return; } // ----------------------------------------------------------------- PWORD PdbTarget (PWORD pwPath, PWORD pwTarget, DWORD dOption) { DWORD i, n; BOOL fSeparator; WORD awExtension [] = L".9876543210"; PWORD pwExtension = NULL; PWORD pwBuffer = NULL; switch (dOption & DISPLAY_OPTION_FLAGS) { case DISPLAY_OPTION_HEADER: { pwExtension = L".header"; break; } case DISPLAY_OPTION_ALLOC: { pwExtension = L".alloc"; break; } case DISPLAY_OPTION_ROOT: { pwExtension = L".root"; break; } case DISPLAY_OPTION_DATA: { wsprintf (awExtension, L".%03lu", dOption & DISPLAY_OPTION_STREAM); pwExtension = awExtension; break; } } if (pwExtension != NULL) { i = lstrlen (pwPath); while (i && (pwPath [i-1] != '\\') && (pwPath [i-1] != ':' )) i--; n = lstrlen (pwTarget); if (fSeparator = (n && (pwTarget [n-1] != '\\') && (pwTarget [n-1] != ':' ))) n++; n += (lstrlen (pwPath+i) + lstrlen (pwExtension)); if ((pwBuffer = malloc ((n+1) * sizeof (WORD))) != NULL) { lstrcpy (pwBuffer, pwTarget); if (fSeparator) lstrcat (pwBuffer, L"\\"); lstrcat (pwBuffer, pwPath+i); lstrcat (pwBuffer, pwExtension); } } return pwBuffer; } // ----------------------------------------------------------------- VOID PdbOutput (PWORD pwPath, PWORD pwTarget, DWORD dOptions, PPDB_HEADER pph, PPDB_ROOT ppr, DWORD dRoot) { PWORD pwTarget1; PVOID pData; DWORD dData, dStream; if (dOptions & DISPLAY_OPTION_HEADER) { if ((pwTarget1 = PdbTarget (pwPath, pwTarget, DISPLAY_OPTION_HEADER)) != NULL) { PdbSave (pwTarget1, pph, pph->dPageSize); free (pwTarget1); } else { printf (L"\r\nUnable to save the header\r\n"); } } if (dOptions & DISPLAY_OPTION_ALLOC) { if ((pwTarget1 = PdbTarget (pwPath, pwTarget, DISPLAY_OPTION_ALLOC)) != NULL) { pData = (PBYTE) pph + pph->dPageSize; dData = ((DWORD) pph->wStartPage - 1) * pph->dPageSize; PdbSave (pwTarget1, pData, dData); free (pwTarget1); } else { printf (L"\r\nUnable to save the allocation bits\r\n"); } } if (dOptions & DISPLAY_OPTION_ROOT) { if ((pwTarget1 = PdbTarget (pwPath, pwTarget, DISPLAY_OPTION_ROOT)) != NULL) { PdbSave (pwTarget1, ppr, dRoot); free (pwTarget1); } else { printf (L"\r\nUnable to save the root stream\r\n"); } } if (dOptions & DISPLAY_OPTION_DATA) { for (dStream = 0; dStream < ppr->wCount; dStream++) { pwTarget1 = PdbTarget (pwPath, pwTarget, DISPLAY_OPTION_DATA | dStream); pData = PdbStream (pph, ppr, dStream, &dData); if ((pwTarget1 != NULL) && (pData != NULL)) { PdbSave (pwTarget1, pData, dData); } else { printf (L"\r\nUnable to save data stream #%lu\r\n", dStream); } free (pwTarget1); free (pData); } } return; } // ----------------------------------------------------------------- VOID PdbExplode (PWORD pwPath, PWORD pwTarget, DWORD dOptions) { PPDB_HEADER pph; PPDB_ROOT ppr; DWORD dRoot; BOOL fInvalid; if ((pph = PdbLoad (pwPath, &fInvalid)) != NULL) { if ((ppr = PdbRoot (pph, &dRoot)) != NULL) { PdbInfo (pwPath, pph, ppr); PdbOutput (pwPath, pwTarget, dOptions, pph, ppr, dRoot); free (ppr); } free (pph); } else { printf ((fInvalid ? L"\r\n\"%s\" is not a PDB file\r\n" : L"\r\nUnable to load \"%s\"\r\n"), pwPath); } return; } */ HRESULT CPdbMaster::Cleanup() { if(m_hFileHandle!=INVALID_HANDLE_VALUE) { CloseHandle(m_hFileHandle); m_hFileHandle=INVALID_HANDLE_VALUE; if(m_pPdbHeader) { delete m_pPdbHeader; m_pPdbHeader=NULL; } } return S_OK; } HRESULT CPdbMaster::ReadHeader() { DWORD dwRead=0; if(!IsLoaded() || this->m_nSignatureLength<=0) return E_FAIL; if(m_pPdbHeader==NULL) m_pPdbHeader=new PDB_HEADER70; SetFilePointer(m_hFileHandle,m_nSignatureLength, 0,FILE_BEGIN); if(this->m_nPdbVersion==200) { PDB_HEADER20 ph; if ((!ReadFile (m_hFileHandle, &ph, sizeof(PDB_HEADER20), &dwRead, NULL)) || (sizeof(PDB_HEADER20) != dwRead) ) return E_FAIL; m_pPdbHeader->dwFilePages=ph.wFilePages; m_pPdbHeader->dwPageSize=ph.dwPageSize; m_pPdbHeader->dwStartPage=ph.wStartPage; m_pPdbHeader->RootStream=ph.RootStream; } else { if ((!ReadFile (m_hFileHandle, m_pPdbHeader, sizeof(PDB_HEADER70), &dwRead, NULL)) || (sizeof(PDB_HEADER70) != dwRead) ) return E_FAIL; } return S_OK; } HRESULT CPdbMaster::Load(LPCTSTR lpszFullFileName) { if(IsLoaded()) return E_FAIL; this->m_hFileHandle = CreateFile (lpszFullFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if(m_hFileHandle == INVALID_HANDLE_VALUE) return E_FAIL; return S_OK; } BOOL CPdbMaster::IsPdb(char *szSignature) { return ( !strcmp (szSignature, PDB_SIGNATURE_200) || !strcmp (szSignature, PDB_SIGNATURE_700) ); } HRESULT CPdbMaster::DumpHeader(HWND hWndListBox) { TCHAR szMsg[MAX_PATH]; if(this->m_nSignatureLength<=0) DumpSignature(hWndListBox); if(m_pPdbHeader==NULL && ReadHeader()!=S_OK) return E_FAIL; _stprintf(szMsg, _T("PageSize: 0x%x [%d]"), m_pPdbHeader->dwPageSize,m_pPdbHeader->dwPageSize); SendMessage(hWndListBox, LB_ADDSTRING,0,(LPARAM)szMsg); _stprintf(szMsg, _T("File Pages: 0x%x [%d]"), m_pPdbHeader->dwFilePages,m_pPdbHeader->dwFilePages); SendMessage(hWndListBox, LB_ADDSTRING,0,(LPARAM)szMsg); _stprintf(szMsg, _T("Start Page: 0x%x [%d]"), m_pPdbHeader->dwStartPage,m_pPdbHeader->dwStartPage); SendMessage(hWndListBox, LB_ADDSTRING,0,(LPARAM)szMsg); _stprintf(szMsg, _T("Root Stream Size: 0x%x [%d]"), m_pPdbHeader->RootStream.dwStreamSize,m_pPdbHeader->RootStream.dwStreamSize); SendMessage(hWndListBox, LB_ADDSTRING,0,(LPARAM)szMsg); _stprintf(szMsg, _T("Root Stream Pages Pointer: 0x%x [%d]"), m_pPdbHeader->RootStream.pwStreamPages,m_pPdbHeader->RootStream.pwStreamPages); SendMessage(hWndListBox, LB_ADDSTRING,0,(LPARAM)szMsg); return S_OK; } HRESULT CPdbMaster::DumpSignature(HWND hWndList) { DWORD dwRead=0; char szSignature[MAX_PATH],*lpsz; TCHAR szMsg[MAX_PATH]; SetFilePointer(m_hFileHandle,0,0,FILE_BEGIN); if ((!ReadFile (m_hFileHandle, szSignature, sizeof(szSignature), &dwRead, NULL)) ) return E_FAIL; szSignature[MAX_PATH-1]=0; #ifdef _UNICODE _stprintf(szMsg, _T("Signature: %S"),szSignature); #else _stprintf(szMsg, _T("Signature: %s"),szSignature); #endif // _UNICODE SendMessage(hWndList, LB_ADDSTRING,0,(LPARAM)szMsg); lpsz=strchr(szSignature,'\x1a'); if(lpsz==NULL) return E_FAIL; *(++lpsz)=0; if(stricmp(szSignature, PDB_SIGNATURE_200)==0) m_nPdbVersion=200; else if(stricmp(szSignature, PDB_SIGNATURE_700)==0) m_nPdbVersion=700; else return E_FAIL; m_nSignatureLength=lpsz-szSignature; // skip the magic signature m_nSignatureLength+=4; // align by dword if(m_nSignatureLength%4) m_nSignatureLength+=4-m_nSignatureLength%4; return S_OK; } HRESULT CPdbMaster::DumpStreamDirectory(HWND hWndList) { int nPages=0,i; WORD * pWord=NULL; TCHAR szMsg[MAX_PATH]; DWORD dwRead=0,dwOffset,*pDWord,dwPageNo4RSPA; // page no to store the page no array of root page stream if(this->m_pPdbHeader==NULL && S_OK!=DumpHeader(hWndList) ) return E_FAIL; nPages=m_pPdbHeader->RootStream.dwStreamSize /m_pPdbHeader->dwPageSize; if(m_pPdbHeader->RootStream.dwStreamSize %m_pPdbHeader->dwPageSize) nPages++; dwOffset=m_nSignatureLength; dwOffset+=this->m_nPdbVersion==200?sizeof(PDB_HEADER20): sizeof(PDB_HEADER70); SetFilePointer(m_hFileHandle, dwOffset, 0,FILE_BEGIN); if(this->m_nPdbVersion==200) { pWord=new WORD[nPages]; if(!ReadFile(m_hFileHandle,pWord,nPages*sizeof(WORD),&dwRead,NULL) && dwRead!=nPages*sizeof(WORD)) return E_FAIL; for(i=0;i<nPages;i++) { dwOffset=*(pWord+i); if(i==0) m_nRootStreamOffset=dwOffset*m_pPdbHeader->dwPageSize; _stprintf(szMsg, _T("Root Page [%d]: no = 0x%x, byte offset = 0x%x"), i, dwOffset, dwOffset*m_pPdbHeader->dwPageSize); SendMessage(hWndList, LB_ADDSTRING,0,(LPARAM)szMsg); } delete pWord; } else { // read a dword if(!ReadFile(m_hFileHandle,&dwPageNo4RSPA,sizeof(DWORD),&dwRead,NULL) && dwRead!=sizeof(DWORD)) return E_FAIL; dwOffset=dwPageNo4RSPA*m_pPdbHeader->dwPageSize; SetFilePointer(m_hFileHandle, dwOffset, 0,FILE_BEGIN); pDWord=new DWORD[nPages]; if(!ReadFile(m_hFileHandle,pDWord,nPages*sizeof(DWORD),&dwRead,NULL) && dwRead!=nPages*sizeof(DWORD)) return E_FAIL; for(i=0;i<nPages;i++) { dwOffset=*(pDWord+i); if(i==0) m_nRootStreamOffset=dwOffset*m_pPdbHeader->dwPageSize; _stprintf(szMsg, _T("Root Page [%d]: no = 0x%x, byte offset = 0x%x"), i, dwOffset, dwOffset*m_pPdbHeader->dwPageSize); SendMessage(hWndList, LB_ADDSTRING,0,(LPARAM)szMsg); } delete pDWord; } return S_OK; } HRESULT CPdbMaster::DumpStreams(HWND hWndList) { PDB_ROOT root; DWORD dwRead=0,i; TCHAR szMsg[MAX_PATH]; PDB_STREAM stream; if(m_nRootStreamOffset<=0) DumpStreamDirectory(hWndList); SetFilePointer(m_hFileHandle, m_nRootStreamOffset, 0,FILE_BEGIN); if(!ReadFile(m_hFileHandle,&root,sizeof(PDB_ROOT),&dwRead,NULL) && dwRead!=sizeof(PDB_ROOT)) return E_FAIL; _stprintf(szMsg, _T("Total streams: [%d]"), root.wCount); SendMessage(hWndList, LB_ADDSTRING,0,(LPARAM)szMsg); for(i=0;i<root.wCount;i++) { if(!ReadFile(m_hFileHandle,&stream,sizeof(PDB_STREAM),&dwRead,NULL) && dwRead!=sizeof(PDB_STREAM)) break; _stprintf(szMsg, _T("Stream[%d], size=%d, pages=0x%x"), i,stream.dwStreamSize,stream.pwStreamPages); SendMessage(hWndList, LB_ADDSTRING,0,(LPARAM)szMsg); } return S_OK; }
[ "oudream@126.com" ]
oudream@126.com
53c8cd4328a225ca26d3baddef8ffb4263b5ac1c
13a06ef97a2e820302bb7061abc6d2137758fee1
/AshEngine/src/Core/Camera.cpp
89629cd6873c59802c741ea6c0cebf61fa90e23d
[ "MIT" ]
permissive
haoxiaoshuai01/3dshow
65c5f94116a610f9613ad068b73288a962dc09d6
1f060dca01e2ec1edc93ddf6601743dea7f22707
refs/heads/main
2023-08-30T03:13:56.450437
2021-07-26T10:06:36
2021-07-26T10:06:36
388,115,006
0
0
null
null
null
null
UTF-8
C++
false
false
5,065
cpp
#include <Camera.h> Camera::Camera(QObject* parent): QObject(0) { int tmp_log_level = log_level; log_level = LOG_LEVEL_WARNING; setObjectName("Camera"); reset(); log_level = tmp_log_level; setParent(parent); } Camera::Camera(QVector3D position, QVector3D direction, QObject* parent): QObject(0) { setObjectName("Camera"); setMovingSpeed(0.1f); setFieldOfView(45.0f); setNearPlane(0.1f); setFarPlane(100000.0f); setPosition(position); setDirection(direction); setParent(parent); } Camera::Camera(const Camera & camera): QObject(0) { m_movingSpeed = camera.m_movingSpeed; m_fieldOfView = camera.m_fieldOfView; m_aspectRatio = camera.m_aspectRatio; m_nearPlane = camera.m_nearPlane; m_farPlane = camera.m_farPlane; m_position = camera.m_position; m_direction = camera.m_direction; m_up = camera.m_up; setObjectName(camera.objectName()); } Camera::~Camera() { if (log_level >= LOG_LEVEL_INFO) dout << "Camera" << this->objectName() << "is destroyed"; } void Camera::moveForward(float shift) { setPosition(m_position + m_direction * shift * m_movingSpeed); } void Camera::moveRight(float shift) { setPosition(m_position + QVector3D::crossProduct(m_direction, m_up) * shift * m_movingSpeed); } void Camera::moveUp(float shift) { setPosition(m_position + m_up * shift* m_movingSpeed); } void Camera::turnLeft(float angle) { QMatrix4x4 mat; mat.rotate(angle, QVector3D(0, 1, 0)); setDirection(mat * m_direction); } void Camera::lookUp(float angle) { QMatrix4x4 mat; mat.rotate(angle, QVector3D::crossProduct(m_direction, m_up)); setDirection(mat * m_direction); } void Camera::dumpObjectInfo(int l) { qDebug().nospace() << tab(l) << "Camera: " << objectName(); qDebug().nospace() << tab(l + 1) << "Position: " << m_position; qDebug().nospace() << tab(l + 1) << "Direction: " << m_direction; qDebug().nospace() << tab(l + 1) << "Up: " << m_up; qDebug().nospace() << tab(l + 1) << "Moving Speed: " << m_movingSpeed; qDebug().nospace() << tab(l + 1) << "Field of View: " << m_fieldOfView; qDebug().nospace() << tab(l + 1) << "Aspect Ratio: " << m_aspectRatio; qDebug().nospace() << tab(l + 1) << "Near Plane: " << m_nearPlane; qDebug().nospace() << tab(l + 1) << "Far Plane: " << m_farPlane; } void Camera::dumpObjectTree(int l) { dumpObjectInfo(l); } // Get properties float Camera::movingSpeed() const { return m_movingSpeed; } float Camera::fieldOfView() const { return m_fieldOfView; } float Camera::aspectRatio() const { return m_aspectRatio; } float Camera::nearPlane() const { return m_nearPlane; } float Camera::farPlane() const { return m_farPlane; } QVector3D Camera::position() const { return m_position; } QVector3D Camera::direction() const { return m_direction; } // Get projection and view matrix QMatrix4x4 Camera::projectionMatrix() const { QMatrix4x4 mat; mat.perspective(m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane); return mat; } QMatrix4x4 Camera::viewMatrix() const { QMatrix4x4 mat; mat.lookAt(m_position, m_position + m_direction, m_up); return mat; } // Public slots void Camera::reset() { setMovingSpeed(0.1f); setFieldOfView(45.0f); setAspectRatio(1.0f); setNearPlane(0.1f); setFarPlane(100000.0f); setPosition(QVector3D(40, 40, 40)); setDirection(QVector3D(-1, -1, -1)); if (log_level >= LOG_LEVEL_INFO) dout << this->objectName() << "is reset"; } void Camera::setMovingSpeed(float movingSpeed) { if (!isEqual(m_movingSpeed, movingSpeed)) { m_movingSpeed = movingSpeed; movingSpeedChanged(m_movingSpeed); } } void Camera::setFieldOfView(float fieldOfView) { if (!isEqual(m_fieldOfView, fieldOfView)) { m_fieldOfView = fieldOfView; fieldOfViewChanged(m_fieldOfView); } } void Camera::setAspectRatio(float aspectRatio) { if (!isEqual(m_aspectRatio, aspectRatio)) { m_aspectRatio = aspectRatio; aspectRatioChanged(m_aspectRatio); } } void Camera::setNearPlane(float nearPlane) { if (!isEqual(m_nearPlane, nearPlane)) { m_nearPlane = nearPlane; nearPlaneChanged(m_nearPlane); } } void Camera::setFarPlane(float farPlane) { if (!isEqual(m_farPlane, farPlane)) { m_farPlane = farPlane; farPlaneChanged(m_farPlane); } } void Camera::setPosition(QVector3D position) { if (!isEqual(m_position, position)) { m_position = position; positionChanged(m_position); } } void Camera::setDirection(QVector3D direction) { direction.normalize(); if (!isEqual(m_direction, direction)) { m_direction = direction; setUpVector(); directionChanged(m_direction); } } // Private functions void Camera::setUpVector() { QVector3D t = QVector3D::crossProduct(m_direction, QVector3D(0, 1, 0)); m_up = QVector3D::crossProduct(t, m_direction); }
[ "15227916361@163.com" ]
15227916361@163.com
ba5fe24e947e5f56fa5d69dde18eb158f92b43bd
5bc47dcf9ab0843b9d06bc25012bcb2f78874216
/53C.cpp
c99cc49bc819989af83b73d5b3f0b6865baf1a26
[]
no_license
MijaTola/Codeforce
428f466248a4e9d42ac457aa971f681320dc5018
9e85803464ed192c6c643bd0f920f345503ac967
refs/heads/master
2021-01-10T16:27:12.479907
2020-10-14T15:00:14
2020-10-14T15:00:14
45,284,776
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include <bits/stdc++.h> using namespace std; int main() { int b; cin >> b; int a = 1; int f = 1; while(a <= b) { if(f) cout << a++ << " "; else cout << b-- << " "; f = !f; } cout << "\n"; return 0; }
[ "mija.tola.ap@gmail.com" ]
mija.tola.ap@gmail.com
dfbde205255c31075c0663c2aef1c3bec6e7c6b1
5469901a3c49f28747b7744274cd137cdd1b42ef
/cplex_2018/Data.h
71dd80c4f5b6fe0a5d3f1a441a9a9711406f59b9
[]
no_license
gaoyangu/cplex_code
68a94ddc1c2b8715386f131bd71fdb1c1e1fb784
957330364e5514e32010819357b317a0232f5db1
refs/heads/master
2022-12-21T15:54:05.499618
2020-09-15T08:56:25
2020-09-15T08:56:25
287,940,845
0
0
null
null
null
null
UTF-8
C++
false
false
651
h
#pragma once #include <list> #include <vector> #include "Flight.h" #include "Deport.h" #include "Passenger.h" using namespace std; class Data { public: int flightNum; int parkNum; int passengerNum; vector<Flight> flightList; vector<Deport> deportList; vector<Passenger> passengerList; vector<vector<int>> isTypeMatching; vector<vector<int>> isConflict; vector<vector<int>> tranTime = { {15, 20, 20, 15}, {35, 40, 40, 35}, {35, 40, 40, 45}, {20, 30, 30, 20} }; };
[ "1600314850@qq.com" ]
1600314850@qq.com
b1d944c7912bab9620b87138759f96c3bd281653
4b0526005426c7855a97d4f3e7cad1a3d5852c11
/j1701(유전자-dp).cpp
d9124562a0148592dc59748f9836e32f1919a62d
[]
no_license
h77h7/jungol
751b5e796bac1deb1c5b0fa9182533a5ce17ed7c
d291b9f188d2c736fd05030d12ffe201b8984c35
refs/heads/main
2023-04-12T12:29:47.181165
2021-05-03T00:36:32
2021-05-03T00:36:32
353,568,058
0
0
null
null
null
null
UTF-8
C++
false
false
1,130
cpp
/************************************************************** Problem: 1701 User: hjee17 Language: C++ Result: Success Time:70 ms Memory:3064 kb dp[i][j] : i번째 부터 j번째 사이의 최대 KOI 유전자 수 ****************************************************************/ #include <iostream> #define UMAX(x,y) (x<y?y:x) using namespace std; const int MAX_N = 500; char dna[MAX_N + 1] = { 0 }; int dp[MAX_N][MAX_N] = { 0 }; int main() { scanf("%s", dna); int n = 0; while (dna[n]) n++; for (int j = 1; j < n; j++) { for (int i = j-1; i >= 0; i--) { if ((dna[i] == 'a' && dna[j] == 't') || (dna[i] == 'g' && dna[j] == 'c')) { //i와 j가 유전자 끝이면 dp[i+1][j-1]+2 dp[i][j] = dp[i + 1][j - 1] + 2; } int m = 0; for (int k = i + 1; k < j; k++) { //i~j사이에서 XY인 유전자의 길이 찾기 m = UMAX(m, dp[i][k] + dp[k][j]); } dp[i][j] = UMAX(m, dp[i][j]); } } printf("%d\n", dp[0][n - 1]); return 0; }
[ "noreply@github.com" ]
h77h7.noreply@github.com
98045de483fd823fcd7b33feec700cac2368ee1c
c057e033602e465adfa3d84d80331a3a21cef609
/C/testcases/CWE127_Buffer_Underread/s01/CWE127_Buffer_Underread__CWE839_listen_socket_82.h
25e31d3aeab7fd7a7aff5f03c5ca23a7160008bb
[]
no_license
Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp
12c2796ae7e580d89e4e7b8274dddf920361c41c
f278f1464588ffb763b7d06e2650fda01702148f
refs/heads/main
2023-04-11T08:29:22.597042
2021-04-09T11:53:16
2021-04-09T11:53:16
356,251,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,449
h
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE127_Buffer_Underread__CWE839_listen_socket_82.h Label Definition File: CWE127_Buffer_Underread__CWE839.label.xml Template File: sources-sinks-82.tmpl.h */ /* * @description * CWE: 127 Buffer Underread * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Non-negative but less than 10 * Sinks: * GoodSink: Ensure the array index is valid * BadSink : Improperly check the array index by not checking to see if the value is negative * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" namespace CWE127_Buffer_Underread__CWE839_listen_socket_82 { class CWE127_Buffer_Underread__CWE839_listen_socket_82_base { public: /* pure virtual function */ virtual void action(int data) = 0; }; #ifndef OMITBAD class CWE127_Buffer_Underread__CWE839_listen_socket_82_bad : public CWE127_Buffer_Underread__CWE839_listen_socket_82_base { public: void action(int data); }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE127_Buffer_Underread__CWE839_listen_socket_82_goodG2B : public CWE127_Buffer_Underread__CWE839_listen_socket_82_base { public: void action(int data); }; class CWE127_Buffer_Underread__CWE839_listen_socket_82_goodB2G : public CWE127_Buffer_Underread__CWE839_listen_socket_82_base { public: void action(int data); }; #endif /* OMITGOOD */ }
[ "65642214+Anzsley@users.noreply.github.com" ]
65642214+Anzsley@users.noreply.github.com
53c7abaaca6dec19e7d464ce3cdfc49eea7fb92d
95791ff410128726d8d940cd0014535ccb9c16af
/第6章/6.36_递归的求幂计算/main.cpp
c9d9878aafd56c4a805dda702f90c67f2e820977
[]
no_license
LiuXJingx/liu_xinjing
d7c6162d636b7040d41907da47975666bdbf8a9a
e752bb3ce882ef1217b5b9f9e897b194011b5c66
refs/heads/master
2020-04-02T10:42:24.754626
2019-04-21T11:10:44
2019-04-21T11:10:44
154,350,958
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include <iostream> using namespace std; int power(int base,int exponent) { if(exponent>1) return base*power(base,exponent-1); } int main() { cout<<"Enter base and exponent: "; int base,exponent; cin>>base>>exponent; cout << power(base,exponent) << endl; return 0; }
[ "2464923693@qq.com" ]
2464923693@qq.com
5b731e52b88fe8cbeea776622b9855e8cb61c296
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/test/multimedia/dmusic/dmtest1/TemplateError/DMTest1/AudioPath_SetVolume_Invalid.cpp
30bc944796c3718192106774f495915a2d7b3ce9
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,130
cpp
/******************************************************************************** FILE: AUDIOPATH8.cpp PURPOSE: Contains AudioPath test functions. BY: DANHAFF ********************************************************************************/ #include "globals.h" #include "cicmusicx.h" /******************************************************************************** Main test function. ********************************************************************************/ HRESULT AudioPath_SetVolume_Invalid(CtIDirectMusicPerformance8* ptPerf8) { HRESULT hr = S_OK; CICMusic Music; CtIDirectMusicAudioPath *ptPath = NULL; //Start the music playing. hr = Music.Init(ptPerf8, g_szDefaultMedia, DMUS_APATH_DYNAMIC_STEREO); if (S_OK != hr) goto TEST_END; hr = Music.GetInterface(&ptPath); hr = ptPath->SetVolume(-10001, 0); Log(FYILOGLEVEL, "ERROR!!!!! Should have int3'd"); hr = ptPath->SetVolume(1, 0); Log(FYILOGLEVEL, "ERROR!!!!! Should have int3'd"); TEST_END: SAFE_RELEASE(ptPath); return hr; };
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
e80cfecea2ca2464d5534f40d0ac4a484ad646d9
4baedf73762706ceedbef490f465eeaeea33c2b8
/fullratio.hpp
a05767cd90d005a8af5d6edd235d9eaadb64bc62
[]
no_license
vapostolopoulos/RationalNumbers
e47809f4f58175f83ce287ec292aaa04ee5030b8
8e9bf2dff08e20c63bc63728e3fad02ceae68af4
refs/heads/master
2023-01-11T06:16:49.351863
2020-11-05T02:28:54
2020-11-05T02:28:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
556
hpp
#ifndef __FULLRATIO_HPP__ #define __FULLRATIO_HPP__ #include <iostream> class rational { public: rational(int n, int d = 1); friend rational operator + (const rational &x, const rational &y); friend rational operator - (const rational &x, const rational &y); friend rational operator * (const rational &x, const rational &y); friend rational operator / (const rational &x, const rational &y); friend std::ostream & operator << (std::ostream &out, const rational &x); private: int nom, den; static int gcd (int a, int b); }; #endif
[ "vnapostolop@gmail.com" ]
vnapostolop@gmail.com
00203e53a3447ca3bb87245db870620b98f1b2a3
11e0959139da59360d91a49fdb0385482fb96262
/InputSetup.cpp
ac6d5fe9eb5824c829d45e2d3ab8cef8d7ef5c8e
[]
no_license
ePubRepo/life
1acfc7def910e6e2e5034cd053091445ef5eb09a
3cdc3462fc2df32bd04e0700c48c9dc568673ce3
refs/heads/master
2021-01-20T05:49:51.084898
2012-12-05T05:02:32
2012-12-05T05:02:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
// // InputSetup.cpp // life // // Copyright 2012 <EAB> #include <iostream> // for cout #include <string> using namespace std; #include "./InputSetup.h" #include "./StanfordCPPLib/console.h" // required of all files that contain the main function #include "./StanfordCPPLib/simpio.h" // for getLine #include "./GridCreator.h" InputSetup::InputSetup() { this->setInputSetupChoice(); } InputSetupChoice InputSetup::processUserSetupInput(const string &userInput) { InputSetupChoice userChoice; if (userInput == "") { userChoice.usetInputSetupChoiceSelection = SEED_RANDOMLY; } else { userChoice.usetInputSetupChoiceSelection = INPUT_FILE; userChoice.filePath = userInput; } return userChoice; } void InputSetup::setInputSetupChoice() { bool validBoardSetup = false; InputSetupChoice userChoice; while (!validBoardSetup) { string userInput = this->getUserSelection(); userChoice = this->processUserSetupInput(userInput); GridCreator myCreator(userChoice); if (myCreator.isValidGridLoaded()) { validBoardSetup = true; this->loadedGrid = myCreator.getLoadedGrid(); } else { cout << "Please enter a valid file." << endl; } } } string InputSetup::getUserSelection() { cout << "You can start your colony with random cells or " "read from a prepared file." << endl; string prompt = "Enter name of colony file (or RETURN to seed randomly): "; return getLine(prompt); } Grid<int> InputSetup::getLoadedGrid() { return this->loadedGrid; }
[ "your@email.com" ]
your@email.com
655be302a04c99033dfe9becbf38d99fb207c8bf
8edd780a12e3342a5fe64477a9062fc6e2522fe4
/03_Contato/contato.cpp
5da79714e6ea3860b4941e4ba2bafe78e99f9d22
[]
no_license
wellingtonumbelino/Cod-POO
979b1849dcb211a9d5f2f36ed48efb8a375924b5
ab2c868eb2251660ce0c3f83bbcbe3cd6ff589e6
refs/heads/master
2020-03-26T17:36:24.103052
2018-10-26T01:13:28
2018-10-26T01:13:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,042
cpp
#include <iostream> #include <vector> #include <sstream> using namespace std; static int proxIndice; class Fone{ public: int indice; string id; string fone; Fone(string id = "", string fone = ""): id(id), fone(fone), indice(proxIndice) { } string toString(){ stringstream ss; ss << "[" << indice << ":" << id << ":" << fone << "]"; return ss.str(); } }; class Contato{ private: string id; vector<Fone> fones; public: Contato(string id = "Vazio"): id(id) { } bool validate(string s){ string valida = "0123456789()."; for(int i = 0; i < s.size(); i++){ for(int j = 0; j < valida.size(); j++){ if(s[i] == valida[j] ){ return true; } } } cout << "failure: caracteres invalidos" << endl; return false; } bool add(Fone fone){ if(validate(fone.fone) == true){ for(auto telefone : fones) if(telefone.fone == fone.fone){ cout << "failure: numero duplicado"; return false; } fones.push_back(fone); proxIndice ++; return true; } return false; } bool rm(int foneId){ for(int i = 0; i < (int) fones.size(); i++){ if(fones[i].indice == foneId){ fones.erase(fones.begin() + i); return true; } } return false; } bool update(string entrada){ string fones[] = entrada.split(" "); for(auto fone : fones){ cout << fone << endl; } } string toString(){ stringstream ss; ss << id << "=>"; for(auto fone : fones) ss << fone.toString(); return ss.str(); } }; struct Controller{ Contato cont; string shell(string line){ stringstream in(line); stringstream out; string op; in >> op; if(op == "help") out << "show; init _nome; add _id _fone; end"; else if(op == "init"){ string nome; in >> nome; cont = Contato(nome); out << "success"; }else if(op == "show"){ out << cont.toString(); }else if(op == "add"){ string id, fone; in >> id >> fone; cont.add(Fone(id, fone)); }else if(op == "rm"){ int id; in >> id; cont.rm(id); } return out.str(); } void exec(){ string line; while(true){ getline(cin, line); if(line == "end") break; cout << " " << shell(line) << endl; } } }; int main(){ Controller controller; controller.exec(); return 0; }
[ "noreply@github.com" ]
wellingtonumbelino.noreply@github.com
8490bca134100db1659fafb5c6c1f971756543a7
7f2aa0e6328e1ea095b1ef2166c772c7c71541ce
/Step 7 - Transform/Render/Device.h
ecee57a837e8a1c2540d6aef5683a0022cb20ed6
[]
no_license
ENgineE777/RS_Steps
97eb5f9bf3aa94c53b76eec8434150f5b5921d40
85d5e43ea12f75ca1e2b2ab0d826d1b6a8dc222b
refs/heads/master
2021-01-19T13:37:41.460416
2017-08-06T17:06:30
2017-08-06T17:09:26
82,404,755
3
0
null
null
null
null
UTF-8
C++
false
false
954
h
#pragma once #include "Helpers/Helpers.h" #include "Shader.h" #include "GeometryBuffer.h" #include "Program.h" #include "Texture.h" class Device { friend class Render; friend class Program; virtual bool Init(int width, int height, void* data) = 0; virtual void Release() = 0; public: enum Primitive { LineStrip = 0, LinesList, TriangleStrip, TrianglesList }; virtual void Clear(bool renderTarget, Color color, bool zbuffer, float zValue) = 0; virtual void Present() = 0; virtual GeometryBuffer* CreateBuffer(int size, int stride) = 0; virtual void SetVertexBuffer(int slot, GeometryBuffer* buffer) = 0; virtual Texture* CreateTexture(int w, int h, Texture::Format f, int l, Texture::Type tp) = 0; virtual void Draw(Primitive prim, int startVertex, int primCount) { if (Program::current) { Program::current->SetShaders(); } } protected: virtual Shader* CreateShader(Shader::Type type, const char* name) = 0; };
[ "enginee777@gmail.com" ]
enginee777@gmail.com
a6217bee854ceaceb798404271dad7dfa6029e55
3d3650565a480d91f47e7ba8a1feb5c1d612b10a
/src/172_fractorial_trailing_zeros.cpp
d538b3a4c935366fdd0baa217b7e797baf806a6f
[]
no_license
Yu-ChenChang/LeetCode
e15c399f0c42a52bdeaa648e88000ff9a01ced7f
690753040d5ae3e6e4433e0b90f78bb9ae38f15d
refs/heads/master
2020-04-06T05:11:40.061743
2016-10-02T18:25:02
2016-10-02T18:25:02
52,691,044
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
#include<vector> #include<string> #include<iostream> using namespace::std; class Solution { public: int trailingZeroes(int n) { int res=0; int five = 5; while(n>=five){ res += n/five; if(five>INT_MAX/5) break; five *= 5; } return res; } }; int main(){ }
[ "chang397@purdue.edu" ]
chang397@purdue.edu
1986cd30ea91e26d266b2d2ee8ddeb37a0f01446
2ba220de6f1279bb7e52234149aa9da13f796c09
/src/locations/location_visitor.hpp
9017c078c4263590c5dd090280b6f605e6d0e636
[]
no_license
marblefactory/Server
b19abfef8ecf179200996d13b393abf368723185
9d19db11e2ef8cb7727047a431ddfb1416eb50b1
refs/heads/master
2021-08-20T09:01:56.131969
2017-11-28T17:50:03
2017-11-28T17:50:03
112,361,812
0
0
null
null
null
null
UTF-8
C++
false
false
393
hpp
// // location_visitor.h // EngineCommandSet // // Created by Albie Baker-Smith on 14/11/2017. // Copyright © 2017 Albie Baker-Smith. All rights reserved. // #ifndef location_visitor_h #define location_visitor_h // Forward declarations. class AbsoluteLocation; class LocationVisitor { public: virtual void visit(AbsoluteLocation &location) = 0; }; #endif /* location_visitor_h */
[ "bakersmitha@gmail.com" ]
bakersmitha@gmail.com
0f96b7b7186c2807bc91d6186252ecf491655ceb
7468375a3a21d7fdb7890d933b600d703d1cf6df
/source/file/min/serial.cpp
476d47c93ce2e1442883d019914c5c1895f5be2d
[ "Apache-2.0" ]
permissive
ocket8888/mgl
71fb815397a1897356538c33eec231036a787397
151f5d9ea54c8389f2a608435ae28bc456488201
refs/heads/master
2020-03-21T05:40:28.108039
2018-10-04T15:43:50
2018-10-04T15:43:50
138,172,766
0
0
null
2018-06-21T13:17:43
2018-06-21T13:17:42
null
UTF-8
C++
false
false
17,203
cpp
#include "serial.h" template unsigned int min::read_le(const std::vector<uint8_t>&, size_t&); template int min::read_le(const std::vector<uint8_t>&, size_t&); template unsigned short min::read_le(const std::vector<uint8_t>&, size_t&); template char min::read_le(const std::vector<uint8_t>&, size_t&); template <typename T> T min::read_le(const std::vector<uint8_t> &stream, size_t &next) { // Check type is compatible static_assert(sizeof(long long) >= sizeof(T), "Invalid type size, sizeof(T) <= sizeof(long long)"); // Size of T in bytes const size_t size = sizeof(T); long long temp = 0; uint8_t shift = 0; for (size_t i = 0; i < size; i++) { // Unpack little endian stream temp |= ((long long)stream[next + i] << shift); shift += 8; } // Change next position next += size; // Avoiding strict aliasing rules of C/C++ const T *out = reinterpret_cast<T *>(&temp); return *out; } template <typename T> T min::read_be(const std::vector<uint8_t> &stream, size_t &next) { // Check type is compatible static_assert(sizeof(long long) >= sizeof(T), "Invalid type size, sizeof(T) <= sizeof(long long)"); // Size of T in bytes const size_t size = sizeof(T); long long temp = 0; uint8_t shift = (sizeof(T) - 1) * 8; for (size_t i = 0; i < size; i++) { // Unpack big endian stream temp |= ((long long)stream[next + i] << shift); shift -= 8; } // Change next position next += size; // Avoiding strict aliasing rules of C/C++ const T *out = reinterpret_cast<T *>(&temp); return *out; } template void min::write_le(std::vector<uint8_t>&, const char); template void min::write_le(std::vector<uint8_t>&, const unsigned int); template void min::write_le(std::vector<uint8_t>&, const int); template <typename T> void min::write_le(std::vector<uint8_t> &stream, const T data) { // Pointer to data uint8_t *const ptr = (uint8_t *)&data; // Size of T in bytes const size_t size = sizeof(T); for (size_t i = 0; i < size; i++) { // Pack little endian stream stream.push_back(ptr[i]); } } template void min::write_be(std::vector<uint8_t>&, const int); template void min::write_be(std::vector<uint8_t>&, const unsigned int); template void min::write_be(std::vector<uint8_t>&, const char); template void min::write_be(std::vector<uint8_t>&, const unsigned short); template <typename T> void min::write_be(std::vector<uint8_t> &stream, const T data) { // Pointer to data uint8_t *const ptr = (uint8_t *)&data; // Size of T in bytes const size_t size = sizeof(T); const size_t offset = size - 1; for (size_t i = 0; i < size; i++) { // Pack big endian stream stream.push_back(ptr[offset - i]); } } template void min::write_le(std::vector<uint8_t>&, const unsigned int, const size_t); template <typename T> void min::write_le(std::vector<uint8_t> &stream, const T data, const size_t offset) { // Pointer to data uint8_t *const ptr = (uint8_t *)&data; // Size of T in bytes const size_t size = sizeof(T); for (size_t i = 0; i < size; i++) { // Pack little endian stream stream[offset + i] = ptr[i]; } } template <typename T> void min::write_be(std::vector<uint8_t> &stream, const T data, const size_t offset) { // Pointer to data uint8_t *const ptr = (uint8_t *)&data; // Size of T in bytes const size_t size = sizeof(T); const size_t be_offset = size - 1; for (size_t i = 0; i < size; i++) { // Pack big endian stream stream[offset + i] = ptr[be_offset - i]; } } template std::vector<unsigned short> min::read_le_vector(const std::vector<uint8_t>&, size_t&); template std::vector<unsigned int> min::read_le_vector(const std::vector<uint8_t>&, size_t&); template <typename T> std::vector<T> min::read_le_vector(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_le<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<T> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(T) * size) > ssize) { throw std::runtime_error("read_le_vector: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const T data = read_le<T>(stream, next); out.push_back(data); } return out; } template <typename T> std::vector<T> min::read_be_vector(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_be<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<T> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(T) * size) > ssize) { throw std::runtime_error("read_be_vector: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const T data = read_be<T>(stream, next); out.push_back(data); } return out; } template void min::write_le_vector(std::vector<uint8_t>&, const std::vector<unsigned short>&); template void min::write_le_vector(std::vector<uint8_t>&, const std::vector<unsigned int>&); template <typename T> void min::write_le_vector(std::vector<uint8_t> &stream, const std::vector<T> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_le<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_le<T>(stream, data[i]); } } template <typename T> void min::write_be_vector(std::vector<uint8_t> &stream, const std::vector<T> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_be<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_be<T>(stream, data[i]); } } template <typename T> min::vec2<T> min::read_le_vec2(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_le<T>(stream, next); const T y = read_le<T>(stream, next); return min::vec2<T>(x, y); } template <typename T> min::vec2<T> min::read_be_vec2(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_be<T>(stream, next); const T y = read_be<T>(stream, next); return min::vec2<T>(x, y); } template <typename T> min::vec3<T> min::read_le_vec3(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_le<T>(stream, next); const T y = read_le<T>(stream, next); const T z = read_le<T>(stream, next); return min::vec3<T>(x, y, z); } template <typename T> min::vec3<T> min::read_be_vec3(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_be<T>(stream, next); const T y = read_be<T>(stream, next); const T z = read_be<T>(stream, next); return min::vec3<T>(x, y, z); } template <typename T> min::vec4<T> min::read_le_vec4(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_le<T>(stream, next); const T y = read_le<T>(stream, next); const T z = read_le<T>(stream, next); const T w = read_le<T>(stream, next); return min::vec4<T>(x, y, z, w); } template <typename T> min::vec4<T> min::read_be_vec4(const std::vector<uint8_t> &stream, size_t &next) { const T x = read_be<T>(stream, next); const T y = read_be<T>(stream, next); const T z = read_be<T>(stream, next); const T w = read_be<T>(stream, next); return min::vec4<T>(x, y, z, w); } template <typename T> void min::write_le_vec2(std::vector<uint8_t> &stream, const min::vec2<T> &v) { write_le<T>(stream, v.x); write_le<T>(stream, v.y); } template <typename T> void min::write_be_vec2(std::vector<uint8_t> &stream, const min::vec2<T> &v) { write_be<T>(stream, v.x); write_be<T>(stream, v.y); } template <typename T> void min::write_le_vec3(std::vector<uint8_t> &stream, const min::vec3<T> &v) { write_le<T>(stream, v.x); write_le<T>(stream, v.y); write_le<T>(stream, v.z); } template <typename T> void min::write_be_vec3(std::vector<uint8_t> &stream, const min::vec3<T> &v) { write_be<T>(stream, v.x); write_be<T>(stream, v.y); write_be<T>(stream, v.z); } template <typename T> void min::write_le_vec4(std::vector<uint8_t> &stream, const min::vec4<T> &v) { write_le<T>(stream, v.x()); write_le<T>(stream, v.y()); write_le<T>(stream, v.z()); write_le<T>(stream, v.w()); } template <typename T> void min::write_be_vec4(std::vector<uint8_t> &stream, const min::vec4<T> &v) { write_be<T>(stream, v.x()); write_be<T>(stream, v.y()); write_be<T>(stream, v.z()); write_be<T>(stream, v.w()); } template std::vector<min::vec2<float>> min::read_le_vector_vec2(const std::vector<uint8_t>&, size_t&); template std::vector<min::vec2<double>> min::read_le_vector_vec2(const std::vector<uint8_t>&, size_t&); template <typename T> std::vector<min::vec2<T>> min::read_le_vector_vec2(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_le<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec2<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec2<T>) * size) > ssize) { throw std::runtime_error("read_le_vector_vec2: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec2<T> data = read_le_vec2<T>(stream, next); out.push_back(data); } return out; } template <typename T> std::vector<min::vec2<T>> min::read_be_vector_vec2(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_be<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec2<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec2<T>) * size) > ssize) { throw std::runtime_error("read_be_vector_vec2: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec2<T> data = read_be_vec2<T>(stream, next); out.push_back(data); } return out; } template std::vector<min::vec3<float>> min::read_le_vector_vec3(const std::vector<uint8_t>&, size_t&); template std::vector<min::vec3<double>> min::read_le_vector_vec3(const std::vector<uint8_t>&, size_t&); template <typename T> std::vector<min::vec3<T>> min::read_le_vector_vec3(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_le<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec3<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec3<T>) * size) > ssize) { throw std::runtime_error("read_le_vector_vec3: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec3<T> data = read_le_vec3<T>(stream, next); out.push_back(data); } return out; } template <typename T> std::vector<min::vec3<T>> min::read_be_vector_vec3(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_be<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec3<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec3<T>) * size) > ssize) { throw std::runtime_error("read_be_vector_vec3: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec3<T> data = read_be_vec3<T>(stream, next); out.push_back(data); } return out; } template std::vector<min::vec4<float>> min::read_le_vector_vec4(const std::vector<uint8_t>&, size_t&); template std::vector<min::vec4<double>> min::read_le_vector_vec4(const std::vector<uint8_t>&, size_t&); template <typename T> std::vector<min::vec4<T>> min::read_le_vector_vec4(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_le<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec4<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec4<T>) * size) > ssize) { throw std::runtime_error("read_le_vector_vec4: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec4<T> data = read_le_vec4<T>(stream, next); out.push_back(data); } return out; } template <typename T> std::vector<min::vec4<T>> min::read_be_vector_vec4(const std::vector<uint8_t> &stream, size_t &next) { const uint32_t size = read_be<uint32_t>(stream, next); // Create output vector and reserve memory std::vector<min::vec4<T>> out; out.reserve(size); // Check that the stream has enough data const size_t ssize = stream.size(); if ((next + sizeof(min::vec4<T>) * size) > ssize) { throw std::runtime_error("read_be_vector_vec4: ran out of data in stream"); } // Read all vector elements for (uint32_t i = 0; i < size; i++) { const min::vec4<T> data = read_be_vec4<T>(stream, next); out.push_back(data); } return out; } template void min::write_le_vector_vec2(std::vector<uint8_t>&, const std::vector<min::vec2<double>>&); template void min::write_le_vector_vec2(std::vector<uint8_t>&, const std::vector<min::vec2<float>>&); template <typename T> void min::write_le_vector_vec2(std::vector<uint8_t> &stream, const std::vector<vec2<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_le<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_le_vec2<T>(stream, data[i]); } } template <typename T> void min::write_be_vector_vec2(std::vector<uint8_t> &stream, const std::vector<vec2<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_be<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_be_vec2<T>(stream, data[i]); } } template void min::write_le_vector_vec3(std::vector<uint8_t>&, const std::vector<vec3<float>>&); template void min::write_le_vector_vec3(std::vector<uint8_t>&, const std::vector<vec3<double>>&); template <typename T> void min::write_le_vector_vec3(std::vector<uint8_t> &stream, const std::vector<vec3<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_le<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_le_vec3<T>(stream, data[i]); } } template <typename T> void min::write_be_vector_vec3(std::vector<uint8_t> &stream, const std::vector<vec3<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_be<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_be_vec3<T>(stream, data[i]); } } template void min::write_le_vector_vec4(std::vector<uint8_t>&, const std::vector<min::vec4<float>>&); template void min::write_le_vector_vec4(std::vector<uint8_t>&, const std::vector<min::vec4<double>>&); template <typename T> void min::write_le_vector_vec4(std::vector<uint8_t> &stream, const std::vector<vec4<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_le<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_le_vec4<T>(stream, data[i]); } } template <typename T> void min::write_be_vector_vec4(std::vector<uint8_t> &stream, const std::vector<vec4<T>> &data) { // Get data size, must be less than 2^32-1 const uint32_t size = data.size(); // Write vector size to stream, zero vector is allowed write_be<uint32_t>(stream, size); // Write each data element for (uint32_t i = 0; i < size; i++) { write_be_vec4<T>(stream, data[i]); } }
[ "ocket8888@gmail.com" ]
ocket8888@gmail.com
32af074297dde14d1214ff102d6fdc6c751a987c
6920669973a1731f3c6bc33b3789095d6fb9c2c0
/101/SymmetricTree.cpp
946d010fb6781874200f92cfd9d3ac2c05052f60
[ "Apache-2.0" ]
permissive
misslzyan/leetcode
47c56a95b30ce2c5c5fdeabb5ec9c635cc9b30be
4ab3e3c8abb35bb9c31c2fd18e81e11ea69ff200
refs/heads/master
2022-12-13T03:52:35.733695
2020-08-24T04:32:14
2020-08-24T04:32:14
285,872,095
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
#include<iostream> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x):val(x),left(nullptr), right(nullptr){} }; class Solution { public: bool isSymmitric(TreeNode* root) { return check(root, root); } bool check(TreeNode* r1, TreeNode* r2) { if (!r1 && !r2) return true; if (!r1 || !r2) return false; return (r1 -> val == r2 -> val) && check(r1 -> left, r2 -> right) && check(r1 -> right, r2 -> left); } }; int main() { //[1,2,2,3,4,4,3] TreeNode* root = new TreeNode(1); root -> left = new TreeNode(2); root -> right = new TreeNode(2); root -> left -> left = new TreeNode(3); root -> left -> right = new TreeNode(4); root -> right -> left = new TreeNode(4); root -> right -> right = new TreeNode(3); Solution s; bool r = s.isSymmitric(root); std::cout << std::boolalpha << r << std::endl; }
[ "misslzyan108@gmail.com" ]
misslzyan108@gmail.com
d623ade0444bac0f1903babe15f74913f61685f0
8c8b6ca7c2b78d8baa65bf34888343ffbe2ebc06
/hostrpc/run_on_hsa.hpp
98678ededd78b4df1c6898747bb0419183f18b2a
[ "MIT" ]
permissive
powderluv/hostrpc
2184879b2d843563017545bf77031097f616fba5
d2fa4127133cae8c23d8a691a0d23bb0ba1aa126
refs/heads/master
2023-04-02T00:25:01.815059
2021-04-12T01:40:29
2021-04-12T01:40:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,901
hpp
#ifndef RUN_ON_HSA_HPP_INCLUDED #define RUN_ON_HSA_HPP_INCLUDED // Call a function with a given name and type: // void known_function_name(void*); // from: // kernel void kernel_known_function_name(__global void *){} // provided that source containing 'HOSTRPC_ENTRY_POINT(foo)' // is compiled as opencl and as c++, which are then linked // Call extern "C" void NAME(TYPE*); defined in amdgcn source from the host // as extern "C" void NAME(hsa_executable_t, TYPE*) // from an instantiation of HOSTRPC_ENTRY_POINT(NAME, TYPE) compiled as // amdgcn ocl/cxx and on the host #include "detail/platform_detect.hpp" #define HOSTRPC_ENTRY_POINT(NAME, TYPE) \ /* void NAME(TYPE*); */ \ HOSTRPC_OPENCL_PART(NAME, TYPE) \ HOSTRPC_CXX_GCN_PART(NAME, TYPE) \ HOSTRPC_CXX_X64_PART(NAME, TYPE) #define HOSTRPC_CAT(X, Y) X##Y #if HOSTRPC_HOST #include "hsa.h" #include "hsa.hpp" #include <stddef.h> #define bang() (bang)(rc, __LINE__) static void(bang)(hsa_status_t rc, unsigned line) { if (rc != HSA_STATUS_SUCCESS) { printf("Fail at line %u, rc %s\n", line, hsa::status_string(rc)); } } namespace hostrpc { // will call name on every agent in ex for which get_symbol_by_name succeeds void run_on_hsa(hsa_executable_t ex, void *arg, size_t len, const char *name); template <typename T> void run_on_hsa_typed(hsa_executable_t ex, T *arg, const char *name) { run_on_hsa(ex, (void *)arg, sizeof(T), name); } } // namespace hostrpc #define HOSTRPC_OPENCL_PART(NAME, TYPE) #define HOSTRPC_CXX_GCN_PART(NAME, TYPE) #define HOSTRPC_CXX_X64_PART(NAME, TYPE) \ extern "C" void NAME(hsa_executable_t ex, TYPE *arg) \ { \ hostrpc::run_on_hsa_typed<TYPE>(ex, arg, "kernel_" #NAME ".kd"); \ } #else #if defined(__OPENCL_C_VERSION__) #define HOSTRPC_OPENCL_PART(NAME, TYPE) \ void HOSTRPC_CAT(cast_, NAME)(__global TYPE *); \ kernel void HOSTRPC_CAT(kernel_, NAME)(__global TYPE * arg) \ { \ HOSTRPC_CAT(cast_, NAME)(arg); \ } #define HOSTRPC_CXX_GCN_PART(NAME, TYPE) #define HOSTRPC_CXX_X64_PART(NAME, TYPE) #else #define HOSTRPC_OPENCL_PART(NAME, TYPE) #define HOSTRPC_CXX_GCN_PART(NAME, TYPE) \ extern "C" void NAME(TYPE *); \ extern "C" void HOSTRPC_CAT( \ cast_, NAME)(__attribute__((address_space(1))) TYPE * asargs) \ { \ TYPE *args = (TYPE *)asargs; \ NAME(args); \ } #define HOSTRPC_CXX_X64_PART(NAME, TYPE) #endif #endif #endif
[ "jonathanchesterfield@gmail.com" ]
jonathanchesterfield@gmail.com
89253842e7bc5e199385eb44bf7f06c03af302e8
b1e7481f8b5bf40c2547c95b1863e25b11b8ef78
/RDF/BTagCalibrationStandalone.h
8e36d456ba1699960be2f7425d152579544e389d
[ "Apache-2.0" ]
permissive
NJManganelli/FourTopNAOD
3df39fd62c0546cdbb1886b23e35ebdc1d3598ad
c86181ae02b1933be59d563c94e76d39b83e0c52
refs/heads/master
2022-12-22T22:33:58.697162
2022-12-17T01:19:36
2022-12-17T01:19:36
143,607,743
1
1
Apache-2.0
2022-06-04T23:11:42
2018-08-05T11:40:42
Python
UTF-8
C++
false
false
5,033
h
#ifndef BTagEntry_H #define BTagEntry_H // Copied from https://github.com/cms-sw/cmssw/blob/master/CondTools/BTau/test/BTagCalibrationStandalone.h // and slightly modified for use in RDataFrame (faster initialization) /** * * BTagEntry * * Represents one pt- or discriminator-dependent calibration function. * * measurement_type: e.g. comb, ttbar, di-mu, boosted, ... * sys_type: e.g. central, plus, minus, plus_JEC, plus_JER, ... * * Everything is converted into a function, as it is easiest to store it in a * txt or json file. * ************************************************************/ #include <string> #include <TF1.h> #include <TH1.h> class BTagEntry { public: enum OperatingPoint { OP_LOOSE=0, OP_MEDIUM=1, OP_TIGHT=2, OP_RESHAPING=3, }; enum JetFlavor { FLAV_B=0, FLAV_C=1, FLAV_UDSG=2, }; struct Parameters { OperatingPoint operatingPoint; std::string measurementType; std::string sysType; JetFlavor jetFlavor; float etaMin; float etaMax; float ptMin; float ptMax; float discrMin; float discrMax; // default constructor Parameters( OperatingPoint op=OP_TIGHT, std::string measurement_type="comb", std::string sys_type="central", JetFlavor jf=FLAV_B, float eta_min=-99999., float eta_max=99999., float pt_min=0., float pt_max=99999., float discr_min=0., float discr_max=99999. ); }; BTagEntry() {} BTagEntry(const std::string &csvLine); BTagEntry(const std::string &func, Parameters p); BTagEntry(const TF1* func, Parameters p); BTagEntry(const TH1* histo, Parameters p); ~BTagEntry() {} static std::string makeCSVHeader(); std::string makeCSVLine() const; static std::string trimStr(std::string str); // public, no getters needed std::string formula; Parameters params; static inline JetFlavor jetFlavourFromHadronFlavour(int hadronFlavour) { switch(hadronFlavour) { case 5: return FLAV_B; case 4: return FLAV_C; default: return FLAV_UDSG; } } }; #endif // BTagEntry_H #ifndef BTagCalibration_H #define BTagCalibration_H /** * BTagCalibration * * The 'hierarchy' of stored information is this: * - by tagger (BTagCalibration) * - by operating point or reshape bin * - by jet parton flavor * - by type of measurement * - by systematic * - by eta bin * - as 1D-function dependent of pt or discriminant * ************************************************************/ #include <map> #include <vector> #include <string> #include <istream> #include <ostream> class BTagCalibration { public: BTagCalibration() {} BTagCalibration(const std::string &tagger); BTagCalibration(const std::string &tagger, const std::string &filename); ~BTagCalibration() {} std::string tagger() const {return tagger_;} void addEntry(const BTagEntry &entry); const std::vector<BTagEntry>& getEntries(const BTagEntry::Parameters &par) const; void readCSV(std::istream &s); void readCSV(const std::string &s); void makeCSV(std::ostream &s) const; std::string makeCSV() const; protected: static std::string token(const BTagEntry::Parameters &par); std::string tagger_; std::map<std::string, std::vector<BTagEntry> > data_; }; #endif // BTagCalibration_H #ifndef BTagCalibrationReader_H #define BTagCalibrationReader_H /** * BTagCalibrationReader * * Helper class to pull out a specific set of BTagEntry's out of a * BTagCalibration. TF1 functions are set up at initialization time. * ************************************************************/ #include <memory> #include <string> class BTagCalibrationReader { public: class BTagCalibrationReaderImpl; BTagCalibrationReader() {} BTagCalibrationReader(BTagEntry::OperatingPoint op, const std::string & sysType="central", const std::vector<std::string> & otherSysTypes={}); void load(const BTagCalibration & c, BTagEntry::JetFlavor jf, const std::string & measurementType="comb"); double eval(BTagEntry::JetFlavor jf, float eta, float pt, float discr=0.) const; /* double eval_auto_bounds(const std::string & sys, */ /* BTagEntry::JetFlavor jf, */ /* float eta, */ /* float pt, */ /* float discr=0.) const; */ double eval_auto_bounds(const std::string & sys, int hf, float eta, float pt, float discr=0.) const; std::pair<float, float> min_max_pt(BTagEntry::JetFlavor jf, float eta, float discr=0.) const; protected: std::shared_ptr<BTagCalibrationReaderImpl> pimpl; }; #endif // BTagCalibrationReader_H
[ "nicholas.james.manganelli@cern.ch" ]
nicholas.james.manganelli@cern.ch
317fc15d508e65a869e9a441faa798ab7ff67b8b
e4044fdb9b9785105f3413a0515c45d7a76cbfc1
/gerentebdd.h
3bfdaace05c249f8db31e402f8ad6450e3fe8f38
[]
no_license
esbrito/aig-eq-verifier
b8dd5d8919471dd912025ba0ced8c49c25a00771
8bc9b30c142551a2f24c5eb85a327f42deab882a
refs/heads/master
2021-05-16T14:46:05.737921
2018-01-25T17:51:27
2018-01-25T17:51:27
118,610,425
0
0
null
null
null
null
UTF-8
C++
false
false
2,138
h
//copyright Prof. Andre Reis - UFRGS #ifndef GERENTEBDD_H #define GERENTEBDD_H #include <iostream> #include <string> #include <map> #include <vector> #include <fstream> #include <sstream> #include <algorithm> #include <set> #include "aig.h" using namespace std; enum Token_value{AND='*', OR='+', LP='(', RP=')', NOT='!', LIT, END=';'}; class nodobdd{ nodobdd *f0; nodobdd *f1; int variavel; int idunico; public: nodobdd(int, nodobdd*, nodobdd*, int); void imprime(ostream& saida); friend class gerentebdd; friend class BooleanFunctionWrapper; }; class gerentebdd{ map<string, nodobdd*> tabelaunica; map<string, int> var_indices; vector <string> variaveis; nodobdd *t0; nodobdd *t1; int proximoIdNodo; int proximoIndiceVar; static Token_value curr_tok; static string string_value; nodobdd* prim(istringstream &equation, set<string> &variaveis); nodobdd* term (istringstream &equation, set<string> &variaveis); nodobdd* expr (istringstream &equation, set<string> &variaveis); Token_value get_token(istringstream &equation); public: gerentebdd(); string chaveunica(string v, nodobdd* n0, nodobdd* n1); nodobdd* novo_ou_velho(string s, nodobdd* n0, nodobdd* n1); nodobdd* novo_ou_velho(int i, nodobdd* n0, nodobdd* n1); nodobdd* cadastravariavel(string s); nodobdd* ite(nodobdd* se, nodobdd* entao, nodobdd* senao, int indice); nodobdd* and2(nodobdd* n1, nodobdd* n2); nodobdd* or2(nodobdd* n1, nodobdd* n2); nodobdd* nand2(nodobdd* n1, nodobdd* n2); nodobdd* nor2(nodobdd* n1, nodobdd* n2); nodobdd* exor2(nodobdd* n1, nodobdd* n2); nodobdd* inv(nodobdd* n1); nodobdd* cofactor(nodobdd* function, nodobdd* variable, char polarity); //nodobdd* createCube(Cube c, int n, vector<string> x17); int xstoresSerie(nodobdd*, int); nodobdd* create_from_equation(string equation, set<string> &variaveis); nodobdd* getConstantZero(); nodobdd* getConstantOne(); std::vector<string> create_equations_from_aig(Aig* aig); }; //copyright Prof. Andre Reis - UFRGS #endif
[ "eduardobrito14@gmail.com" ]
eduardobrito14@gmail.com
3dc9325c7747c1c698cc7952ad3e0c77df195e84
36184239a2d964ed5f587ad8e83f66355edb17aa
/.history/hw3/ElectoralMap_20211022000959.h
da6901ec51f98ce332d87131f516f14ee629ed8d
[]
no_license
xich4932/csci3010
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
refs/heads/master
2023-08-24T04:03:12.748713
2021-10-22T08:22:58
2021-10-22T08:22:58
415,140,207
0
0
null
null
null
null
UTF-8
C++
false
false
3,899
h
#ifndef __ELECTORALMAP__ #define __ELECTORALMAP__ //#include"District.h" #include<iostream> #include<map> #include<vector> enum party{one, two, three, none}; class District{ public: District(); District(int); void change_party(party,party, int); //void get_constituent(party); double get_square_mile(){return square_mile;}; int get_id() const {return id;}; int get_constituent(party party_name){return map_party[party_name];}; void convert_constituent(party, party, int); party get_max(); int get_sum_constitutent(); party get_max_party(); int get_sum_constitutent_exclude_none(party); friend std::ostream & operator<<(std::ostream& os, District print_district); /* bool operator <(const District& less)const{ if(this->id < less.get_id()) return true; return false; }; bool operator >(const District& less)const{ if(this->id > less.get_id()) return true; return false; }; bool operator ==(const District& less)const{ if(this->id == less.get_id()) return true; return false; }; */ private: double square_mile; std::map<party, int> map_party; int id; }; class Candidate{ public: Candidate(); Candidate(int, party, std::string); int get_ids(); std::string get_name(){return name;}; int get_vote(int dis){return votes[dis];}; party get_party(){return party_affiliation;}; void plus_vote(const int, int); std::map<int,int> get_all_votes() {return votes;} static int party_one_candidate; static int party_two_candidate; static int party_three_candidate; int get_total_vote(){return total_vote;}; // static int party_none; void print_vote(); //debug public: int id_candidate; party party_affiliation; std::string name; std::map<int ,int> votes; int total_vote; }; class Election{ public: Election(); // void register_candidate(party, std::string); bool check_win(); void report_win(); void voting(); void register_candidate(party, std::string); Candidate* who_campaigning(); int where_campaigning(); bool check_end(); //void call_votes(); //void voting(); //void report_win(); //Candidate get_candidat_by_id(int id){ return candidate_[id];}; void print_each_Vote(); virtual void test(){std::cout <<"from base"<<std::endl;}; void converting(District*, Candidate* ); Candidate* get_candidate(int ); // std::vector<Candidate> get_all_candidate(); static int ids; static std::vector<int> party_one_active; static std::vector<int> party_two_active; static std::vector<int> party_three_active; static std::vector<int> party_none; static int active_party[3]; private: std::map<int, Candidate*> candidate_; // std::map<party, int> count_votes; }; class RepresentativeELection : public Election{ public: RepresentativeELection(); void calculate_vote(); void voting(); void test(){std::cout <<"from derivative"<<std::endl;}; void report_win(); private: std::vector<int> vote_per_district; std::map<int, Candidate*> candidate_ ; }; class ElectoralMap{ public: static ElectoralMap& getInstance(){ static ElectoralMap instance; return instance; } //static District* getDistrict(int); friend std::ostream & operator<<(std::ostream& os, ElectoralMap map); static int count_district; std::map<int, District*> get_map(){return map;}; private: ElectoralMap(); std::map<int, District*> map; }; #endif
[ "70279863+xich4932@users.noreply.github.com" ]
70279863+xich4932@users.noreply.github.com
d563011680e44d7705eb7013680a1b9cc9f876d2
84cb6172f8afd975707c486b11ac8c812960a8a1
/ccfZCO14001.cpp
c4558eb75372ae631362c006c07d688d3418da08
[]
no_license
numan947/Curiously-Bored
d4d761923102831cac83c828e2e6a44daa5d5ac7
7bfffec3989d6cb75697bf7f569da01c3adb1a19
refs/heads/master
2021-07-10T22:01:27.716481
2020-07-02T19:16:16
2020-07-02T19:16:16
152,405,037
2
0
null
null
null
null
UTF-8
C++
false
false
6,027
cpp
#include <bits/stdc++.h> using namespace std; /*Like set but has some more functionality: 1. Find kth smallest minimum 2. Find the index of an element Does these in O(log n) time How to use: ordered_set<type> ss; ss.insert(val); ss.insert(val); ss.insert(val); cout<<ss.ordere_of_key(val)<<endl; // number of elements in ss less than val cout<<*ss.find_by_order(k)<<endl; // prints the kth smallest number in s (0-based) */ /*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; */ #define ms(s, n) memset(s, n, sizeof(s)) #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define FORd(i, a, b) for (int i = (a) - 1; i >= (b); --i) #define FORall(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) #define mapHas(t, x) (t.find(x) != t.end()) //for map #define vectHas(v,x) (find(v.begin(),v.end(),x)!=v.end()) //for vector #define setHas(t,x) (t.count(x)!=0) #define pb push_back #define pf push_front #define mp make_pair #define fi first #define se second #define prec(n) fixed<<setprecision(n) //bit manipulation #define bit(n, i) (((n) >> (i)) & 1) //check bit #define setBit(n,i) (n|=(1<<i)) //set i'th bit of n #define checkBit(n,i) (n &(1<<i)) //check i'th bit of n #define resetBit(n,i) (n&=~(1<<i)) //reset i'th bit of n #define toggleBit(n,i) (n^=(1<<i)) //toggle i'th bit of n #define lsOnBit(n) (n&(-n)) //get lsb of n that is on #define turnOnAll(n) ((1<<n) - 1) //turn on size of n bits from right (kind of opposite of clear) #define remainder(s,n) (s & (n-1)) //remainder of s when divided by n, where n is power of 2 #define powerOfTwo(s) ((s & (s-1)) == 0) //determine if s is a power of 2 #define turnOffLastSetBit(s) (s=(s&(s-1))) #define turnOnLastZero(s) (s=(s|(s+1))) #define numLeadZero(s) __builtin_clz(s) #define numTrailZero(s) __builtin_ctz(s) #define numOnes(s) __builtin_popcount(s) #define parity(s) __builtin_parity(s) //shorthands typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef pair<char, int> pci; typedef pair<int, char> pic; typedef pair<int, string> pis; typedef pair<string, int> psi; typedef pair<string, string> pss; typedef vector<int> vi; typedef vector<pii> vii; typedef vector<string> vs; const int MOD = (int) 1e9 + 7; const int FFTMOD = 1007681537; const int INF = (int) 1e9; const ll LINF = (ll) 1e18; const ld PI = acos((ld) -1); const ld EPS = 1e-6; //some common functions inline ll gcd(ll a, ll b) {ll r; while (b) {r = a % b; a = b; b = r;} return a;} //gcd inline ll lcm(ll a, ll b) {return a / gcd(a, b) * b;} //lcm inline ll fpow(ll n, ll k, int p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n % p; n = n * n % p;} return r;} //nth power inline void addmod(int& a, int val, int p = MOD) {if ((a = (a + val)) >= p) a -= p;} //add mod inline void submod(int& a, int val, int p = MOD) {if ((a = (a - val)) < 0) a += p;} //sub mod inline ll isqrt(ll k) {ll r = sqrt(k) + 1; while (r * r > k) r--; return r;} //check sqrt inline ll icbrt(ll k) {ll r = cbrt(k) + 1; while (r * r * r > k) r--; return r;} //check cbrt //some helper functions for input processing inline void tokenize(string str,vector<string> &tokens, string delim){ tokens.clear();size_t s = str.find_first_not_of(delim), e=s; while(s!=std::string::npos){e=str.find(delim,s);tokens.push_back(str.substr(s,e-s));s=str.find_first_not_of(delim,e);}} inline bool isPalindrome(string str){for(int i=0;i<(str.size())/2;i++)if(str[i]!=str[str.size()-1-i])return false;return true;} inline string customStrip(string in,string delim){string ret = "";for(int i=0;i<in.size();i++){if(delim.find(in[i],0)==std::string::npos)ret+=in[i];}return ret;} inline string commaSeparate(long long value){string numWithCommas = to_string(value);int insertPosition = numWithCommas.length() - 3;while (insertPosition > 0) {numWithCommas.insert(insertPosition, ",");insertPosition-=3;}return numWithCommas;} inline string strip(string s){int i=0;while(i<s.size()){if(isspace(s[i]))i++;else break;}s.erase(0,i);i = s.size()-1;while(i>=0){if(isspace(s[i]))i--;else break;}s.erase(i+1,s.size()-i-1);return s;} //errors #define db(x) cerr << #x << " = " << (x) << "\n"; #define endl '\n' /* //double comparisons and ops //d1==d2 inline bool EQ(double d1,double d2){return fabs(d1-d2)<EPS;} //d1>d2 inline bool GT(double d1,double d2){return (d1-d2)>EPS;} //d1<d2 inline bool LT(double d1,double d2){return GT(d2,d1);} //d1>=d2 inline bool GTE(double d1, double d2){return GT(d1,d2)||EQ(d1,d2);} //d1<=d2 inline bool LTE(double d1,double d2){return LT(d1,d2)||EQ(d1,d2);} //numPosAfterDecimal={10,100,1000,10000,....} //Roundoff(3.56985,10000) = 3.5699 inline double Roundoff(double val,int numPosAfterDecimal){return round(val*numPosAfterDecimal)/numPosAfterDecimal;} */ /*//4 directional movement int dx[]={1,0,-1,0}; int dy[]={0,1,0,-1};*/ #define MAX 100001 int stk[MAX]; int main() { /*The standard C++ I/O functions (cin/cout) flush the buffer on every next I/O call which unncecessarily increase I/O time. For enhancing C++ I/O speed,you can either use C’s standard I/O function (scanf/printf) instead of (cin/cout) or you can write the following lines in main function.*/ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int N,H; cin>>N>>H; FOR(i,0,N) cin>>stk[i]; int iPos=0,iStat=0,cmd; while(cin>>cmd){ if(!cmd)break; switch(cmd){ case 1: if(iPos>0) iPos--; break; case 2: if(iPos<N-1) iPos++; break; case 3: if(!iStat && stk[iPos]){ iStat = 1; stk[iPos]--; } break; case 4: if(iStat&&stk[iPos]<H){ iStat = 0; stk[iPos]++; } break; } } cout<<stk[0]; FOR(i,1,N) cout<<" "<<stk[i]; cout<<endl; return 0; }
[ "mahmudulhasan947@gmail.com" ]
mahmudulhasan947@gmail.com
08c13c3751cf892237ccd7d90209409db64e1a6b
a04701966913695a1cbc003bf4b609754b62ed1c
/src/libtsduck/tsAVCVideoDescriptor.h
6a499ef3cb2a8ca436dc104da3f395e3a5b72f4e
[ "BSD-2-Clause" ]
permissive
anto35/tsduck
b80c7bed9138f78d402534fbf94f1635fd9d0c4a
6aa32ce5a59865d8d5509fd22a0c7cd110f79dc0
refs/heads/master
2021-08-30T22:45:45.542104
2017-12-18T22:26:32
2017-12-18T22:26:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,153
h
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2017, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! Representation of an AVC_video_descriptor //! //---------------------------------------------------------------------------- #pragma once #include "tsAbstractDescriptor.h" namespace ts { //! //! Representation of an AVC_video_descriptor. //! //! This MPG-defined descriptor is not defined in ISO/IEC 13818-1, //! ITU-T Rec. H.222.0. See its "Amendment 3: Transport of AVC video //! over ITU-T Rec. H.222.0 | ISO/IEC 13818-1 streams" (document W5771), //! section 2.6.54. //! class TSDUCKDLL AVCVideoDescriptor : public AbstractDescriptor { public: // Public members: uint8_t profile_idc; //!< Same as AVC concept. bool constraint_set0; //!< Same as AVC concept. bool constraint_set1; //!< Same as AVC concept. bool constraint_set2; //!< Same as AVC concept. uint8_t AVC_compatible_flags; //!< Same as AVC concept. uint8_t level_idc; //!< Same as AVC concept. bool AVC_still_present; //!< May contain still pictures. bool AVC_24_hour_picture; //!< May contain 25-hour pictures. //! //! Default constructor. //! AVCVideoDescriptor(); //! //! Constructor from a binary descriptor //! @param [in] bin A binary descriptor to deserialize. //! @param [in] charset If not zero, character set to use without explicit table code. //! AVCVideoDescriptor(const Descriptor& bin, const DVBCharset* charset = 0); // Inherited methods virtual void serialize(Descriptor&, const DVBCharset* = 0) const override; virtual void deserialize(const Descriptor&, const DVBCharset* = 0) override; virtual void buildXML(xml::Element*) const override; virtual void fromXML(const xml::Element*) override; //! //! Static method to display a descriptor. //! @param [in,out] display Display engine. //! @param [in] did Descriptor id. //! @param [in] payload Address of the descriptor payload. //! @param [in] size Size in bytes of the descriptor payload. //! @param [in] indent Indentation width. //! @param [in] tid Table id of table containing the descriptors. //! @param [in] pds Private Data Specifier. Used to interpret private descriptors. //! static void DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* payload, size_t size, int indent, TID tid, PDS pds); }; }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
320df1b17be0f7ebc04f9832ba6956219578d42d
8a274dffceab9d4e63fc0962e20fb7dab761555c
/CSES/Repetitions CSES.cpp
e84e4cac0ec1bbf1d344b228dd8cf16424d3c863
[]
no_license
mkp0/CP
669ce9ab399660d90d829f77b05f1462cd92ede5
80321819e46ebf4dd6512d6577add645da83708a
refs/heads/master
2023-06-01T22:07:36.006530
2021-06-25T21:41:23
2021-06-25T21:41:23
273,572,017
3
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
#include <bits/stdc++.h> #define ll long long #define pi (3.141592653589) #define all(x) (x).begin(), (x).end() #define vi vector<int> #define vll vector<long long> #define pii pair<int, int> #define pll pair<long long, long long> #define pb push_back #define mp make_pair #define S second #define loop(i, a, b, c) for (int i = (a); i <= (b); i = i + (c)) #define MOD 1e9 + 7 using namespace std; //stringMul String Multiplication , trie trie, zalgo Z-Algorithm, segTree Segmentation Tree, BS binary Search , subStr Substring , mrg Merge,SOE sieve of Era,permutate PermutationOfString ,graphi GraphIntialzation , graphBFS Graph BFS ,graphDFS graph DFS,exdGCD ExtendedGCD,nCR with Factorial ,axbyn ax+by=n /* I am gonna be the King of the Pirates */ void solve() { string s; cin >> s; int n = s.size(); int ans = 0; for (int i = 0; i < n;) { int j = i; int co = 0; while ((j < n) && (s[i] == s[j])) { co += 1; j++; } ans = max(co, ans); i = j; } cout << ans << "\n"; } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; while (t--) { solve(); } return 0; }
[ "shadymasum@gmail.com" ]
shadymasum@gmail.com
a162d87099d1269563d04bc3d51f85c6a83570a7
8959cdaf3e8f3259f303e50e2fd9e78b9ea318c7
/dorf.h
994810d504a71a977784148832a0435cf6884509
[]
no_license
FFaser/TW2AttackPlanner
4bf9da9c0d23bebfaba9ce1617863a5db0819fa9
95853c3ced072308edd7d5b9b2a711fec1b0c317
refs/heads/master
2021-04-12T10:48:53.056128
2016-07-27T13:39:30
2016-07-27T13:39:30
64,309,904
0
0
null
null
null
null
UTF-8
C++
false
false
1,986
h
#ifndef DORF_H #define DORF_H #include <QObject> //#include <QMetaEnum> #include <QStringList> #include <QList> #include <QMessageBox> enum eDorfState{ undefined, active , ontheway, eDorfState_MAX = ontheway}; enum eDorfMark{ empty = 0, mark1 = 1 << 0, mark2 = 1 << 1, mark3 = 1 << 2, mark4 = 1 << 3, mark5 = 1 << 4, mark6 = 1 << 5, mark7 = 1 << 6, mark8 = 1 << 7, mark9 = 1 << 8, mark10 = 1 << 9, eDorfMark_MAX = mark10}; namespace helpers { QList<eDorfMark> uintMarkToFlags(uint Mark); eDorfMark uintToeDorfMark(uint Mark); uint eDorfMarkToUint(eDorfMark Mark); } class Dorf { public: Dorf(); Dorf(QString DorfName, int X, int Y ); Dorf(QString DorfName, int X, int Y, uint Marks, int State ); Dorf(const Dorf *dorf); void set(QString DorfName, int X, int Y); void set(QString DorfName, int X, int Y, uint Marks, int State); bool isInitializedProperly(); QString getDorfName()const; int getX()const; int getY()const; void setDorfName(QString DorfName); void setX(int X); void setY(int Y); void setSpeed(double C); double getSpeed() const; void setSlowestSpeed(); void setNextSlowestMarksAndSpeedFrom(eDorfMark Mark); static bool equals(Dorf A, Dorf B); eDorfState getState() const ; eDorfMark getMark() const; uint getMarks() const; void setState(eDorfState DorfState); void setMark(eDorfMark Mark); //WARNING think how to init this void setMarks(uint DorfMark); static double eDorfMarkToSpeed(eDorfMark Mark); private: QString dorfName; int x; int y; bool isInitialized; eDorfState dorfState; eDorfMark tempDorfMark; uint dorfMarks; double c = 0; }; #endif // DORF_H
[ "polka@gmx.net" ]
polka@gmx.net
99b9b5b56a650644df32f65e654b563692404a80
a15950e54e6775e6f7f7004bb90a5585405eade7
/extensions/shell/browser/shell_app_delegate.cc
0023132d3786dbce980d730a6b6033583908f92b
[ "BSD-3-Clause" ]
permissive
whycoding126/chromium
19f6b44d0ec3e4f1b5ef61cc083cae587de3df73
9191e417b00328d59a7060fa6bbef061a3fe4ce4
refs/heads/master
2023-02-26T22:57:28.582142
2018-04-09T11:12:57
2018-04-09T11:12:57
128,760,157
1
0
null
2018-04-09T11:17:03
2018-04-09T11:17:03
null
UTF-8
C++
false
false
3,454
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 "extensions/shell/browser/shell_app_delegate.h" #include "content/public/browser/web_contents.h" #include "extensions/common/constants.h" #include "extensions/shell/browser/media_capture_util.h" #include "extensions/shell/browser/shell_extension_web_contents_observer.h" namespace extensions { ShellAppDelegate::ShellAppDelegate() { } ShellAppDelegate::~ShellAppDelegate() { } void ShellAppDelegate::InitWebContents(content::WebContents* web_contents) { ShellExtensionWebContentsObserver::CreateForWebContents(web_contents); } void ShellAppDelegate::RenderViewCreated( content::RenderViewHost* render_view_host) { // The views implementation of AppWindow takes focus via SetInitialFocus() // and views::WebView but app_shell is aura-only and must do it manually. content::WebContents::FromRenderViewHost(render_view_host)->Focus(); } void ShellAppDelegate::ResizeWebContents(content::WebContents* web_contents, const gfx::Size& size) { NOTIMPLEMENTED(); } content::WebContents* ShellAppDelegate::OpenURLFromTab( content::BrowserContext* context, content::WebContents* source, const content::OpenURLParams& params) { NOTIMPLEMENTED(); return NULL; } void ShellAppDelegate::AddNewContents(content::BrowserContext* context, content::WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture) { NOTIMPLEMENTED(); } content::ColorChooser* ShellAppDelegate::ShowColorChooser( content::WebContents* web_contents, SkColor initial_color) { NOTIMPLEMENTED(); return NULL; } void ShellAppDelegate::RunFileChooser( content::RenderFrameHost* render_frame_host, const content::FileChooserParams& params) { NOTIMPLEMENTED(); } void ShellAppDelegate::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback, const extensions::Extension* extension) { media_capture_util::GrantMediaStreamRequest( web_contents, request, callback, extension); } bool ShellAppDelegate::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, content::MediaStreamType type, const Extension* extension) { media_capture_util::VerifyMediaAccessPermission(type, extension); return true; } int ShellAppDelegate::PreferredIconSize() const { return extension_misc::EXTENSION_ICON_SMALL; } void ShellAppDelegate::SetWebContentsBlocked( content::WebContents* web_contents, bool blocked) { NOTIMPLEMENTED(); } bool ShellAppDelegate::IsWebContentsVisible( content::WebContents* web_contents) { return true; } void ShellAppDelegate::SetTerminatingCallback(const base::Closure& callback) { // TODO(jamescook): Should app_shell continue to close the app window // manually or should it use a browser termination callback like Chrome? } bool ShellAppDelegate::TakeFocus(content::WebContents* web_contents, bool reverse) { return false; } } // namespace extensions
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2e9cbe6a1fd9e9fbdcec136da0bd6f7ee82dca1b
4bad7578931dd47c38dc283aec7eb961be6e1f30
/src/wallet/api/pending_transaction.h
db0a52324ce20d62a108c01ae705bc0441328bd3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cyberstormdotmu/electroneum-classic
d034453071a3c9fa37f494c212e3ffc6d0effc9b
494bd2b5f9d9d759c10568e0326dde1737cefad6
refs/heads/master
2020-04-01T06:25:43.262217
2018-10-17T04:16:13
2018-10-17T04:16:13
152,947,188
0
0
null
2018-10-14T06:47:32
2018-10-14T06:47:32
null
UTF-8
C++
false
false
2,622
h
// Copyrights(c) 2018, The Electroneum Classic Project // Copyrights(c) 2017-2018, The Electroneum Project // Copyrights(c) 2014-2017, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "wallet/wallet2_api.h" #include "wallet/wallet2.h" #include <string> #include <vector> namespace Electroneum { class WalletImpl; class PendingTransactionImpl : public PendingTransaction { public: PendingTransactionImpl(WalletImpl &wallet); ~PendingTransactionImpl(); int status() const; std::string errorString() const; bool commit(const std::string &filename = "", bool overwrite = false); uint64_t amount() const; uint64_t dust() const; uint64_t fee() const; std::vector<std::string> txid() const; uint64_t txCount() const; // TODO: continue with interface; private: friend class WalletImpl; WalletImpl &m_wallet; int m_status; std::string m_errorString; std::vector<tools::wallet2::pending_tx> m_pending_tx; }; } namespace Bitelectroneum = Electroneum;
[ "vans_163@yahoo.com" ]
vans_163@yahoo.com
302ddf89f942e3ecefaf58d379ed1c55dd8eec7e
88a7edbe0a2a2a12de392da8fa43ace9fae7ace5
/StudioProject3/Base/Source/SkyBox/SkyBoxEntity.cpp
8339da52df4e0492341e8e3ce89a34c5477ff69d
[]
no_license
hotaru08/Studio-Proj-3
9fed81cf23d3fcabae33a6a1a90e717c89b455e8
f014fc00b3a4260ea82cd05aed7aee39233ed317
refs/heads/master
2021-01-16T21:24:43.742812
2017-08-30T02:14:57
2017-08-30T02:14:57
100,228,937
0
3
null
null
null
null
UTF-8
C++
false
false
3,797
cpp
#include "SkyBoxEntity.h" #include "MeshBuilder.h" #include "../EntityManager.h" #include "GraphicsManager.h" #include "RenderHelper.h" SkyBoxEntity::SkyBoxEntity(void) : size(1000.0f, 1000.0f, 1000.0f) , m_bBoundaryDefined(false) { } SkyBoxEntity::~SkyBoxEntity() { } void SkyBoxEntity::Update(double _dt) { // Does nothing here, can inherit & override or create your own version of this class :D } void SkyBoxEntity::Render() { MS& modelStack = GraphicsManager::GetInstance()->GetModelStack(); modelStack.PushMatrix(); // Front modelStack.PushMatrix(); modelStack.Translate(0, 0, -size.z / 2 - 250.f); modelStack.Scale(size.x, size.y, size.z); RenderHelper::RenderMesh(modelMesh[FRONT]); modelStack.PopMatrix(); // Back modelStack.PushMatrix(); modelStack.Rotate(180, 0, 1, 0); modelStack.Translate(0, 0, -size.z / 2 - 250.f); modelStack.Scale(size.x, size.y, size.z); RenderHelper::RenderMesh(modelMesh[BACK]); modelStack.PopMatrix(); // Left modelStack.PushMatrix(); modelStack.Rotate(-90, 0, 1, 0); modelStack.Translate(0, 0, -size.z / 2); modelStack.Scale(size.x + 500, size.y, size.z); RenderHelper::RenderMesh(modelMesh[LEFT]); modelStack.PopMatrix(); // Right modelStack.PushMatrix(); modelStack.Rotate(90, 0, 1, 0); modelStack.Translate(0, 0, -size.z / 2); modelStack.Scale(size.x + 500, size.y, size.z); RenderHelper::RenderMesh(modelMesh[RIGHT]); modelStack.PopMatrix(); // Top modelStack.PushMatrix(); modelStack.Rotate(90, 1, 0, 0); modelStack.Translate(0, 0, -size.z / 2); modelStack.Rotate(-90, 0, 0, 1); modelStack.Scale(size.x + 500, size.y, size.z); RenderHelper::RenderMesh(modelMesh[TOP]); modelStack.PopMatrix(); // Bottom modelStack.PushMatrix(); modelStack.Rotate(-90, 1, 0, 0); modelStack.Translate(0, 0, -size.z / 2); modelStack.Rotate(90, 0, 0, 1); modelStack.Scale(size.x, size.y, size.z); RenderHelper::RenderMesh(modelMesh[BOTTOM]); modelStack.PopMatrix(); modelStack.PopMatrix(); } // Set a mesh to this class void SkyBoxEntity::SetMesh(const int _side, Mesh* _modelMesh) { modelMesh[_side] = _modelMesh; } Vector3 SkyBoxEntity::GetBoundary(void) { if (!m_bBoundaryDefined) { boundary = Vector3( position.x - (size.x*scale.x) / 2.0f, position.y - (size.y*scale.y) / 2.0f, position.z - (size.z*scale.z) / 2.0f); m_bBoundaryDefined = true; } return boundary; }; SkyBoxEntity* Create::SkyBox( const std::string& _meshName0, const std::string& _meshName1, const std::string& _meshName2, const std::string& _meshName3, const std::string& _meshName4, const std::string& _meshName5) { Mesh* modelMesh0 = MeshBuilder::GetInstance()->GetMesh(_meshName0); if (modelMesh0 == nullptr) return nullptr; Mesh* modelMesh1 = MeshBuilder::GetInstance()->GetMesh(_meshName1); if (modelMesh1 == nullptr) return nullptr; Mesh* modelMesh2 = MeshBuilder::GetInstance()->GetMesh(_meshName2); if (modelMesh2 == nullptr) return nullptr; Mesh* modelMesh3 = MeshBuilder::GetInstance()->GetMesh(_meshName3); if (modelMesh3 == nullptr) return nullptr; Mesh* modelMesh4 = MeshBuilder::GetInstance()->GetMesh(_meshName4); if (modelMesh4 == nullptr) return nullptr; Mesh* modelMesh5 = MeshBuilder::GetInstance()->GetMesh(_meshName5); if (modelMesh5 == nullptr) return nullptr; SkyBoxEntity* result = new SkyBoxEntity(); result->SetMesh(SkyBoxEntity::FRONT, modelMesh0); result->SetMesh(SkyBoxEntity::BACK, modelMesh1); result->SetMesh(SkyBoxEntity::LEFT, modelMesh2); result->SetMesh(SkyBoxEntity::RIGHT, modelMesh3); result->SetMesh(SkyBoxEntity::TOP, modelMesh4); result->SetMesh(SkyBoxEntity::BOTTOM, modelMesh5); EntityManager::GetInstance()->AddEntity(result); return result; }
[ "lzyjeann@gmail.com" ]
lzyjeann@gmail.com
5c1ffd4684739b0960fb93ffad4d5db24a329b74
c0c71f93369449a23a97643a19801665d0b16c47
/arduino_robot.ino
af41576573bbe78708f94dfee554fe9443cdb9cb
[]
no_license
Kounouklas92/Arduino-robot
72457f63651629da496ba89d9b28b028d4b6a669
a3c187e1d2940b0cafa1b15cb8d8a3ed37befa49
refs/heads/main
2023-01-29T07:50:49.554394
2020-12-14T00:02:27
2020-12-14T00:02:27
321,175,989
0
0
null
null
null
null
UTF-8
C++
false
false
4,342
ino
#define sensor A0 // Sharp IR GP2Y0A41SK0F #include <Servo.h> float volts; const int motorR1 = 6; const int motorR2 = 5; const int motorL1 = 11; const int motorL2 = 10; const int servo = 9; void stop1(); void forward(); void backward(); void right(); void left(); Servo myservo; unsigned int rightDistance; unsigned int leftDistance; int distance ; int pos; // for servo, 90 deg looking forward int incomingData; char mode = 'm'; // m for manual, a for automatic int vSpeed = 200; void setup(){ //Define inputs and outputs pinMode(motorR1, OUTPUT); pinMode(motorR2, OUTPUT); pinMode(motorL1, OUTPUT); pinMode(motorL2, OUTPUT); myservo.attach(9); myservo.write(pos); Serial.begin(9600); } void loop(){ if(Serial.available() > 0){ // read the incoming byte: incomingData = Serial.read(); if (incomingData == 'A'){mode = 'a'; } if (incomingData == 'M'){mode = 'm'; stop1(); pos=90;; myservo.write(pos); } } //Change speed if (incomingData == '0'){ vSpeed=0;} else if (incomingData == '1'){ vSpeed=100;} else if (incomingData == '2'){ vSpeed=180;} else if (incomingData == '3'){ vSpeed=200;} else if (incomingData == '4'){ vSpeed=255;} //Manual mode if (mode == 'm'){ if (incomingData=='F'){ forward(); } else if (incomingData=='B'){ backward(); } else if (incomingData=='R'){ right(); } else if (incomingData=='L'){ left(); } else if (incomingData=='S'){ stop1(); } } //Automatic mode else if (mode == 'a'){ // distance sensor volts = analogRead(sensor)*0.0048828125; distance = 13*pow(volts, -1); if (distance <= 10){ Serial.println(distance); stop1(); for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' delay(20); // waits 20ms for the servo to reach the position } //Read new distance from the right side volts = analogRead(sensor)*0.0048828125; distance = 13*pow(volts, -1);// leftDistance = distance; delay(100); //Now look left for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' delay(20); // waits 20ms for the servo to reach the position } //Read new distance from the left side volts = analogRead(sensor)*0.0048828125; distance = 13*pow(volts, -1); rightDistance = distance; delay(100); pos = 90; // look forward again myservo.write(pos); //Finally compare left and right distances and make the best turn decision if (leftDistance > rightDistance){ left(); delay(500); } else if (leftDistance < rightDistance){ right(); delay(500); } else{ //distances is equal backward(); delay(1000);// Go back for 1 sec left(); // and turn left delay(500); } }else{ forward(); } } } //Movement functions void forward(){ analogWrite(motorR1, vSpeed); analogWrite(motorR2, 0); analogWrite(motorL1, vSpeed); analogWrite(motorL2, 0); } void backward(){ analogWrite(motorR1, 0); analogWrite(motorR2, vSpeed); analogWrite(motorL1, 0); analogWrite(motorL2, vSpeed); } void right(){ analogWrite(motorR1, 0); analogWrite(motorR2, vSpeed); analogWrite(motorL1, vSpeed); analogWrite(motorL2, 0); } void left(){ analogWrite(motorR1, vSpeed); analogWrite(motorR2, 0); analogWrite(motorL1, 0); analogWrite(motorL2, vSpeed); } void stop1(){ analogWrite(motorR1, 0); analogWrite(motorR2, 0); analogWrite(motorL1, 0); analogWrite(motorL2, 0); }
[ "noreply@github.com" ]
Kounouklas92.noreply@github.com
674ce9fcb1c0227fcd7fb451ba0055a9b0afd5c9
49cfc3f1a96b3f75adf74821342999a20da3e04d
/examples/system_process_pipes.cpp
1726dd571310164c58ac69d96b2ec72e241d0bc2
[ "MIT" ]
permissive
mrexodia/CppCommon
bfb4456b984ceea64dd98853816f388c29bfe006
422bec80be2412e909539b73be40972ecc8acf83
refs/heads/master
2020-05-17T15:10:23.069691
2019-04-25T14:36:20
2019-04-25T14:36:20
183,780,482
1
0
MIT
2019-04-27T14:05:08
2019-04-27T14:05:08
null
UTF-8
C++
false
false
1,342
cpp
/*! \file system_process_pipes.cpp \brief Process pipes example \author Ivan Shynkarenka \date 07.12.2016 \copyright MIT License */ #include "system/environment.h" #include "system/process.h" #include <algorithm> #include <iostream> #include <string> int main(int argc, char** argv) { if (argc > 1) { std::string message = "test message"; std::string endline = CppCommon::Environment::EndLine(); std::cout << "Executing child process..." << std::endl; CppCommon::Pipe input; CppCommon::Pipe output; CppCommon::Pipe error; CppCommon::Process child = CppCommon::Process::Execute(argv[1], nullptr, nullptr, nullptr, &input, &output, &error); input.Write(message); input.Write(endline); std::string out = output.ReadAllText(); std::string err = error.ReadAllText(); int result = child.Wait(); std::cout << "Executed child process! Result = " << result << std::endl; std::cout << "stdout: " << out << std::endl; std::cout << "stderr: " << err << std::endl; return 0; } std::string line; if (getline(std::cin, line)) { std::cout << line << std::endl; std::reverse(line.begin(), line.end()); std::cerr << line << std::endl; } return 123; }
[ "chronoxor@gmail.com" ]
chronoxor@gmail.com
70ffea673f3095f8e9d9a01fbf004e0e19fa15a4
aa66004b533a8d9e8f8ce175d4df6fce1b3137f4
/src/SmartPointers/chrono.cpp
2eef54d2d389a28cbcab33a7adf4063d9a9c1ea2
[]
no_license
ricleal/CppTests
c036ba235765f742504195dba61b85ff752de337
84ac0253604ac02776498ec2a5f05f3e2dda7df9
refs/heads/master
2021-06-25T17:50:13.894692
2017-03-22T18:10:40
2017-03-22T18:10:40
13,873,119
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
#include <iostream> #include <vector> #include <numeric> #include <chrono> volatile int sink; int main_chrono() { for (auto size = 1ull; size < 1000000000ull; size *= 100) { // record start time auto start = std::chrono::system_clock::now(); // do some work std::vector<int> v(size, 42); sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect // record end time auto end = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end-start; std::cout << "Time to fill and iterate a vector of " << size << " ints : " << diff.count() << " s\n"; } }
[ "ricleal@gmail.com" ]
ricleal@gmail.com
0d88ad45f6f55023f6474fd2ceadb20bf1cb2551
b9d8b5bd3dc3c9bd6f3e84670c7fdfb004b661f5
/object.h
960ac120ef1d84d9ce290cf049904db9faea1103
[]
no_license
alex-peng/AnimVis
a6440a69ca73f92e1d07f317bbf0e48b82fc635f
f2e5d788ddc42d1d2e79394e93f9518a517358ed
refs/heads/master
2016-09-06T15:59:39.772963
2013-04-19T00:37:21
2013-04-19T00:37:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
846
h
#ifndef _OBJECT_H_ #define _OBJECT_H_ namespace AMT { typedef enum { WIREFRAME = 0, GOURAUD, TEXTURED } TRenderMode; class CBoundingBox { public: float center[3]; float size; CBoundingBox() : size(0.0f) {}; }; class CRenderObject { public: bool m_visiable; bool m_VisiableTest; bool m_ShaderReady; float alpha; // For transparent display float beginx, beginy; /* position of mouse */ float position[3]; float m_VisibiltyTime; float quat[4]; CBoundingBox boundingBox; CRenderObject( bool _visiable = true, float _alpha = 1.0f ); void ResetPosition(); virtual void draw() = 0; virtual void destroyMyself() = 0; virtual unsigned int getFaceNumber() = 0; virtual void ChangeRenderMode(TRenderMode rm ) = 0; virtual void SetShader() = 0; virtual unsigned int getVisFaceNumber() { return getFaceNumber(); } }; } #endif
[ "mipeng@vt.edu" ]
mipeng@vt.edu
b06522065a944101f9f7507fba882738e800c03c
ca36def64eba15232bd8eb886353517f43610491
/tensorflow/core/profiler/rpc/client/remote_profiler_session_manager.cc
87575ee67a11e24d696b3ea689a1b9b5ff406bba
[ "Apache-2.0" ]
permissive
pulmo/tensorflow
a82d09948bf0678fcb2152ac13527d543edab8ea
ce321f0c9d09936f3084bfb93d0812c7ffa174e6
refs/heads/master
2022-12-25T03:38:47.564304
2020-09-30T20:39:38
2020-09-30T20:45:35
300,059,104
1
0
Apache-2.0
2020-09-30T20:50:07
2020-09-30T20:50:06
null
UTF-8
C++
false
false
6,476
cc
/* Copyright 2020 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 "tensorflow/core/profiler/rpc/client/remote_profiler_session_manager.h" #include <cstddef> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tensorflow/core/platform/env_time.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/rpc/client/save_profile.h" #include "tensorflow/core/profiler/utils/time_utils.h" #include "tensorflow/core/protobuf/error_codes.pb.h" namespace tensorflow { namespace profiler { namespace { constexpr uint64 kMaxEvents = 1000000; // TODO(yisitu) merge with the implementation in capture_profile. void PopulateProfileRequest(const RemoteProfilerSessionManagerOptions& options, absl::string_view session_id, absl::string_view host_name, ProfileRequest* request) { request->set_max_events(kMaxEvents); request->set_repository_root(options.profiler_options().repository_path()); request->set_session_id(session_id.data(), session_id.size()); request->add_tools("trace_viewer"); request->add_tools("op_profile"); request->add_tools("input_pipeline"); request->add_tools("kernel_stats"); request->add_tools("memory_viewer"); request->add_tools("memory_profile"); request->add_tools("overview_page"); request->add_tools("pod_viewer"); request->add_tools("tensorflow_stats"); request->set_host_name(host_name.data(), host_name.size()); *request->mutable_opts() = options.profiler_options(); request->set_duration_ms(options.profiler_options().duration_ms()); } } // namespace /*static*/ std::unique_ptr<RemoteProfilerSessionManager> RemoteProfilerSessionManager::Create( const RemoteProfilerSessionManagerOptions& options, tensorflow::Status& out_status, AddressResolver resolver) { VLOG(1) << "Creating a RemoteProfilerSessionManager."; auto session_manager = absl::WrapUnique(new RemoteProfilerSessionManager(options, resolver)); out_status = session_manager->Init(); if (!out_status.ok()) { return nullptr; } return session_manager; } RemoteProfilerSessionManager::RemoteProfilerSessionManager( RemoteProfilerSessionManagerOptions options, AddressResolver resolver) : options_(std::move(options)) { if (resolver) { resolver_ = std::move(resolver); } else { resolver_ = [](absl::string_view addr) { return std::string(addr); }; } } RemoteProfilerSessionManager::~RemoteProfilerSessionManager() { VLOG(2) << "Destroying RemoteProfilerSessionManager."; } Status RemoteProfilerSessionManager::Init() { mutex_lock lock(mutex_); VLOG(1) << "SessionManager initializing."; // TODO(b/169482824) Move validation to call site. Status status = ValidateOptionsLocked(); if (!status.ok()) { LOG(ERROR) << status; return status; } std::string session_id = GetCurrentTimeStampAsString(); const absl::Time session_created_ts = absl::FromUnixNanos(options_.session_creation_timestamp_ns()); const absl::Time deadline = session_created_ts + absl::Milliseconds(options_.max_session_duration_ms()); LOG(INFO) << "Deadline set to " << deadline << " because max_session_duration_ms was " << options_.max_session_duration_ms() << " and session_creation_timestamp_ns was " << options_.session_creation_timestamp_ns() << " [" << session_created_ts << "]"; // Prepare a list of clients. clients_.reserve(options_.service_addresses_size()); for (auto& service_addr : options_.service_addresses()) { std::string resolved_service_addr = resolver_(service_addr); ProfileRequest profile_request; PopulateProfileRequest(options_, session_id, resolved_service_addr, &profile_request); // Creation also issues Profile RPC asynchronously. auto client = RemoteProfilerSession::Create( std::move(resolved_service_addr), deadline, std::move(profile_request)); clients_.push_back(std::move(client)); } LOG(INFO) << absl::StrFormat("Issued Profile gRPC to %u clients", clients_.size()); return Status::OK(); } Status RemoteProfilerSessionManager::ValidateOptionsLocked() { if (!options_.service_addresses_size()) { return errors::InvalidArgument("No service addresses specified."); } if (options_.profiler_options().duration_ms() == 0) { if (options_.max_session_duration_ms() != 0) { return errors::InvalidArgument( "If local profiler duration is unbounded, profiling session duration " "must be unbounded."); } } if (options_.max_session_duration_ms() < options_.profiler_options().duration_ms()) { return errors::InvalidArgument( "The maximum profiling session duration must be greater than or equal " "to the local profiler duration."); } return Status::OK(); } std::vector<RemoteProfilerSessionManager::Response> RemoteProfilerSessionManager::WaitForCompletion() { mutex_lock lock(mutex_); std::vector<RemoteProfilerSessionManager::Response> remote_responses; remote_responses.reserve(clients_.size()); for (auto& client : clients_) { remote_responses.emplace_back(); auto* profile_response = &remote_responses.back().profile_response; Status& status = remote_responses.back().status; std::string* service_addr = &remote_responses.back().service_addr; *profile_response = client->WaitForCompletion(status); *service_addr = client->GetServiceAddress(); } return remote_responses; } } // namespace profiler } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
8a11b3d42521dbedf29fc78c99c3d89ea2a75254
099f2181439ba42a5fbeb774a182faf3db9bad8c
/problems/347-top-k-frequent-elements.cpp
33e1fca42782bcc10bde6f4cdfdfd49875201170
[]
no_license
luchenqun/leet-code
76a9193e315975b094225d15f0281d0d462c2ee7
38b3f660e5173ad175b8451a730bf4ee3f03a66b
refs/heads/master
2021-07-09T09:49:36.068938
2019-01-15T07:15:22
2019-01-15T07:15:22
102,130,497
1
0
null
null
null
null
UTF-8
C++
false
false
893
cpp
/* * [347] Top K Frequent Elements * * https://leetcode-cn.com/problems/top-k-frequent-elements/description/ * https://leetcode.com/problems/top-k-frequent-elements/discuss/ * * algorithms * Medium (46.38%) * Total Accepted: 561 * Total Submissions: 1.2K * Testcase Example: '[1,1,1,2,2,3]\n2' * * 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 * 例如, * 给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。 * 注意: * 你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。 * 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 */ #include <iostream> #include <string> using namespace std; class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { } }; int main() { Solution s; return 0; }
[ "luchenqun@juzix.io" ]
luchenqun@juzix.io
289137a2ffdae5eb87d99216fdd96ddb5bdfa0bd
9eacc869fa1d8f8b2a2dfb6c3dba613e41992f72
/app/music/music/bottom/bottomwidgets.cpp
13cc2a802cc03ef727dd3cabeb65d9fba9476c13
[ "Apache-2.0" ]
permissive
hyperkin-game/hyperkin-gb
9093c4e29212924cdbb7492e7e13002105f33801
e333185e8a2a4f5c90e84dca515e335e62565a3b
refs/heads/main
2023-04-27T18:17:09.675136
2021-05-14T10:20:59
2021-05-14T10:20:59
331,823,448
6
1
null
null
null
null
UTF-8
C++
false
false
6,046
cpp
#include "bottomwidgets.h" #include "constant.h" #include <QHBoxLayout> #ifdef DEVICE_EVB int playButton_size = 100; int bottom_height = 150; int bottom_spacing = 25; int layout3_size = 70; int layout3_temp = 25; int progress_slider_height = 20; #else int playButton_size = 55; int bottom_height = 80; int bottom_spacing = 20; int layout3_size = 45; int layout3_temp = 10; int progress_slider_height = 10; #endif BottomWidgets::BottomWidgets(QWidget *parent) : BaseWidget(parent) , m_duration(-1) { setBackgroundColor(54, 54, 54); initLayout(); initConnection(); } void BottomWidgets::initLayout() { QVBoxLayout *layout = new QVBoxLayout; QHBoxLayout *mainLayout = new QHBoxLayout; /*----------------- position layout -------------------*/ m_labPosition = new QLabel(this); m_labPosition->setAlignment(Qt::AlignCenter); BaseWidget::setWidgetFontSize(m_labPosition, font_size_large); /* set the whole widget height = this label height + baseSlider height */ m_labPosition->setFixedHeight(bottom_height); /*----------------- play control button ----------------*/ m_btnNext = new FlatButton(this); m_btnPrevious = new FlatButton(this); m_btnPlay = new FlatButton(this); m_btnNext->setFixedSize(playButton_size, playButton_size); m_btnPrevious->setFixedSize(playButton_size, playButton_size); m_btnPlay->setFixedSize(playButton_size, playButton_size); m_btnNext->setBackgroundImage(":/image/music/btn_next (2).png"); m_btnPrevious->setBackgroundImage(":/image/music/btn_previous (2).png"); m_btnPlay->setBackgroundImage(":/image/music/btn_play (2).png"); QHBoxLayout *playControlLayout = new QHBoxLayout; playControlLayout->addWidget(m_btnPrevious); playControlLayout->addWidget(m_btnPlay); playControlLayout->addWidget(m_btnNext); playControlLayout->setMargin(0); playControlLayout->setSpacing(bottom_spacing); /*----------------- volume、playmode ----------------*/ m_volWid = new VolWidget(this); m_btnPlayMode = new FlatButton(this); m_btnPlayMode->setFixedSize(layout3_size, layout3_size); m_btnPlayMode->setBackgroundImage(":/image/music/btn_mode_random.png"); m_btnRefresh = new FlatButton(this); m_btnRefresh->setFixedSize(layout3_size, layout3_size); m_btnRefresh->setBackgroundImage(":/image/music/btn_refresh.png"); m_btnRefresh->setVisible(false); QHBoxLayout *layout3 = new QHBoxLayout; layout3->addStretch(0); layout3->addWidget(m_btnPlayMode); layout3->addWidget(m_volWid); layout3->addStretch(0); layout3->setMargin(0); layout3->setSpacing(bottom_spacing); /*-- whole layout contains control layout and progressSlider --*/ mainLayout->addWidget(m_labPosition, 1); mainLayout->addLayout(playControlLayout, 1); mainLayout->addLayout(layout3, 1); mainLayout->setMargin(0); mainLayout->setSpacing(0); m_progressSlider = new BaseSlider(Qt::Horizontal, this); m_progressSlider->setFixedHeight(progress_slider_height); layout->addWidget(m_progressSlider); layout->addLayout(mainLayout); layout->setMargin(0); layout->setSpacing(0); layout->setContentsMargins(15,15,15,0); setLayout(layout); } void BottomWidgets::initConnection() { connect(m_btnPrevious, SIGNAL(longPressedEvent()), this, SIGNAL(lastLongPressed())); connect(m_btnNext, SIGNAL(longPressedEvent()), this, SIGNAL(nextLongPressed())); connect(m_btnNext, SIGNAL(clicked(bool)), this, SIGNAL(nextClick())); connect(m_btnPrevious, SIGNAL(clicked(bool)), this, SIGNAL(lastClick())); connect(m_btnPlay, SIGNAL(clicked(bool)), this, SIGNAL(playPauseClick())); connect(m_progressSlider, SIGNAL(sig_sliderPositionChanged(int)), this, SIGNAL(progressSliderPositionChanged(int))); connect(m_volWid, SIGNAL(sig_valueChanged(int)), this, SIGNAL(volumeChanged(int))); connect(m_btnPlayMode, SIGNAL(clicked(bool)), this, SIGNAL(playModeClick())); connect(m_btnRefresh, SIGNAL(clicked(bool)), this, SIGNAL(refreshClick())); } void BottomWidgets::setPauseStyle() { m_btnPlay->setBackgroundImage(":/image/music/btn_pause (2).png"); } void BottomWidgets::setPlayStyle() { m_btnPlay->setBackgroundImage(":/image/music/btn_play (2).png"); } void BottomWidgets::setPositionLabel(QTime currentTime, QTime totalTime) { QString ret; ret.append(currentTime.toString("mm:ss")).append("/").append(totalTime.toString("mm:ss")); m_labPosition->setText(ret); } void BottomWidgets::updateVolumeSliderValue(int value) { m_volWid->updateSlider(value); } void BottomWidgets::onPlayerDurationChanged(qint64 duration) { m_duration = duration; m_progressSlider->setRange(0, duration); } void BottomWidgets::onPlayerPositionChanged(qint64 position) { QTime currentTime((position % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60), (position % (1000 * 60 * 60)) / (1000 * 60), (position % (1000 * 60)) / 1000); QTime totalTime((m_duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60), (m_duration % (1000 * 60 * 60)) / (1000 * 60), (m_duration % (1000 * 60)) / 1000); setPositionLabel(currentTime, totalTime); m_progressSlider->setValue(position); } void BottomWidgets::updatePlayModeIcon(PlayMode playMode) { switch (playMode) { case PlayRandom: m_btnPlayMode->setBackgroundImage(":/image/music/btn_mode_random.png"); break; case PlayOneCircle: m_btnPlayMode->setBackgroundImage(":/image/music/btn_mode_single.png"); break; case PlayInOrder: m_btnPlayMode->setBackgroundImage(":/image/music/btn_mode_list.png"); break; } } void BottomWidgets::setOriginState() { m_progressSlider->setValue(0); setPositionLabel(QTime(0, 0, 0), QTime(0, 0, 0)); }
[ "stanley@bte.com.tw" ]
stanley@bte.com.tw
ffcb6d14462bcb2161c1b5b9e96fec2627493b1d
813d9380b3fbf66a0d344937a6be52f408b54078
/runtime/regiontemplates/examples/RTPipelineBundle/HelloWorld.cpp
55a4a0dab31cf60ad5f7c3bc862082531a4e0aee
[]
no_license
SBU-BMI/region-templates
6b63fab2809ac281e458053069d26782d04cd1e5
ab311b70eaeee3353ae09e1b8ba694e29d4d982d
refs/heads/master
2023-03-05T03:26:03.580106
2017-07-13T03:02:35
2017-07-13T03:02:35
35,566,013
5
6
null
2017-04-17T20:04:58
2015-05-13T18:10:24
C++
UTF-8
C++
false
false
2,639
cpp
/* * HelloWorld.cpp * * Created on: Feb 15, 2012 * Author: george */ #include <sstream> #include <stdlib.h> #include <iostream> #include "FileUtils.h" #include "RegionTemplate.h" #include "RegionTemplateCollection.h" #include "SysEnv.h" #include "Segmentation.h" #define NUM_PIPELINE_INSTANCES 1 void parseInputArguments(int argc, char**argv, std::string &inputFolder){ // Used for parameters parsing for(int i = 0; i < argc-1; i++){ if(argv[i][0] == '-' && argv[i][1] == 'i'){ inputFolder = argv[i+1]; } } } RegionTemplateCollection* RTFromFiles(std::string inputFolderPath){ // Search for input files in folder path FileUtils fileUtils("tif"); std::vector<std::string> fileList; fileUtils.traverseDirectoryRecursive(inputFolderPath, fileList); RegionTemplateCollection* rtCollection = new RegionTemplateCollection(); rtCollection->setName("inputimage"); std::cout << "Input Folder: "<< inputFolderPath <<std::endl; // Create one region template instance for each input data file // (creates representations without instantiating them) for(int i = 0; i < fileList.size(); i++){ DenseDataRegion2D *ddr2d = new DenseDataRegion2D(); ddr2d->setName("BGR"); ddr2d->setInputType(DataSourceType::FILE_SYSTEM); // ddr2d->setOutputType(-1); // ddr2d->setOutputType(DataSourceType::DATA_SPACES); ddr2d->setId(fileList[i]); // ddr2d->setInBds(new FileSystemImageDataSource(fileList[i])); RegionTemplate *rt = new RegionTemplate(); rt->setName("tile"); rt->insertDataRegion(ddr2d); rtCollection->addRT(rt); } return rtCollection; } int main (int argc, char **argv){ // Folder when input data images are stored std::string inputFolderPath; std::vector<RegionTemplate *> inputRegionTemplates; RegionTemplateCollection *rtCollection; parseInputArguments(argc, argv, inputFolderPath); // Handler to the distributed execution system environment SysEnv sysEnv; // Tell the system which libraries should be used sysEnv.startupSystem(argc, argv, "libcomponentsrtbundle.so"); // Create region templates description without instantiating data rtCollection = RTFromFiles(inputFolderPath); // Build application dependency graph // Instantiate application dependency graph for(int i = 0; i < rtCollection->getNumRTs(); i++){ Segmentation *seg = new Segmentation(); seg->addRegionTemplateInstance(rtCollection->getRT(i), rtCollection->getRT(i)->getName()); sysEnv.executeComponent(seg); } // End Create Dependency Graph sysEnv.startupExecution(); // Finalize all processes running and end execution sysEnv.finalizeSystem(); delete rtCollection; return 0; }
[ "george@Georges-MacBook-Pro-2.local" ]
george@Georges-MacBook-Pro-2.local
824ed6266cacf3f5227db633302ca5b83f4bd47c
fbc3ee4467922e3a01aaef61af33ad0a79e6a8df
/Algorithms/sorting/bubble_Sort.cpp
1d092c8838a990ea7ca35e3213e0d27a68a0bd37
[]
no_license
snh3003/CB-Master-Course
9c5026c65ae02dd6114946981f08faff97501fc1
fd6599fce1463c68fc4c2c1fa3552718fdd43b24
refs/heads/master
2023-08-24T12:41:38.067743
2021-09-30T07:17:36
2021-09-30T07:17:36
288,263,538
0
0
null
null
null
null
UTF-8
C++
false
false
633
cpp
#include<bits/stdc++.h> using namespace std; void bubble_sort(vector<int> &v, int n){ // run a loop from 0 to n-1 as the last element always gets sorted for(int i=0; i<(n-1); i++){ // loop runs from 0 to (n-i-1) to check the unsorted part for(int j=0; j<(n-i-1); j++){ if(v[j] > v[j+1]){ // pairwise swap swap(v[j], v[j+1]); } } } } int main(){ int n, ip; cin>>n; vector<int> v; for(int i=0; i<n; i++){ cin>>ip; v.push_back(ip); } bubble_sort(v, n); for(auto x: v){ cout<<x<<" "; } }
[ "shahsama542@gmail.com" ]
shahsama542@gmail.com
a66fcd830da454746793f7f4179157b7febcd454
563579e51032a07492f11e9a3b5fc5e1e128f523
/hphp/third_party/folly/folly/io/IOBufQueue.h
71966f49cb1819f5cc332cf9b4e8a4253bfa4c27
[ "Apache-2.0", "Zend-2.0", "LicenseRef-scancode-unknown-license-reference", "PHP-3.01" ]
permissive
sachintaware/hiphop-php
6a54d4d71bcd2e0b18fddb5a6ecf1cf562b8117e
d95ca0dc9ad160cc1dfd691ecc1245a5a7798327
refs/heads/master
2021-01-16T18:41:50.061432
2013-08-15T21:17:24
2013-08-15T22:19:36
12,209,930
1
0
null
null
null
null
UTF-8
C++
false
false
8,019
h
/* * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FOLLY_IO_IOBUF_QUEUE_H #define FOLLY_IO_IOBUF_QUEUE_H #include "folly/io/IOBuf.h" #include <stdexcept> #include <string> namespace folly { /** * An IOBufQueue encapsulates a chain of IOBufs and provides * convenience functions to append data to the back of the chain * and remove data from the front. * * You may also prepend data into the headroom of the first buffer in the * chain, if any. */ class IOBufQueue { public: struct Options { Options() : cacheChainLength(false) { } bool cacheChainLength; }; /** * Commonly used Options, currently the only possible value other than * the default. */ static Options cacheChainLength() { Options options; options.cacheChainLength = true; return options; } explicit IOBufQueue(const Options& options = Options()); /** * Return a space to prepend bytes and the amount of headroom available. */ std::pair<void*, uint32_t> headroom(); /** * Indicate that n bytes from the headroom have been used. */ void markPrepended(uint32_t n); /** * Prepend an existing range; throws std::overflow_error if not enough * room. */ void prepend(const void* buf, uint32_t n); /** * Add a buffer or buffer chain to the end of this queue. The * queue takes ownership of buf. * * If pack is true, we try to reduce wastage at the end of this queue * by copying some data from the first buffers in the buf chain (and * releasing the buffers), if possible. If pack is false, we leave * the chain topology unchanged. */ void append(std::unique_ptr<folly::IOBuf>&& buf, bool pack=false); /** * Add a queue to the end of this queue. The queue takes ownership of * all buffers from the other queue. */ void append(IOBufQueue& other, bool pack=false); void append(IOBufQueue&& other, bool pack=false) { append(other, pack); // call lvalue reference overload, above } /** * Copy len bytes, starting at buf, to the end of this queue. * The caller retains ownership of the source data. */ void append(const void* buf, size_t len); /** * Copy a string to the end of this queue. * The caller retains ownership of the source data. */ void append(const std::string& buf) { append(buf.data(), buf.length()); } /** * Append a chain of IOBuf objects that point to consecutive regions * within buf. * * Just like IOBuf::wrapBuffer, this should only be used when the caller * knows ahead of time and can ensure that all IOBuf objects that will point * to this buffer will be destroyed before the buffer itself is destroyed; * all other caveats from wrapBuffer also apply. * * Every buffer except for the last will wrap exactly blockSize bytes. * Importantly, this method may be used to wrap buffers larger than 4GB. */ void wrapBuffer(const void* buf, size_t len, uint32_t blockSize=(1U << 31)); // default block size: 2GB /** * Obtain a writable block of contiguous bytes at the end of this * queue, allocating more space if necessary. The amount of space * reserved will be at least min. If min contiguous space is not * available at the end of the queue, and IOBuf with size newAllocationSize * is appended to the chain and returned. The actual available space * may be larger than newAllocationSize, but will be truncated to max, * if specified. * * If the caller subsequently writes anything into the returned space, * it must call the postallocate() method. * * @return The starting address of the block and the length in bytes. * * @note The point of the preallocate()/postallocate() mechanism is * to support I/O APIs such as Thrift's TAsyncSocket::ReadCallback * that request a buffer from the application and then, in a later * callback, tell the application how much of the buffer they've * filled with data. */ std::pair<void*,uint32_t> preallocate( uint32_t min, uint32_t newAllocationSize, uint32_t max = std::numeric_limits<uint32_t>::max()); /** * Tell the queue that the caller has written data into the first n * bytes provided by the previous preallocate() call. * * @note n should be less than or equal to the size returned by * preallocate(). If n is zero, the caller may skip the call * to postallocate(). If n is nonzero, the caller must not * invoke any other non-const methods on this IOBufQueue between * the call to preallocate and the call to postallocate(). */ void postallocate(uint32_t n); /** * Obtain a writable block of n contiguous bytes, allocating more space * if necessary, and mark it as used. The caller can fill it later. */ void* allocate(uint32_t n) { void* p = preallocate(n, n).first; postallocate(n); return p; } /** * Split off the first n bytes of the queue into a separate IOBuf chain, * and transfer ownership of the new chain to the caller. The IOBufQueue * retains ownership of everything after the split point. * * @warning If the split point lies in the middle of some IOBuf within * the chain, this function may, as an implementation detail, * clone that IOBuf. * * @throws std::underflow_error if n exceeds the number of bytes * in the queue. */ std::unique_ptr<folly::IOBuf> split(size_t n); /** * Similar to IOBuf::trimStart, but works on the whole queue. Will * pop off buffers that have been completely trimmed. */ void trimStart(size_t amount); /** * Similar to IOBuf::trimEnd, but works on the whole queue. Will * pop off buffers that have been completely trimmed. */ void trimEnd(size_t amount); /** * Transfer ownership of the queue's entire IOBuf chain to the caller. */ std::unique_ptr<folly::IOBuf> move() { chainLength_ = 0; return std::move(head_); } /** * Access */ const folly::IOBuf* front() const { return head_.get(); } /** * returns the first IOBuf in the chain and removes it from the chain * * @return first IOBuf in the chain or nullptr if none. */ std::unique_ptr<folly::IOBuf> pop_front(); /** * Total chain length, only valid if cacheLength was specified in the * constructor. */ size_t chainLength() const { if (!options_.cacheChainLength) { throw std::invalid_argument("IOBufQueue: chain length not cached"); } return chainLength_; } /** * Returns true iff the IOBuf chain length is 0. */ bool empty() const { return !head_ || head_->empty(); } const Options& options() const { return options_; } /** * Clear the queue. Note that this does not release the buffers, it * just sets their length to zero; useful if you want to reuse the * same queue without reallocating. */ void clear(); /** Movable */ IOBufQueue(IOBufQueue&&); IOBufQueue& operator=(IOBufQueue&&); private: static const size_t kChainLengthNotCached = (size_t)-1; /** Not copyable */ IOBufQueue(const IOBufQueue&) = delete; IOBufQueue& operator=(const IOBufQueue&) = delete; Options options_; size_t chainLength_; /** Everything that has been appended but not yet discarded or moved out */ std::unique_ptr<folly::IOBuf> head_; }; } // folly #endif // FOLLY_IO_IOBUF_QUEUE_H
[ "sgolemon@fb.com" ]
sgolemon@fb.com
bb82519d6db8208156b47ccda0dc52529e2e2828
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Operator/UserDataDTO.h
27a1e4aa4580bd841a0a396e3b67916832cb8aa5
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
/**@file UserDataDTO.h * @brief 유저 개인의 정보를 담는 DTO를 정의한다. * @author siva */ #ifndef USER_DATA_DTO_H #define USER_DATA_DTO_H /**@ingroup GroupDAM * @class CUserDataDTO * @brief 유저 개인의 정보를 담는다.\n * @remarks 비밀번호는 모두 단방향 해싱을 거친 값들을 갖는다.\n * 유저 id는 당방향 해싱 후의 로우레벨 패스워드(학번)다. */ class CUserDataDTO { public : /**@brief 여기선 단순히 해당 유저의 low level password를 사용한다. */ CString m_userId; CString m_name; CString m_lowLevelPassword; /**@brief sha1으로 해싱된 digest message를 갖는다. */ CString m_highLevelPassword; int m_level; CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, CString a_highLevelPassword, int a_level); CUserDataDTO(CString a_userId, CString a_name, CString a_lowLevelPassword, int a_level, CString a_hashedHighLevelPassword); CUserDataDTO(){} ~CUserDataDTO(){} private : CString HashMessage(CString a_message); }; #endif
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c
f8d5e6b902ba3ff8901c869fe41699b2078ee755
bbb3e624cc17ac7a6ce280797eb2d2cfad8ea754
/selenium/vagrant-tiennguyen-php-selenium/firefox-sdk/include/nsIDOMCharacterData.h
407469ed8b754b65db940f90541b2f00daa255f9
[]
no_license
Virtual-Machine-Vagrant/TienNguyen-vagrant-env
dff187eaeafc8ca1bb68d81853144d914d6fd293
fe8eaa107dd1a22f07e562937113139c5a4e2687
refs/heads/master
2021-01-13T12:59:28.637343
2017-01-12T08:45:51
2017-01-12T08:45:51
78,718,617
0
0
null
null
null
null
UTF-8
C++
false
false
8,150
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl/nsIDOMCharacterData.idl */ #ifndef __gen_nsIDOMCharacterData_h__ #define __gen_nsIDOMCharacterData_h__ #ifndef __gen_nsIDOMNode_h__ #include "nsIDOMNode.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMCharacterData */ #define NS_IDOMCHARACTERDATA_IID_STR "4109a2d2-e7af-445d-bb72-c7c9b875f35e" #define NS_IDOMCHARACTERDATA_IID \ {0x4109a2d2, 0xe7af, 0x445d, \ { 0xbb, 0x72, 0xc7, 0xc9, 0xb8, 0x75, 0xf3, 0x5e }} class NS_NO_VTABLE nsIDOMCharacterData : public nsIDOMNode { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMCHARACTERDATA_IID) /* attribute DOMString data; */ NS_IMETHOD GetData(nsAString & aData) = 0; NS_IMETHOD SetData(const nsAString & aData) = 0; /* readonly attribute unsigned long length; */ NS_IMETHOD GetLength(uint32_t *aLength) = 0; /* DOMString substringData (in unsigned long offset, in unsigned long count) raises (DOMException); */ NS_IMETHOD SubstringData(uint32_t offset, uint32_t count, nsAString & _retval) = 0; /* void appendData (in DOMString arg) raises (DOMException); */ NS_IMETHOD AppendData(const nsAString & arg) = 0; /* void insertData (in unsigned long offset, in DOMString arg) raises (DOMException); */ NS_IMETHOD InsertData(uint32_t offset, const nsAString & arg) = 0; /* void deleteData (in unsigned long offset, in unsigned long count) raises (DOMException); */ NS_IMETHOD DeleteData(uint32_t offset, uint32_t count) = 0; /* void replaceData (in unsigned long offset, in unsigned long count, in DOMString arg) raises (DOMException); */ NS_IMETHOD ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg) = 0; /* [binaryname(MozRemove)] void remove (); */ NS_IMETHOD MozRemove(void) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMCharacterData, NS_IDOMCHARACTERDATA_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMCHARACTERDATA \ NS_IMETHOD GetData(nsAString & aData) override; \ NS_IMETHOD SetData(const nsAString & aData) override; \ NS_IMETHOD GetLength(uint32_t *aLength) override; \ NS_IMETHOD SubstringData(uint32_t offset, uint32_t count, nsAString & _retval) override; \ NS_IMETHOD AppendData(const nsAString & arg) override; \ NS_IMETHOD InsertData(uint32_t offset, const nsAString & arg) override; \ NS_IMETHOD DeleteData(uint32_t offset, uint32_t count) override; \ NS_IMETHOD ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg) override; \ NS_IMETHOD MozRemove(void) override; /* Use this macro when declaring the members of this interface when the class doesn't implement the interface. This is useful for forwarding. */ #define NS_DECL_NON_VIRTUAL_NSIDOMCHARACTERDATA \ NS_METHOD GetData(nsAString & aData); \ NS_METHOD SetData(const nsAString & aData); \ NS_METHOD GetLength(uint32_t *aLength); \ NS_METHOD SubstringData(uint32_t offset, uint32_t count, nsAString & _retval); \ NS_METHOD AppendData(const nsAString & arg); \ NS_METHOD InsertData(uint32_t offset, const nsAString & arg); \ NS_METHOD DeleteData(uint32_t offset, uint32_t count); \ NS_METHOD ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg); \ NS_METHOD MozRemove(void); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMCHARACTERDATA(_to) \ NS_IMETHOD GetData(nsAString & aData) override { return _to GetData(aData); } \ NS_IMETHOD SetData(const nsAString & aData) override { return _to SetData(aData); } \ NS_IMETHOD GetLength(uint32_t *aLength) override { return _to GetLength(aLength); } \ NS_IMETHOD SubstringData(uint32_t offset, uint32_t count, nsAString & _retval) override { return _to SubstringData(offset, count, _retval); } \ NS_IMETHOD AppendData(const nsAString & arg) override { return _to AppendData(arg); } \ NS_IMETHOD InsertData(uint32_t offset, const nsAString & arg) override { return _to InsertData(offset, arg); } \ NS_IMETHOD DeleteData(uint32_t offset, uint32_t count) override { return _to DeleteData(offset, count); } \ NS_IMETHOD ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg) override { return _to ReplaceData(offset, count, arg); } \ NS_IMETHOD MozRemove(void) override { return _to MozRemove(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMCHARACTERDATA(_to) \ NS_IMETHOD GetData(nsAString & aData) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetData(aData); } \ NS_IMETHOD SetData(const nsAString & aData) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetData(aData); } \ NS_IMETHOD GetLength(uint32_t *aLength) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLength(aLength); } \ NS_IMETHOD SubstringData(uint32_t offset, uint32_t count, nsAString & _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SubstringData(offset, count, _retval); } \ NS_IMETHOD AppendData(const nsAString & arg) override { return !_to ? NS_ERROR_NULL_POINTER : _to->AppendData(arg); } \ NS_IMETHOD InsertData(uint32_t offset, const nsAString & arg) override { return !_to ? NS_ERROR_NULL_POINTER : _to->InsertData(offset, arg); } \ NS_IMETHOD DeleteData(uint32_t offset, uint32_t count) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DeleteData(offset, count); } \ NS_IMETHOD ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg) override { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceData(offset, count, arg); } \ NS_IMETHOD MozRemove(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->MozRemove(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMCharacterData : public nsIDOMCharacterData { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMCHARACTERDATA nsDOMCharacterData(); private: ~nsDOMCharacterData(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsDOMCharacterData, nsIDOMCharacterData) nsDOMCharacterData::nsDOMCharacterData() { /* member initializers and constructor code */ } nsDOMCharacterData::~nsDOMCharacterData() { /* destructor code */ } /* attribute DOMString data; */ NS_IMETHODIMP nsDOMCharacterData::GetData(nsAString & aData) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMCharacterData::SetData(const nsAString & aData) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long length; */ NS_IMETHODIMP nsDOMCharacterData::GetLength(uint32_t *aLength) { return NS_ERROR_NOT_IMPLEMENTED; } /* DOMString substringData (in unsigned long offset, in unsigned long count) raises (DOMException); */ NS_IMETHODIMP nsDOMCharacterData::SubstringData(uint32_t offset, uint32_t count, nsAString & _retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void appendData (in DOMString arg) raises (DOMException); */ NS_IMETHODIMP nsDOMCharacterData::AppendData(const nsAString & arg) { return NS_ERROR_NOT_IMPLEMENTED; } /* void insertData (in unsigned long offset, in DOMString arg) raises (DOMException); */ NS_IMETHODIMP nsDOMCharacterData::InsertData(uint32_t offset, const nsAString & arg) { return NS_ERROR_NOT_IMPLEMENTED; } /* void deleteData (in unsigned long offset, in unsigned long count) raises (DOMException); */ NS_IMETHODIMP nsDOMCharacterData::DeleteData(uint32_t offset, uint32_t count) { return NS_ERROR_NOT_IMPLEMENTED; } /* void replaceData (in unsigned long offset, in unsigned long count, in DOMString arg) raises (DOMException); */ NS_IMETHODIMP nsDOMCharacterData::ReplaceData(uint32_t offset, uint32_t count, const nsAString & arg) { return NS_ERROR_NOT_IMPLEMENTED; } /* [binaryname(MozRemove)] void remove (); */ NS_IMETHODIMP nsDOMCharacterData::MozRemove() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMCharacterData_h__ */
[ "mac-l011@mac-l011s-MacBook-Pro-2.local" ]
mac-l011@mac-l011s-MacBook-Pro-2.local
4cc016260fdcc37e4e50de75b0ddefc650af6270
81bed8a9185b9a23b32db7e43c1b653954955ecd
/TimerQueue.cpp
e0d919772d095a4605a077ce19603530932d001d
[]
no_license
UltramanWu/SimpleWebServer
cb6e934fc6f516c0522b92db0efdd0ff4f4b7e55
b1eda0a42503d868b8bd5e4e15135f8d55b842a9
refs/heads/master
2021-04-01T07:01:28.320665
2020-04-02T04:02:33
2020-04-02T04:02:33
248,166,353
0
0
null
null
null
null
UTF-8
C++
false
false
904
cpp
// // Created by wu on 3/18/20. // #include "TimerQueue.h" #include "HttpData.h" TimerNode::TimerNode(SPHttpData httpdata,int timeout):m_httpdata(httpdata),deleted(false){ struct timeval now; gettimeofday(&now,NULL); // 时间结构体 时区 expiredTime = (((now.tv_sec%10000)*1000)+(now.tv_usec/1000))+timeout; } TimerNode::~TimerNode() { if(m_httpdata) m_httpdata->CloseHandle(); } void TimerQueue::AddTimer(SPHttpData httpData, int timeout) { SPTimerNode item(std::make_shared<TimerNode>(httpData,timeout)); TimerNodeQueue.push(item); httpData->LinkTimer(item); // 将TimerNode与HttpData进行关联 } void TimerQueue::HandleExpired() { while(!TimerNodeQueue.empty()){ SPTimerNode tn = TimerNodeQueue.top(); if(tn->IsValid()==false || tn->GetDeleted()==true){ TimerNodeQueue.pop(); } else break; } }
[ "shida_wu@163.com" ]
shida_wu@163.com
0ff8d27d3c7fb61d3a0e332def90a0d93a52ff47
c74b0c37ac8e2d3d1a3c0ffaa2b608bc4deff1c6
/Toolkit/FreyaReflect/Lib/3party/elsa/smbase/hashtbl.cc
3f100e3bae7da6140d366fd44ed0c63df0474480
[]
no_license
crsib/freya-3d
c33beeb787e572f2faf9528c6f3a1fa3875749c5
ff1f54b09f7bc0e253053a474f3fe5635dbedde6
refs/heads/master
2022-05-21T19:42:30.694778
2011-03-11T13:49:00
2011-03-11T13:49:00
259,894,429
1
0
null
null
null
null
UTF-8
C++
false
false
6,361
cc
// hashtbl.cc see license.txt for copyright and terms of use // code for hashtbl.h #include "hashtbl.h" // this module #include "xassert.h" // xassert #include <string.h> // memset unsigned HashTable::hashFunction(void const *key) const { return coreHashFn(key) % (unsigned)tableSize; } HashTable::HashTable(GetKeyFn gk, HashFn hf, EqualKeyFn ek, int initSize) : getKey(gk), coreHashFn(hf), equalKeys(ek), enableShrink(true) { makeTable(initSize); } HashTable::~HashTable() { delete[] hashTable; } void HashTable::makeTable(int size) { hashTable = new void*[size]; tableSize = size; memset(hashTable, 0, sizeof(void*) * tableSize); numEntries = 0; } inline int HashTable::getEntry(void const *key) const { int index = hashFunction(key); int originalIndex = index; for(;;) { if (hashTable[index] == NULL) { // unmapped return index; } if (equalKeys(key, getKey(hashTable[index]))) { // mapped here return index; } // this entry is mapped, but not with this key, i.e. // we have a collision -- so just go to the next entry, // wrapping as necessary index = nextIndex(index); // detect infinite looping xassert(index != originalIndex); } } void *HashTable::get(void const *key) const { return hashTable[getEntry(key)]; } void HashTable::resizeTable(int newSize) { // Make sure newSize is not the result of an overflowed computation, and // that we're not going to resizeTable again right away in the add() call. xassert(newSize >= numEntries); xassert(newSize/3*2 >= numEntries-1); // save old stuff void **oldTable = hashTable; int oldSize = tableSize; int oldEntries = numEntries; // make the new table (sets 'numEntries' to 0) makeTable(newSize); // set this now, rather than incrementing it with each add numEntries = oldEntries; // move entries to the new table for (int i=0; i<oldSize; i++) { if (oldTable[i] != NULL) { // This function is worth optimizing; it accounts for 12% of qualcc // runtime. This simple inlining reduces resizeTable()'s impact from // 12% to 2%. if (0) { // original code: add(getKey(oldTable[i]), oldTable[i]); } else { // inlined version: int newIndex = getEntry(getKey(oldTable[i])); xassertdb(hashTable[newIndex] == NULL); // must not be a mapping yet hashTable[newIndex] = oldTable[i]; } oldEntries--; } } xassert(oldEntries == 0); // deallocate the old table delete[] oldTable; } void HashTable::add(void const *key, void *value) { if (numEntries+1 > tableSize*2/3) { // We're over the usage threshold; increase table size. // // Note: Resizing by numEntries*4 instead of tableSize*2 gives 42% speedup // in total time used by resizeTable(), at the expense of more memory used. resizeTable(tableSize * 2 + 1); } // make sure above didn't fail due to integer overflow xassert(numEntries+1 < tableSize); int index = getEntry(key); xassert(hashTable[index] == NULL); // must not be a mapping yet hashTable[index] = value; numEntries++; } void *HashTable::remove(void const *key) { if (enableShrink && numEntries-1 < tableSize/5 && tableSize > defaultSize) { // we're below threshold; reduce table size resizeTable(tableSize / 2); } int index = getEntry(key); xassert(hashTable[index] != NULL); // must be a mapping to remove // remove this entry void *retval = hashTable[index]; hashTable[index] = NULL; numEntries--; // now, if we ever inserted something and it collided with this one, // leaving things like this would prevent us from finding that other // mapping because the search stops as soon as a NULL entry is // discovered; so we must examine all entries that could have // collided, and re-insert them int originalIndex = index; for(;;) { index = nextIndex(index); xassert(index != originalIndex); // prevent infinite loops if (hashTable[index] == NULL) { // we've reached the end of the list of possible colliders break; } // remove this one void *data = hashTable[index]; hashTable[index] = NULL; numEntries--; // add it back add(getKey(data), data); } return retval; } void HashTable::empty(int initSize) { delete[] hashTable; makeTable(initSize); } void HashTable::selfCheck() const { int ct=0; for (int i=0; i<tableSize; i++) { if (hashTable[i] != NULL) { checkEntry(i); ct++; } } xassert(ct == numEntries); } void HashTable::checkEntry(int entry) const { int index = getEntry(getKey(hashTable[entry])); int originalIndex = index; for(;;) { if (index == entry) { // the entry lives where it will be found, so that's good return; } if (hashTable[index] == NULL) { // the search for this entry would stop before finding it, // so that's bad! xfailure("checkEntry: entry in wrong slot"); } // collision; keep looking index = nextIndex(index); xassert(index != originalIndex); } } // ------------------ HashTableIter -------------------- HashTableIter::HashTableIter(HashTable &t) : table(t) { index = 0; moveToSth(); } void HashTableIter::adv() { xassert(!isDone()); // move off the current item index++; // keep moving until we find something moveToSth(); } void HashTableIter::moveToSth() { while (index < table.tableSize && table.hashTable[index] == NULL) { index++; } if (index == table.tableSize) { index = -1; // mark as done } } void *HashTableIter::data() const { xassert(!isDone()); return table.hashTable[index]; } STATICDEF void const *HashTable::identityKeyFn(void *data) { return data; } unsigned lcprngTwoSteps(unsigned v) { // this is the core of the LC PRNG in one of the many libcs // running around the net v = (v * 1103515245) + 12345; // do it again for good measure v = (v * 1103515245) + 12345; return v; } STATICDEF unsigned HashTable::lcprngHashFn(void const *key) { return lcprngTwoSteps((unsigned)pointerToInteger(key)); } STATICDEF bool HashTable:: pointerEqualKeyFn(void const *key1, void const *key2) { return key1 == key2; }
[ "crsib@localhost" ]
crsib@localhost
026def37c977b56f5cedce2775c933df7c385fb8
6c791f734525495793e82ffd591ad3efbd874042
/libraryreclamation/intermediaire.cpp
1bed3ff79887e85f3420b3c1ed985526256a88fb
[]
no_license
myriamkhachlouf/LibroDevo
11868f13c4ce95c5f08769782d77b4b9260fdd4d
94a6b30e06859af59247d43128152987d22f0967
refs/heads/master
2020-09-20T13:47:26.059188
2019-12-13T10:02:05
2019-12-13T10:02:05
224,500,673
1
0
null
null
null
null
UTF-8
C++
false
false
991
cpp
#include "intermediaire.h" #include "ui_intermediaire.h" #include "gestion_livre.h" #include "gestion_rayon.h" #include"capteur.h" #include<QPixmap> intermediaire::intermediaire(QWidget *parent) : QDialog(parent), ui(new Ui::intermediaire) { ui->setupUi(this); QPixmap pix("C:/Users/kamel/Desktop/lib2.jpg"); ui->label_pic->setPixmap(pix); } intermediaire::~intermediaire() { delete ui; } void intermediaire::on_rayon_pushbutton_clicked() {QSound::play("C:/Users/ZIZOU/Desktop/click.wav"); hide(); gestion_rayon *r= new gestion_rayon(this); r->show(); } void intermediaire::on_livre_pushbutton_clicked() {QSound::play("C:/Users/ZIZOU/Desktop/click.wav"); hide(); gestion_livre *l= new gestion_livre(this); l->show(); } void intermediaire::on_capteur_pushButton_clicked() {QSound::play("C:/Users/ZIZOU/Desktop/click.wav"); hide(); capteur *c; c=new capteur(); c->show(); }
[ "noreply@github.com" ]
myriamkhachlouf.noreply@github.com
7cab39d108786df856ff3a138e0051c450453ff1
9a0a582bdba0dfbeffddd2dfd59948789e0915d8
/prototype1/include/peaklightbardetector.h
ecb806a0aef309680c5ac668c762cae808428cfd
[]
no_license
Gerold31/Streifenprojektion
25eca8c608c5ead546df2e951b4e905e98f90299
31dfa7d0883d9e269280e12381637af81300cc80
refs/heads/master
2021-01-16T23:09:58.093331
2015-05-22T20:54:23
2015-05-22T20:54:23
25,968,337
0
0
null
null
null
null
UTF-8
C++
false
false
638
h
#ifndef PEAKLIGHTBARDETECTOR_H #define PEAKLIGHTBARDETECTOR_H #include <opencv2/core/core.hpp> #include "lightbardetector.h" struct WorkData; class PeakLightBarDetector : public LightBarDetector { public: PeakLightBarDetector() {} virtual ~PeakLightBarDetector() {} virtual void processImage(const cv::Mat& img, Line& line) override; private: void computeAreaAvg(WorkData& data) const; void computeEval(WorkData& data) const; void computeLine(WorkData& data) const; double evaluate(const cv::Vec3d color) const; cv::Vec2i areaSize = {11, 11}; double threshold = 0.6; int median = 1; }; #endif // PEAKLIGHTBARDETECTOR_H
[ "johannes.spangenberg@hotmail.de" ]
johannes.spangenberg@hotmail.de
8ed9054b74b0144ca9c0e1bce34c8d9d75f52961
3818b7af7a6407b636870288779014b29b186535
/Source/Editor/FrEdUtil.h
88eb6a36ca125ffdf7b1ec50d75bda64d3f69b8c
[]
no_license
VladGordienko28/ProtoGame
de287b44b6db4de9fc888869e3a663db81dc85ed
3d88f5578f6ceca4275af9ee14a468b190bbfb7c
refs/heads/master
2020-04-16T06:53:18.813931
2019-11-11T19:42:19
2019-11-11T19:42:19
165,364,799
1
0
null
null
null
null
UTF-8
C++
false
false
2,107
h
/*============================================================================= FrEdUtil.h: Various editor stuff. Copyright Jul.2016 Vlad Gordienko. =============================================================================*/ /*----------------------------------------------------------------------------- CGUIRender. -----------------------------------------------------------------------------*/ // // GUI Render. // class CGUIRender: public CGUIRenderBase { public: // CGUIRender interface. CGUIRender(); ~CGUIRender(); void BeginPaint( gfx::DrawContext& drawContext ); void EndPaint( gfx::DrawContext& drawContext ); // CGUIRenderBase interface. void DrawRegion( TPoint P, TSize S, math::Color Color, math::Color BorderColor, EBrushPattern Pattern ); void DrawText( TPoint P, const Char* Text, Int32 Len, math::Color Color, fnt::Font::Ptr Font ); void SetClipArea( TPoint P, TSize S ); void DrawImage( TPoint P, TSize S, TPoint BP, TSize BS, img::Image::Ptr image ); void DrawTexture( TPoint P, TSize S, TPoint BP, TSize BS, rend::Texture2DHandle image, UInt32 width, UInt32 height ); void SetBrightness( Float Brig ); private: Float m_brightness; gfx::TextDrawer m_textDrawer; ffx::Effect::Ptr m_coloredEffect; ffx::Effect::Ptr m_texturedEffect; ffx::TechniqueId m_solidTech; ffx::TechniqueId m_stippleTech; rend::VertexBufferHandle m_coloredVB; rend::VertexBufferHandle m_texturedVB; gfx::DrawContext* m_drawContext; }; /*----------------------------------------------------------------------------- CSG. -----------------------------------------------------------------------------*/ // CSG functions. extern void CSGUnion( FBrushComponent* Brush, FLevel* Level ); extern void CSGIntersection( FBrushComponent* Brush, FLevel* Level ); extern void CSGDifference( FBrushComponent* Brush, FLevel* Level ); // // Experimental stuff // JSon::Ptr exportLevel( FLevel* level ); /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
[ "vladgordienko28@gmail.com" ]
vladgordienko28@gmail.com
f50157140e2f6994804c282437f794bc6a287928
527739ed800e3234136b3284838c81334b751b44
/include/RED4ext/Types/generated/audio/VisualTagToNPCMetadata.hpp
2ade393a6ca000337214a85fd8a4302a133b4dd3
[ "MIT" ]
permissive
0xSombra/RED4ext.SDK
79ed912e5b628ef28efbf92d5bb257b195bfc821
218b411991ed0b7cb7acd5efdddd784f31c66f20
refs/heads/master
2023-07-02T11:03:45.732337
2021-04-15T16:38:19
2021-04-15T16:38:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
575
hpp
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> namespace RED4ext { namespace audio { struct VisualTagToNPCMetadata { static constexpr const char* NAME = "audioVisualTagToNPCMetadata"; static constexpr const char* ALIAS = NAME; DynArray<CName> visualTags; // 00 CName foleyNPCMetadata; // 10 }; RED4EXT_ASSERT_SIZE(VisualTagToNPCMetadata, 0x18); } // namespace audio } // namespace RED4ext
[ "expired6978@gmail.com" ]
expired6978@gmail.com
44948cf2e10d13c406ed4c0ddc26e4fcedbdc12d
acc2f5336d768a7d86dbd2eec441283cfd11d52d
/src/server/gameserver/EffectSafeForceScroll.cpp
fb76ef16c4ac0b6f52c5952cec9dc4c572515887
[]
no_license
stevexk/server
86df9e8c2448ad97db9c3ab86820beec507ef092
4ddb6e7cfa510bb13ccd87f56db008aa1be1baad
refs/heads/master
2020-01-23T22:00:57.359964
2015-09-18T14:58:27
2015-09-18T14:58:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,809
cpp
////////////////////////////////////////////////////////////////////////////// // Filename : EffectSafeForceScroll.cpp // Written by : bezz // Description : ////////////////////////////////////////////////////////////////////////////// #include "EffectSafeForceScroll.h" #include "PlayerCreature.h" #include "Zone.h" #include "GCRemoveEffect.h" #include "Timeval.h" #include "DB.h" ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// EffectSafeForceScroll::EffectSafeForceScroll(Creature* pCreature) throw(Error) { __BEGIN_TRY setTarget(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::affect() throw(Error) { __BEGIN_TRY Creature* pCreature = dynamic_cast<Creature *>(m_pTarget); affect(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::affect(Creature* pCreature) throw(Error) { __BEGIN_TRY PlayerCreature* pPC = dynamic_cast<PlayerCreature*>(pCreature); Assert(pPC != NULL); pPC->initAllStatAndSend(); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::unaffect() throw(Error) { __BEGIN_TRY Creature* pCreature = dynamic_cast<Creature *>(m_pTarget); unaffect(pCreature); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::unaffect(Creature* pCreature) throw(Error) { __BEGIN_TRY PlayerCreature* pPC = dynamic_cast<PlayerCreature*>(pCreature); Assert(pPC != NULL); Zone* pZone = pPC->getZone(); Assert(pZone != NULL); pPC->removeFlag(getEffectClass()); pPC->initAllStatAndSend(); GCRemoveEffect gcRemoveEffect; gcRemoveEffect.setObjectID(pCreature->getObjectID()); gcRemoveEffect.addEffectList(getEffectClass()); pZone->broadcastPacket(pPC->getX(), pPC->getY(), &gcRemoveEffect); destroy(pPC->getName()); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::create(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Timeval currentTime; getCurrentTime(currentTime); Timeval remainTime = timediff(m_Deadline, currentTime); Turn_t remainTurn = remainTime.tv_sec * 10 + remainTime.tv_usec / 100000; pStmt->executeQuery("INSERT INTO EffectSafeForceScroll (OwnerID, RemainTime ) VALUES('%s',%lu)", ownerID.c_str(), remainTurn); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::destroy(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); pStmt->executeQuery("DELETE FROM EffectSafeForceScroll WHERE OwnerID = '%s'", ownerID.c_str()); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScroll::save(const string& ownerID ) throw(Error) { __BEGIN_TRY Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Timeval currentTime; getCurrentTime(currentTime); Timeval remainTime = timediff(m_Deadline, currentTime); Turn_t remainTurn = remainTime.tv_sec * 10 + remainTime.tv_usec / 100000; pStmt->executeQuery("UPDATE EffectSafeForceScroll SET RemainTime = %lu WHERE OwnerID = '%s'", remainTurn, ownerID.c_str()); SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// string EffectSafeForceScroll::toString() const throw() { __BEGIN_TRY StringStream msg; msg << "EffectSafeForceScroll(" << "ObjectID:" << getObjectID() << ")"; return msg.toString(); __END_CATCH } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void EffectSafeForceScrollLoader::load(Creature* pCreature ) throw(Error) { __BEGIN_TRY Assert(pCreature != NULL); Statement* pStmt = NULL; BEGIN_DB { pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement(); Result* pResult = pStmt->executeQuery("SELECt RemainTime FROM EffectSafeForceScroll WHERE OwnerID = '%s'", pCreature->getName().c_str()); if (pResult->next() ) { Turn_t remainTurn = pResult->getDWORD(1); Timeval currentTime; getCurrentTime(currentTime); EffectSafeForceScroll* pEffect = new EffectSafeForceScroll(pCreature); pEffect->setDeadline(remainTurn); pCreature->addEffect(pEffect); pCreature->setFlag(pEffect->getEffectClass()); } SAFE_DELETE(pStmt); } END_DB(pStmt) __END_CATCH } EffectSafeForceScrollLoader* g_pEffectSafeForceScrollLoader = NULL;
[ "tiancaiamao@gmail.com" ]
tiancaiamao@gmail.com
4ed64e6e8b6339b9da996cee07124c3b75e8fc8c
a5239258d872ce52cd24a52d7b1ef19ce9eec537
/GameCode/GameEntity.hpp
4af488e26cab103ce92aec3566d6207d7b6f97a6
[]
no_license
derofim/simple_miner
e3aaafb1eab1369f3d61c15bd978fe26a696e939
0c4419eba585343ca581f60579175cc0a6caf92c
refs/heads/master
2020-07-03T03:23:05.349392
2016-11-03T15:27:20
2016-11-03T15:27:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,608
hpp
//================================================================================= // GameEntity.hpp // Author: Tyler George // Date : April 23, 2015 //================================================================================= #pragma once #ifndef __included_GameEntity__ #define __included_GameEntity__ #include <vector> #include "Engine/Math/PhysicsMotion3D.hpp" #include "Engine/Math/AABB3D.hpp" #include "Engine/Renderer/OpenGLRenderer.hpp" ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- class GameEntity { public: ///--------------------------------------------------------------------------------- /// Constructors ///--------------------------------------------------------------------------------- GameEntity() {}; explicit GameEntity( const Vector3& position, const EulerAngles& orientation, const Vector3& boundingBoxOffsets ); ~GameEntity() {}; ///--------------------------------------------------------------------------------- /// Accessors/Queries ///--------------------------------------------------------------------------------- const Vector3 GetPosition() const; const Vector3 GetVelocity() const; const EulerAngles GetOrientation() const; const EulerAngles GetAngularVelocity() const; const Vector3s GetBoundingBoxVertices() const; const Vector3s GetBottomVertices() const; const Vector3 GetBottomPosition() const; ///--------------------------------------------------------------------------------- /// Mutators ///--------------------------------------------------------------------------------- void SetPosition( const Vector3& position ); void SetVelocity( const Vector3& velocity ); void SetOrientation( const EulerAngles& orientation ); void SetAngularVelocity( const EulerAngles& angularVelocity ); void ApplyAcceleration( const Vector3& acceleration ); ///--------------------------------------------------------------------------------- /// Upadate ///--------------------------------------------------------------------------------- virtual void Update( double deltaSeconds ); ///--------------------------------------------------------------------------------- /// Render ///--------------------------------------------------------------------------------- virtual void Render( OpenGLRenderer* renderer, bool debugModeEnabled ) const; private: ///--------------------------------------------------------------------------------- /// Private member variables ///--------------------------------------------------------------------------------- PhysicsMotion3D m_physics; AABB3D m_boundingBox; Vector3 m_boundingBoxOffsets; Vector3 m_bottomPosition; }; typedef std::vector< GameEntity* > GameEntities; ///--------------------------------------------------------------------------------- /// Inline function implementations ///--------------------------------------------------------------------------------- ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline GameEntity::GameEntity( const Vector3& position, const EulerAngles& orientation, const Vector3& boundingBoxOffsets ) { m_physics.m_position = position; m_physics.m_orientationDegrees = orientation; m_boundingBoxOffsets = boundingBoxOffsets; m_boundingBox.m_mins.x = -m_boundingBoxOffsets.x; m_boundingBox.m_mins.y = -m_boundingBoxOffsets.y; m_boundingBox.m_mins.z = -m_boundingBoxOffsets.z; m_boundingBox.m_maxs.x = m_boundingBoxOffsets.x; m_boundingBox.m_maxs.y = m_boundingBoxOffsets.y; m_boundingBox.m_maxs.z = m_boundingBoxOffsets.z; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetPosition() const { return m_physics.m_position; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetVelocity() const { return m_physics.m_velocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const EulerAngles GameEntity::GetOrientation() const { return m_physics.m_orientationDegrees; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const EulerAngles GameEntity::GetAngularVelocity() const { return m_physics.m_orientationVelocityDegreesPerSecond; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline const Vector3 GameEntity::GetBottomPosition() const { return m_bottomPosition; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetPosition( const Vector3& position ) { m_physics.m_position = position; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetVelocity( const Vector3& velocity ) { m_physics.m_velocity = velocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetOrientation( const EulerAngles& orientation ) { m_physics.m_orientationDegrees = orientation; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::SetAngularVelocity( const EulerAngles& angularVelocity ) { m_physics.m_orientationVelocityDegreesPerSecond = angularVelocity; } ///--------------------------------------------------------------------------------- /// ///--------------------------------------------------------------------------------- inline void GameEntity::ApplyAcceleration( const Vector3& acceleration ) { m_physics.ApplyAcceleration( acceleration ); } #endif
[ "tyler.george@live.com" ]
tyler.george@live.com
01a60db1be3cd7e76e3e51f9a57d2b983da1c57b
3c325c073ae1f04ac71e20a9f3c083b81ef30cef
/Source/AdvGameProgProject/Private/AI/STrackerBot.cpp
8ad51a8418cc1cf4fcefeb8dba08dd2a3533083b
[]
no_license
JustinRobbins7/AdvGraphicsSemesterProject
0b4b946d9bd9bea2e6fff6ea1d1612bd35be1509
a9d36c996181a46cd5b3c89776314166dd6b7c36
refs/heads/master
2020-03-29T18:03:28.327704
2018-10-04T17:06:56
2018-10-04T17:06:56
150,192,528
0
0
null
null
null
null
UTF-8
C++
false
false
2,203
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "AI/STrackerBot.h" #include "Components/StaticMeshComponent.h" #include "Kismet/GameplayStatics.h" #include "AI/Navigation/NavigationSystem.h" #include "AI/Navigation/NavigationPath.h" #include "GameFramework/Character.h" #include "DrawDebugHelpers.h" // Sets default values ASTrackerBot::ASTrackerBot() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp")); RootComponent = MeshComp; MeshComp->SetCanEverAffectNavigation(false); MeshComp->SetSimulatePhysics(true); bUseVelocityChange = true; MovementForce = 1000; RequiredDistanceToTarget = 100; } // Called when the game starts or when spawned void ASTrackerBot::BeginPlay() { Super::BeginPlay(); //Find initial move to NextPathPoint = GetNextPathPoint(); } FVector ASTrackerBot::GetNextPathPoint() { //Hack to get player location ACharacter* PlayerPawn = UGameplayStatics::GetPlayerCharacter(this, 0); UNavigationPath* NavPath = UNavigationSystem::FindPathToActorSynchronously(this, GetActorLocation(), PlayerPawn); if (NavPath->PathPoints.Num() > 1) { //Return next point in path return NavPath->PathPoints[1]; } return GetActorLocation(); } // Called every frame void ASTrackerBot::Tick(float DeltaTime) { Super::Tick(DeltaTime); float DistanceToTarget = (GetActorLocation() - NextPathPoint).Size(); if (DistanceToTarget <= RequiredDistanceToTarget) { NextPathPoint = GetNextPathPoint(); DrawDebugString(GetWorld(), GetActorLocation(), "Target Reached!"); } else { //Keep moving towards next target FVector ForceDirection = NextPathPoint - GetActorLocation(); ForceDirection.Normalize(); ForceDirection *= MovementForce; MeshComp->AddForce(ForceDirection, NAME_None, bUseVelocityChange); DrawDebugDirectionalArrow(GetWorld(), GetActorLocation(), GetActorLocation() + ForceDirection, 32, FColor::Orange, false, 0.0f, 0, 1.0f); } DrawDebugSphere(GetWorld(), NextPathPoint, 20, 12, FColor::Orange, false, 0.0f, 1.0f); }
[ "robbinsju@gmail.com" ]
robbinsju@gmail.com
60cf8160aa7d5e951c1f5a6de03c6c66c1b73c41
902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96
/Sources/Tools/EPI/Document/Properties/PtyMaterial.moc.h
1114d4e9d7e6c205e1b9fc7abb2a457b96e09811
[ "BSD-3-Clause" ]
permissive
benkaraban/anima-games-engine
d4e26c80f1025dcef05418a071c0c9cbd18a5670
8aa7a5368933f1b82c90f24814f1447119346c3b
refs/heads/master
2016-08-04T18:31:46.790039
2015-03-22T08:13:55
2015-03-22T08:13:55
32,633,432
2
0
null
null
null
null
UTF-8
C++
false
false
9,766
h
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * 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 holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EPI_PROPERTY_MATERIAL_H_ #define EPI_PROPERTY_MATERIAL_H_ #include <QWidget> #include <QGridLayout> #include <QCheckBox> #include <EPI/Document/PropertyNode.moc.h> #include <EPI/Document/PropertyWidget.moc.h> #include <Universe/NodeMesh.h> #include <Universe/NodeSkeleton.h> namespace QtToolbox { class CollapsibleWidget; class QuickColorPicker; class SingleSlidingDouble; class ComboBox; class SingleSlidingHDR; }//namespace QtToolbox namespace EPI { class CustomLine; class PtyWidgetMaterial; //----------------------------------------------------------------------------- LM_ENUM_2 (EPtyMaterialDataType, MATERIAL_DATA_NODE_MESH, MATERIAL_DATA_SKELETON_SKIN) class LM_API_EPI PtyMaterial : public PropertyNode { Q_OBJECT friend class PtyWidgetMaterial; public: //constraucteur pour modifier le material d'un nodeMesh PtyMaterial(const Ptr<Universe::RessourcePool>& pRessourcePool, const Core::List<Ptr<Universe::NodeMesh> >& pNodesM, const Core::String& title = L"Material", bool isSelectable = true); //constructeur pour modifier le material d'un SkeletonSkin PtyMaterial(const Ptr<Universe::RessourcePool>& pRessourcePool, const Core::List<Ptr<Universe::SkeletonSkin> >& pSkin, const Core::String& title = L"Material", bool isSelectable = true); virtual ~PtyMaterial(); virtual Ptr<PropertyWidget> internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDtaProxy, QWidget * parent = 0); virtual void updateData(); void updateProperty(); virtual Ptr<Property> clone() const; virtual void internalCopy(const Ptr<Property>& pSrc); void setNodeMesh(const Ptr<Universe::NodeMesh>& pNodeM, bool keepPtyMaterial = false); void copy(Assets::Material& mat); virtual bool isIntersecting(const Core::Rayf& ray, float& distance); void setBoundingBoxVisible(bool visible); Core::AABoxf getBoundingBox() const; virtual EPropertyClassName getCalssName() const {return PTY_MATERIAL;} virtual String getIconFileName() {return L":/icons/ptyMaterial.png";} private: void setDataMaterial (const Renderer::Material & material); const Renderer::Material& getDataMaterial(); void setDataDiffuseTexture (const String & texName); void setDataSpecularTexture (const String & texName); void setDataNormalTexture (const String & texName); void setDataLightTexture (const String & texName); void setDataCustomTexture0 (const String & texName); void setDataCustomTexture1 (const String & texName); void setDataCustomTexture2 (const String & texName); public: void getDataDiffuseTexture (String & texName); void getDataSpecularTexture (String & texName); void getDataNormalTexture (String & texName); void getDataLightTexture (String & texName); void getDataCustomTexture0 (String & texName); void getDataCustomTexture1 (String & texName); void getDataCustomTexture2 (String & texName); private: Ptr<Universe::RessourcePool> _pRessourcePool; Core::List<Ptr<Universe::NodeMesh> > _pNodesM; Core::List<Ptr<Universe::SkeletonSkin> > _pSkins; Core::List<Ptr<Universe::Node> > _pNodes; EPtyMaterialDataType _dataType; Assets::EMaterialType _matType; bool _translucidTexture; bool _clampTextureBorder; String _diffuseTex; String _specularTex; String _normalTex; Core::Vector4f _emissive; Core::Vector4f _diffuse; Core::Vector4f _specular; double _shininess; Core::Vector4f _glow; Core::Vector4f _reflexions; double _glowExtent; Core::Vector4f _refracColor; double _refracScale; double _refracIndex; bool _dynamicShadowCaster; bool _dynamicShadowReceiver; //Custom String _texture0Name; String _texture1Name; String _texture2Name; Assets::ECustomMode _customMode; Core::Vector4f _customColor; float _colorFactor; float _glowFactor; Assets::EOperationType _opColor01; Assets::EOperationType _opColor12; Core::Vector2f _duv0; Core::Vector2f _duv1; Core::Vector2f _duv2; }; //----------------------------------------------------------------------------- class LM_API_EPI PtyWidgetMaterial : public PropertyWidget { Q_OBJECT friend class PtyMaterial; friend class PtyWidgetModel; public: PtyWidgetMaterial(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent = 0); virtual ~PtyWidgetMaterial(); void readProperty(); void writeProperty(QWidget* pWidget); void setupUi(); void showMaterialParameter(); private: void showMaterialStandard(bool flag); void showMaterialCustom(bool flag); private: QGridLayout * _layout; QtToolbox::CollapsibleWidget * _groupBox; QtToolbox::ComboBox * _matType; QCheckBox * _translucidTexture; QCheckBox * _clampTextureBorder; QCheckBox * _dynamicShadowCaster; QCheckBox * _dynamicShadowReceiver; CustomLine * _diffuseTex; CustomLine * _specularTex; CustomLine * _normalTex; QtToolbox::QuickColorPicker * _emissive; QtToolbox::QuickColorPicker * _diffuse; QtToolbox::QuickColorPicker * _specular; QtToolbox::SingleSlidingDouble* _shininess; QtToolbox::QuickColorPicker * _glow; QtToolbox::QuickColorPicker * _reflexions; QtToolbox::SingleSlidingDouble* _glowExtent; QtToolbox::QuickColorPicker * _refracColor; QtToolbox::SingleSlidingDouble* _refracScale; QtToolbox::SingleSlidingDouble* _refracIndex; CustomLine * _customTex0; CustomLine * _customTex1; CustomLine * _customTex2; QtToolbox::ComboBox * _customMode; QtToolbox::QuickColorPicker * _customColor; QtToolbox::SingleSlidingDouble* _colorFactor; QtToolbox::SingleSlidingDouble* _glowFactor; QtToolbox::ComboBox * _opColor01; QtToolbox::ComboBox * _opColor12; QtToolbox::SingleSlidingHDR* _duv0_X; QtToolbox::SingleSlidingHDR* _duv1_X; QtToolbox::SingleSlidingHDR* _duv2_X; QtToolbox::SingleSlidingHDR* _duv0_Y; QtToolbox::SingleSlidingHDR* _duv1_Y; QtToolbox::SingleSlidingHDR* _duv2_Y; }; //----------------------------------------------------------------------------- } // namespace EPI #endif /*EPI_PROPERTY_MATERIAL_H_*/
[ "contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c" ]
contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c
403ba5c0f91869137a88307dae5ed91ddeffb04b
1321b27ee8b6f757d23c0d538257ce648c1d7c03
/src/bitcoinrpc.cpp
4be193d98b9916bb7e7e25c4e5d2036f7aed0de0
[ "MIT" ]
permissive
peter600/ParkByte
1a9348f1cc15b445c66af11ea26bedf0dda4187c
b7fcc7e7d92d6bf8638e98b48182240704077490
refs/heads/master
2020-05-29T11:07:11.986054
2015-05-06T23:46:00
2015-05-06T23:46:00
35,618,241
1
0
null
2015-05-14T15:12:55
2015-05-14T15:12:55
null
UTF-8
C++
false
false
48,057
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; const Object emptyobj; void ThreadRPCServer3(void* parg); static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 59061 : 59060; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64_t AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64_t nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64_t amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } // // Utilities: convert hex-encoded Values // (throws error if not hex). // uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "stop <detach>\n" "<detach> is true or false to detach the database or not for this stop only\n" "Stop ParkByte server (and possibly override the detachdb config value)."); // Shutdown will take long enough that the response should get back if (params.size() > 0) bitdb.SetDetach(params[0].get_bool()); StartShutdown(); return "ParkByte server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safemd unlocked // ------------------------ ----------------------- ------ -------- { "help", &help, true, true }, { "stop", &stop, true, true }, { "getbestblockhash", &getbestblockhash, true, false }, { "getblockcount", &getblockcount, true, false }, { "getconnectioncount", &getconnectioncount, true, false }, { "getpeerinfo", &getpeerinfo, true, false }, { "getdifficulty", &getdifficulty, true, false }, { "getinfo", &getinfo, true, false }, { "getsubsidy", &getsubsidy, true, false }, { "getmininginfo", &getmininginfo, true, false }, { "getstakinginfo", &getstakinginfo, true, false }, { "getnewaddress", &getnewaddress, true, false }, { "getnewpubkey", &getnewpubkey, true, false }, { "getaccountaddress", &getaccountaddress, true, false }, { "setaccount", &setaccount, true, false }, { "getaccount", &getaccount, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false }, { "sendtoaddress", &sendtoaddress, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false }, { "backupwallet", &backupwallet, true, false }, { "keypoolrefill", &keypoolrefill, true, false }, { "walletpassphrase", &walletpassphrase, true, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false }, { "walletlock", &walletlock, true, false }, { "encryptwallet", &encryptwallet, false, false }, { "validateaddress", &validateaddress, true, false }, { "validatepubkey", &validatepubkey, true, false }, { "getbalance", &getbalance, false, false }, { "move", &movecmd, false, false }, { "sendfrom", &sendfrom, false, false }, { "sendmany", &sendmany, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false }, { "addredeemscript", &addredeemscript, false, false }, { "getrawmempool", &getrawmempool, true, false }, { "getblock", &getblock, false, false }, { "getblockbynumber", &getblockbynumber, false, false }, { "getblockhash", &getblockhash, false, false }, { "gettransaction", &gettransaction, false, false }, { "listtransactions", &listtransactions, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false }, { "signmessage", &signmessage, false, false }, { "verifymessage", &verifymessage, false, false }, { "getwork", &getwork, true, false }, { "getworkex", &getworkex, true, false }, { "listaccounts", &listaccounts, false, false }, { "settxfee", &settxfee, false, false }, { "getblocktemplate", &getblocktemplate, true, false }, { "submitblock", &submitblock, false, false }, { "listsinceblock", &listsinceblock, false, false }, { "dumpprivkey", &dumpprivkey, false, false }, { "dumpwallet", &dumpwallet, true, false }, { "importwallet", &importwallet, false, false }, { "importprivkey", &importprivkey, false, false }, { "listunspent", &listunspent, false, false }, { "getrawtransaction", &getrawtransaction, false, false }, { "createrawtransaction", &createrawtransaction, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false }, { "decodescript", &decodescript, false, false }, { "signrawtransaction", &signrawtransaction, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false }, { "getcheckpoint", &getcheckpoint, true, false }, { "reservebalance", &reservebalance, false, true}, { "checkwallet", &checkwallet, false, true}, { "repairwallet", &repairwallet, false, true}, { "resendtx", &resendtx, false, true}, { "makekeypair", &makekeypair, false, true}, { "sendalert", &sendalert, false, false}, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: ParkByte-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: ParkByte-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: ParkByte-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { // Make this thread recognisable as the RPC listener RenameThread("ParkByte-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!NewThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use parkbyted"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=pkbrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"ParkByte Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); boost::signals2::signal<void ()> StopRequests; bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { // Make this thread recognisable as the RPC handler RenameThread("ParkByte-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; while (true) { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->unlocked) result = pcmd->actor(params, false); else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]); if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]); if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]); if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]); if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
[ "rzimail@aol.com" ]
rzimail@aol.com
787a335ab571e25147cea1ddf7d1b724e635d773
3c6ed046eda83e35ab754883a59dcb7099233b39
/components/password_manager/core/browser/password_generation_state_unittest.cc
1e4a5ac7bb1f0dd236d57460cf0cecfdbf6047b7
[ "BSD-3-Clause" ]
permissive
ssln2014/chromium
66c5021c8893313dee78b963082cbdf948bd2d6a
4bad77148cc4a36373e40cf985444bc649c0eeff
refs/heads/master
2023-03-06T03:21:39.801883
2019-06-08T16:11:10
2019-06-08T16:11:10
190,914,348
1
0
BSD-3-Clause
2019-06-08T17:08:38
2019-06-08T17:08:38
null
UTF-8
C++
false
false
14,480
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/password_manager/core/browser/password_generation_state.h" #include "base/memory/scoped_refptr.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" #include "base/test/simple_test_clock.h" #include "components/password_manager/core/browser/form_saver_impl.h" #include "components/password_manager/core/browser/mock_password_store.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace password_manager { namespace { using autofill::PasswordForm; using base::ASCIIToUTF16; using testing::_; constexpr char kURL[] = "https://example.in/login"; constexpr char kSubdomainURL[] = "https://m.example.in/login"; constexpr time_t kTime = 123456789; constexpr time_t kAnotherTime = 987654321; // Creates a dummy saved credential. PasswordForm CreateSaved() { PasswordForm form; form.origin = GURL(kURL); form.signon_realm = form.origin.spec(); form.action = GURL("https://login.example.org"); form.username_value = ASCIIToUTF16("old_username"); form.password_value = ASCIIToUTF16("12345"); return form; } // Creates a dummy saved PSL credential. PasswordForm CreateSavedPSL() { PasswordForm form; form.origin = GURL(kSubdomainURL); form.signon_realm = form.origin.spec(); form.action = GURL("https://login.example.org"); form.username_value = ASCIIToUTF16("old_username2"); form.password_value = ASCIIToUTF16("passw0rd"); form.is_public_suffix_match = true; return form; } // Creates a dummy generated password. PasswordForm CreateGenerated() { PasswordForm form; form.origin = GURL(kURL); form.signon_realm = form.origin.spec(); form.action = GURL("https://signup.example.org"); form.username_value = ASCIIToUTF16("MyName"); form.password_value = ASCIIToUTF16("Strong password"); form.preferred = true; form.type = autofill::PasswordForm::Type::kGenerated; return form; } MATCHER_P(FormHasUniqueKey, key, "") { return ArePasswordFormUniqueKeysEqual(arg, key); } class PasswordGenerationStateTest : public testing::Test { public: PasswordGenerationStateTest(); ~PasswordGenerationStateTest() override; MockPasswordStore& store() { return *mock_store_; } PasswordGenerationState& state() { return generation_state_; } FormSaverImpl& form_saver() { return form_saver_; } StubPasswordManagerClient& client() { return client_; } private: // For the MockPasswordStore. base::test::ScopedTaskEnvironment task_environment_; scoped_refptr<MockPasswordStore> mock_store_; // Test with the real form saver for better robustness. FormSaverImpl form_saver_; StubPasswordManagerClient client_; PasswordGenerationState generation_state_; }; PasswordGenerationStateTest::PasswordGenerationStateTest() : mock_store_(new testing::StrictMock<MockPasswordStore>()), form_saver_(mock_store_.get()), generation_state_(&form_saver_, &client_) { auto clock = std::make_unique<base::SimpleTestClock>(); clock->SetNow(base::Time::FromTimeT(kTime)); generation_state_.set_clock(std::move(clock)); } PasswordGenerationStateTest::~PasswordGenerationStateTest() { mock_store_->ShutdownOnUIThread(); } // Check that presaving a password for the first time results in adding it. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_New) { const PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password for the second time results in updating it. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_Replace) { PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); PasswordForm generated_updated = generated; generated_updated.password_value = ASCIIToUTF16("newgenpwd"); generated_with_date = generated_updated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(generated))); state().PresaveGeneratedPassword(generated_updated, {}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password for the third time results in updating it. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_ReplaceTwice) { PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); PasswordForm generated_updated = generated; generated_updated.password_value = ASCIIToUTF16("newgenpwd"); generated_with_date = generated_updated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(generated))); state().PresaveGeneratedPassword(generated_updated, {}); generated = generated_updated; generated_updated.password_value = ASCIIToUTF16("newgenpwd2"); generated_updated.username_value = ASCIIToUTF16("newusername"); generated_with_date = generated_updated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(generated))); state().PresaveGeneratedPassword(generated_updated, {}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password with a known username results in clearing the // username. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_WithConflict) { const PasswordForm generated = CreateGenerated(); PasswordForm saved = CreateSaved(); saved.username_value = generated.username_value; PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); generated_with_date.username_value.clear(); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {&saved}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password with an unknown username saves it as is. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_WithoutConflict) { const PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); const PasswordForm saved = CreateSaved(); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {&saved}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password followed by a call to save a pending // credential (as new) results in replacing the presaved password with the // pending one. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_ThenSaveAsNew) { const PasswordForm generated = CreateGenerated(); EXPECT_CALL(store(), AddLogin(_)); state().PresaveGeneratedPassword(generated, {}); // User edits after submission. PasswordForm pending = generated; pending.password_value = ASCIIToUTF16("edited_password"); pending.username_value = ASCIIToUTF16("edited_username"); PasswordForm generated_with_date = pending; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(generated))); state().CommitGeneratedPassword(pending, {} /* matches */, base::string16() /* old_password */); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password followed by a call to save a pending // credential (as update) results in replacing the presaved password with the // pending one. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_ThenUpdate) { PasswordForm generated = CreateGenerated(); PasswordForm related_password = CreateSaved(); related_password.username_value = ASCIIToUTF16("username"); related_password.username_element = ASCIIToUTF16("username_field"); related_password.password_value = ASCIIToUTF16("old password"); PasswordForm related_psl_password = CreateSavedPSL(); related_psl_password.username_value = ASCIIToUTF16("username"); related_psl_password.password_value = ASCIIToUTF16("old password"); PasswordForm unrelated_password = CreateSaved(); unrelated_password.preferred = true; unrelated_password.username_value = ASCIIToUTF16("another username"); unrelated_password.password_value = ASCIIToUTF16("some password"); PasswordForm unrelated_psl_password = CreateSavedPSL(); unrelated_psl_password.preferred = true; unrelated_psl_password.username_value = ASCIIToUTF16("another username"); unrelated_psl_password.password_value = ASCIIToUTF16("some password"); EXPECT_CALL(store(), AddLogin(_)); const std::vector<const autofill::PasswordForm*> matches = { &related_password, &related_psl_password, &unrelated_password, &unrelated_psl_password}; state().PresaveGeneratedPassword(generated, matches); generated.username_value = ASCIIToUTF16("username"); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(CreateGenerated()))); PasswordForm related_password_expected = related_password; related_password_expected.password_value = generated.password_value; EXPECT_CALL(store(), UpdateLogin(related_password_expected)); PasswordForm related_psl_password_expected = related_psl_password; related_psl_password_expected.password_value = generated.password_value; EXPECT_CALL(store(), UpdateLogin(related_psl_password_expected)); PasswordForm unrelated_password_expected = unrelated_password; unrelated_password_expected.preferred = false; EXPECT_CALL(store(), UpdateLogin(unrelated_password_expected)); state().CommitGeneratedPassword(generated, matches, ASCIIToUTF16("old password")); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that removing a presaved password removes the presaved password. TEST_F(PasswordGenerationStateTest, PasswordNoLongerGenerated) { PasswordForm generated = CreateGenerated(); EXPECT_CALL(store(), AddLogin(_)); state().PresaveGeneratedPassword(generated, {}); generated.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), RemoveLogin(generated)); state().PasswordNoLongerGenerated(); EXPECT_FALSE(state().HasGeneratedPassword()); } // Check that removing the presaved password and then presaving again results in // adding the second presaved password as new. TEST_F(PasswordGenerationStateTest, PasswordNoLongerGenerated_AndPresaveAgain) { PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); EXPECT_CALL(store(), RemoveLogin(generated_with_date)); state().PasswordNoLongerGenerated(); generated.username_value = ASCIIToUTF16("newgenusername"); generated.password_value = ASCIIToUTF16("newgenpwd"); generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); EXPECT_TRUE(state().HasGeneratedPassword()); } // Check that presaving a password once in original and then once in clone // results in the clone calling update, not a fresh save. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_CloneUpdates) { PasswordForm generated = CreateGenerated(); PasswordForm generated_with_date = generated; generated_with_date.date_created = base::Time::FromTimeT(kTime); EXPECT_CALL(store(), AddLogin(generated_with_date)); state().PresaveGeneratedPassword(generated, {}); std::unique_ptr<FormSaver> cloned_saver = form_saver().Clone(); std::unique_ptr<PasswordGenerationState> cloned_state = state().Clone(cloned_saver.get()); std::unique_ptr<base::SimpleTestClock> clock(new base::SimpleTestClock); clock->SetNow(base::Time::FromTimeT(kAnotherTime)); cloned_state->set_clock(std::move(clock)); EXPECT_TRUE(cloned_state->HasGeneratedPassword()); PasswordForm generated_updated = generated; generated_updated.username_value = ASCIIToUTF16("newname"); generated_with_date = generated_updated; generated_with_date.date_created = base::Time::FromTimeT(kAnotherTime); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(generated_with_date, FormHasUniqueKey(generated))); cloned_state->PresaveGeneratedPassword(generated_updated, {}); EXPECT_TRUE(cloned_state->HasGeneratedPassword()); } // Check that a clone can still work after the original is destroyed. TEST_F(PasswordGenerationStateTest, PresaveGeneratedPassword_CloneSurvives) { auto original = std::make_unique<PasswordGenerationState>(&form_saver(), &client()); const PasswordForm generated = CreateGenerated(); EXPECT_CALL(store(), AddLogin(_)); original->PresaveGeneratedPassword(generated, {}); std::unique_ptr<FormSaver> cloned_saver = form_saver().Clone(); std::unique_ptr<PasswordGenerationState> cloned_state = original->Clone(cloned_saver.get()); original.reset(); EXPECT_CALL(store(), UpdateLoginWithPrimaryKey(_, _)); cloned_state->PresaveGeneratedPassword(generated, {}); } } // namespace } // namespace password_manager
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ecb2d694fe0896503192ffd8cef6574f31941dc1
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/12_21114_30.cpp
cc093b6656190654746fada02bb937fab5bfe32a
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,491
cpp
#include<algorithm> #include<cassert> #include<complex> #include<cstdio> #include<cstring> #include<iostream> #include<map> #include<queue> #include<set> #include<sstream> #include<stack> #include<string> #include<vector> #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define FORD(i,a,b) for(int i=(a);i>=(b);--i) #define REP(i,n) for(int i=0;i<(n);++i) #define fup FOR #define fdo FORD #define VAR(v,i) __typeof(i) v=(i) #define FORE(i,c) for(VAR(i,(c).begin());i!=(c).end();++i) #define ALL(x) (x).begin(),(x).end() #define SIZE(x) ((int)(x).size()) #define SZ SIZE #define CLR memset((x),0,sizeof (x)) #define PB push_back #define MP make_pair #define FI first #define SE second #define SQR(a) ((a)*(a)) #define DEBUG 1 #define debug(x) {if(DEBUG) cerr << #x << " = " << x << endl;} #define debugv(x) {if(DEBUG) {cerr << #x << " = "; FORE(it,(x)) cerr << *it << " . "; cerr <<endl;}} using namespace std; typedef long long LL; typedef long double LD; typedef pair<int,int> PII; typedef vector<int> VI; typedef VI vi; typedef LL lli; const int inf = 1000000000; int dx[6] = {1, 0, -1, -1, 0, 1}, dy[6] = {1, 1, 0, -1, -1, 0}; int ng(PII p, PII q) { int ddx = p.FI - q.FI; int ddy = p.SE - q.SE; REP(i, 6) if(ddx == dx[i] && ddy == dy[i]) return i; return -1; } int s; int corner(int i, int j) { if (i == 2*s-1) { if (j == 2*s-1) return 0; else if (j == s) return 5; } else if (i == s) { if (j == 2*s-1) return 1; else if (j == 1) return 4; } else if (i == 1) { if (j == s) return 2; else if (j == 1) return 3; } return -1; } int edge(int i, int j) { if (i == 2*s-1) return 5; else if (j == 2*s-1) return 0; else if (j-i == s-1) return 1; else if (i == 1) return 2; else if (j == 1) return 3; else if (i-j == s-1) return 4; return -1; } const int MN = 101; int cmp[MN][MN]; const int MAXN = MN * MN; vector<PII> C[MAXN]; int crn[MAXN]; int edg[MAXN][6]; int c; int comp(int x, int y) { cmp[x][y] = c; REP(i, 6) edg[c][i] = 0; crn[c] = 0; C[c]= vector<PII>(); C[c].PB(MP(x,y)); int cr = corner(x,y); if (cr != -1) crn[c] = 1; else { int e = edge(x, y); if (e != -1) edg[c][e] = 1; } return c++; } bool bridge, ffork, ring; int merge(int c1, int c2) { if (c1 == c2) return c1; if (SZ(C[c1]) < SZ(C[c2])) swap(c1, c2); FORE(it, C[c2]) { cmp[it->FI][it->SE] = c1; C[c1].PB(*it); } crn[c1] += crn[c2]; int e = 0; REP(i, 6) { edg[c1][i] |= edg[c2][i]; e += edg[c1][i]; assert(edg[c1][i] == 0 || edg[c1][i] == 1); } if (e >= 3) ffork = true; if (crn[c1]>=2) bridge = true; return c1; } void solve(int tcase) { int m; scanf("%d%d", &s, &m); //printf("%d %d\n", s,m); c = 0; REP(i, 2*s+1) REP(j, 2*s+1) { cmp[i][j] = -1; } REP(i, MAXN) { crn[i] = 0; REP(t, 6) edg[i][t] = 0; C[i].clear(); } printf("Case #%d: ", tcase); bool d = false; bridge = ffork = ring = false; REP(i, m) { int x, y; scanf("%d%d", &x, &y); if (!d) { int n[12]; int cm = comp(x, y); REP(t, 6) { n[t] = cmp[x+dx[t]][y+dy[t]]; n[t+6] = n[t]; } REP(t, 6) { if (n[t] != -1) { cm = merge(cm, cmp[x+dx[t]][y+dy[t]]); } } REP(t, 6) { FOR(j,1, 5) { if (n[t] != -1 && n[t+1] == -1 && n[t] == n[t+j] && n[t+j+1] == -1) ring = true; } } if (bridge) { printf("bridge"); if (ffork || ring) printf("-"); } if (ffork) { printf("fork"); if (ring) printf("-"); } if (ring) printf("ring"); if (bridge || ffork || ring) { printf(" in move %d\n", i+1); d = true; } } } if (!d) printf("none\n"); } int main() { int t; scanf("%d", &t); s = 3; /* FOR(i,1, 5) FOR(j,1, 5) { int cr = corner(i,j); int e = edge(i,j); if (i-j >= 3 || j-i >= 3) continue; if (cr != -1) printf("%d %d: C %d\n", i,j,cr); else if (e != -1) printf("%d %d E %d\n", i,j,e); }*/ REP(i, t) solve(i+1); return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
296159bea89346bf337f1cdab663dd7e2619d315
9e3bf531bb53bf4e25cb3d843fd2b19f2567b4a8
/w3/Text.cpp
d8ec30c8fcb8fdb82e6d9cb54cdf2a2139a8e6bf
[]
no_license
vithusonv/OOP345
e177b018d7bf4d86d84e1de7a3d3212739fbb3a1
c08cd2576842bea047e51e529d322c62f536665e
refs/heads/master
2020-03-30T02:14:15.561489
2018-09-27T17:14:23
2018-09-27T17:14:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,981
cpp
//includes #include <fstream> #include <string> #include <iostream> #include "Text.h" //namespaces using namespace std; namespace w3 { Text::Text():count(0),lineTable(nullptr) { } Text::Text(const char* filename):count(0),lineTable(nullptr) { ifstream is(filename); if(is.is_open()) { string line; while(getline(is,line)) { count++; } cout << "Read" << count << "lines\n"; lineTable= new string[count]; is.clear(); is.seekg(0); for(int line=0;line < count;line++) { getline(is,lineTable[line]); auto cr = lineTable[line].find('\r'); if(cr != std::string::npos) { lineTable[line].erase(cr); } } int lines = count; if(lines > 20) { lines=20; } for(int line=0;line < lines;line++) { cout << line+1 << ":" << lineTable[line] << "\n"; } is.close(); } else { cerr << "Cannot open file " << filename << "\n"; exit(1); } } Text& Text::operator=(const Text& rhs) { if(this != &rhs) { if(lineTable) { delete [] lineTable; lineTable = nullptr; count = 0; } count = rhs.count; if(count) { lineTable = new std::string[count]; for(int line=0;line < count;line++) { lineTable[line]=rhs.lineTable[line]; } } } return *this; } Text&& Text::operator=(Text& rhs) { if(this != &rhs) { if(lineTable) { delete [] lineTable; lineTable = nullptr; count = 0; } count = rhs.count; lineTable=rhs.lineTable; rhs.count=0; rhs.lineTable=nullptr; } return move(*this); } Text::Text(const Text& rhs):count(0),lineTable(nullptr) { *this = rhs; } Text::Text(Text&& rhs):count(0),lineTable(nullptr) { *this = move(rhs); } Text::~Text() { delete [] lineTable; } size_t Text::size() { return count; } }
[ "noreply@github.com" ]
vithusonv.noreply@github.com
9a43fb21618de67c2756653de7e5e3e4d00923a3
e99c20155e9b08c7e7598a3f85ccaedbd127f632
/ sjtu-project-pipe/thirdparties/VTK.Net/src/Filtering/vtkVertex.cxx
d7db4aac28986a09ce782f496a93a97724c1bdbb
[ "BSD-3-Clause" ]
permissive
unidevop/sjtu-project-pipe
38f00462d501d9b1134ce736bdfbfe4f9d075e4a
5a09f098db834d5276a2921d861ef549961decbe
refs/heads/master
2020-05-16T21:32:47.772410
2012-03-19T01:24:14
2012-03-19T01:24:14
38,281,086
1
1
null
null
null
null
UTF-8
C++
false
false
8,081
cxx
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkVertex.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkVertex.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointLocator.h" #include "vtkPoints.h" vtkCxxRevisionMacro(vtkVertex, "$Revision: 1.1 $"); vtkStandardNewMacro(vtkVertex); //---------------------------------------------------------------------------- // Construct the vertex with a single point. vtkVertex::vtkVertex() { this->Points->SetNumberOfPoints(1); this->PointIds->SetNumberOfIds(1); for (int i = 0; i < 1; i++) { this->Points->SetPoint(i, 0.0, 0.0, 0.0); this->PointIds->SetId(i,0); } } //---------------------------------------------------------------------------- // Make a new vtkVertex object with the same information as this object. int vtkVertex::EvaluatePosition(double x[3], double* closestPoint, int& subId, double pcoords[3], double& dist2, double *weights) { double X[3]; subId = 0; pcoords[1] = pcoords[2] = 0.0; this->Points->GetPoint(0, X); if (closestPoint) { closestPoint[0] = X[0]; closestPoint[1] = X[1]; closestPoint[2] = X[2]; } dist2 = vtkMath::Distance2BetweenPoints(X,x); weights[0] = 1.0; if (dist2 == 0.0) { pcoords[0] = 0.0; return 1; } else { pcoords[0] = -10.0; return 0; } } //---------------------------------------------------------------------------- void vtkVertex::EvaluateLocation(int& vtkNotUsed(subId), double vtkNotUsed(pcoords)[3], double x[3], double *weights) { this->Points->GetPoint(0, x); weights[0] = 1.0; } //---------------------------------------------------------------------------- // Given parametric coordinates of a point, return the closest cell boundary, // and whether the point is inside or outside of the cell. The cell boundary // is defined by a list of points (pts) that specify a vertex (1D cell). // If the return value of the method is != 0, then the point is inside the cell. int vtkVertex::CellBoundary(int vtkNotUsed(subId), double pcoords[3], vtkIdList *pts) { pts->SetNumberOfIds(1); pts->SetId(0,this->PointIds->GetId(0)); if ( pcoords[0] != 0.0 ) { return 0; } else { return 1; } } //---------------------------------------------------------------------------- // Generate contouring primitives. The scalar list cellScalars are // scalar values at each cell point. The point locator is essentially a // points list that merges points as they are inserted (i.e., prevents // duplicates). void vtkVertex::Contour(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkCellArray *vtkNotUsed(lines), vtkCellArray *vtkNotUsed(polys), vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd) { if ( value == cellScalars->GetComponent(0,0) ) { int newCellId; vtkIdType pts[1]; pts[0] = locator->InsertNextPoint(this->Points->GetPoint(0)); if ( outPd ) { outPd->CopyData(inPd,this->PointIds->GetId(0),pts[0]); } newCellId = verts->InsertNextCell(1,pts); outCd->CopyData(inCd,cellId,newCellId); } } //---------------------------------------------------------------------------- // Intersect with a ray. Return parametric coordinates (both line and cell) // and global intersection coordinates, given ray definition and tolerance. // The method returns non-zero value if intersection occurs. int vtkVertex::IntersectWithLine(double p1[3], double p2[3], double tol, double& t, double x[3], double pcoords[3], int& subId) { int i; double X[3], ray[3], rayFactor, projXYZ[3]; subId = 0; pcoords[1] = pcoords[2] = 0.0; this->Points->GetPoint(0, X); for (i=0; i<3; i++) { ray[i] = p2[i] - p1[i]; } if (( rayFactor = vtkMath::Dot(ray,ray)) == 0.0 ) { return 0; } // // Project each point onto ray. Determine whether point is within tolerance. // t = (ray[0]*(X[0]-p1[0]) + ray[1]*(X[1]-p1[1]) + ray[2]*(X[2]-p1[2])) / rayFactor; if ( t >= 0.0 && t <= 1.0 ) { for (i=0; i<3; i++) { projXYZ[i] = p1[i] + t*ray[i]; if ( fabs(X[i]-projXYZ[i]) > tol ) { break; } } if ( i > 2 ) // within tolerance { pcoords[0] = 0.0; x[0] = X[0]; x[1] = X[1]; x[2] = X[2]; return 1; } } pcoords[0] = -10.0; return 0; } //---------------------------------------------------------------------------- // Triangulate the vertex. This method fills pts and ptIds with information // from the only point in the vertex. int vtkVertex::Triangulate(int vtkNotUsed(index),vtkIdList *ptIds, vtkPoints *pts) { pts->Reset(); ptIds->Reset(); pts->InsertPoint(0,this->Points->GetPoint(0)); ptIds->InsertId(0,this->PointIds->GetId(0)); return 1; } //---------------------------------------------------------------------------- // Get the derivative of the vertex. Returns (0.0, 0.0, 0.0) for all // dimensions. void vtkVertex::Derivatives(int vtkNotUsed(subId), double vtkNotUsed(pcoords)[3], double *vtkNotUsed(values), int dim, double *derivs) { int i, idx; for (i=0; i<dim; i++) { idx = i*dim; derivs[idx] = 0.0; derivs[idx+1] = 0.0; derivs[idx+2] = 0.0; } } //---------------------------------------------------------------------------- void vtkVertex::Clip(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd, int insideOut) { double s, x[3]; int newCellId; vtkIdType pts[1]; s = cellScalars->GetComponent(0,0); if ( ( !insideOut && s > value) || (insideOut && s <= value) ) { this->Points->GetPoint(0, x); if ( locator->InsertUniquePoint(x, pts[0]) ) { outPd->CopyData(inPd,this->PointIds->GetId(0),pts[0]); } newCellId = verts->InsertNextCell(1,pts); outCd->CopyData(inCd,cellId,newCellId); } } //---------------------------------------------------------------------------- // Compute interpolation functions // void vtkVertex::InterpolationFunctions(double vtkNotUsed(pcoords)[3], double weights[1]) { weights[0] = 1.0; } //---------------------------------------------------------------------------- static double vtkVertexCellPCoords[3] = {0.0,0.0,0.0}; double *vtkVertex::GetParametricCoords() { return vtkVertexCellPCoords; } //---------------------------------------------------------------------------- void vtkVertex::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
[ "useminmin@gmail.com" ]
useminmin@gmail.com
eb07b041fa0259d2c4c79379b3437e0a385b15fa
090243cf699213f32f870baf2902eb4211f825d6
/CDOJ/Contest/56/A.cpp
5743875ae3269ae4c7662747b643546e1d97e8e0
[]
no_license
zhu-he/ACM-Source
0d4d0ac0668b569846b12297e7ed4abbb1c16571
02e3322e50336063d0d2dad37b2761ecb3d4e380
refs/heads/master
2021-06-07T18:27:19.702607
2016-07-10T09:20:48
2016-07-10T09:20:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,218
cpp
#include <cstdio> #include <cstring> #include <queue> #include <vector> #include <algorithm> #include <map> using namespace std; struct Node { long long w; int p; bool operator < (const Node rhs) const { return w > rhs.w || (w == rhs.w && p < rhs.p); } }; int n, m; vector<pair<int, int> > G[100000]; int s, e, p1, p2, K; bool vis[100000]; long long solve(int from, int to) { priority_queue<Node> q; q.push((Node) {0, from}); while (!q.empty()) { Node p = q.top(); q.pop(); if (p.p == to) { return p.w; } vis[p.p] = true; for (int i = 0; i < G[p.p].size(); ++i) { int v = G[p.p][i].first; if (!vis[v]) { int w = G[p.p][i].second; Node t; t.p = v; t.w = p.w + w; q.push(t); } } } return -1; } int main() { int T; scanf("%d", &T); for (int kase = 1; kase <= T; ++kase) { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) { G[i].clear(); } map<pair<int, int>, int> roads; for (int i = 0; i < m; ++i) { int x, y, w; scanf("%d %d %d", &x, &y, &w); if (x > y) { swap(x, y); } pair<int, int> p = make_pair(x, y); if ((roads.count(p) && roads[p] > w) || !roads.count(p)) { roads[p] = w; } } for (map<pair<int, int>, int>::iterator i = roads.begin(); i != roads.end(); ++i) { int x = i->first.first; int y = i->first.second; int w = i->second; G[x].push_back(make_pair(y, w)); G[y].push_back(make_pair(x, w)); } scanf("%d %d %d %d %d", &s, &e, &p1, &p2, &K); memset(vis, 0, sizeof(vis)); vis[p1] = true; long long se = solve(s, e); memset(vis, 0, sizeof(vis)); long long sp1 = solve(s, p1); memset(vis, 0, sizeof(vis)); long long p2e = solve(p2, e); memset(vis, 0, sizeof(vis)); long long p1p2 = solve(p1, p2); memset(vis, 0, sizeof(vis)); vis[p1] = true; long long _p2e = solve(p2, e); long long ans = -1; if (se != -1 && p1 != s) { ans = se; } if (sp1 != -1 && p1p2 != -1 && p2e != -1 && (ans == -1 || ans > sp1 + p1p2 * (K - 1) + p2e)) { ans = sp1 + p1p2 * (K - 1) + p2e; } if (sp1 != -1 && _p2e != -1 && (ans == -1 || ans > sp1 + _p2e)) { ans = sp1 + _p2e; } printf("Case #%d: %lld\n", kase, ans); } return 0; }
[ "841815229@qq.com" ]
841815229@qq.com
90123c38dca741d98842db37053b03a1949504c3
6edda4cef6bea60a7d38041a833508bcd51a0fbc
/3110.cpp
b207e8b1aa04a9906f76019ff5ec01bb2d253cd2
[]
no_license
IIIIIIIIIU/onlysky
addd908364c2e4f42dfdf09b0ea7995b354b78f6
c534c66a3e208734f3fd6f3eb9b76e82a9e6d036
refs/heads/master
2021-09-14T21:45:40.795263
2018-05-20T07:49:28
2018-05-20T07:49:28
104,289,423
2
1
null
null
null
null
UTF-8
C++
false
false
2,590
cpp
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> typedef unsigned int uint; const int maxn=5e4+5; const int maxtree=maxn<<2|1; const int maxtree2=maxn*400; struct operation { int op,a,b,c; }; struct operation oper[maxn]; int n,m,ai[maxn],num,ch[maxtree2][2],root[maxtree],tot,L[maxtree],R[maxtree]; int mid[maxtree]; uint val[maxtree2],tag[maxtree2]; inline void read(int &now) { char Cget; now=0; int if_z=1; while(!isdigit(Cget=getchar())) if(Cget=='-') if_z=-1; while(isdigit(Cget)) { now=now*10+Cget-'0'; Cget=getchar(); } now*=if_z; } inline void pushdown(int now,int l,int r) { if(!ch[now][0]) ch[now][0]=++tot; if(!ch[now][1]) ch[now][1]=++tot; int Mid=l+r>>1; val[ch[now][0]]+=(Mid-l+1)*tag[now]; val[ch[now][1]]+=(r-Mid)*tag[now]; tag[ch[now][0]]+=tag[now]; tag[ch[now][1]]+=tag[now]; tag[now]=0; } inline void ADD(int &now,int l,int r,int tl,int tr) { if(!now) now=++tot; if(l>=tl&&r<=tr) { val[now]+=r-l+1; tag[now]++; return; } if(tag[now]) pushdown(now,l,r); int Mid=l+r>>1; if(tl<=Mid) ADD(ch[now][0],l,Mid,tl,tr); if(tr>Mid) ADD(ch[now][1],Mid+1,r,tl,tr); val[now]=val[ch[now][0]]+val[ch[now][1]]; } inline uint QUERY(int now,int l,int r,int tl,int tr) { if(!now) return 0; if(l>=tl&&r<=tr) return val[now]; if(tag[now]) pushdown(now,l,r); uint Mid=l+r>>1,res=0; if(tl<=Mid) res+=QUERY(ch[now][0],l,Mid,tl,tr); if(tr>Mid) res+=QUERY(ch[now][1],Mid+1,r,tl,tr); return res; } void build(int now,int l,int r) { L[now]=l; R[now]=r; if(l==r) return; mid[now]=l+r>>1; build(now<<1,l,mid[now]); build(now<<1|1,mid[now]+1,r); } inline void add(int now,int to,int a,int b) { ADD(root[now],1,n,a,b); if(L[now]==R[now]) return; if(to<=mid[now]) add(now<<1,to,a,b); else add(now<<1|1,to,a,b); } inline int query(int now,int a,int b,int c) { if(L[now]==R[now]) return ai[L[now]]; uint tmp=QUERY(root[now<<1|1],1,n,a,b); if(tmp>=c) return query(now<<1|1,a,b,c); else return query(now<<1,a,b,c-tmp); } int main() { freopen("data.txt","r",stdin); read(n); read(m); for(int i=1;i<=m;i++) { read(oper[i].op); read(oper[i].a); read(oper[i].b); read(oper[i].c); if(oper[i].op==1) ai[++num]=oper[i].c; } std::sort(ai+1,ai+num+1); num=std::unique(ai+1,ai+num+1)-ai-1; for(int i=1;i<=m;i++) if(oper[i].op==1) oper[i].c=std::lower_bound(ai+1,ai+num+1,oper[i].c)-ai; build(1,1,num); for(int i=1;i<=m;i++) if(oper[i].op==1) add(1,oper[i].c,oper[i].a,oper[i].b); else printf("%d\n",query(1,oper[i].a,oper[i].b,oper[i].c)); return 0; }
[ "noreply@github.com" ]
IIIIIIIIIU.noreply@github.com
4b7f4d145c3641cfa2bbf8b04cfd3365d244c5c3
3dbe9a64fbac88d53aeec8bf9c5b544c63d6352d
/pointer.cpp
b5751618a795d3e6c62d679fc14504d44843d0ef
[]
no_license
nidjaj/Data-structure
7d19dd4b324efff30cf14a3d25f9ccdce8a3a26f
a915a4dfa23f789ffcac1f0a806119014640970e
refs/heads/master
2022-07-30T16:04:50.619535
2020-05-19T17:59:40
2020-05-19T17:59:40
263,988,130
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
#include<stdio.h> int main() { int a=10; int *p; if(p) printf("hi"); else printf("bye"); p=&a; if(p) printf("hi"); else printf("bye"); }
[ "noreply@github.com" ]
nidjaj.noreply@github.com
251fa57b6d943041be67645af8518081706328e4
0a626f9383a7a9b5085f63e6ce214ae8e19203cc
/src/wasm/function-body-decoder-impl.h
6c47141d375da513a9231086b3485e7a2d40c305
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
xtuc/v8
8a494f80ad65f6597f766bf8b295740ae07a4adc
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
refs/heads/master
2021-09-28T21:30:37.358269
2018-11-20T04:58:57
2018-11-20T06:36:53
153,456,519
0
0
NOASSERTION
2018-11-06T14:37:55
2018-10-17T12:53:24
C++
UTF-8
C++
false
false
98,300
h
// Copyright 2017 the V8 project 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 V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ #define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ // Do only include this header for implementing new Interface of the // WasmFullDecoder. #include "src/base/platform/elapsed-timer.h" #include "src/bit-vector.h" #include "src/wasm/decoder.h" #include "src/wasm/function-body-decoder.h" #include "src/wasm/wasm-features.h" #include "src/wasm/wasm-limits.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-opcodes.h" namespace v8 { namespace internal { namespace wasm { struct WasmGlobal; struct WasmException; #define TRACE(...) \ do { \ if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \ } while (false) #define TRACE_INST_FORMAT " @%-8d #%-20s|" // Return the evaluation of `condition` if validate==true, DCHECK that it's // true and always return true otherwise. #define VALIDATE(condition) \ (validate ? (condition) : [&] { \ DCHECK(condition); \ return true; \ }()) #define RET_ON_PROTOTYPE_OPCODE(feat) \ DCHECK(!this->module_ || this->module_->origin == kWasmOrigin); \ if (!this->enabled_.feat) { \ this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \ } else { \ this->detected_->feat = true; \ } #define CHECK_PROTOTYPE_OPCODE(feat) \ DCHECK(!this->module_ || this->module_->origin == kWasmOrigin); \ if (!this->enabled_.feat) { \ this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \ break; \ } else { \ this->detected_->feat = true; \ } #define OPCODE_ERROR(opcode, message) \ (this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \ (message))) #define ATOMIC_OP_LIST(V) \ V(AtomicWake, Uint32) \ V(I32AtomicWait, Uint32) \ V(I32AtomicLoad, Uint32) \ V(I64AtomicLoad, Uint64) \ V(I32AtomicLoad8U, Uint8) \ V(I32AtomicLoad16U, Uint16) \ V(I64AtomicLoad8U, Uint8) \ V(I64AtomicLoad16U, Uint16) \ V(I64AtomicLoad32U, Uint32) \ V(I32AtomicAdd, Uint32) \ V(I32AtomicAdd8U, Uint8) \ V(I32AtomicAdd16U, Uint16) \ V(I64AtomicAdd, Uint64) \ V(I64AtomicAdd8U, Uint8) \ V(I64AtomicAdd16U, Uint16) \ V(I64AtomicAdd32U, Uint32) \ V(I32AtomicSub, Uint32) \ V(I64AtomicSub, Uint64) \ V(I32AtomicSub8U, Uint8) \ V(I32AtomicSub16U, Uint16) \ V(I64AtomicSub8U, Uint8) \ V(I64AtomicSub16U, Uint16) \ V(I64AtomicSub32U, Uint32) \ V(I32AtomicAnd, Uint32) \ V(I64AtomicAnd, Uint64) \ V(I32AtomicAnd8U, Uint8) \ V(I32AtomicAnd16U, Uint16) \ V(I64AtomicAnd8U, Uint8) \ V(I64AtomicAnd16U, Uint16) \ V(I64AtomicAnd32U, Uint32) \ V(I32AtomicOr, Uint32) \ V(I64AtomicOr, Uint64) \ V(I32AtomicOr8U, Uint8) \ V(I32AtomicOr16U, Uint16) \ V(I64AtomicOr8U, Uint8) \ V(I64AtomicOr16U, Uint16) \ V(I64AtomicOr32U, Uint32) \ V(I32AtomicXor, Uint32) \ V(I64AtomicXor, Uint64) \ V(I32AtomicXor8U, Uint8) \ V(I32AtomicXor16U, Uint16) \ V(I64AtomicXor8U, Uint8) \ V(I64AtomicXor16U, Uint16) \ V(I64AtomicXor32U, Uint32) \ V(I32AtomicExchange, Uint32) \ V(I64AtomicExchange, Uint64) \ V(I32AtomicExchange8U, Uint8) \ V(I32AtomicExchange16U, Uint16) \ V(I64AtomicExchange8U, Uint8) \ V(I64AtomicExchange16U, Uint16) \ V(I64AtomicExchange32U, Uint32) \ V(I32AtomicCompareExchange, Uint32) \ V(I64AtomicCompareExchange, Uint64) \ V(I32AtomicCompareExchange8U, Uint8) \ V(I32AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange8U, Uint8) \ V(I64AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange32U, Uint32) #define ATOMIC_STORE_OP_LIST(V) \ V(I32AtomicStore, Uint32) \ V(I64AtomicStore, Uint64) \ V(I32AtomicStore8U, Uint8) \ V(I32AtomicStore16U, Uint16) \ V(I64AtomicStore8U, Uint8) \ V(I64AtomicStore16U, Uint16) \ V(I64AtomicStore32U, Uint32) // Helpers for decoding different kinds of immediates which follow bytecodes. template <Decoder::ValidateFlag validate> struct LocalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; unsigned length; inline LocalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "local index"); } }; template <Decoder::ValidateFlag validate> struct ExceptionIndexImmediate { uint32_t index; const WasmException* exception = nullptr; unsigned length; inline ExceptionIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "exception index"); } }; template <Decoder::ValidateFlag validate> struct ImmI32Immediate { int32_t value; unsigned length; inline ImmI32Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i32v<validate>(pc + 1, &length, "immi32"); } }; template <Decoder::ValidateFlag validate> struct ImmI64Immediate { int64_t value; unsigned length; inline ImmI64Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i64v<validate>(pc + 1, &length, "immi64"); } }; template <Decoder::ValidateFlag validate> struct ImmF32Immediate { float value; unsigned length = 4; inline ImmF32Immediate(Decoder* decoder, const byte* pc) { // Avoid bit_cast because it might not preserve the signalling bit of a NaN. uint32_t tmp = decoder->read_u32<validate>(pc + 1, "immf32"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct ImmF64Immediate { double value; unsigned length = 8; inline ImmF64Immediate(Decoder* decoder, const byte* pc) { // Avoid bit_cast because it might not preserve the signalling bit of a NaN. uint64_t tmp = decoder->read_u64<validate>(pc + 1, "immf64"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct GlobalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; const WasmGlobal* global = nullptr; unsigned length; inline GlobalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "global index"); } }; template <Decoder::ValidateFlag validate> struct BlockTypeImmediate { unsigned length = 1; ValueType type = kWasmStmt; uint32_t sig_index = 0; FunctionSig* sig = nullptr; inline BlockTypeImmediate(const WasmFeatures& enabled, Decoder* decoder, const byte* pc) { uint8_t val = decoder->read_u8<validate>(pc + 1, "block type"); if (!decode_local_type(val, &type)) { // Handle multi-value blocks. if (!VALIDATE(enabled.mv)) { decoder->error(pc + 1, "invalid block type"); return; } if (!VALIDATE(decoder->ok())) return; int32_t index = decoder->read_i32v<validate>(pc + 1, &length, "block arity"); if (!VALIDATE(length > 0 && index >= 0)) { decoder->error(pc + 1, "invalid block type index"); return; } sig_index = static_cast<uint32_t>(index); } } // Decode a byte representing a local type. Return {false} if the encoded // byte was invalid or the start of a type index. inline bool decode_local_type(uint8_t val, ValueType* result) { switch (static_cast<ValueTypeCode>(val)) { case kLocalVoid: *result = kWasmStmt; return true; case kLocalI32: *result = kWasmI32; return true; case kLocalI64: *result = kWasmI64; return true; case kLocalF32: *result = kWasmF32; return true; case kLocalF64: *result = kWasmF64; return true; case kLocalS128: *result = kWasmS128; return true; case kLocalAnyFunc: *result = kWasmAnyFunc; return true; case kLocalAnyRef: *result = kWasmAnyRef; return true; default: *result = kWasmVar; return false; } } uint32_t in_arity() const { if (type != kWasmVar) return 0; return static_cast<uint32_t>(sig->parameter_count()); } uint32_t out_arity() const { if (type == kWasmStmt) return 0; if (type != kWasmVar) return 1; return static_cast<uint32_t>(sig->return_count()); } ValueType in_type(uint32_t index) { DCHECK_EQ(kWasmVar, type); return sig->GetParam(index); } ValueType out_type(uint32_t index) { if (type == kWasmVar) return sig->GetReturn(index); DCHECK_NE(kWasmStmt, type); DCHECK_EQ(0, index); return type; } }; template <Decoder::ValidateFlag validate> struct BreakDepthImmediate { uint32_t depth; unsigned length; inline BreakDepthImmediate(Decoder* decoder, const byte* pc) { depth = decoder->read_u32v<validate>(pc + 1, &length, "break depth"); } }; template <Decoder::ValidateFlag validate> struct CallIndirectImmediate { uint32_t table_index; uint32_t sig_index; FunctionSig* sig = nullptr; unsigned length = 0; inline CallIndirectImmediate(Decoder* decoder, const byte* pc) { unsigned len = 0; sig_index = decoder->read_u32v<validate>(pc + 1, &len, "signature index"); if (!VALIDATE(decoder->ok())) return; table_index = decoder->read_u8<validate>(pc + 1 + len, "table index"); if (!VALIDATE(table_index == 0)) { decoder->errorf(pc + 1 + len, "expected table index 0, found %u", table_index); } length = 1 + len; } }; template <Decoder::ValidateFlag validate> struct CallFunctionImmediate { uint32_t index; FunctionSig* sig = nullptr; unsigned length; inline CallFunctionImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "function index"); } }; template <Decoder::ValidateFlag validate> struct MemoryIndexImmediate { uint32_t index; unsigned length = 1; inline MemoryIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u8<validate>(pc + 1, "memory index"); if (!VALIDATE(index == 0)) { decoder->errorf(pc + 1, "expected memory index 0, found %u", index); } } }; template <Decoder::ValidateFlag validate> struct TableIndexImmediate { uint32_t index; unsigned length = 1; inline TableIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u8<validate>(pc + 1, "table index"); if (!VALIDATE(index == 0)) { decoder->errorf(pc + 1, "expected table index 0, found %u", index); } } }; template <Decoder::ValidateFlag validate> struct BranchTableImmediate { uint32_t table_count; const byte* start; const byte* table; inline BranchTableImmediate(Decoder* decoder, const byte* pc) { DCHECK_EQ(kExprBrTable, decoder->read_u8<validate>(pc, "opcode")); start = pc + 1; unsigned len = 0; table_count = decoder->read_u32v<validate>(pc + 1, &len, "table count"); table = pc + 1 + len; } }; // A helper to iterate over a branch table. template <Decoder::ValidateFlag validate> class BranchTableIterator { public: unsigned cur_index() { return index_; } bool has_next() { return VALIDATE(decoder_->ok()) && index_ <= table_count_; } uint32_t next() { DCHECK(has_next()); index_++; unsigned length; uint32_t result = decoder_->read_u32v<validate>(pc_, &length, "branch table entry"); pc_ += length; return result; } // length, including the length of the {BranchTableImmediate}, but not the // opcode. unsigned length() { while (has_next()) next(); return static_cast<unsigned>(pc_ - start_); } const byte* pc() { return pc_; } BranchTableIterator(Decoder* decoder, const BranchTableImmediate<validate>& imm) : decoder_(decoder), start_(imm.start), pc_(imm.table), table_count_(imm.table_count) {} private: Decoder* decoder_; const byte* start_; const byte* pc_; uint32_t index_ = 0; // the current index. uint32_t table_count_; // the count of entries, not including default. }; template <Decoder::ValidateFlag validate> struct MemoryAccessImmediate { uint32_t alignment; uint32_t offset; unsigned length = 0; inline MemoryAccessImmediate(Decoder* decoder, const byte* pc, uint32_t max_alignment) { unsigned alignment_length; alignment = decoder->read_u32v<validate>(pc + 1, &alignment_length, "alignment"); if (!VALIDATE(alignment <= max_alignment)) { decoder->errorf(pc + 1, "invalid alignment; expected maximum alignment is %u, " "actual alignment is %u", max_alignment, alignment); } if (!VALIDATE(decoder->ok())) return; unsigned offset_length; offset = decoder->read_u32v<validate>(pc + 1 + alignment_length, &offset_length, "offset"); length = alignment_length + offset_length; } }; // Immediate for SIMD lane operations. template <Decoder::ValidateFlag validate> struct SimdLaneImmediate { uint8_t lane; unsigned length = 1; inline SimdLaneImmediate(Decoder* decoder, const byte* pc) { lane = decoder->read_u8<validate>(pc + 2, "lane"); } }; // Immediate for SIMD shift operations. template <Decoder::ValidateFlag validate> struct SimdShiftImmediate { uint8_t shift; unsigned length = 1; inline SimdShiftImmediate(Decoder* decoder, const byte* pc) { shift = decoder->read_u8<validate>(pc + 2, "shift"); } }; // Immediate for SIMD S8x16 shuffle operations. template <Decoder::ValidateFlag validate> struct Simd8x16ShuffleImmediate { uint8_t shuffle[kSimd128Size] = {0}; inline Simd8x16ShuffleImmediate(Decoder* decoder, const byte* pc) { for (uint32_t i = 0; i < kSimd128Size; ++i) { shuffle[i] = decoder->read_u8<validate>(pc + 2 + i, "shuffle"); if (!VALIDATE(decoder->ok())) return; } } }; template <Decoder::ValidateFlag validate> struct MemoryInitImmediate { MemoryIndexImmediate<validate> memory; uint32_t data_segment_index; unsigned length; inline MemoryInitImmediate(Decoder* decoder, const byte* pc) : memory(decoder, pc + 1) { data_segment_index = decoder->read_i32v<validate>( pc + 2 + memory.length, &length, "data segment index"); length += memory.length; } }; template <Decoder::ValidateFlag validate> struct MemoryDropImmediate { uint32_t index; unsigned length; inline MemoryDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_i32v<validate>(pc + 2, &length, "data segment index"); } }; template <Decoder::ValidateFlag validate> struct TableInitImmediate { TableIndexImmediate<validate> table; uint32_t elem_segment_index; unsigned length; inline TableInitImmediate(Decoder* decoder, const byte* pc) : table(decoder, pc + 1) { elem_segment_index = decoder->read_i32v<validate>( pc + 2 + table.length, &length, "elem segment index"); length += table.length; } }; template <Decoder::ValidateFlag validate> struct TableDropImmediate { uint32_t index; unsigned length; inline TableDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_i32v<validate>(pc + 2, &length, "elem segment index"); } }; // An entry on the value stack. struct ValueBase { const byte* pc; ValueType type; // Named constructors. static ValueBase Unreachable(const byte* pc) { return {pc, kWasmVar}; } static ValueBase New(const byte* pc, ValueType type) { return {pc, type}; } }; template <typename Value> struct Merge { uint32_t arity; union { Value* array; Value first; } vals; // Either multiple values or a single value. // Tracks whether this merge was ever reached. Uses precise reachability, like // Reachability::kReachable. bool reached; Merge(bool reached = false) : reached(reached) {} Value& operator[](uint32_t i) { DCHECK_GT(arity, i); return arity == 1 ? vals.first : vals.array[i]; } }; enum ControlKind : uint8_t { kControlIf, kControlIfElse, kControlBlock, kControlLoop, kControlTry, kControlTryCatch, kControlTryCatchAll }; enum Reachability : uint8_t { // reachable code. kReachable, // reachable code in unreachable block (implies normal validation). kSpecOnlyReachable, // code unreachable in its own block (implies polymorphic validation). kUnreachable }; // An entry on the control stack (i.e. if, block, loop, or try). template <typename Value> struct ControlBase { ControlKind kind; uint32_t stack_depth; // stack height at the beginning of the construct. const byte* pc; Reachability reachability = kReachable; // Values merged into the start or end of this control construct. Merge<Value> start_merge; Merge<Value> end_merge; ControlBase() = default; ControlBase(ControlKind kind, uint32_t stack_depth, const byte* pc) : kind(kind), stack_depth(stack_depth), pc(pc) {} // Check whether the current block is reachable. bool reachable() const { return reachability == kReachable; } // Check whether the rest of the block is unreachable. // Note that this is different from {!reachable()}, as there is also the // "indirect unreachable state", for which both {reachable()} and // {unreachable()} return false. bool unreachable() const { return reachability == kUnreachable; } // Return the reachability of new control structs started in this block. Reachability innerReachability() const { return reachability == kReachable ? kReachable : kSpecOnlyReachable; } bool is_if() const { return is_onearmed_if() || is_if_else(); } bool is_onearmed_if() const { return kind == kControlIf; } bool is_if_else() const { return kind == kControlIfElse; } bool is_block() const { return kind == kControlBlock; } bool is_loop() const { return kind == kControlLoop; } bool is_incomplete_try() const { return kind == kControlTry; } bool is_try_catch() const { return kind == kControlTryCatch; } bool is_try_catchall() const { return kind == kControlTryCatchAll; } bool is_try() const { return is_incomplete_try() || is_try_catch() || is_try_catchall(); } inline Merge<Value>* br_merge() { return is_loop() ? &this->start_merge : &this->end_merge; } // Named constructors. static ControlBase Block(const byte* pc, uint32_t stack_depth) { return {kControlBlock, stack_depth, pc}; } static ControlBase If(const byte* pc, uint32_t stack_depth) { return {kControlIf, stack_depth, pc}; } static ControlBase Loop(const byte* pc, uint32_t stack_depth) { return {kControlLoop, stack_depth, pc}; } static ControlBase Try(const byte* pc, uint32_t stack_depth) { return {kControlTry, stack_depth, pc}; } }; #define CONCRETE_NAMED_CONSTRUCTOR(concrete_type, abstract_type, name) \ template <typename... Args> \ static concrete_type name(Args&&... args) { \ concrete_type val; \ static_cast<abstract_type&>(val) = \ abstract_type::name(std::forward<Args>(args)...); \ return val; \ } // Provide the default named constructors, which default-initialize the // ConcreteType and the initialize the fields of ValueBase correctly. // Use like this: // struct Value : public ValueWithNamedConstructors<Value> { int new_field; }; template <typename ConcreteType> struct ValueWithNamedConstructors : public ValueBase { // Named constructors. CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, Unreachable) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ValueBase, New) }; // Provide the default named constructors, which default-initialize the // ConcreteType and the initialize the fields of ControlBase correctly. // Use like this: // struct Control : public ControlWithNamedConstructors<Control, Value> { // int my_uninitialized_field; // char* other_field = nullptr; // }; template <typename ConcreteType, typename Value> struct ControlWithNamedConstructors : public ControlBase<Value> { // Named constructors. CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Block) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, If) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Loop) CONCRETE_NAMED_CONSTRUCTOR(ConcreteType, ControlBase<Value>, Try) }; // This is the list of callback functions that an interface for the // WasmFullDecoder should implement. // F(Name, args...) #define INTERFACE_FUNCTIONS(F) \ /* General: */ \ F(StartFunction) \ F(StartFunctionBody, Control* block) \ F(FinishFunction) \ F(OnFirstError) \ F(NextInstruction, WasmOpcode) \ /* Control: */ \ F(Block, Control* block) \ F(Loop, Control* block) \ F(Try, Control* block) \ F(If, const Value& cond, Control* if_block) \ F(FallThruTo, Control* c) \ F(PopControl, Control* block) \ F(EndControl, Control* block) \ /* Instructions: */ \ F(UnOp, WasmOpcode opcode, FunctionSig*, const Value& value, Value* result) \ F(BinOp, WasmOpcode opcode, FunctionSig*, const Value& lhs, \ const Value& rhs, Value* result) \ F(I32Const, Value* result, int32_t value) \ F(I64Const, Value* result, int64_t value) \ F(F32Const, Value* result, float value) \ F(F64Const, Value* result, double value) \ F(RefNull, Value* result) \ F(Drop, const Value& value) \ F(DoReturn, Vector<Value> values, bool implicit) \ F(GetLocal, Value* result, const LocalIndexImmediate<validate>& imm) \ F(SetLocal, const Value& value, const LocalIndexImmediate<validate>& imm) \ F(TeeLocal, const Value& value, Value* result, \ const LocalIndexImmediate<validate>& imm) \ F(GetGlobal, Value* result, const GlobalIndexImmediate<validate>& imm) \ F(SetGlobal, const Value& value, const GlobalIndexImmediate<validate>& imm) \ F(Unreachable) \ F(Select, const Value& cond, const Value& fval, const Value& tval, \ Value* result) \ F(Br, Control* target) \ F(BrIf, const Value& cond, Control* target) \ F(BrTable, const BranchTableImmediate<validate>& imm, const Value& key) \ F(Else, Control* if_block) \ F(LoadMem, LoadType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, Value* result) \ F(StoreMem, StoreType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, const Value& value) \ F(CurrentMemoryPages, Value* result) \ F(MemoryGrow, const Value& value, Value* result) \ F(CallDirect, const CallFunctionImmediate<validate>& imm, \ const Value args[], Value returns[]) \ F(CallIndirect, const Value& index, \ const CallIndirectImmediate<validate>& imm, const Value args[], \ Value returns[]) \ F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result) \ F(SimdLaneOp, WasmOpcode opcode, const SimdLaneImmediate<validate>& imm, \ const Vector<Value> inputs, Value* result) \ F(SimdShiftOp, WasmOpcode opcode, const SimdShiftImmediate<validate>& imm, \ const Value& input, Value* result) \ F(Simd8x16ShuffleOp, const Simd8x16ShuffleImmediate<validate>& imm, \ const Value& input0, const Value& input1, Value* result) \ F(Throw, const ExceptionIndexImmediate<validate>& imm, \ const Vector<Value>& args) \ F(Rethrow, Control* block) \ F(CatchException, const ExceptionIndexImmediate<validate>& imm, \ Control* block, Vector<Value> caught_values) \ F(CatchAll, Control* block) \ F(AtomicOp, WasmOpcode opcode, Vector<Value> args, \ const MemoryAccessImmediate<validate>& imm, Value* result) \ F(MemoryInit, const MemoryInitImmediate<validate>& imm, Vector<Value> args) \ F(MemoryDrop, const MemoryDropImmediate<validate>& imm) \ F(MemoryCopy, const MemoryIndexImmediate<validate>& imm, Vector<Value> args) \ F(MemoryFill, const MemoryIndexImmediate<validate>& imm, Vector<Value> args) \ F(TableInit, const TableInitImmediate<validate>& imm, Vector<Value> args) \ F(TableDrop, const TableDropImmediate<validate>& imm) \ F(TableCopy, const TableIndexImmediate<validate>& imm, Vector<Value> args) // Generic Wasm bytecode decoder with utilities for decoding immediates, // lengths, etc. template <Decoder::ValidateFlag validate> class WasmDecoder : public Decoder { public: WasmDecoder(const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, FunctionSig* sig, const byte* start, const byte* end, uint32_t buffer_offset = 0) : Decoder(start, end, buffer_offset), module_(module), enabled_(enabled), detected_(detected), sig_(sig), local_types_(nullptr) {} const WasmModule* module_; const WasmFeatures enabled_; WasmFeatures* detected_; FunctionSig* sig_; ZoneVector<ValueType>* local_types_; uint32_t total_locals() const { return local_types_ == nullptr ? 0 : static_cast<uint32_t>(local_types_->size()); } static bool DecodeLocals(const WasmFeatures& enabled, Decoder* decoder, const FunctionSig* sig, ZoneVector<ValueType>* type_list) { DCHECK_NOT_NULL(type_list); DCHECK_EQ(0, type_list->size()); // Initialize from signature. if (sig != nullptr) { type_list->assign(sig->parameters().begin(), sig->parameters().end()); } // Decode local declarations, if any. uint32_t entries = decoder->consume_u32v("local decls count"); if (decoder->failed()) return false; TRACE("local decls count: %u\n", entries); while (entries-- > 0 && VALIDATE(decoder->ok()) && decoder->more()) { uint32_t count = decoder->consume_u32v("local count"); if (decoder->failed()) return false; DCHECK_LE(type_list->size(), kV8MaxWasmFunctionLocals); if (count > kV8MaxWasmFunctionLocals - type_list->size()) { decoder->error(decoder->pc() - 1, "local count too large"); return false; } byte code = decoder->consume_u8("local type"); if (decoder->failed()) return false; ValueType type; switch (code) { case kLocalI32: type = kWasmI32; break; case kLocalI64: type = kWasmI64; break; case kLocalF32: type = kWasmF32; break; case kLocalF64: type = kWasmF64; break; case kLocalAnyRef: if (enabled.anyref) { type = kWasmAnyRef; break; } decoder->error(decoder->pc() - 1, "invalid local type"); return false; case kLocalExceptRef: if (enabled.eh) { type = kWasmExceptRef; break; } decoder->error(decoder->pc() - 1, "invalid local type"); return false; case kLocalS128: if (enabled.simd) { type = kWasmS128; break; } V8_FALLTHROUGH; default: decoder->error(decoder->pc() - 1, "invalid local type"); return false; } type_list->insert(type_list->end(), count, type); } DCHECK(decoder->ok()); return true; } static BitVector* AnalyzeLoopAssignment(Decoder* decoder, const byte* pc, uint32_t locals_count, Zone* zone) { if (pc >= decoder->end()) return nullptr; if (*pc != kExprLoop) return nullptr; // The number of locals_count is augmented by 2 so that 'locals_count - 2' // can be used to track mem_size, and 'locals_count - 1' to track mem_start. BitVector* assigned = new (zone) BitVector(locals_count, zone); int depth = 0; // Iteratively process all AST nodes nested inside the loop. while (pc < decoder->end() && VALIDATE(decoder->ok())) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); unsigned length = 1; switch (opcode) { case kExprLoop: case kExprIf: case kExprBlock: case kExprTry: length = OpcodeLength(decoder, pc); depth++; break; case kExprSetLocal: // fallthru case kExprTeeLocal: { LocalIndexImmediate<validate> imm(decoder, pc); if (assigned->length() > 0 && imm.index < static_cast<uint32_t>(assigned->length())) { // Unverified code might have an out-of-bounds index. assigned->Add(imm.index); } length = 1 + imm.length; break; } case kExprMemoryGrow: case kExprCallFunction: case kExprCallIndirect: // Add instance cache nodes to the assigned set. // TODO(titzer): make this more clear. assigned->Add(locals_count - 1); length = OpcodeLength(decoder, pc); break; case kExprEnd: depth--; break; default: length = OpcodeLength(decoder, pc); break; } if (depth <= 0) break; pc += length; } return VALIDATE(decoder->ok()) ? assigned : nullptr; } inline bool Validate(const byte* pc, LocalIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < total_locals())) { errorf(pc + 1, "invalid local index: %u", imm.index); return false; } imm.type = local_types_ ? local_types_->at(imm.index) : kWasmStmt; return true; } inline bool Validate(const byte* pc, ExceptionIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->exceptions.size())) { errorf(pc + 1, "Invalid exception index: %u", imm.index); return false; } imm.exception = &module_->exceptions[imm.index]; return true; } inline bool Validate(const byte* pc, GlobalIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->globals.size())) { errorf(pc + 1, "invalid global index: %u", imm.index); return false; } imm.global = &module_->globals[imm.index]; imm.type = imm.global->type; return true; } inline bool Complete(const byte* pc, CallFunctionImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->functions.size())) { return false; } imm.sig = module_->functions[imm.index].sig; return true; } inline bool Validate(const byte* pc, CallFunctionImmediate<validate>& imm) { if (Complete(pc, imm)) { return true; } errorf(pc + 1, "invalid function index: %u", imm.index); return false; } inline bool Complete(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.sig_index < module_->signatures.size())) { return false; } imm.sig = module_->signatures[imm.sig_index]; return true; } inline bool Validate(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && !module_->tables.empty())) { error("function table has to exist to execute call_indirect"); return false; } if (!Complete(pc, imm)) { errorf(pc + 1, "invalid signature index: #%u", imm.sig_index); return false; } return true; } inline bool Validate(const byte* pc, BreakDepthImmediate<validate>& imm, size_t control_depth) { if (!VALIDATE(imm.depth < control_depth)) { errorf(pc + 1, "invalid break depth: %u", imm.depth); return false; } return true; } bool Validate(const byte* pc, BranchTableImmediate<validate>& imm, size_t block_depth) { if (!VALIDATE(imm.table_count < kV8MaxWasmFunctionSize)) { errorf(pc + 1, "invalid table count (> max function size): %u", imm.table_count); return false; } return checkAvailable(imm.table_count); } inline bool Validate(const byte* pc, WasmOpcode opcode, SimdLaneImmediate<validate>& imm) { uint8_t num_lanes = 0; switch (opcode) { case kExprF32x4ExtractLane: case kExprF32x4ReplaceLane: case kExprI32x4ExtractLane: case kExprI32x4ReplaceLane: num_lanes = 4; break; case kExprI16x8ExtractLane: case kExprI16x8ReplaceLane: num_lanes = 8; break; case kExprI8x16ExtractLane: case kExprI8x16ReplaceLane: num_lanes = 16; break; default: UNREACHABLE(); break; } if (!VALIDATE(imm.lane >= 0 && imm.lane < num_lanes)) { error(pc_ + 2, "invalid lane index"); return false; } else { return true; } } inline bool Validate(const byte* pc, WasmOpcode opcode, SimdShiftImmediate<validate>& imm) { uint8_t max_shift = 0; switch (opcode) { case kExprI32x4Shl: case kExprI32x4ShrS: case kExprI32x4ShrU: max_shift = 32; break; case kExprI16x8Shl: case kExprI16x8ShrS: case kExprI16x8ShrU: max_shift = 16; break; case kExprI8x16Shl: case kExprI8x16ShrS: case kExprI8x16ShrU: max_shift = 8; break; default: UNREACHABLE(); break; } if (!VALIDATE(imm.shift >= 0 && imm.shift < max_shift)) { error(pc_ + 2, "invalid shift amount"); return false; } else { return true; } } inline bool Validate(const byte* pc, Simd8x16ShuffleImmediate<validate>& imm) { uint8_t max_lane = 0; for (uint32_t i = 0; i < kSimd128Size; ++i) { max_lane = std::max(max_lane, imm.shuffle[i]); } // Shuffle indices must be in [0..31] for a 16 lane shuffle. if (!VALIDATE(max_lane <= 2 * kSimd128Size)) { error(pc_ + 2, "invalid shuffle mask"); return false; } return true; } inline bool Complete(BlockTypeImmediate<validate>& imm) { if (imm.type != kWasmVar) return true; if (!VALIDATE((module_ && imm.sig_index < module_->signatures.size()))) { return false; } imm.sig = module_->signatures[imm.sig_index]; return true; } inline bool Validate(BlockTypeImmediate<validate>& imm) { if (!Complete(imm)) { errorf(pc_, "block type index %u out of bounds (%zu signatures)", imm.sig_index, module_ ? module_->signatures.size() : 0); return false; } return true; } inline bool Validate(MemoryIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && module_->has_memory)) { errorf(pc_ + 1, "memory instruction with no memory"); return false; } return true; } inline bool Validate(MemoryInitImmediate<validate>& imm) { if (!Validate(imm.memory)) return false; // TODO(binji): validate imm.data_segment_index return true; } inline bool Validate(MemoryDropImmediate<validate>& imm) { // TODO(binji): validate imm.data_segment_index return true; } inline bool Validate(const byte* pc, TableIndexImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->tables.size())) { errorf(pc_ + 1, "invalid table index: %u", imm.index); return false; } return true; } inline bool Validate(TableInitImmediate<validate>& imm) { if (!Validate(pc_ + 1, imm.table)) return false; if (!VALIDATE(module_ != nullptr && imm.elem_segment_index < module_->table_inits.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.elem_segment_index); return false; } return true; } inline bool Validate(TableDropImmediate<validate>& imm) { if (!VALIDATE(module_ != nullptr && imm.index < module_->table_inits.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.index); return false; } return true; } static unsigned OpcodeLength(Decoder* decoder, const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc, UINT32_MAX); return 1 + imm.length; } case kExprRethrow: case kExprBr: case kExprBrIf: { BreakDepthImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprSetGlobal: case kExprGetGlobal: { GlobalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallFunction: { CallFunctionImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprTry: case kExprIf: // fall through case kExprLoop: case kExprBlock: { BlockTypeImmediate<validate> imm(kAllWasmFeatures, decoder, pc); return 1 + imm.length; } case kExprThrow: case kExprCatch: { ExceptionIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprSetLocal: case kExprTeeLocal: case kExprGetLocal: { LocalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprBrTable: { BranchTableImmediate<validate> imm(decoder, pc); BranchTableIterator<validate> iterator(decoder, imm); return 1 + iterator.length(); } case kExprI32Const: { ImmI32Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprI64Const: { ImmI64Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprRefNull: { return 1; } case kExprMemoryGrow: case kExprMemorySize: { MemoryIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprF32Const: return 5; case kExprF64Const: return 9; case kNumericPrefix: { byte numeric_index = decoder->read_u8<validate>(pc + 1, "numeric_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kNumericPrefix << 8 | numeric_index); switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: return 2; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryDrop: { MemoryDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryCopy: case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(decoder, pc + 1); return 2 + imm.length; } case kExprTableInit: { TableInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableDrop: { TableDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableCopy: { TableIndexImmediate<validate> imm(decoder, pc + 1); return 2 + imm.length; } default: decoder->error(pc, "invalid numeric opcode"); return 2; } } case kSimdPrefix: { byte simd_index = decoder->read_u8<validate>(pc + 1, "simd_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kSimdPrefix << 8 | simd_index); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 2; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 3; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX); return 2 + imm.length; } // Shuffles require a byte per lane, or 16 immediate bytes. case kExprS8x16Shuffle: return 2 + kSimd128Size; default: decoder->error(pc, "invalid SIMD opcode"); return 2; } } case kAtomicPrefix: { byte atomic_index = decoder->read_u8<validate>(pc + 1, "atomic_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kAtomicPrefix << 8 | atomic_index); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_ATOMIC_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX); return 2 + imm.length; } default: decoder->error(pc, "invalid Atomics opcode"); return 2; } } default: return 1; } } std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); // Handle "simple" opcodes with a fixed signature first. FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) return {sig->parameter_count(), sig->return_count()}; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: // clang-format off switch (opcode) { case kExprSelect: return {3, 1}; FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) return {2, 0}; FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) case kExprTeeLocal: case kExprMemoryGrow: return {1, 1}; case kExprSetLocal: case kExprSetGlobal: case kExprDrop: case kExprBrIf: case kExprBrTable: case kExprIf: return {1, 0}; case kExprGetLocal: case kExprGetGlobal: case kExprI32Const: case kExprI64Const: case kExprF32Const: case kExprF64Const: case kExprRefNull: case kExprMemorySize: return {0, 1}; case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); return {imm.sig->parameter_count(), imm.sig->return_count()}; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); // Indirect calls pop an additional argument for the table index. return {imm.sig->parameter_count() + 1, imm.sig->return_count()}; } case kExprBr: case kExprBlock: case kExprLoop: case kExprEnd: case kExprElse: case kExprNop: case kExprReturn: case kExprUnreachable: return {0, 0}; case kNumericPrefix: case kAtomicPrefix: case kSimdPrefix: { opcode = static_cast<WasmOpcode>(opcode << 8 | *(pc + 1)); switch (opcode) { FOREACH_SIMD_1_OPERAND_1_PARAM_OPCODE(DECLARE_OPCODE_CASE) return {1, 1}; FOREACH_SIMD_1_OPERAND_2_PARAM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_SIMD_MASK_OPERAND_OPCODE(DECLARE_OPCODE_CASE) return {2, 1}; default: { sig = WasmOpcodes::Signature(opcode); if (sig) { return {sig->parameter_count(), sig->return_count()}; } } } V8_FALLTHROUGH; } default: V8_Fatal(__FILE__, __LINE__, "unimplemented opcode: %x (%s)", opcode, WasmOpcodes::OpcodeName(opcode)); return {0, 0}; } #undef DECLARE_OPCODE_CASE // clang-format on } }; #define CALL_INTERFACE(name, ...) interface_.name(this, ##__VA_ARGS__) #define CALL_INTERFACE_IF_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ if (VALIDATE(this->ok()) && control_.back().reachable()) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) #define CALL_INTERFACE_IF_PARENT_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ if (VALIDATE(this->ok()) && \ (control_.size() == 1 || control_at(1)->reachable())) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) template <Decoder::ValidateFlag validate, typename Interface> class WasmFullDecoder : public WasmDecoder<validate> { using Value = typename Interface::Value; using Control = typename Interface::Control; using MergeValues = Merge<Value>; // All Value types should be trivially copyable for performance. We push, pop, // and store them in local variables. ASSERT_TRIVIALLY_COPYABLE(Value); public: template <typename... InterfaceArgs> WasmFullDecoder(Zone* zone, const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, const FunctionBody& body, InterfaceArgs&&... interface_args) : WasmDecoder<validate>(module, enabled, detected, body.sig, body.start, body.end, body.offset), zone_(zone), interface_(std::forward<InterfaceArgs>(interface_args)...), local_type_vec_(zone), stack_(zone), control_(zone), args_(zone), last_end_found_(false) { this->local_types_ = &local_type_vec_; } Interface& interface() { return interface_; } bool Decode() { DCHECK(stack_.empty()); DCHECK(control_.empty()); base::ElapsedTimer decode_timer; if (FLAG_trace_wasm_decode_time) { decode_timer.Start(); } if (this->end_ < this->pc_) { this->error("function body end < start"); return false; } DCHECK_EQ(0, this->local_types_->size()); WasmDecoder<validate>::DecodeLocals(this->enabled_, this, this->sig_, this->local_types_); CALL_INTERFACE(StartFunction); DecodeFunctionBody(); if (!this->failed()) CALL_INTERFACE(FinishFunction); if (this->failed()) return this->TraceFailed(); if (!control_.empty()) { // Generate a better error message whether the unterminated control // structure is the function body block or an innner structure. if (control_.size() > 1) { this->error(control_.back().pc, "unterminated control structure"); } else { this->error("function body must end with \"end\" opcode"); } return TraceFailed(); } if (!last_end_found_) { this->error("function body must end with \"end\" opcode"); return false; } if (FLAG_trace_wasm_decode_time) { double ms = decode_timer.Elapsed().InMillisecondsF(); PrintF("wasm-decode %s (%0.3f ms)\n\n", VALIDATE(this->ok()) ? "ok" : "failed", ms); } else { TRACE("wasm-decode %s\n\n", VALIDATE(this->ok()) ? "ok" : "failed"); } return true; } bool TraceFailed() { TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_offset_, this->GetBufferRelativeOffset(this->error_offset_), this->error_msg_.c_str()); return false; } const char* SafeOpcodeNameAt(const byte* pc) { if (pc >= this->end_) return "<end>"; return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(*pc)); } inline Zone* zone() const { return zone_; } inline uint32_t NumLocals() { return static_cast<uint32_t>(local_type_vec_.size()); } inline ValueType GetLocalType(uint32_t index) { return local_type_vec_[index]; } inline WasmCodePosition position() { int offset = static_cast<int>(this->pc_ - this->start_); DCHECK_EQ(this->pc_ - this->start_, offset); // overflows cannot happen return offset; } inline uint32_t control_depth() const { return static_cast<uint32_t>(control_.size()); } inline Control* control_at(uint32_t depth) { DCHECK_GT(control_.size(), depth); return &control_.back() - depth; } inline uint32_t stack_size() const { DCHECK_GE(kMaxUInt32, stack_.size()); return static_cast<uint32_t>(stack_.size()); } inline Value* stack_value(uint32_t depth) { DCHECK_GT(stack_.size(), depth); return &stack_[stack_.size() - depth - 1]; } inline Value& GetMergeValueFromStack( Control* c, Merge<Value>* merge, uint32_t i) { DCHECK(merge == &c->start_merge || merge == &c->end_merge); DCHECK_GT(merge->arity, i); DCHECK_GE(stack_.size(), c->stack_depth + merge->arity); return stack_[stack_.size() - merge->arity + i]; } private: static constexpr size_t kErrorMsgSize = 128; Zone* zone_; Interface interface_; ZoneVector<ValueType> local_type_vec_; // types of local variables. ZoneVector<Value> stack_; // stack of values. ZoneVector<Control> control_; // stack of blocks, loops, and ifs. ZoneVector<Value> args_; // parameters of current block or call bool last_end_found_; bool CheckHasMemory() { if (!VALIDATE(this->module_->has_memory)) { this->error(this->pc_ - 1, "memory instruction with no memory"); return false; } return true; } bool CheckHasSharedMemory() { if (!VALIDATE(this->module_->has_shared_memory)) { this->error(this->pc_ - 1, "Atomic opcodes used without shared memory"); return false; } return true; } class TraceLine { public: static constexpr int kMaxLen = 512; ~TraceLine() { if (!FLAG_trace_wasm_decoder) return; PrintF("%.*s\n", len_, buffer_); } // Appends a formatted string. PRINTF_FORMAT(2, 3) void Append(const char* format, ...) { if (!FLAG_trace_wasm_decoder) return; va_list va_args; va_start(va_args, format); size_t remaining_len = kMaxLen - len_; Vector<char> remaining_msg_space(buffer_ + len_, remaining_len); int len = VSNPrintF(remaining_msg_space, format, va_args); va_end(va_args); len_ += len < 0 ? remaining_len : len; } private: char buffer_[kMaxLen]; int len_ = 0; }; // Decodes the body of a function. void DecodeFunctionBody() { TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n", reinterpret_cast<const void*>(this->start()), reinterpret_cast<const void*>(this->end()), this->pc_offset(), static_cast<int>(this->end() - this->start())); // Set up initial function block. { auto* c = PushBlock(); InitMerge(&c->start_merge, 0, [](uint32_t) -> Value { UNREACHABLE(); }); InitMerge(&c->end_merge, static_cast<uint32_t>(this->sig_->return_count()), [&] (uint32_t i) { return Value::New(this->pc_, this->sig_->GetReturn(i)); }); CALL_INTERFACE(StartFunctionBody, c); } while (this->pc_ < this->end_) { // decoding loop. unsigned len = 1; WasmOpcode opcode = static_cast<WasmOpcode>(*this->pc_); CALL_INTERFACE_IF_REACHABLE(NextInstruction, opcode); #if DEBUG TraceLine trace_msg; #define TRACE_PART(...) trace_msg.Append(__VA_ARGS__) if (!WasmOpcodes::IsPrefixOpcode(opcode)) { TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); } #else #define TRACE_PART(...) #endif FunctionSig* sig = const_cast<FunctionSig*>(kSimpleOpcodeSigs[opcode]); if (sig) { BuildSimpleOperator(opcode, sig); } else { // Complex bytecode. switch (opcode) { case kExprNop: break; case kExprBlock: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* block = PushBlock(); SetBlockType(block, imm); CALL_INTERFACE_IF_REACHABLE(Block, block); PushMergeValues(block, &block->start_merge); len = 1 + imm.length; break; } case kExprRethrow: { CHECK_PROTOTYPE_OPCODE(eh); BreakDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!VALIDATE(c->is_try_catchall() || c->is_try_catch())) { this->error("rethrow not targeting catch or catch-all"); break; } CALL_INTERFACE_IF_REACHABLE(Rethrow, c); len = 1 + imm.length; EndControl(); break; } case kExprThrow: { CHECK_PROTOTYPE_OPCODE(eh); ExceptionIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; PopArgs(imm.exception->ToFunctionSig()); CALL_INTERFACE_IF_REACHABLE(Throw, imm, VectorOf(args_)); EndControl(); break; } case kExprTry: { CHECK_PROTOTYPE_OPCODE(eh); BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* try_block = PushTry(); SetBlockType(try_block, imm); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Try, try_block); PushMergeValues(try_block, &try_block->start_merge); break; } case kExprCatch: { CHECK_PROTOTYPE_OPCODE(eh); ExceptionIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; len = 1 + imm.length; if (!VALIDATE(!control_.empty())) { this->error("catch does not match any try"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_try())) { this->error("catch does not match any try"); break; } if (!VALIDATE(!c->is_try_catchall())) { this->error("catch after catch-all for try"); break; } c->kind = kControlTryCatch; FallThruTo(c); stack_.resize(c->stack_depth); const WasmExceptionSig* sig = imm.exception->sig; for (size_t i = 0, e = sig->parameter_count(); i < e; ++i) { Push(sig->GetParam(i)); } Vector<Value> values(stack_.data() + c->stack_depth, sig->parameter_count()); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchException, imm, c, values); break; } case kExprCatchAll: { CHECK_PROTOTYPE_OPCODE(eh); if (!VALIDATE(!control_.empty())) { this->error("catch-all does not match any try"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_try())) { this->error("catch-all does not match any try"); break; } if (!VALIDATE(!c->is_try_catchall())) { this->error("catch-all already present for try"); break; } c->kind = kControlTryCatchAll; FallThruTo(c); stack_.resize(c->stack_depth); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchAll, c); break; } case kExprLoop: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; PopArgs(imm.sig); auto* block = PushLoop(); SetBlockType(&control_.back(), imm); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Loop, block); PushMergeValues(block, &block->start_merge); break; } case kExprIf: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; auto cond = Pop(0, kWasmI32); PopArgs(imm.sig); if (!VALIDATE(this->ok())) break; auto* if_block = PushIf(); SetBlockType(if_block, imm); CALL_INTERFACE_IF_REACHABLE(If, cond, if_block); len = 1 + imm.length; PushMergeValues(if_block, &if_block->start_merge); break; } case kExprElse: { if (!VALIDATE(!control_.empty())) { this->error("else does not match any if"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_if())) { this->error(this->pc_, "else does not match an if"); break; } if (c->is_if_else()) { this->error(this->pc_, "else already present for if"); break; } FallThruTo(c); c->kind = kControlIfElse; CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c); PushMergeValues(c, &c->start_merge); c->reachability = control_at(1)->innerReachability(); break; } case kExprEnd: { if (!VALIDATE(!control_.empty())) { this->error("end does not match any if, try, or block"); return; } Control* c = &control_.back(); if (!VALIDATE(!c->is_incomplete_try())) { this->error(this->pc_, "missing catch or catch-all in try"); break; } if (c->is_onearmed_if()) { // Emulate empty else arm. FallThruTo(c); if (this->failed()) break; CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c); PushMergeValues(c, &c->start_merge); c->reachability = control_at(1)->innerReachability(); } if (c->is_try_catch()) { // Emulate catch-all + re-throw. FallThruTo(c); c->reachability = control_at(1)->innerReachability(); CALL_INTERFACE_IF_PARENT_REACHABLE(CatchAll, c); CALL_INTERFACE_IF_REACHABLE(Rethrow, c); EndControl(); } FallThruTo(c); // A loop just leaves the values on the stack. if (!c->is_loop()) PushMergeValues(c, &c->end_merge); if (control_.size() == 1) { // If at the last (implicit) control, check we are at end. if (!VALIDATE(this->pc_ + 1 == this->end_)) { this->error(this->pc_ + 1, "trailing code after function end"); break; } last_end_found_ = true; // The result of the block is the return value. TRACE_PART("\n" TRACE_INST_FORMAT, startrel(this->pc_), "(implicit) return"); DoReturn(c, true); } PopControl(c); break; } case kExprSelect: { auto cond = Pop(2, kWasmI32); auto fval = Pop(); auto tval = Pop(0, fval.type); auto* result = Push(tval.type == kWasmVar ? fval.type : tval.type); CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result); break; } case kExprBr: { BreakDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!TypeCheckBreak(c)) break; if (control_.back().reachable()) { CALL_INTERFACE(Br, c); c->br_merge()->reached = true; } len = 1 + imm.length; EndControl(); break; } case kExprBrIf: { BreakDepthImmediate<validate> imm(this, this->pc_); auto cond = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); if (!TypeCheckBreak(c)) break; if (control_.back().reachable()) { CALL_INTERFACE(BrIf, cond, c); c->br_merge()->reached = true; } len = 1 + imm.length; break; } case kExprBrTable: { BranchTableImmediate<validate> imm(this, this->pc_); BranchTableIterator<validate> iterator(this, imm); auto key = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; uint32_t br_arity = 0; std::vector<bool> br_targets(control_.size()); while (iterator.has_next()) { const uint32_t i = iterator.cur_index(); const byte* pos = iterator.pc(); uint32_t target = iterator.next(); if (!VALIDATE(target < control_.size())) { this->errorf(pos, "improper branch in br_table target %u (depth %u)", i, target); break; } // Avoid redundant break target checks. if (br_targets[target]) continue; br_targets[target] = true; // Check that label types match up. Control* c = control_at(target); uint32_t arity = c->br_merge()->arity; if (i == 0) { br_arity = arity; } else if (!VALIDATE(br_arity == arity)) { this->errorf(pos, "inconsistent arity in br_table target %u" " (previous was %u, this one %u)", i, br_arity, arity); } if (!TypeCheckBreak(c)) break; } if (this->failed()) break; if (control_.back().reachable()) { CALL_INTERFACE(BrTable, imm, key); for (uint32_t depth = control_depth(); depth-- > 0;) { if (!br_targets[depth]) continue; control_at(depth)->br_merge()->reached = true; } } len = 1 + iterator.length(); EndControl(); break; } case kExprReturn: { DoReturn(&control_.back(), false); break; } case kExprUnreachable: { CALL_INTERFACE_IF_REACHABLE(Unreachable); EndControl(); break; } case kExprI32Const: { ImmI32Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(I32Const, value, imm.value); len = 1 + imm.length; break; } case kExprI64Const: { ImmI64Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmI64); CALL_INTERFACE_IF_REACHABLE(I64Const, value, imm.value); len = 1 + imm.length; break; } case kExprF32Const: { ImmF32Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmF32); CALL_INTERFACE_IF_REACHABLE(F32Const, value, imm.value); len = 1 + imm.length; break; } case kExprF64Const: { ImmF64Immediate<validate> imm(this, this->pc_); auto* value = Push(kWasmF64); CALL_INTERFACE_IF_REACHABLE(F64Const, value, imm.value); len = 1 + imm.length; break; } case kExprRefNull: { CHECK_PROTOTYPE_OPCODE(anyref); auto* value = Push(kWasmAnyRef); CALL_INTERFACE_IF_REACHABLE(RefNull, value); len = 1; break; } case kExprGetLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto* value = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(GetLocal, value, imm); len = 1 + imm.length; break; } case kExprSetLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto value = Pop(0, local_type_vec_[imm.index]); CALL_INTERFACE_IF_REACHABLE(SetLocal, value, imm); len = 1 + imm.length; break; } case kExprTeeLocal: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; auto value = Pop(0, local_type_vec_[imm.index]); auto* result = Push(value.type); CALL_INTERFACE_IF_REACHABLE(TeeLocal, value, result, imm); len = 1 + imm.length; break; } case kExprDrop: { auto value = Pop(); CALL_INTERFACE_IF_REACHABLE(Drop, value); break; } case kExprGetGlobal: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; auto* result = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(GetGlobal, result, imm); break; } case kExprSetGlobal: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; if (!VALIDATE(imm.global->mutability)) { this->errorf(this->pc_, "immutable global #%u cannot be assigned", imm.index); break; } auto value = Pop(0, imm.type); CALL_INTERFACE_IF_REACHABLE(SetGlobal, value, imm); break; } case kExprI32LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI32Load8S); break; case kExprI32LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI32Load8U); break; case kExprI32LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI32Load16S); break; case kExprI32LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI32Load16U); break; case kExprI32LoadMem: len = 1 + DecodeLoadMem(LoadType::kI32Load); break; case kExprI64LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI64Load8S); break; case kExprI64LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI64Load8U); break; case kExprI64LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI64Load16S); break; case kExprI64LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI64Load16U); break; case kExprI64LoadMem32S: len = 1 + DecodeLoadMem(LoadType::kI64Load32S); break; case kExprI64LoadMem32U: len = 1 + DecodeLoadMem(LoadType::kI64Load32U); break; case kExprI64LoadMem: len = 1 + DecodeLoadMem(LoadType::kI64Load); break; case kExprF32LoadMem: len = 1 + DecodeLoadMem(LoadType::kF32Load); break; case kExprF64LoadMem: len = 1 + DecodeLoadMem(LoadType::kF64Load); break; case kExprI32StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI32Store8); break; case kExprI32StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI32Store16); break; case kExprI32StoreMem: len = 1 + DecodeStoreMem(StoreType::kI32Store); break; case kExprI64StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI64Store8); break; case kExprI64StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI64Store16); break; case kExprI64StoreMem32: len = 1 + DecodeStoreMem(StoreType::kI64Store32); break; case kExprI64StoreMem: len = 1 + DecodeStoreMem(StoreType::kI64Store); break; case kExprF32StoreMem: len = 1 + DecodeStoreMem(StoreType::kF32Store); break; case kExprF64StoreMem: len = 1 + DecodeStoreMem(StoreType::kF64Store); break; case kExprMemoryGrow: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; DCHECK_NOT_NULL(this->module_); if (!VALIDATE(this->module_->origin == kWasmOrigin)) { this->error("grow_memory is not supported for asmjs modules"); break; } auto value = Pop(0, kWasmI32); auto* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(MemoryGrow, value, result); break; } case kExprMemorySize: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); auto* result = Push(kWasmI32); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(CurrentMemoryPages, result); break; } case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; // TODO(clemensh): Better memory management. PopArgs(imm.sig); auto* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallDirect, imm, args_.data(), returns); break; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; auto index = Pop(0, kWasmI32); PopArgs(imm.sig); auto* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallIndirect, index, imm, args_.data(), returns); break; } case kNumericPrefix: { ++len; byte numeric_index = this->template read_u8<validate>( this->pc_ + 1, "numeric index"); opcode = static_cast<WasmOpcode>(opcode << 8 | numeric_index); if (opcode < kExprMemoryInit) { CHECK_PROTOTYPE_OPCODE(sat_f2i_conversions); } else { CHECK_PROTOTYPE_OPCODE(bulk_memory); } TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeNumericOpcode(opcode); break; } case kSimdPrefix: { CHECK_PROTOTYPE_OPCODE(simd); len++; byte simd_index = this->template read_u8<validate>(this->pc_ + 1, "simd index"); opcode = static_cast<WasmOpcode>(opcode << 8 | simd_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeSimdOpcode(opcode); break; } case kAtomicPrefix: { CHECK_PROTOTYPE_OPCODE(threads); if (!CheckHasSharedMemory()) break; len++; byte atomic_index = this->template read_u8<validate>(this->pc_ + 1, "atomic index"); opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); len += DecodeAtomicOpcode(opcode); break; } // Note that prototype opcodes are not handled in the fastpath // above this switch, to avoid checking a feature flag. #define SIMPLE_PROTOTYPE_CASE(name, opc, sig) \ case kExpr##name: /* fallthrough */ FOREACH_SIMPLE_PROTOTYPE_OPCODE(SIMPLE_PROTOTYPE_CASE) #undef SIMPLE_PROTOTYPE_CASE BuildSimplePrototypeOperator(opcode); break; default: { // Deal with special asmjs opcodes. if (this->module_ != nullptr && this->module_->origin == kAsmJsOrigin) { sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) { BuildSimpleOperator(opcode, sig); } } else { this->error("Invalid opcode"); return; } } } } #if DEBUG if (FLAG_trace_wasm_decoder) { TRACE_PART(" "); for (Control& c : control_) { switch (c.kind) { case kControlIf: TRACE_PART("I"); break; case kControlBlock: TRACE_PART("B"); break; case kControlLoop: TRACE_PART("L"); break; case kControlTry: TRACE_PART("T"); break; default: break; } if (c.start_merge.arity) TRACE_PART("%u-", c.start_merge.arity); TRACE_PART("%u", c.end_merge.arity); if (!c.reachable()) TRACE_PART("%c", c.unreachable() ? '*' : '#'); } TRACE_PART(" | "); for (size_t i = 0; i < stack_.size(); ++i) { auto& val = stack_[i]; WasmOpcode opcode = static_cast<WasmOpcode>(*val.pc); if (WasmOpcodes::IsPrefixOpcode(opcode)) { opcode = static_cast<WasmOpcode>(opcode << 8 | *(val.pc + 1)); } TRACE_PART(" %c@%d:%s", ValueTypes::ShortNameOf(val.type), static_cast<int>(val.pc - this->start_), WasmOpcodes::OpcodeName(opcode)); // If the decoder failed, don't try to decode the immediates, as this // can trigger a DCHECK failure. if (this->failed()) continue; switch (opcode) { case kExprI32Const: { ImmI32Immediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%d]", imm.value); break; } case kExprGetLocal: case kExprSetLocal: case kExprTeeLocal: { LocalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } case kExprGetGlobal: case kExprSetGlobal: { GlobalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } default: break; } } } #endif this->pc_ += len; } // end decode loop if (!VALIDATE(this->pc_ == this->end_) && this->ok()) { this->error("Beyond end of code"); } } void EndControl() { DCHECK(!control_.empty()); auto* current = &control_.back(); stack_.resize(current->stack_depth); CALL_INTERFACE_IF_REACHABLE(EndControl, current); current->reachability = kUnreachable; } template<typename func> void InitMerge(Merge<Value>* merge, uint32_t arity, func get_val) { merge->arity = arity; if (arity == 1) { merge->vals.first = get_val(0); } else if (arity > 1) { merge->vals.array = zone_->NewArray<Value>(arity); for (unsigned i = 0; i < arity; i++) { merge->vals.array[i] = get_val(i); } } } void SetBlockType(Control* c, BlockTypeImmediate<validate>& imm) { DCHECK_EQ(imm.in_arity(), this->args_.size()); const byte* pc = this->pc_; Value* args = this->args_.data(); InitMerge(&c->end_merge, imm.out_arity(), [pc, &imm](uint32_t i) { return Value::New(pc, imm.out_type(i)); }); InitMerge(&c->start_merge, imm.in_arity(), [args](uint32_t i) { return args[i]; }); } // Pops arguments as required by signature into {args_}. V8_INLINE void PopArgs(FunctionSig* sig) { int count = sig ? static_cast<int>(sig->parameter_count()) : 0; args_.resize(count); for (int i = count - 1; i >= 0; --i) { args_[i] = Pop(i, sig->GetParam(i)); } } ValueType GetReturnType(FunctionSig* sig) { DCHECK_GE(1, sig->return_count()); return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn(); } Control* PushControl(Control&& new_control) { Reachability reachability = control_.empty() ? kReachable : control_.back().innerReachability(); control_.emplace_back(std::move(new_control)); Control* c = &control_.back(); c->reachability = reachability; c->start_merge.reached = c->reachable(); return c; } Control* PushBlock() { return PushControl(Control::Block(this->pc_, stack_size())); } Control* PushLoop() { return PushControl(Control::Loop(this->pc_, stack_size())); } Control* PushIf() { return PushControl(Control::If(this->pc_, stack_size())); } Control* PushTry() { // current_catch_ = static_cast<int32_t>(control_.size() - 1); return PushControl(Control::Try(this->pc_, stack_size())); } void PopControl(Control* c) { DCHECK_EQ(c, &control_.back()); CALL_INTERFACE_IF_PARENT_REACHABLE(PopControl, c); bool reached = c->end_merge.reached; control_.pop_back(); // If the parent block was reachable before, but the popped control does not // return to here, this block becomes indirectly unreachable. if (!control_.empty() && !reached && control_.back().reachable()) { control_.back().reachability = kSpecOnlyReachable; } } int DecodeLoadMem(LoadType type, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, type.size_log_2()); auto index = Pop(0, kWasmI32); auto* result = Push(type.value_type()); CALL_INTERFACE_IF_REACHABLE(LoadMem, type, imm, index, result); return imm.length; } int DecodeStoreMem(StoreType store, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, store.size_log_2()); auto value = Pop(1, store.value_type()); auto index = Pop(0, kWasmI32); CALL_INTERFACE_IF_REACHABLE(StoreMem, store, imm, index, value); return imm.length; } unsigned SimdExtractLane(WasmOpcode opcode, ValueType type) { SimdLaneImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[] = {Pop(0, kWasmS128)}; auto* result = Push(type); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } unsigned SimdReplaceLane(WasmOpcode opcode, ValueType type) { SimdLaneImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[2]; inputs[1] = Pop(1, type); inputs[0] = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } unsigned SimdShiftOp(WasmOpcode opcode) { SimdShiftImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, opcode, imm)) { auto input = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(SimdShiftOp, opcode, imm, input, result); } return imm.length; } unsigned Simd8x16ShuffleOp() { Simd8x16ShuffleImmediate<validate> imm(this, this->pc_); if (this->Validate(this->pc_, imm)) { auto input1 = Pop(1, kWasmS128); auto input0 = Pop(0, kWasmS128); auto* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(Simd8x16ShuffleOp, imm, input0, input1, result); } return 16; } unsigned DecodeSimdOpcode(WasmOpcode opcode) { unsigned len = 0; switch (opcode) { case kExprF32x4ExtractLane: { len = SimdExtractLane(opcode, kWasmF32); break; } case kExprI32x4ExtractLane: case kExprI16x8ExtractLane: case kExprI8x16ExtractLane: { len = SimdExtractLane(opcode, kWasmI32); break; } case kExprF32x4ReplaceLane: { len = SimdReplaceLane(opcode, kWasmF32); break; } case kExprI32x4ReplaceLane: case kExprI16x8ReplaceLane: case kExprI8x16ReplaceLane: { len = SimdReplaceLane(opcode, kWasmI32); break; } case kExprI32x4Shl: case kExprI32x4ShrS: case kExprI32x4ShrU: case kExprI16x8Shl: case kExprI16x8ShrS: case kExprI16x8ShrU: case kExprI8x16Shl: case kExprI8x16ShrS: case kExprI8x16ShrU: { len = SimdShiftOp(opcode); break; } case kExprS8x16Shuffle: { len = Simd8x16ShuffleOp(); break; } case kExprS128LoadMem: len = DecodeLoadMem(LoadType::kS128Load, 1); break; case kExprS128StoreMem: len = DecodeStoreMem(StoreType::kS128Store, 1); break; default: { FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!VALIDATE(sig != nullptr)) { this->error("invalid simd opcode"); break; } PopArgs(sig); auto* results = sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(SimdOp, opcode, VectorOf(args_), results); } } return len; } unsigned DecodeAtomicOpcode(WasmOpcode opcode) { unsigned len = 0; ValueType ret_type; FunctionSig* sig = WasmOpcodes::Signature(opcode); if (sig != nullptr) { MachineType memtype; switch (opcode) { #define CASE_ATOMIC_STORE_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = kWasmStmt; \ break; \ } ATOMIC_STORE_OP_LIST(CASE_ATOMIC_STORE_OP) #undef CASE_ATOMIC_OP #define CASE_ATOMIC_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = GetReturnType(sig); \ break; \ } ATOMIC_OP_LIST(CASE_ATOMIC_OP) #undef CASE_ATOMIC_OP default: this->error("invalid atomic opcode"); return 0; } MemoryAccessImmediate<validate> imm( this, this->pc_ + 1, ElementSizeLog2Of(memtype.representation())); len += imm.length; PopArgs(sig); auto result = ret_type == kWasmStmt ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(AtomicOp, opcode, VectorOf(args_), imm, result); } else { this->error("invalid atomic opcode"); } return len; } unsigned DecodeNumericOpcode(WasmOpcode opcode) { unsigned len = 0; FunctionSig* sig = WasmOpcodes::Signature(opcode); if (sig != nullptr) { switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: BuildSimpleOperator(opcode, sig); break; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryInit, imm, VectorOf(args_)); break; } case kExprMemoryDrop: { MemoryDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(MemoryDrop, imm); break; } case kExprMemoryCopy: { MemoryIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryCopy, imm, VectorOf(args_)); break; } case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(MemoryFill, imm, VectorOf(args_)); break; } case kExprTableInit: { TableInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableInit, imm, VectorOf(args_)); break; } case kExprTableDrop: { TableDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(TableDrop, imm); break; } case kExprTableCopy: { TableIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_ + 1, imm)) break; len += imm.length; PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableCopy, imm, VectorOf(args_)); break; } default: this->error("invalid numeric opcode"); break; } } else { this->error("invalid numeric opcode"); } return len; } void DoReturn(Control* c, bool implicit) { int return_count = static_cast<int>(this->sig_->return_count()); args_.resize(return_count); // Pop return values off the stack in reverse order. for (int i = return_count - 1; i >= 0; --i) { args_[i] = Pop(i, this->sig_->GetReturn(i)); } // Simulate that an implicit return morally comes after the current block. if (implicit && c->end_merge.reached) c->reachability = kReachable; CALL_INTERFACE_IF_REACHABLE(DoReturn, VectorOf(args_), implicit); EndControl(); } inline Value* Push(ValueType type) { DCHECK_NE(kWasmStmt, type); stack_.push_back(Value::New(this->pc_, type)); return &stack_.back(); } void PushMergeValues(Control* c, Merge<Value>* merge) { DCHECK_EQ(c, &control_.back()); DCHECK(merge == &c->start_merge || merge == &c->end_merge); stack_.resize(c->stack_depth); if (merge->arity == 1) { stack_.push_back(merge->vals.first); } else { for (unsigned i = 0; i < merge->arity; i++) { stack_.push_back(merge->vals.array[i]); } } DCHECK_EQ(c->stack_depth + merge->arity, stack_.size()); } Value* PushReturns(FunctionSig* sig) { size_t return_count = sig->return_count(); if (return_count == 0) return nullptr; size_t old_size = stack_.size(); for (size_t i = 0; i < return_count; ++i) { Push(sig->GetReturn(i)); } return stack_.data() + old_size; } Value Pop(int index, ValueType expected) { auto val = Pop(); if (!VALIDATE(val.type == expected || val.type == kWasmVar || expected == kWasmVar)) { this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s", SafeOpcodeNameAt(this->pc_), index, ValueTypes::TypeName(expected), SafeOpcodeNameAt(val.pc), ValueTypes::TypeName(val.type)); } return val; } Value Pop() { DCHECK(!control_.empty()); uint32_t limit = control_.back().stack_depth; if (stack_.size() <= limit) { // Popping past the current control start in reachable code. if (!VALIDATE(control_.back().unreachable())) { this->errorf(this->pc_, "%s found empty stack", SafeOpcodeNameAt(this->pc_)); } return Value::Unreachable(this->pc_); } auto val = stack_.back(); stack_.pop_back(); return val; } int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); } void FallThruTo(Control* c) { DCHECK_EQ(c, &control_.back()); if (!TypeCheckFallThru(c)) return; if (!c->reachable()) return; if (!c->is_loop()) CALL_INTERFACE(FallThruTo, c); c->end_merge.reached = true; } bool TypeCheckMergeValues(Control* c, Merge<Value>* merge) { DCHECK(merge == &c->start_merge || merge == &c->end_merge); DCHECK_GE(stack_.size(), c->stack_depth + merge->arity); // Typecheck the topmost {merge->arity} values on the stack. for (uint32_t i = 0; i < merge->arity; ++i) { auto& val = GetMergeValueFromStack(c, merge, i); auto& old = (*merge)[i]; if (val.type != old.type) { // If {val.type} is polymorphic, which results from unreachable, make // it more specific by using the merge value's expected type. // If it is not polymorphic, this is a type error. if (!VALIDATE(val.type == kWasmVar)) { this->errorf( this->pc_, "type error in merge[%u] (expected %s, got %s)", i, ValueTypes::TypeName(old.type), ValueTypes::TypeName(val.type)); return false; } val.type = old.type; } } return true; } bool TypeCheckFallThru(Control* c) { DCHECK_EQ(c, &control_.back()); if (!validate) return true; uint32_t expected = c->end_merge.arity; DCHECK_GE(stack_.size(), c->stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - c->stack_depth; // Fallthrus must match the arity of the control exactly. if (!InsertUnreachablesIfNecessary(expected, actual) || actual > expected) { this->errorf( this->pc_, "expected %u elements on the stack for fallthru to @%d, found %u", expected, startrel(c->pc), actual); return false; } return TypeCheckMergeValues(c, &c->end_merge); } bool TypeCheckBreak(Control* c) { // Breaks must have at least the number of values expected; can have more. uint32_t expected = c->br_merge()->arity; DCHECK_GE(stack_.size(), control_.back().stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth; if (!InsertUnreachablesIfNecessary(expected, actual)) { this->errorf(this->pc_, "expected %u elements on the stack for br to @%d, found %u", expected, startrel(c->pc), actual); return false; } return TypeCheckMergeValues(c, c->br_merge()); } inline bool InsertUnreachablesIfNecessary(uint32_t expected, uint32_t actual) { if (V8_LIKELY(actual >= expected)) { return true; // enough actual values are there. } if (!VALIDATE(control_.back().unreachable())) { // There aren't enough values on the stack. return false; } // A slow path. When the actual number of values on the stack is less // than the expected number of values and the current control is // unreachable, insert unreachable values below the actual values. // This simplifies {TypeCheckMergeValues}. auto pos = stack_.begin() + (stack_.size() - actual); stack_.insert(pos, (expected - actual), Value::Unreachable(this->pc_)); return true; } void onFirstError() override { this->end_ = this->pc_; // Terminate decoding loop. TRACE(" !%s\n", this->error_msg_.c_str()); CALL_INTERFACE(OnFirstError); } void BuildSimplePrototypeOperator(WasmOpcode opcode) { if (WasmOpcodes::IsSignExtensionOpcode(opcode)) { RET_ON_PROTOTYPE_OPCODE(se); } if (WasmOpcodes::IsAnyRefOpcode(opcode)) { RET_ON_PROTOTYPE_OPCODE(anyref); } FunctionSig* sig = WasmOpcodes::Signature(opcode); BuildSimpleOperator(opcode, sig); } inline void BuildSimpleOperator(WasmOpcode opcode, FunctionSig* sig) { switch (sig->parameter_count()) { case 1: { auto val = Pop(0, sig->GetParam(0)); auto* ret = sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0)); CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, sig, val, ret); break; } case 2: { auto rval = Pop(1, sig->GetParam(1)); auto lval = Pop(0, sig->GetParam(0)); auto* ret = sig->return_count() == 0 ? nullptr : Push(sig->GetReturn(0)); CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, sig, lval, rval, ret); break; } default: UNREACHABLE(); } } }; #undef CALL_INTERFACE #undef CALL_INTERFACE_IF_REACHABLE #undef CALL_INTERFACE_IF_PARENT_REACHABLE class EmptyInterface { public: static constexpr Decoder::ValidateFlag validate = Decoder::kValidate; using Value = ValueBase; using Control = ControlBase<Value>; using FullDecoder = WasmFullDecoder<validate, EmptyInterface>; #define DEFINE_EMPTY_CALLBACK(name, ...) \ void name(FullDecoder* decoder, ##__VA_ARGS__) {} INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK) #undef DEFINE_EMPTY_CALLBACK }; #undef TRACE #undef TRACE_INST_FORMAT #undef VALIDATE #undef CHECK_PROTOTYPE_OPCODE #undef OPCODE_ERROR } // namespace wasm } // namespace internal } // namespace v8 #endif // V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d042fbfab4dc7a584f2c90f59e09a3f37e07c958
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/ds/security/services/scerpc/sceutil.cpp
7bf2780f465026a28af03bdc36d35dd72c22b75c
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
65,144
cpp
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: sceutil.cpp Abstract: Shared APIs Author: Jin Huang Revision History: jinhuang 23-Jan-1998 merged from multiple modules --*/ #include "headers.h" #include "sceutil.h" #include "infp.h" #include <sddl.h> #include "commonrc.h" #include "client\CGenericLogger.h" extern HINSTANCE MyModuleHandle; BOOL ScepInitNameTable() { LoadString(MyModuleHandle, IDS_EVERYONE, NameTable[0].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_OWNER, NameTable[1].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_GROUP, NameTable[2].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_OWNER_SERVER, NameTable[3].Name, 36); LoadString(MyModuleHandle, IDS_CREATOR_GROUP_SERVER, NameTable[4].Name, 36); LoadString(MyModuleHandle, IDS_DIALUP, NameTable[5].Name, 36); LoadString(MyModuleHandle, IDS_NETWORK, NameTable[6].Name, 36); LoadString(MyModuleHandle, IDS_BATCH, NameTable[7].Name, 36); LoadString(MyModuleHandle, IDS_INTERACTIVE, NameTable[8].Name, 36); LoadString(MyModuleHandle, IDS_SERVICE, NameTable[9].Name, 36); LoadString(MyModuleHandle, IDS_ANONYMOUS_LOGON, NameTable[10].Name, 36); LoadString(MyModuleHandle, IDS_PROXY, NameTable[11].Name, 36); LoadString(MyModuleHandle, IDS_ENTERPRISE_DOMAIN, NameTable[12].Name, 36); LoadString(MyModuleHandle, IDS_NAME_SELF, NameTable[13].Name, 36); LoadString(MyModuleHandle, IDS_AUTHENTICATED_USERS, NameTable[14].Name, 36); LoadString(MyModuleHandle, IDS_RESTRICTED, NameTable[15].Name, 36); LoadString(MyModuleHandle, IDS_TERMINAL_SERVER_USER, NameTable[16].Name, 36); LoadString(MyModuleHandle, IDS_LOCAL_SYSTEM, NameTable[17].Name, 36); LoadString(MyModuleHandle, IDS_LOCALSERVICE, NameTable[18].Name, 36); LoadString(MyModuleHandle, IDS_NETWORKSERVICE, NameTable[19].Name, 36); LoadString(MyModuleHandle, IDS_ADMINISTRATORS, NameTable[20].Name, 36); LoadString(MyModuleHandle, IDS_NAME_USERS, NameTable[21].Name, 36); LoadString(MyModuleHandle, IDS_NAME_GUESTS, NameTable[22].Name, 36); LoadString(MyModuleHandle, IDS_POWER_USERS, NameTable[23].Name, 36); LoadString(MyModuleHandle, IDS_ACCOUNT_OPERATORS, NameTable[24].Name, 36); LoadString(MyModuleHandle, IDS_SERVER_OPERATORS, NameTable[25].Name, 36); LoadString(MyModuleHandle, IDS_PRINT_OPERATORS, NameTable[26].Name, 36); LoadString(MyModuleHandle, IDS_BACKUP_OPERATORS, NameTable[27].Name, 36); LoadString(MyModuleHandle, IDS_REPLICATOR, NameTable[28].Name, 36); LoadString(MyModuleHandle, IDS_RAS_SERVERS, NameTable[29].Name, 36); LoadString(MyModuleHandle, IDS_PREW2KCOMPACCESS, NameTable[30 ].Name, 36); LoadString(MyModuleHandle, IDS_REMOTE_DESKTOP_USERS, NameTable[31].Name, 36); LoadString(MyModuleHandle, IDS_NETWORK_CONFIGURATION_OPERATORS, NameTable[32].Name, 36); return TRUE; } BOOL ScepLookupNameTable( IN PWSTR Name, OUT PWSTR *StrSid ) { if ( Name == NULL || Name[0] == L'\0' ) { return FALSE; } for (int i = 0; i < TABLE_SIZE; i++) { if ( _wcsicmp(NameTable[i].Name, Name) == 0 ) { //found match *StrSid = (PWSTR)ScepAlloc((UINT)0, (2+wcslen(NameTable[i].StrSid))*sizeof(WCHAR)); if ( *StrSid == NULL ) { return FALSE; } else { (*StrSid)[0] = L'*'; wcscpy((*StrSid)+1, NameTable[i].StrSid); return TRUE; } } } return FALSE; } INT ScepLookupPrivByName( IN PCWSTR Right ) /* ++ Routine Description: This routine looksup a user right in SCE_Rights table and returns the index component in SCE_Rights. The index component indicates the bit number for the user right. Arguments: Right - The user right to look up Return value: The index component in SCE_Rights table if a match is found, -1 for no match -- */ { DWORD i; for (i=0; i<cPrivCnt; i++) { if ( _wcsicmp(Right, SCE_Privileges[i].Name) == 0 ) return (i); } return(-1); } SCESTATUS WINAPI SceLookupPrivRightName( IN INT Priv, OUT PWSTR Name, OUT PINT NameLen ) { INT Len; if ( Name != NULL && NameLen == NULL ) return(SCESTATUS_INVALID_PARAMETER); if ( Priv >= 0 && Priv < cPrivCnt ) { Len = wcslen(SCE_Privileges[Priv].Name); if ( Name != NULL ) { if ( *NameLen >= Len ) wcscpy(Name, SCE_Privileges[Priv].Name); else { *NameLen = Len; return(SCESTATUS_BUFFER_TOO_SMALL); } } if ( NameLen != NULL) *NameLen = Len; return(SCESTATUS_SUCCESS); } else return SCESTATUS_RECORD_NOT_FOUND; } SCESTATUS SceInfpOpenProfile( IN PCWSTR ProfileName, IN HINF *hInf ) /* Routine Description: This routine opens a profile and returns a handle. This handle may be used when read information out of the profile using Setup APIs. The handle must be closed by calling SCECloseInfProfile. Arguments: ProfileName - The profile to open hInf - the address for inf handle Return value: SCESTATUS */ { if ( ProfileName == NULL || hInf == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } // // Check to see if the INF file is opened OK. // SetupOpenInfFile is defined in setupapi.h // *hInf = SetupOpenInfFile(ProfileName, NULL, INF_STYLE_WIN4, NULL ); if (*hInf == INVALID_HANDLE_VALUE) return( ScepDosErrorToSceStatus( GetLastError() ) ); else return( SCESTATUS_SUCCESS); } SCESTATUS SceInfpCloseProfile( IN HINF hInf ) { if ( hInf != INVALID_HANDLE_VALUE ) SetupCloseInfFile( hInf ); return(SCESTATUS_SUCCESS); } SCESTATUS ScepConvertMultiSzToDelim( IN PWSTR pValue, IN DWORD Len, IN WCHAR DelimFrom, IN WCHAR Delim ) /* Convert the multi-sz delimiter \0 to space */ { DWORD i; for ( i=0; i<Len && pValue; i++) { // if ( *(pValue+i) == L'\0' && *(pValue+i+1) != L'\0') { if ( *(pValue+i) == DelimFrom && i+1 < Len && *(pValue+i+1) != L'\0' ) { // // a NULL delimiter is encounted and it's not the end (double NULL) // *(pValue+i) = Delim; } } return(SCESTATUS_SUCCESS); } /* SCESTATUS SceInfpInfErrorToSceStatus( IN SCEINF_STATUS InfErr ) /* ++ Routine Description: This routine converts error codes from Inf routines into SCESTATUS code. Arguments: InfErr - The error code from Inf routines Return Value: SCESTATUS code -- *//* { SCESTATUS rc; switch ( InfErr ) { case SCEINF_SUCCESS: rc = SCESTATUS_SUCCESS; break; case SCEINF_PROFILE_NOT_FOUND: rc = SCESTATUS_PROFILE_NOT_FOUND; break; case SCEINF_NOT_ENOUGH_MEMORY: rc = SCESTATUS_NOT_ENOUGH_RESOURCE; break; case SCEINF_INVALID_PARAMETER: rc = SCESTATUS_INVALID_PARAMETER; break; case SCEINF_CORRUPT_PROFILE: rc = SCESTATUS_BAD_FORMAT; break; case SCEINF_INVALID_DATA: rc = SCESTATUS_INVALID_DATA; break; case SCEINF_ACCESS_DENIED: rc = SCESTATUS_ACCESS_DENIED; break; default: rc = SCESTATUS_OTHER_ERROR; break; } return(rc); } */ // // below are exported APIs in secedit.h // SCESTATUS WINAPI SceCreateDirectory( IN PCWSTR ProfileLocation, IN BOOL FileOrDir, PSECURITY_DESCRIPTOR pSecurityDescriptor ) { return ( ScepCreateDirectory(ProfileLocation, FileOrDir, pSecurityDescriptor )); } SCESTATUS WINAPI SceCompareSecurityDescriptors( IN AREA_INFORMATION Area, IN PSECURITY_DESCRIPTOR pSD1, IN PSECURITY_DESCRIPTOR pSD2, IN SECURITY_INFORMATION SeInfo, OUT PBOOL IsDifferent ) { SE_OBJECT_TYPE ObjectType; BYTE resultSD=0; SCESTATUS rc; BOOL bContainer = FALSE; switch ( Area) { case AREA_REGISTRY_SECURITY: ObjectType = SE_REGISTRY_KEY; bContainer = TRUE; break; case AREA_FILE_SECURITY: ObjectType = SE_FILE_OBJECT; break; case AREA_DS_OBJECTS: ObjectType = SE_DS_OBJECT; bContainer = TRUE; break; case AREA_SYSTEM_SERVICE: ObjectType = SE_SERVICE; break; default: ObjectType = SE_FILE_OBJECT; break; } rc = ScepCompareObjectSecurity( ObjectType, bContainer, pSD1, pSD2, SeInfo, &resultSD); if ( resultSD ) *IsDifferent = TRUE; else *IsDifferent = FALSE; return(rc); } SCESTATUS WINAPI SceAddToNameStatusList( IN OUT PSCE_NAME_STATUS_LIST *pNameStatusList, IN PWSTR Name, IN ULONG Len, IN DWORD Status ) { return(ScepAddToNameStatusList( pNameStatusList, Name, Len, Status) ); } SCESTATUS WINAPI SceAddToNameList( IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR Name, IN ULONG Len ) { return( ScepDosErrorToSceStatus( ScepAddToNameList( pNameList, Name, Len ) ) ); } SCESTATUS WINAPI SceAddToObjectList( IN OUT PSCE_OBJECT_LIST *pObjectList, IN PWSTR Name, IN ULONG Len, IN BOOL IsContainer, // TRUE if the object is a container type IN BYTE Status, // SCE_STATUS_IGNORE, SCE_STATUS_CHECK, SCE_STATUS_OVERWRITE IN BYTE byFlags // SCE_CHECK_DUP if duplicate Name entry should not be added, SCE_INCREASE_COUNT ) { return(ScepDosErrorToSceStatus( ScepAddToObjectList( pObjectList, Name, Len, IsContainer, Status, 0, byFlags ) ) ); } BOOL SceCompareNameList( IN PSCE_NAME_LIST pList1, IN PSCE_NAME_LIST pList2 ) /* Routine Description: This routine compares two name lists for exact match. Sequence is not important in comparsion. */ { PSCE_NAME_LIST pName1, pName2; DWORD Count1=0, Count2=0; if ( (pList2 == NULL && pList1 != NULL) || (pList2 != NULL && pList1 == NULL) ) { // return(TRUE); // should be not equal return(FALSE); } for ( pName2=pList2; pName2 != NULL; pName2 = pName2->Next ) { if ( pName2->Name == NULL ) { continue; } Count2++; } for ( pName1=pList1; pName1 != NULL; pName1 = pName1->Next ) { if ( pName1->Name == NULL ) { continue; } Count1++; for ( pName2=pList2; pName2 != NULL; pName2 = pName2->Next ) { if ( pName2->Name == NULL ) { continue; } if ( _wcsicmp(pName1->Name, pName2->Name) == 0 ) { // // find a match // break; // the second for loop } } if ( pName2 == NULL ) { // // does not find a match // return(FALSE); } } if ( Count1 != Count2 ) return(FALSE); return(TRUE); } DWORD WINAPI SceEnumerateServices( OUT PSCE_SERVICES *pServiceList, IN BOOL bServiceNameOnly ) /* Routine Description: Enumerate all services installed on the local system. The information returned include startup status and security descriptor on each service object. Arguments: pServiceList - the list of services returned. Must be freed by LocalFree return value: ERROR_SUCCESS Win32 error codes */ { SC_HANDLE hScManager=NULL; LPENUM_SERVICE_STATUS pEnumBuffer=NULL, pTempEnum; DWORD ResumeHandle=0, BytesNeeded, ServicesCount=0; DWORD BufSize=1024; // // check arguments // if ( NULL == pServiceList ) return(ERROR_INVALID_PARAMETER); // // open service control manager // hScManager = OpenSCManager( NULL, NULL, MAXIMUM_ALLOWED //SC_MANAGER_ALL_ACCESS // SC_MANAGER_CONNECT | // SC_MANAGER_ENUMERATE_SERVICE | // SC_MANAGER_QUERY_LOCK_STATUS ); if ( NULL == hScManager ) { return( GetLastError() ); } DWORD rc=NO_ERROR; DWORD i; DWORD status; if ( !bServiceNameOnly ) { // // Adjust privilege for setting SACL // status = SceAdjustPrivilege( SE_SECURITY_PRIVILEGE, TRUE, NULL ); // // if can't adjust privilege, ignore (will error out later if SACL is requested) // } do { // // enumerate all services // pEnumBuffer = (LPENUM_SERVICE_STATUS)LocalAlloc(LMEM_FIXED,(UINT)BufSize); if ( NULL == pEnumBuffer ) { rc = ERROR_NOT_ENOUGH_MEMORY; break; } if ( !EnumServicesStatus( hScManager, SERVICE_WIN32, // do not expose driver | SERVICE_DRIVER, SERVICE_STATE_ALL, pEnumBuffer, BufSize, &BytesNeeded, &ServicesCount, &ResumeHandle) ) { rc = GetLastError(); } else rc = ERROR_SUCCESS; pTempEnum = pEnumBuffer; // // Process each service // if ( rc == ERROR_SUCCESS || rc == ERROR_MORE_DATA || rc == ERROR_INSUFFICIENT_BUFFER ) { rc = ERROR_SUCCESS; for ( i=0; pEnumBuffer && i<ServicesCount; i++ ) { // // add the service to our list // if ( bServiceNameOnly ) { // // only ask for service name, do not need to query // status = ScepAddOneServiceToList( pEnumBuffer->lpServiceName, pEnumBuffer->lpDisplayName, 0, NULL, 0, TRUE, pServiceList ); } else { // // query startup and security descriptor // status = ScepQueryAndAddService( hScManager, pEnumBuffer->lpServiceName, pEnumBuffer->lpDisplayName, pServiceList ); } if ( status != ERROR_SUCCESS ) { rc = status; break; } pEnumBuffer++; } } // // Free buffer for next enumeration // if ( pTempEnum ) { LocalFree(pTempEnum); pTempEnum = NULL; } pEnumBuffer = NULL; BufSize = BytesNeeded + 2; ServicesCount = 0; } while ( rc == ERROR_SUCCESS && BytesNeeded > 0 ); // // clear memory and close handle // CloseServiceHandle (hScManager); if ( rc != ERROR_SUCCESS ) { // // free memory in pServiceList // SceFreePSCE_SERVICES(*pServiceList); *pServiceList = NULL; } if ( !bServiceNameOnly ) { // // Adjust privilege for SACL // SceAdjustPrivilege( SE_SECURITY_PRIVILEGE, FALSE, NULL ); } return(rc); } DWORD ScepQueryAndAddService( IN SC_HANDLE hScManager, IN LPWSTR lpServiceName, IN LPWSTR lpDisplayName, OUT PSCE_SERVICES *pServiceList ) /* Routine Description: Queries the security descriptor of the service and add all information to PSCE_SERVICE list Arguments: hScManager - service control manager handle lpServiceName - The service name ServiceStatus - The service status pServiceList - The service list to output Return Value: ERROR_SUCCESS Win32 errors */ { SC_HANDLE hService; DWORD rc=ERROR_SUCCESS; if ( hScManager == NULL || lpServiceName == NULL || pServiceList == NULL ) { return(ERROR_INVALID_PARAMETER); } // // Open the service // SERVICE_ALL_ACCESS | // READ_CONTROL | // ACCESS_SYSTEM_SECURITY // hService = OpenService( hScManager, lpServiceName, MAXIMUM_ALLOWED | ACCESS_SYSTEM_SECURITY ); if ( hService != NULL ) { // // Query the startup type // DWORD BytesNeeded=0; DWORD BufSize; // // Query configuration (Startup type) // get size first // if ( !QueryServiceConfig( hService, NULL, 0, &BytesNeeded ) ) { rc = GetLastError(); if ( rc == ERROR_INSUFFICIENT_BUFFER ) { // // should always gets here // LPQUERY_SERVICE_CONFIG pConfig=NULL; pConfig = (LPQUERY_SERVICE_CONFIG)LocalAlloc(0, BytesNeeded+1); if ( pConfig != NULL ) { rc = ERROR_SUCCESS; BufSize=BytesNeeded; // // the real query for Startup type (pConfig->dwStartType) // if ( QueryServiceConfig( hService, pConfig, BufSize, &BytesNeeded ) ) { // // Query the security descriptor length // the following function does not take NULL for the // address of security descriptor so use a temp buffer first // to get the real length // BYTE BufTmp[128]; SECURITY_INFORMATION SeInfo; // // only query DACL and SACL information // /* SeInfo = DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION; */ SeInfo = DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION; if ( !QueryServiceObjectSecurity( hService, SeInfo, (PSECURITY_DESCRIPTOR)BufTmp, 128, &BytesNeeded ) ) { rc = GetLastError(); if ( rc == ERROR_INSUFFICIENT_BUFFER || rc == ERROR_MORE_DATA ) { // // if buffer is not enough, it is ok // because BytesNeeded is the real length // rc = ERROR_SUCCESS; } } else rc = ERROR_SUCCESS; if ( rc == ERROR_SUCCESS ) { // // allocate buffer for security descriptor // PSECURITY_DESCRIPTOR pSecurityDescriptor=NULL; pSecurityDescriptor = (PSECURITY_DESCRIPTOR)LocalAlloc(LMEM_FIXED, BytesNeeded+2); if ( NULL != pSecurityDescriptor ) { // // query the security descriptor // BufSize = BytesNeeded; if ( QueryServiceObjectSecurity( hService, SeInfo, pSecurityDescriptor, BufSize, &BytesNeeded ) ) { // // create a service node and add it to the list // rc = ScepAddOneServiceToList( lpServiceName, lpDisplayName, pConfig->dwStartType, pSecurityDescriptor, SeInfo, TRUE, pServiceList ); } else { // // error query the security descriptor // rc = GetLastError(); } if ( rc != ERROR_SUCCESS ) { LocalFree(pSecurityDescriptor); } } else { // // cannot allocate memory for security descriptor // rc = ERROR_NOT_ENOUGH_MEMORY; } } } else { // // cannot query config // rc = GetLastError(); } LocalFree(pConfig); } else rc = ERROR_NOT_ENOUGH_MEMORY; } } else { // // should not fall in here, if it does, just return success // } CloseServiceHandle(hService); } else { // // cannot open service // rc = GetLastError(); } return(rc); } INT ScepLookupPrivByValue( IN DWORD Priv ) /* ++ Routine Description: This routine looksup a privilege in SCE_Privileges table and returns the index for the priv. Arguments: Priv - The privilege to look up Return value: The index in SCE_Privileges table if a match is found, or -1 for no match -- */ { DWORD i; if ( Priv == 0 ) return (-1); for ( i=0; i<cPrivCnt; i++) { if ( SCE_Privileges[i].Value == Priv ) return i; } return (-1); } SCESTATUS ScepGetProductType( OUT PSCE_SERVER_TYPE srvProduct ) { NT_PRODUCT_TYPE theType; if ( RtlGetNtProductType(&theType) ) { #if _WIN32_WINNT>=0x0500 // // NT5+ // switch (theType) { case NtProductLanManNt: *srvProduct = SCESVR_DC_WITH_DS; break; case NtProductServer: *srvProduct = SCESVR_NT5_SERVER; break; case NtProductWinNt: *srvProduct = SCESVR_NT5_WKS; break; default: *srvProduct = SCESVR_UNKNOWN; } #else // // NT4 // switch (theType) { case NtProductLanManNt: *srvProduct = SCESVR_DC; break; case NtProductServer: *srvProduct = SCESVR_NT4_SERVER; break; case NtProductWinNt: *srvProduct = SCESVR_NT4_WKS; break; default: *srvProduct = SCESVR_UNKNOWN; } #endif } else { *srvProduct = SCESVR_UNKNOWN; } return(SCESTATUS_SUCCESS); } DWORD ScepAddTwoNamesToNameList( OUT PSCE_NAME_LIST *pNameList, IN BOOL bAddSeparator, IN PWSTR Name1, IN ULONG Length1, IN PWSTR Name2, IN ULONG Length2 ) /* ++ Routine Description: This routine adds two names (wchar) to the name list in the format of Name1\Name2, or Name1Name2, depends if bSeparator is TRUE. This routine is used for Domain\Account tracking list Arguments: pNameList - The name list to add to. Name1 - The name 1 to add Length1 - the length of name1 (number of wchars) Name2 - the name 2 to add Length2 - the length of name2 (number of wchars) Return value: Win32 error code -- */ { PSCE_NAME_LIST pList=NULL; ULONG Length; if ( pNameList == NULL ) return(ERROR_INVALID_PARAMETER); if ( Name1 == NULL && Name2 == NULL ) return(NO_ERROR); Length = Length1 + Length2; if ( Length <= 0 ) return(NO_ERROR); pList = (PSCE_NAME_LIST)ScepAlloc( (UINT)0, sizeof(SCE_NAME_LIST)); if ( pList == NULL ) return(ERROR_NOT_ENOUGH_MEMORY); if ( bAddSeparator ) { Length++; } pList->Name = (PWSTR)ScepAlloc( LMEM_ZEROINIT, (Length+1)*sizeof(TCHAR)); if ( pList->Name == NULL ) { ScepFree(pList); return(ERROR_NOT_ENOUGH_MEMORY); } if ( Name1 != NULL && Length1 > 0 ) wcsncpy(pList->Name, Name1, Length1); if ( bAddSeparator ) { wcsncat(pList->Name, L"\\", 1); } if ( Name2 != NULL && Length2 > 0 ) wcsncat(pList->Name, Name2, Length2); pList->Next = *pNameList; *pNameList = pList; return(NO_ERROR); } NTSTATUS ScepDomainIdToSid( IN PSID DomainId, IN ULONG RelativeId, OUT PSID *Sid ) /*++ Routine Description: Given a domain Id and a relative ID create a SID Arguments: DomainId - The template SID to use. RelativeId - The relative Id to append to the DomainId. Sid - Returns a pointer to an allocated buffer containing the resultant Sid. Free this buffer using NetpMemoryFree. Return Value: NTSTATUS --*/ { UCHAR DomainIdSubAuthorityCount; // Number of sub authorities in domain ID ULONG SidLength; // Length of newly allocated SID // // Allocate a Sid which has one more sub-authority than the domain ID. // DomainIdSubAuthorityCount = *(RtlSubAuthorityCountSid( DomainId )); SidLength = RtlLengthRequiredSid(DomainIdSubAuthorityCount+1); if ((*Sid = (PSID) ScepAlloc( (UINT)0, SidLength )) == NULL ) { return STATUS_NO_MEMORY; } // // Initialize the new SID to have the same inital value as the // domain ID. // if ( !NT_SUCCESS( RtlCopySid( SidLength, *Sid, DomainId ) ) ) { ScepFree( *Sid ); *Sid = NULL; return STATUS_INTERNAL_ERROR; } // // Adjust the sub-authority count and // add the relative Id unique to the newly allocated SID // (*(RtlSubAuthorityCountSid( *Sid ))) ++; *RtlSubAuthoritySid( *Sid, DomainIdSubAuthorityCount ) = RelativeId; return ERROR_SUCCESS; } DWORD ScepConvertSidToPrefixStringSid( IN PSID pSid, OUT PWSTR *StringSid ) /* The pair routine to convert stringsid to a Sid is ConvertStringSidToSid defined in sddl.h */ { if ( pSid == NULL || StringSid == NULL ) { return(ERROR_INVALID_PARAMETER); } UNICODE_STRING UnicodeStringSid; DWORD rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, pSid, TRUE )); if ( ERROR_SUCCESS == rc ) { *StringSid = (PWSTR)ScepAlloc(LPTR, UnicodeStringSid.Length+2*sizeof(WCHAR)); if ( *StringSid ) { (*StringSid)[0] = L'*'; wcsncpy( (*StringSid)+1, UnicodeStringSid.Buffer, UnicodeStringSid.Length/2); } else { rc = ERROR_NOT_ENOUGH_MEMORY; } RtlFreeUnicodeString( &UnicodeStringSid ); } return(rc); } NTSTATUS ScepConvertSidToName( IN LSA_HANDLE LsaPolicy, IN PSID AccountSid, IN BOOL bFromDomain, OUT PWSTR *AccountName, OUT DWORD *Length OPTIONAL ) { if ( LsaPolicy == NULL || AccountSid == NULL || AccountName == NULL ) { return(STATUS_INVALID_PARAMETER); } PSID pTmpSid=AccountSid; PLSA_TRANSLATED_NAME Names=NULL; PLSA_REFERENCED_DOMAIN_LIST ReferencedDomains=NULL; NTSTATUS NtStatus = LsaLookupSids( LsaPolicy, 1, (PSID *)&pTmpSid, &ReferencedDomains, &Names ); DWORD Len=0; if ( NT_SUCCESS(NtStatus) ) { if ( ( Names[0].Use != SidTypeInvalid && Names[0].Use != SidTypeUnknown ) ) { // // build the account name without domain name // if ( bFromDomain && Names[0].Use != SidTypeWellKnownGroup && ReferencedDomains->Entries > 0 && ReferencedDomains->Domains != NULL && Names[0].DomainIndex != -1 && (ULONG)(Names[0].DomainIndex) < ReferencedDomains->Entries && ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length > 0 && ScepIsSidFromAccountDomain( ReferencedDomains->Domains[Names[0].DomainIndex].Sid ) ) { // // build domain name\account name // Len = Names[0].Name.Length + ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length + 2; *AccountName = (PWSTR)LocalAlloc(LPTR, Len+sizeof(TCHAR)); if ( *AccountName ) { wcsncpy(*AccountName, ReferencedDomains->Domains[Names[0].DomainIndex].Name.Buffer, ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2); (*AccountName)[ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2] = L'\\'; wcsncpy((*AccountName)+ReferencedDomains->Domains[Names[0].DomainIndex].Name.Length/2+1, Names[0].Name.Buffer, Names[0].Name.Length/2); } else { NtStatus = STATUS_NO_MEMORY; } Len /= 2; } else { Len = Names[0].Name.Length/2; *AccountName = (PWSTR)LocalAlloc(LPTR, Names[0].Name.Length+2); if ( *AccountName ) { wcsncpy(*AccountName, Names[0].Name.Buffer, Len); } else { NtStatus = STATUS_NO_MEMORY; } } } else { NtStatus = STATUS_NONE_MAPPED; } } if ( ReferencedDomains ) { LsaFreeMemory(ReferencedDomains); ReferencedDomains = NULL; } if ( Names ) { LsaFreeMemory(Names); Names = NULL; } if ( NT_SUCCESS(NtStatus) && Length ) { *Length = Len; } return(NtStatus); } NTSTATUS ScepConvertNameToSid( IN LSA_HANDLE LsaPolicy, IN PWSTR AccountName, OUT PSID *AccountSid ) { if ( LsaPolicy == NULL || AccountName == NULL || AccountSid == NULL ) { return(STATUS_INVALID_PARAMETER); } PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; NTSTATUS NtStatus = ScepLsaLookupNames2( LsaPolicy, LSA_LOOKUP_ISOLATED_AS_LOCAL, AccountName, &RefDomains, &Sids ); if ( NT_SUCCESS(NtStatus) && Sids ) { // // build the account sid // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid != NULL ) { // // this name is mapped, the SID is in Sids[0].Sid // DWORD SidLength = RtlLengthSid(Sids[0].Sid); if ( (*AccountSid = (PSID) ScepAlloc( (UINT)0, SidLength)) == NULL ) { NtStatus = STATUS_NO_MEMORY; } else { // // copy the SID // NtStatus = RtlCopySid( SidLength, *AccountSid, Sids[0].Sid ); if ( !NT_SUCCESS(NtStatus) ) { ScepFree( *AccountSid ); *AccountSid = NULL; } } } else { NtStatus = STATUS_NONE_MAPPED; } } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(NtStatus); } NTSTATUS ScepLsaLookupNames2( IN LSA_HANDLE PolicyHandle, IN ULONG Flags, IN PWSTR pszAccountName, OUT PLSA_REFERENCED_DOMAIN_LIST *ReferencedDomains, OUT PLSA_TRANSLATED_SID2 *Sids ) /*++ Routine Description: Similar to LsaLookupNames2 except that on local lookup failures, it resolves free text accounts to the domain this machine is joined to Arguments: PolicyHandle - handle to LSA Flags - usually LSA_LOOKUP_ISOLATED_AS_LOCAL pszAccountName - name of account to lookup ReferencedDomains - returns the reference domain id (to be freed by caller) Sids - returns the SID looked up (to be freed by caller) Return Value: NTSTATUS --*/ { PWSTR pszScopedName = NULL; UNICODE_STRING UnicodeName; PPOLICY_ACCOUNT_DOMAIN_INFO pDomainInfo = NULL; RtlInitUnicodeString(&UnicodeName, pszAccountName); NTSTATUS NtStatus = LsaLookupNames2( PolicyHandle, Flags, 1, &UnicodeName, ReferencedDomains, Sids ); if ((NtStatus == STATUS_SOME_NOT_MAPPED || NtStatus == STATUS_NONE_MAPPED) && NULL == wcschr(pszAccountName, L'\\') ) { NtStatus = LsaQueryInformationPolicy(PolicyHandle, PolicyDnsDomainInformation, ( PVOID * )&pDomainInfo ); if (!NT_SUCCESS(NtStatus) || pDomainInfo == NULL || pDomainInfo->DomainName.Buffer == NULL || pDomainInfo->DomainName.Length <= 0) { NtStatus = STATUS_SOME_NOT_MAPPED; goto ExitHandler; } pszScopedName = (PWSTR) LocalAlloc(LMEM_ZEROINIT, (pDomainInfo->DomainName.Length/2 + wcslen(pszAccountName) + 2) * sizeof(WCHAR)); if (pszScopedName == NULL) { NtStatus = STATUS_NO_MEMORY; goto ExitHandler; } wcsncpy(pszScopedName, pDomainInfo->DomainName.Buffer, pDomainInfo->DomainName.Length/2); wcscat(pszScopedName, L"\\"); wcscat(pszScopedName, pszAccountName); RtlInitUnicodeString(&UnicodeName, pszScopedName); NtStatus = LsaLookupNames2( PolicyHandle, Flags, 1, &UnicodeName, ReferencedDomains, Sids ); } ExitHandler: if (pszScopedName) { LocalFree(pszScopedName); } if (pDomainInfo) { LsaFreeMemory( pDomainInfo ); } if ( STATUS_SUCCESS != NtStatus ) return STATUS_NONE_MAPPED; else return STATUS_SUCCESS; } SCESTATUS ScepConvertNameToSidString( IN LSA_HANDLE LsaHandle, IN PWSTR Name, IN BOOL bAccountDomainOnly, OUT PWSTR *SidString, OUT DWORD *SidStrLen ) { if ( LsaHandle == NULL || Name == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } if ( Name[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } if ( SidString == NULL || SidStrLen == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; NtStatus = ScepLsaLookupNames2( LsaHandle, LSA_LOOKUP_ISOLATED_AS_LOCAL, Name, &RefDomains, &Sids ); rc = RtlNtStatusToDosError(NtStatus); if ( ERROR_SUCCESS == rc && Sids ) { // // name is found, make domain\account format // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid != NULL ) { // // this name is mapped // if ( !bAccountDomainOnly || ScepIsSidFromAccountDomain( Sids[0].Sid ) ) { // // convert to a sid string, note: a prefix "*" should be added // UNICODE_STRING UnicodeStringSid; rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, Sids[0].Sid, TRUE )); if ( ERROR_SUCCESS == rc ) { *SidStrLen = UnicodeStringSid.Length/2 + 1; *SidString = (PWSTR)ScepAlloc(LPTR, UnicodeStringSid.Length + 2*sizeof(WCHAR)); if ( *SidString ) { (*SidString)[0] = L'*'; wcsncpy((*SidString)+1, UnicodeStringSid.Buffer, (*SidStrLen)-1); } else { *SidStrLen = 0; rc = ERROR_NOT_ENOUGH_MEMORY; } RtlFreeUnicodeString( &UnicodeStringSid ); } } else { // // add only the account name // rc = ERROR_NONE_MAPPED; } } else { rc = ERROR_NONE_MAPPED; } } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } SCESTATUS ScepLookupSidStringAndAddToNameList( IN LSA_HANDLE LsaHandle, IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR LookupString, IN ULONG Len ) { if ( LsaHandle == NULL || LookupString == NULL ) { return(SCESTATUS_INVALID_PARAMETER); } if ( LookupString[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } if ( Len <= 3 || (LookupString[1] != L'S' && LookupString[1] != L's') || LookupString[2] != L'-' ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_NAME Names=NULL; if ( ConvertStringSidToSid(LookupString+1, &pSid) ) { NtStatus = LsaLookupSids( LsaHandle, 1, &pSid, &RefDomains, &Names ); rc = RtlNtStatusToDosError(NtStatus); LocalFree(pSid); pSid = NULL; } else { rc = GetLastError(); } if ( ERROR_SUCCESS == rc && Names && RefDomains ) { // // name is found, make domain\account format // if ( ( Names[0].Use != SidTypeInvalid && Names[0].Use != SidTypeUnknown ) ) { // // this name is mapped // if ( RefDomains->Entries > 0 && Names[0].Use != SidTypeWellKnownGroup && RefDomains->Domains != NULL && Names[0].DomainIndex != -1 && (ULONG)(Names[0].DomainIndex) < RefDomains->Entries && RefDomains->Domains[Names[0].DomainIndex].Name.Length > 0 && ScepIsSidFromAccountDomain( RefDomains->Domains[Names[0].DomainIndex].Sid ) ) { // // add both domain name and account name // rc = ScepAddTwoNamesToNameList( pNameList, TRUE, RefDomains->Domains[Names[0].DomainIndex].Name.Buffer, RefDomains->Domains[Names[0].DomainIndex].Name.Length/2, Names[0].Name.Buffer, Names[0].Name.Length/2); } else { // // add only the account name // rc = ScepAddToNameList( pNameList, Names[0].Name.Buffer, Names[0].Name.Length/2); } } else { rc = ERROR_NONE_MAPPED; } } else { // // lookup in the constant table for builtin accounts // note. This will resolve the builtin SIDs to the language of the binary // which may not be the locale the process is running (UI) // for (int i = 0; i < TABLE_SIZE; i++) { if ( _wcsicmp(NameTable[i].StrSid, LookupString+1) == 0 ) { // //found match // rc = ScepAddToNameList( pNameList, NameTable[i].Name, 0); break; } } } if ( ERROR_SUCCESS != rc ) { // // either invalid sid string, or not found a name map, or // failed to add to the name list, just simply add the sid string to the name list // rc = ScepAddToNameList( pNameList, LookupString, Len); } if ( Names ) { LsaFreeMemory(Names); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } SCESTATUS ScepLookupNameAndAddToSidStringList( IN LSA_HANDLE LsaHandle, IN OUT PSCE_NAME_LIST *pNameList, IN PWSTR LookupString, IN ULONG Len ) { if ( LsaHandle == NULL || LookupString == NULL || Len == 0 ) { return(SCESTATUS_INVALID_PARAMETER); } if ( LookupString[0] == L'\0' ) { return(SCESTATUS_INVALID_PARAMETER); } // // convert the sid string to a real sid // PSID pSid=NULL; NTSTATUS NtStatus; DWORD rc; PLSA_REFERENCED_DOMAIN_LIST RefDomains=NULL; PLSA_TRANSLATED_SID2 Sids=NULL; UNICODE_STRING UnicodeName; NtStatus = ScepLsaLookupNames2( LsaHandle, LSA_LOOKUP_ISOLATED_AS_LOCAL, LookupString, &RefDomains, &Sids ); rc = RtlNtStatusToDosError(NtStatus); if ( ERROR_SUCCESS == rc && Sids ) { // // name is found, make domain\account format // if ( Sids[0].Use != SidTypeInvalid && Sids[0].Use != SidTypeUnknown && Sids[0].Sid ) { // // this name is mapped // convert to a sid string, note: a prefix "*" should be added // UNICODE_STRING UnicodeStringSid; rc = RtlNtStatusToDosError( RtlConvertSidToUnicodeString(&UnicodeStringSid, Sids[0].Sid, TRUE )); if ( ERROR_SUCCESS == rc ) { rc = ScepAddTwoNamesToNameList( pNameList, FALSE, TEXT("*"), 1, UnicodeStringSid.Buffer, UnicodeStringSid.Length/2); RtlFreeUnicodeString( &UnicodeStringSid ); } } else { rc = ERROR_NONE_MAPPED; } } if ( ERROR_SUCCESS != rc ) { // // either invalid sid string, or not found a name map, or // failed to add to the name list, just simply add the sid string to the name list // rc = ScepAddToNameList( pNameList, LookupString, Len); } if ( Sids ) { LsaFreeMemory(Sids); } if ( RefDomains ) { LsaFreeMemory(RefDomains); } return(ScepDosErrorToSceStatus(rc)); } NTSTATUS ScepOpenLsaPolicy( IN ACCESS_MASK access, OUT PLSA_HANDLE pPolicyHandle, IN BOOL bDoNotNotify ) /* ++ Routine Description: This routine opens the LSA policy with the desired access. Arguments: access - the desired access to the policy pPolicyHandle - returned address of the Policy Handle Return value: NTSTATUS -- */ { NTSTATUS NtStatus; LSA_OBJECT_ATTRIBUTES attributes; SECURITY_QUALITY_OF_SERVICE service; memset( &attributes, 0, sizeof(attributes) ); attributes.Length = sizeof(attributes); attributes.SecurityQualityOfService = &service; service.Length = sizeof(service); service.ImpersonationLevel= SecurityImpersonation; service.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING; service.EffectiveOnly = TRUE; // // open the lsa policy first // NtStatus = LsaOpenPolicy( NULL, &attributes, access, pPolicyHandle ); /* if ( NT_SUCCESS(NtStatus) && bDoNotNotify && *pPolicyHandle ) { NtStatus = LsaSetPolicyReplicationHandle(pPolicyHandle); if ( !NT_SUCCESS(NtStatus) ) { LsaClose( *pPolicyHandle ); *pPolicyHandle = NULL; } } */ return(NtStatus); } BOOL ScepIsSidFromAccountDomain( IN PSID pSid ) { if ( pSid == NULL ) { return(FALSE); } if ( !RtlValidSid(pSid) ) { return(FALSE); } PSID_IDENTIFIER_AUTHORITY pia = RtlIdentifierAuthoritySid ( pSid ); if ( pia ) { if ( pia->Value[5] != 5 || pia->Value[0] != 0 || pia->Value[1] != 0 || pia->Value[2] != 0 || pia->Value[3] != 0 || pia->Value[4] != 0 ) { // // this is not a account from account domain // return(FALSE); } if ( RtlSubAuthorityCountSid( pSid ) == 0 || *RtlSubAuthoritySid ( pSid, 0 ) != SECURITY_NT_NON_UNIQUE ) { return(FALSE); } return(TRUE); } return(FALSE); } //+-------------------------------------------------------------------------- // // Function: SetupINFAsUCS2 // // Synopsis: Dumps some UCS-2 to the specified INF file if it // doesn't already exist; this makes the .inf/.ini manipulation code // use UCS-2. // // Arguments: The file to create and dump to // // Returns: 0 == failure, non-zero == success; use GetLastError() // to retrieve the error code (same as WriteFile). // //+-------------------------------------------------------------------------- BOOL SetupINFAsUCS2(LPCTSTR szName) { HANDLE file; BOOL status; file = CreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) { if (GetLastError() != ERROR_ALREADY_EXISTS) // Well, this isn't good -- we lose. status = FALSE; else // Otherwise, the file already existed, which is just fine. // We'll just let the .inf/.ini manipulation code keep using // the same charset&encoding... status = TRUE; } else { // We created the file -- it didn't exist. // So we need to spew a little UCS-2 into it. static WCHAR str[] = L"0[Unicode]\r\nUnicode=yes\r\n"; DWORD n_written; BYTE *pbStr = (BYTE *)str; pbStr[0] = 0xFF; pbStr[1] = 0xFE; status = WriteFile(file, (LPCVOID)str, sizeof(str) - sizeof(UNICODE_NULL), &n_written, NULL); CloseHandle(file); } return status; } //+-------------------------------------------------------------------------- // // Function: ScepStripPrefix // // Arguments: pwszPath to look in // // Returns: Returns ptr to stripped path (same if no stripping) // //+-------------------------------------------------------------------------- WCHAR * ScepStripPrefix( IN LPTSTR pwszPath ) { WCHAR wszMachPrefix[] = TEXT("LDAP://CN=Machine,"); INT iMachPrefixLen = lstrlen( wszMachPrefix ); WCHAR wszUserPrefix[] = TEXT("LDAP://CN=User,"); INT iUserPrefixLen = lstrlen( wszUserPrefix ); WCHAR *pwszPathSuffix; // // Strip out prefix to get the canonical path to Gpo // if ( CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, pwszPath, iUserPrefixLen, wszUserPrefix, iUserPrefixLen ) == CSTR_EQUAL ) { pwszPathSuffix = pwszPath + iUserPrefixLen; } else if ( CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, pwszPath, iMachPrefixLen, wszMachPrefix, iMachPrefixLen ) == CSTR_EQUAL ) { pwszPathSuffix = pwszPath + iMachPrefixLen; } else pwszPathSuffix = pwszPath; return pwszPathSuffix; } //+-------------------------------------------------------------------------- // // Function: ScepGenerateGuid // // Arguments: out: the guid string // // Returns: Returns guid string (has to be freed outside // //+-------------------------------------------------------------------------- /* DWORD ScepGenerateGuid( OUT PWSTR *ppwszGuid ) { GUID guid; DWORD rc = ERROR_SUCCESS; if (ppwszGuid == NULL) return ERROR_INVALID_PARAMETER; *ppwszGuid = (PWSTR) ScepAlloc(LMEM_ZEROINIT, (MAX_GUID_STRING_LEN + 1) * sizeof(WCHAR)); if (*ppwszGuid) { if (ERROR_SUCCESS == (rc = ScepWbemErrorToDosError(CoCreateGuid( &guid )))) { if (!SCEP_NULL_GUID(guid)) SCEP_GUID_TO_STRING(guid, *ppwszGuid); else { rc = ERROR_INVALID_PARAMETER; } } } else rc = ERROR_NOT_ENOUGH_MEMORY; return rc; } */ SCESTATUS SceInfpGetPrivileges( IN HINF hInf, IN BOOL bLookupAccount, OUT PSCE_PRIVILEGE_ASSIGNMENT *pPrivileges, OUT PSCE_ERROR_LOG_INFO *Errlog OPTIONAL ) /* ++ Description: Get user right assignments from a INF template. If bLookupAccount is set to TRUE, the accounts in user right assignments will be translated to account names (from SID format); else the information is returned in the same way as defined in the template. Arguments: Return Value: -- */ { INFCONTEXT InfLine; SCESTATUS rc=SCESTATUS_SUCCESS; PSCE_PRIVILEGE_ASSIGNMENT pCurRight=NULL; WCHAR Keyname[SCE_KEY_MAX_LENGTH]; PWSTR StrValue=NULL; DWORD DataSize; DWORD PrivValue; DWORD i, cFields; LSA_HANDLE LsaHandle=NULL; // // [Privilege Rights] section // if(SetupFindFirstLine(hInf,szPrivilegeRights,NULL,&InfLine)) { // // open lsa policy handle for sid/name lookup // rc = RtlNtStatusToDosError( ScepOpenLsaPolicy( POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, &LsaHandle, TRUE )); if ( ERROR_SUCCESS != rc ) { ScepBuildErrorLogInfo( rc, Errlog, SCEERR_ADD, TEXT("LSA") ); return(ScepDosErrorToSceStatus(rc)); } do { memset(Keyname, '\0', SCE_KEY_MAX_LENGTH*sizeof(WCHAR)); rc = SCESTATUS_SUCCESS; if ( SetupGetStringField(&InfLine, 0, Keyname, SCE_KEY_MAX_LENGTH, NULL) ) { // // find a key name (which is a privilege name here ). // lookup privilege's value // if ( ( PrivValue = ScepLookupPrivByName(Keyname) ) == -1 ) { ScepBuildErrorLogInfo( ERROR_INVALID_DATA, Errlog, SCEERR_INVALID_PRIVILEGE, Keyname ); // goto NextLine; } // // a sm_privilege_assignment structure. allocate buffer // pCurRight = (PSCE_PRIVILEGE_ASSIGNMENT)ScepAlloc( LMEM_ZEROINIT, sizeof(SCE_PRIVILEGE_ASSIGNMENT) ); if ( pCurRight == NULL ) { rc = SCESTATUS_NOT_ENOUGH_RESOURCE; goto Done; } pCurRight->Name = (PWSTR)ScepAlloc( (UINT)0, (wcslen(Keyname)+1)*sizeof(WCHAR)); if ( pCurRight->Name == NULL ) { ScepFree(pCurRight); rc = SCESTATUS_NOT_ENOUGH_RESOURCE; goto Done; } wcscpy(pCurRight->Name, Keyname); pCurRight->Value = PrivValue; cFields = SetupGetFieldCount( &InfLine ); for ( i=0; i<cFields && rc==SCESTATUS_SUCCESS; i++) { // // read each user/group name // if ( SetupGetStringField( &InfLine, i+1, NULL, 0, &DataSize ) ) { if (DataSize > 1) { StrValue = (PWSTR)ScepAlloc( 0, (DataSize+1)*sizeof(WCHAR) ); if ( StrValue == NULL ) rc = SCESTATUS_NOT_ENOUGH_RESOURCE; else { StrValue[DataSize] = L'\0'; if ( SetupGetStringField( &InfLine, i+1, StrValue, DataSize, NULL) ) { if ( bLookupAccount && StrValue[0] == L'*' && DataSize > 0 ) { // // this is a SID format, should look it up // rc = ScepLookupSidStringAndAddToNameList( LsaHandle, &(pCurRight->AssignedTo), StrValue, // +1, DataSize // -1 ); } else { rc = ScepAddToNameList(&(pCurRight->AssignedTo), StrValue, DataSize ); } } else rc = SCESTATUS_INVALID_DATA; } ScepFree( StrValue ); StrValue = NULL; } } else { ScepBuildErrorLogInfo( ERROR_INVALID_DATA, Errlog, SCEERR_QUERY_INFO, Keyname ); rc = SCESTATUS_INVALID_DATA; } } if ( rc == SCESTATUS_SUCCESS ) { // // add this node to the list // pCurRight->Next = *pPrivileges; *pPrivileges = pCurRight; pCurRight = NULL; } else ScepFreePrivilege(pCurRight); } else rc = SCESTATUS_BAD_FORMAT; //NextLine: if (rc != SCESTATUS_SUCCESS ) { ScepBuildErrorLogInfo( ScepSceStatusToDosError(rc), Errlog, SCEERR_QUERY_INFO, szPrivilegeRights ); goto Done; } } while(SetupFindNextLine(&InfLine,&InfLine)); } Done: if ( StrValue != NULL ) ScepFree(StrValue); if ( LsaHandle ) { LsaClose(LsaHandle); } return(rc); } NTSTATUS ScepIsSystemContext( IN HANDLE hUserToken, OUT BOOL *pbSystem ) { NTSTATUS NtStatus; DWORD nRequired; // // variables to determine calling context // PTOKEN_USER pUser=NULL; SID_IDENTIFIER_AUTHORITY ia=SECURITY_NT_AUTHORITY; PSID SystemSid=NULL; BOOL b; // // get current user SID in the token // NtStatus = NtQueryInformationToken (hUserToken, TokenUser, NULL, 0, &nRequired ); if ( STATUS_BUFFER_TOO_SMALL == NtStatus ) { pUser = (PTOKEN_USER)LocalAlloc(0,nRequired+1); if ( pUser ) { NtStatus = NtQueryInformationToken (hUserToken, TokenUser, (PVOID)pUser, nRequired, &nRequired ); } else { NtStatus = STATUS_NO_MEMORY; } } b = FALSE; if ( NT_SUCCESS(NtStatus) && pUser && pUser->User.Sid ) { // // build system sid and compare with the current user SID // NtStatus = RtlAllocateAndInitializeSid (&ia,1,SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &SystemSid); if ( NT_SUCCESS(NtStatus) && SystemSid ) { // // check to see if it is system sid // if ( RtlEqualSid(pUser->User.Sid, SystemSid) ) { b=TRUE; } } } // // free memory allocated // if ( SystemSid ) { FreeSid(SystemSid); } if ( pUser ) { LocalFree(pUser); } *pbSystem = b; return NtStatus; } BOOL IsNT5() { WCHAR szInfName[MAX_PATH*2+1]; szInfName[0] = L'\0'; DWORD cNumCharsReturned = GetSystemWindowsDirectory(szInfName, MAX_PATH); if (cNumCharsReturned) { wcscat(szInfName, L"\\system32\\$winnt$.inf"); } else { return TRUE; } UINT nRet = GetPrivateProfileInt( L"Networking", L"BuildNumber", 0, szInfName ); if (nRet == 0) { return TRUE; } else if (nRet > 1381) { return TRUE; } return FALSE; } DWORD ScepVerifyTemplateName( IN PWSTR InfTemplateName, OUT PSCE_ERROR_LOG_INFO *pErrlog OPTIONAL ) /* Routine Description: This routine verifies the template name for read protection and invalid path Arguments: InfTemplateName - the full path name of the inf template pErrlog - the error log buffer Return Value: WIN32 error code */ { if ( !InfTemplateName ) { return(ERROR_INVALID_PARAMETER); } PWSTR DefProfile; DWORD rc; // // verify the InfTemplateName to generate // if read only, or access denied, return ERROR_ACCESS_DENIED // if invalid path, return ERROR_PATH_NOT_FOUND // DefProfile = InfTemplateName + wcslen(InfTemplateName)-1; while ( DefProfile > InfTemplateName+1 ) { if ( *DefProfile != L'\\') { DefProfile--; } else { break; } } rc = NO_ERROR; if ( DefProfile > InfTemplateName+2 ) { // at least allow a drive letter, a colon, and a \ // // find the directory path // DWORD Len=(DWORD)(DefProfile-InfTemplateName); PWSTR TmpBuf=(PWSTR)LocalAlloc(0, (Len+1)*sizeof(WCHAR)); if ( TmpBuf ) { wcsncpy(TmpBuf, InfTemplateName, Len); TmpBuf[Len] = L'\0'; if ( 0xFFFFFFFF == GetFileAttributes(TmpBuf) ) rc = ERROR_PATH_NOT_FOUND; LocalFree(TmpBuf); } else { rc = ERROR_NOT_ENOUGH_MEMORY; } } else if ( DefProfile == InfTemplateName+2 && InfTemplateName[1] == L':' ) { // // this is a template path off the root // } else { // // invalid directory path // rc = ERROR_PATH_NOT_FOUND; } if ( rc != NO_ERROR ) { // // error occurs // if ( ERROR_PATH_NOT_FOUND == rc ) { ScepBuildErrorLogInfo( rc, pErrlog, SCEERR_INVALID_PATH, InfTemplateName ); } return(rc); } // // make it unicode aware // do not worry about failure // SetupINFAsUCS2(InfTemplateName); // // validate if the template is write protected // FILE *hTempFile; hTempFile = _wfopen(InfTemplateName, L"a+"); if ( !hTempFile ) { // // can't overwrite/create the file, must be access denied // rc = ERROR_ACCESS_DENIED; ScepBuildErrorLogInfo( rc, pErrlog, SCEERR_ERROR_CREATE, InfTemplateName ); return(rc); } else { fclose( hTempFile ); } return(rc); }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
ee7e8bdd3deeada4ec2bfbff8b62d93713e3b169
cb417c58658ac99e26fda8c79d2737de4b8688f9
/tagkeyedit.cpp
8d6c81f3309b602bc424f8ade6be35b338846d39
[]
no_license
SinixCosix/Mosaic
b2760da7ac161f91b4d61482b4560abc53273a78
262d3fc4390a6b60084af577085acb32dbf589c3
refs/heads/master
2022-09-16T19:15:19.203715
2020-05-28T12:46:32
2020-05-28T12:46:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include "tagkeyeditlist.h" TagKeyEdit::TagKeyEdit(QWidget *parent) : TagBaseWidget(parent) { this->exif_name = new QComboBox(); setExifName(); connect(exif_name, &QComboBox::currentTextChanged, this, &TagKeyEdit::checkValid); layout->addWidget(short_name_lineEdit); layout->addWidget(exif_name); layout->addWidget(remove_btn); setLayout(layout); setData(); } void TagKeyEdit::setExifName() { exif_name->addItems(extra.getExtra()); exif_name->setEditable(true); QCompleter *c = new QCompleter(extra.getExtra(), exif_name); c->setCaseSensitivity(Qt::CaseInsensitive); exif_name->setCompleter(c); } void TagKeyEdit::setExifName(const QString &cur_text) { setExifName(); exif_name->setCurrentIndex(exif_name->findText(cur_text)); } void TagKeyEdit::setData() { setShortName(); setExifName(); } void TagKeyEdit::setData(QPair<QString, QString> data) { setShortName(data.first); setExifName(data.second); } QPair<QString, QString> TagKeyEdit::getData() { QPair<QString, QString> pair(short_name_lineEdit->text(), exif_name->currentText()); return pair; } bool TagKeyEdit::isValid() { return !(short_name_lineEdit->text().isEmpty() or exif_name->currentText().isEmpty() or exif_name->findText(exif_name->currentText()) == -1); }
[ "rainbowshardofdeath@gmail.com" ]
rainbowshardofdeath@gmail.com
af31f561da07cd75baf90f7c1b00cb3d414704e3
27c75711bbe10b3120c158971bb4e830af0c33e8
/AsZ/2015.09.13/9.cpp
d6c902df0aa6d311d29b73f478ef55a2a5f2d12b
[]
no_license
yl3i/ACM
9d2f7a6f3faff905eb2ed6854c2dbf040a002372
29bb023cb13489bda7626f8105756ef64f89674f
refs/heads/master
2021-05-22T02:00:56.486698
2020-04-04T05:45:10
2020-04-04T05:45:10
252,918,033
0
0
null
2020-04-04T05:36:11
2020-04-04T05:36:11
null
UTF-8
C++
false
false
2,243
cpp
#include <bits/stdc++.h> #define N 50500 #define INF 0x3f3f3f3f using namespace std; int dp[N], p; void calc(int v, int c, int s) { int upper = min(p + 100 - v, s); for (int i = upper; i >= 0; i--) dp[i + v] = min(dp[i + v], dp[i] + c); } void calc1(int v, int c, int s) { int upper = min(p - v, s); // cout << v << " " << c << " " << s << endl; // cout << upper << endl; for (int i = upper; i >= 0; i--) { if (dp[i] == -1) continue; dp[i + v] = max(dp[i + v], dp[i] + c); } } int main() { //freopen("9.in", "r", stdin); int ttt; scanf("%d", &ttt); while (ttt--) { int n, m; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i <= p + 200; i++) dp[i] = INF; dp[0] = 0; int sum = 0; for (int i = 0; i < n; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); for (int k = 1; k <= z; k <<= 1) { calc(x * k, y * k, sum); z -= k, sum += k * x; } if (z) { calc(x * z, y * z, sum); sum += z * x; } } // cout << endl; int minspace = INF; for (int i = p; i <= p + 100; i++) minspace = min(minspace, dp[i]); p = 50000, sum = 0; for (int i = 0; i <= p; i++) dp[i] = -1; dp[0] = 0; for (int i = 0; i < m; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); for (int k = 1; k <= z; k <<= 1) { calc1(y * k, x * k, sum); z -= k, sum += k * y; } if (z) { calc1(y * z, x * z, sum); sum += z * y; } } // for (int i = 0; i <= 20; i++) // printf("%d%c", dp[i], " \n"[i == 20]); bool flag = false; for (int i = 0; i <= p; i++) if (dp[i] >= minspace) { printf("%d\n", i); flag = true; break; } if (!flag) printf("TAT\n"); } return 0; }
[ "yuzhou627@gmail.com" ]
yuzhou627@gmail.com
d989762f67fa5df6af4abbe39a3b1b2501f53dde
3764f1bcd1b95ea9c26b713e525130edac47bc73
/mach/mach/machine/machine_runtime.cpp
5cd52e91d810a20c5682200242cbe4bc42aadffb
[ "MIT" ]
permissive
benbraide/mach
bc5d46185ff8e17afa0e26dbecbdb035e8e3c9c6
a723b6392778ab8391723a78ac52f53c455da6f5
refs/heads/master
2020-04-15T01:55:24.866280
2019-02-04T23:41:47
2019-02-04T23:41:47
164,296,462
0
0
null
null
null
null
UTF-8
C++
false
false
2,120
cpp
#include "machine_runtime.h" mach::machine::runtime::runtime(io::reader &reader){ init_(reader); } mach::machine::runtime::runtime(qword entry) : entry_(entry){} mach::machine::runtime::runtime(byte *data, std::size_t size){ init_(data, size); } void mach::machine::runtime::run(){ if (stack_ != nullptr) return;//Already running memory_block *module_block = nullptr; if (module_size_ != 0u){//Load module module_block = ((reader_ == nullptr) ? memory_.allocate_block(data_, module_size_) : memory_.allocate_block(module_size_)); if (reader_ != nullptr)//Write module to memory memory_.copy(*reader_, module_block->get_address(), module_block->get_size()); entry_ += module_block->get_address(); } auto stack_block = memory_.allocate_block(stack_size_); stack_ = std::make_shared<stack>(stack_block->get_data(), stack_block->get_real_size()); reg_table_.get_instruction_pointer()->write_scalar(entry_); while (stack_ != nullptr){ switch (memory_.read_scalar<op_code>(reg_table_.get_instruction_pointer()->read_scalar<qword>())){ case op_code::nop://No operation break; case op_code::mov: byte_code::mov_instruction::execute(memory_, reg_table_, *stack_); break; default: throw byte_code::instruction_error_code::unrecognized_instruction; break; } } memory_.deallocate_block(stack_block->get_address()); if (module_block != nullptr)//Unload module memory_.deallocate_block(module_block->get_address()); } void mach::machine::runtime::init_(io::reader &reader){ prepare_(reader); reader_ = &reader; } void mach::machine::runtime::init_(byte *data, std::size_t size){ io::binary_buffer_reader reader(data, size); prepare_(reader); data_ = (data + reader.get_offset()); } void mach::machine::runtime::prepare_(io::reader &reader){ if ((stack_size_ = reader.read_scalar<std::size_t>()) == 0u) stack_size_ = (1024u * 1024u);//Use default size -- 1MB module_size_ = reader.read_scalar<std::size_t>(); entry_ = reader.read_scalar<qword>(); } mach::machine::memory mach::machine::runtime::memory_; std::size_t mach::machine::runtime::stack_size_ = 0u;
[ "benbraide@yahoo.com" ]
benbraide@yahoo.com
bcd183501c27515766d16f978f48dc5ec272b1f2
de5bbebd0b6c83f76bd65fc8984c5bb2154d8446
/2020-2021/previous/simplemetaheuristics/simannealing.cpp
479fa3b6d51b87b741c9a5d8f54922cab79fae0b
[ "MIT" ]
permissive
pantadeusz/examples-ai
5760f812de6112c2d66924160b35eef89b823300
7529242eb47123dd948d13eb44c5a28d225d11b9
refs/heads/master
2023-01-24T03:02:28.022307
2023-01-18T11:36:34
2023-01-18T11:36:34
90,629,458
3
2
null
null
null
null
UTF-8
C++
false
false
5,857
cpp
/* * Copyright 2017 Tadeusz Puźniakowski * * 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. * * */ // g++ -std=c++11 simannealing.cpp -o simannealing #include <tuple> #include <iostream> #include <cstdlib> #include <cmath> #include <functional> #include <vector> #include <list> #include <random> #include <chrono> using namespace std; /* The simulated annealing algorithm */ vector < double > simulatedAnnealing(const vector< double > solution0, function < bool (const vector<double>&) > inDomain, function < double (const vector<double>&) > goalF, function < bool (const vector<double>&) > termCondition, function < double ( int ) > T = [](const double k){return pow(0.99999,(double)k);}, bool maximize = false, unsigned generatorSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count() ); //////////////////////////////////////////////////////////////////////// // // The main function testing the execution of optimization // //////////////////////////////////////////////////////////////////////// int main () { // random start point default_random_engine generator(chrono::high_resolution_clock::now().time_since_epoch().count()); uniform_real_distribution<double> rdist(-5, 5); vector< double > solution = {rdist(generator), rdist(generator)}; // start point // check if value is in function domain vector< double > minV = {-5,-5}, maxV = {5,5}; auto functionDomain = [&](const vector < double > & v){ for (int i = 0; i < v.size(); i++) { if((v[i] <= minV[i]) || (v[i] >= maxV[i])) {return false;} } return true; }; // function -- Ackley - minimization auto f = [](const vector<double > &solution) -> double { double x,y; tie(x,y) = pair<double, double>(solution[0], solution[1]); return (-20*exp(-0.2*sqrt(0.5*(x*x+y*y)))- exp(0.5*(cos(2.0*M_PI*x)+cos(2*M_PI*y))) + M_E + 20); }; int i = 0; solution = simulatedAnnealing(solution, functionDomain, f, [&](const vector < double > &){i++;if (i > 100000) return true; return false;}, [](const double k){return pow(0.99999,(double)k);} ); cout << "Solution ( " << f(solution) << " ): " << solution[0] << " , " << solution[1] << endl; return 0; } /* The simulated annealing */ vector < double > simulatedAnnealing( const vector< double > solution0, // initial solution function < bool (const vector<double>&) > inDomain, // solution domain check function < double (const vector<double>&) > goalF, // goal function (for minimization) function < bool (const vector<double>&) > termCondition, // termination condition function < double ( int ) > T, // temperature function bool maximize, // maximize or minimize unsigned generatorSeed // random number generator seed ) { std::default_random_engine generator(generatorSeed); std::normal_distribution<double> rdist(0.0,0.01); // distribution for neighbour finding // std::uniform_real_distribution<double> rdist(-0.01, 0.01); list < vector< double > > solution = { solution0 }; // classic approach - store every result in container std::uniform_real_distribution<double> zerooneprob(0, 1); int i = 0; while (!termCondition(solution.back())) { auto solutionCandidate = solution.back(); for (auto &e: solutionCandidate) { e = e+rdist(generator); // new solution based on the previous solution } if(inDomain(solutionCandidate)) { auto y = goalF(solution.back()); // current solution quality (previous) auto yp = goalF(solutionCandidate); // new solution quality if (((y > yp) && !maximize) || (((y < yp) && maximize))) { // better solution solution.push_back(solutionCandidate); } else { auto e = exp(-(fabs(yp-y)/T(i))); if ( zerooneprob(generator) < e ) { // not that good, but temperature allows us to accept solution.push_back(solutionCandidate); } } } i++; } auto best = solution.back(); for (auto e : solution) { auto y = goalF(best); // current solution quality (previous) auto yp = goalF(e); // new solution quality if (((y > yp) && !maximize) || (((y < yp) && maximize))) best = e; } return best; }
[ "pantadeusz@pjwstk.edu.pl" ]
pantadeusz@pjwstk.edu.pl
dfbc5722dabaf6fa7f5b8ecd59e2158c99fe1ec8
addbaa42a916bac9510d8f44f4ced3a6d324a4a3
/CODE_BASE/src/scene/character.h
3222a758ef348b5d7b78f7a153152b8dd2319d68
[]
no_license
iCodeIN/Game-Engine-Project
424725053c8002ada75bd018888359247d3f22a8
513773d8f5f52e36542021c5c5f52eaa365412b0
refs/heads/master
2023-03-20T11:31:14.438239
2019-06-29T21:22:22
2019-06-29T21:22:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
#pragma once #include "globals.h" #include "scene_object.h" #include "rig_solver.h" #include "bone.h" class Character : public SceneObject { RigSolver rig_solver_; std::vector<Bone*> bones_; std::shared_ptr<SceneObject> bone_obj_vis_; public: Character(); Character( const char* file_path, Filetype file_type, std::shared_ptr<ShaderProgram> using_program, const char* name, const glm::vec3& pos); Character( std::vector<shared_ptr<Drawable>>* body, std::shared_ptr<ShaderProgram> using_program, const char* name, const glm::vec3& pos); Character(const char* name, const glm::vec3& pos); ~Character(); void Jump(std::shared_ptr<Camera>& c); void Crouch(std::shared_ptr<Camera>& c); // temp void SetBones(std::vector<Bone*> bones); void SetBoneObjectVisual(std::shared_ptr<SceneObject> bone_obj_vis) { bone_obj_vis_ = bone_obj_vis; } void DrawBones(const glm::mat4& view_proj); virtual void Draw(const glm::mat4 view_proj); void HoldStaff(const glm::vec3& loc); };
[ "hanbollar@gmail.com" ]
hanbollar@gmail.com
f9ac533538f56fdea0e286b02dd2df6d57e0e179
8635e9e8cde70ce1f55aac7b50d8090add38a163
/Problems/bzoj/1565.cpp
c67233d72852caac21b98eeea17d0c03930399d4
[]
no_license
99hgz/Algorithms
f0b696f60331ece11e99c93e75eb8a38326ddd96
a24c22bdee5432925f615aef58949402814473cd
refs/heads/master
2023-04-14T15:21:58.434225
2023-04-03T13:01:04
2023-04-03T13:01:04
88,978,471
3
1
null
null
null
null
UTF-8
C++
false
false
3,687
cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <queue> #include <vector> using namespace std; typedef long long ll; int Q[1100], dep[1100], score[1000]; int tot, Head[1100], cur[1100], Next[21000]; ll Val[21000], To[21000]; int n, m, S, T, u, v; int calc(int x, int y) { return (x - 1) * m + y; } bool bfs() { memset(dep, -1, sizeof dep); int t = 0, w = 1; Q[w] = S; dep[S] = 0; while (t != w) { t++; int u = Q[t]; //printf("bfs:%d\n", u); for (int it = Head[u]; it; it = Next[it]) { int v = To[it]; if (Val[it] > 0 && dep[v] == -1) { dep[v] = dep[u] + 1; w++; Q[w] = v; } } } return dep[T] != -1; } ll dfs(int x, ll flow) { //printf("%lld\n", flow); if (x == T) return flow; ll used = 0; for (int it = cur[x]; it; it = Next[it]) { int v = To[it]; if (dep[v] == dep[x] + 1) { ll tmp = dfs(v, min(Val[it], flow - used)); used += tmp; Val[it] -= tmp; Val[it ^ 1] += tmp; cur[x] = it; if (used == flow) return flow; } } if (used == 0) dep[x] = -1; return used; } ll dinic() { ll ans = 0; while (bfs()) { for (int i = 1; i <= T; i++) cur[i] = Head[i]; ans += dfs(S, 1LL << 60); //printf("%lld\n", ans); } return ans; } void addedge(int u, int v, ll flow) { //printf("%d->%d\n", u, v); tot++; Next[tot] = Head[u]; Head[u] = tot; Val[tot] = flow; To[tot] = v; tot++; Next[tot] = Head[v]; Head[v] = tot; Val[tot] = 0; To[tot] = u; } vector<int> vec[1000]; vector<int> revec[1000]; int indegree[1000]; bool chose[1000]; void addedge1(int u, int v) { vec[u].push_back(v); revec[v].push_back(u); indegree[u]++; } void topsort() { queue<int> Q; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (indegree[calc(i, j)] == 0) Q.push(calc(i, j)); while (!Q.empty()) { int u = Q.front(); Q.pop(); chose[u] = true; for (int i = 0; i < revec[u].size(); i++) { int v = revec[u][i]; indegree[v]--; if (indegree[v] == 0) Q.push(v); } } } int SUM; void build() { for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int id = calc(i, j); if (!chose[id]) continue; if (score[id] >= 0) { SUM += score[id]; addedge(S, id, score[id]); } else addedge(id, T, -score[id]); for (int it = 0; it < vec[id].size(); it++) addedge(id, vec[id][it], 0x3f3f3f3f); } } int main() { tot = 1; scanf("%d%d", &n, &m); S = n * m + 1; T = n * m + 2; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (j != m) addedge1(calc(i, j), calc(i, j + 1)); scanf("%d", &score[calc(i, j)]); int nnum; scanf("%d", &nnum); for (int k = 1; k <= nnum; k++) { int x, y; scanf("%d%d", &x, &y); x++, y++; addedge1(calc(x, y), calc(i, j)); } } } topsort(); build(); printf("%lld", SUM - dinic()); system("pause"); return 0; }
[ "2252870379@qq.com" ]
2252870379@qq.com
aef02a58526ea95bd463729fb57b43bb6fa07392
988e7ad6574222ca77e8620b9fbe15e1b0cc9a1a
/rain_water_harvesting.cpp
330ff7235fbd962be309b7a35ce7361d649d41f6
[]
no_license
vaarigupta/C-_programs
361df5af8ebb9eb36f79a24189e4ff0be3934bd6
ae5d5c6f3b147b16c5dbdbc449de2c6fbb8a5dac
refs/heads/master
2020-03-12T20:36:20.483047
2018-04-26T08:36:29
2018-04-26T08:36:29
130,809,479
0
0
null
null
null
null
UTF-8
C++
false
false
967
cpp
#include<iostream> using namespace std; int main() { int n, height[20]={0}, k=1,j=n-1,left_ht[20]={0},right_ht[20] ={0}, current_height, sum=0; cin>>n; for(int i=0;i<n;i++) { cin>>height[i]; } current_height = height[0]; for(int i=0;i<n;i++) { left_ht[0]=height[0]; if(height[i]>current_height&&i!=0) { current_height =height[i]; } left_ht[k]=current_height; k++; } for(int i=0;i<n;i++) { cout<<left_ht[i]<<endl;; } current_height =height[n-1]; for(int i=n-1;i>=0;i--) { right_ht[n-1]=height[n-1]; if(height[i]>current_height&&i!=(n-1)) { current_height =height[i]; } right_ht[j]= current_height; j--; } cout<<endl; for(int i=0;i<n;i++) { cout<<right_ht[i]<<endl;; } for(int i=0;i<n;i++) { sum += min(left_ht[i],right_ht[i]) - height[i]; } cout<<sum; return 0; }
[ "cutievaarigupta@gmail.com" ]
cutievaarigupta@gmail.com
632808b5e6ab290f0c5bcb8079bb4d9ee5b5b920
841776845974ba2645eff58ff8fabedd873093f0
/LeetCode/1013将数组分成和相等的三个部分.cpp
76a7c174c30076dcece23eed9d20b7026294c525
[]
no_license
hello-sources/Coding-Training
f2652c9b8e58d244a172922e56897fa2a3ad52fb
d885ca23676cb712243640169cf2e5bef2d8c70e
refs/heads/master
2023-01-19T11:17:36.097846
2023-01-01T00:49:09
2023-01-01T00:49:09
246,630,755
4
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
bool canThreePartsEqualSum(int* arr, int arrSize){ int sum = 0, num = 0; for (int i = 0; i < arrSize; i++) sum += arr[i]; if (sum % 3 != 0) return false; num = sum / 3; int temp = 0, temp2 = 0; for (int i = 0; i < arrSize - 2; i++) { temp += arr[i]; if (temp == num) { for (int j = i + 1; j < arrSize - 1; j++) { temp2 += arr[j]; if (temp2 == temp) return true; } } } return false; }
[ "3245849061@qq.com" ]
3245849061@qq.com
41b8edae2958da41e17ee97a8144b9a5e72fd4f6
e176ee182c7737e98434cf6702a6ed0fff6431fb
/include/UdmBase.h
e7ef51d12f61535328be989b3f3b483c84f0c3ab
[ "BSD-2-Clause" ]
permissive
syoyo/UDMlib
4d1d1a61170b543f6199f62133b02081dbcce035
f7796265d9381a7f0e878112842b7ce4bfe9af15
refs/heads/master
2023-09-04T12:37:22.953014
2015-04-20T03:25:52
2015-04-20T03:25:52
34,649,537
0
0
null
2015-04-27T06:22:51
2015-04-27T06:22:50
null
UTF-8
C++
false
false
2,026
h
/* * UDMlib - Unstructured Data Management Library * * Copyright (C) 2012-2015 Institute of Industrial Science, The University of Tokyo. * All rights reserved. * */ #ifndef _UDMBASE_H_ #define _UDMBASE_H_ /** * @file UdmBase.h * UDMlibライブラリのすべてのクラスの基底クラスのヘッダーファイル */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <vector> #include <map> #include <set> #include <iostream> #include <cstdio> #include <limits> #include <sstream> #include <math.h> #include <limits> #include "UdmErrorHandler.h" #include "utils/UdmStopWatch.h" #include "udmlib.h" #include "udm_memutils.h" #include "udm_define.h" /** * @file UdmGeneral.h * モデル構成の基底クラスのヘッダーファイル */ /** * UDMlibライブラリのネームスペース */ namespace udm { /** * 大文字・小文字を無視して比較する. */ struct insensitive_compare { std::string _compare; insensitive_compare( const std::string &src ) : _compare(src) {} bool operator() ( const std::string &dest ) const { if (_compare.size() != dest.size()) { return false; } for (std::string::const_iterator c1 = _compare.begin(), c2 = dest.begin(); c1 != _compare.end(); ++c1, ++c2) { if (tolower(*c1) != tolower(*c2)) { return false; } } return true; } }; struct map_case_compare { bool operator() (const std::string& lhs, const std::string& rhs) const { return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; } }; /** * UDMlibライブラリのすべてのクラスの基底クラス */ class UdmBase { public: UdmBase(); virtual ~UdmBase(); protected: int split(const std::string &str, char delim, std::vector<std::string>& results) const; void trim(char *buf); bool compareCaseInsensitive(const std::string& str1, const std::string& str2); }; } /* namespace udm */ #endif /* _UDMBASE_H_ */
[ "keno@riken.jp" ]
keno@riken.jp
ed42ea7e82dfcce3c03f16adfc8be0e68f21e8b0
f2a10941c41312b228b74a935013a27ef13c2838
/z3D/Core/SMem.cpp
99a393872e4b1afe2904e93c7338f1e7356b5d62
[]
no_license
vinceplusplus/z3D
375df45283c9ed64f5d2e991e2361352151ca030
7b52534db183298b7c92ff8cf6493fce0ac6e0d9
refs/heads/master
2020-12-24T19:13:21.574789
2016-05-05T17:04:17
2016-05-05T17:04:17
58,145,312
6
0
null
null
null
null
UTF-8
C++
false
false
1,418
cpp
#include "SMem.h" #include "interlocked.h" namespace z3D { namespace Core { void SMem::___ctor() { _block = 0; _size = 0; } void SMem::___ctor(const SMem& rhs) { if(!rhs._block) { ___ctor(); return; } _block = rhs._block; _size = rhs._size; _dealloc_func = rhs._dealloc_func; interlocked::increment(&_block->ref_count); } void SMem::___dtor() { if(!_block) return; if(interlocked::decrement(&_block->ref_count) != 0) return; if(_dealloc_func.valid()) _dealloc_func(_block); } SMem::SMem() { ___ctor(); } SMem::SMem(const SMem& rhs) { ___ctor(rhs); } SMem::~SMem() { ___dtor(); } SMem& SMem::operator=(const SMem& rhs) { if(this == &rhs) return *this; ___dtor(); ___ctor(rhs); return *this; } size_t SMem::getRequiredSize(size_t data_size) { return sizeof(BLOCK) - 1 + data_size; } SMem SMem::create(void* required_mem, size_t data_size, const functor1<void, void*>& dealloc_func) { SMem sm; sm._block = (BLOCK*)required_mem; sm._size = data_size; sm._dealloc_func = dealloc_func; interlocked::exchange(&sm._block->ref_count, 1); return sm; } void* SMem::get() const { return _block->data; } size_t SMem::size() const { return _size; } void SMem::reset() { ___dtor(); ___ctor(); } }; };
[ "vinceplusplus@gmail.com" ]
vinceplusplus@gmail.com
1fffd194233ffa0c366a83229c6af41508f892e3
3047545349bf224a182b2c33bf1f110aef1ce9b6
/Transims60/Converge_Service/Fuel_Check.cpp
b71ed57d3cbe2229458fb73523b7e32a26a88d95
[]
no_license
qingswu/Transim
585afe71d9666557cff53f6683cf54348294954c
f182d1639a4db612dd7b43a379a3fa344c2de9ea
refs/heads/master
2021-01-10T21:04:50.576267
2015-04-08T19:07:28
2015-04-08T19:07:28
35,232,171
1
1
null
null
null
null
UTF-8
C++
false
false
6,866
cpp
//********************************************************* // Fuel_Check.cpp - check the fuel supply and build path //********************************************************* #include "Converge_Service.hpp" //--------------------------------------------------------- // Fuel_Check //--------------------------------------------------------- void Converge_Service::Fuel_Check (Plan_Data &plan) { if (plan.size () == 0) return; double supply = initial_fuel [plan.Index ()]; if (supply <= 0) return; Veh_Type_Data *veh_type_ptr = &veh_type_array [plan.Veh_Type ()]; int seek_level = DTOI (veh_type_ptr->Fuel_Cap () * seek_fuel / 100.0); if (seek_level < 1) seek_level = 1; int function = veh_type_ptr->Fuel_Func (); if (function < 0) function = 0; Dtime tod; int leg, fuel_leg, fuel_id; double speed, factor, ttime; Loc_Fuel_Data *fuel_ptr; Plan_Leg_Itr itr, itr2; Integers stop_list; Int_Itr stop_itr; factor = (Metric_Flag ()) ? 1000.0 : 5280.0; //---- find the last fuel location ---- fuel_leg = fuel_id = -1; for (leg=0, itr = plan.begin (); itr != plan.end (); itr++, leg++) { if (itr->Type () == LOCATION_ID && itr->Mode () == WAIT_MODE) { fuel_ptr = &loc_fuel_array [itr->ID ()]; if (fuel_ptr->supply > 0) { fuel_leg = leg; fuel_id = itr->ID (); stop_list.push_back (itr->ID ()); } } } bool look_ahead = true; bool reserve = (info_flag && info_range.In_Range (plan.Type ())); //---- monitor the fuel supply ---- tod = plan.Depart (); for (leg=0, itr = plan.begin (); itr != plan.end (); itr++, leg++) { tod += itr->Time (); if (itr->Type () == LOCATION_ID && itr->Mode () == WAIT_MODE) { fuel_ptr = &loc_fuel_array [itr->ID ()]; if (fuel_ptr->supply <= 0) continue; if (leg < fuel_leg) { MAIN_LOCK fuel_ptr->failed++; END_LOCK continue; } //---- try to fill the tank ---- MAIN_LOCK if (reserve) { if (plan.Method () != BUILD_PATH) { fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); } supply = veh_type_ptr->Fuel_Cap (); } else if ((fuel_ptr->consumed + veh_type_ptr->Fuel_Cap ()) <= fuel_ptr->supply) { fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); supply = veh_type_ptr->Fuel_Cap (); } else { fuel_ptr->failed++; Set_Problem (FUEL_PROBLEM); } END_LOCK continue; } //---- consume fuel ---- if (itr->Mode () != DRIVE_MODE) continue; ttime = itr->Time () / 3600.0; if (ttime > 0) { speed = itr->Length () / (factor * ttime); } else { speed = 1; } supply -= ttime * functions.Apply_Function (function, speed); if (supply > seek_level) continue; if (supply < 0) { plan.Problem (FUEL_PROBLEM); if (fuel_id >= 0) { fuel_ptr = &loc_fuel_array [fuel_id]; MAIN_LOCK fuel_ptr->ran_out++; END_LOCK } if (reserve) { initial_fuel [plan.Index ()] = veh_type_ptr->Fuel_Cap (); plan.Stop_Location (-2); Time_Index new_index = plan.Get_Time_Index (); MAIN_LOCK Time_Index index = time_itr->first; new_index.Start (index.Start () + 10); if (!plan_time_map.insert (Time_Map_Data (new_index, plan.Index ())).second) { Warning (String ("Fuel Time Index Problem Plan %d-%d-%d-%d") % plan.Household () % plan.Person () % plan.Tour () % plan.Trip ()); } time_itr = plan_time_map.find (index); END_LOCK } else { plan.Stop_Location (-1); } return; } if (leg < fuel_leg) continue; //---- look for fuel ---- if (itr->Type () != DIR_ID || plan.Priority () == SKIP || plan.Method () != BUILD_PATH || !look_ahead) continue; int i, node, best; double x1, y1, x2, y2, x3, y3, x, y, dx, dy, diff1, diff2, diff, best_diff, best_diff2; bool flag; Dir_Data *dir_ptr; Link_Data *link_ptr; Node_Data *node_ptr; Location_Itr loc_itr; Location_Data *loc_ptr; dir_ptr = &dir_array [itr->ID ()]; link_ptr = &link_array [dir_ptr->Link ()]; if (dir_ptr->Dir () == 0) { node = link_ptr->Bnode (); } else { node = link_ptr->Anode (); } node_ptr = &node_array [node]; x1 = node_ptr->X (); y1 = node_ptr->Y (); loc_ptr = &location_array [plan.Destination ()]; x2 = loc_ptr->X (); y2 = loc_ptr->Y (); dx = x2 - x1; dy = y2 - y1; diff1 = dx * dx + dy * dy; best = -1; best_diff = 0; for (i=0, loc_itr = location_array.begin (); loc_itr != location_array.end (); loc_itr++, i++) { fuel_ptr = &loc_fuel_array [i]; if (fuel_ptr->supply <= 0) continue; if (reserve) { if ((fuel_ptr->consumed + veh_type_ptr->Fuel_Cap ()) > fuel_ptr->supply) continue; } for (flag=false, stop_itr = stop_list.begin (); stop_itr != stop_list.end (); stop_itr++) { if (*stop_itr == i) { flag = true; break; } } if (flag) continue; x = loc_itr->X (); y = loc_itr->Y (); dx = x - x2; dy = y - y2; diff = dx * dx + dy * dy; if (diff > diff1) { continue; } dx = x - x1; dy = y - y1; diff += diff2 = (dx * dx + dy * dy) * 2.0; best_diff2 = diff + diff2; for (itr2 = itr + 1; itr2 != plan.end (); itr2++) { if (itr2->Mode () != DRIVE_MODE || itr2->Type () != DIR_ID) continue; dir_ptr = &dir_array [itr2->ID ()]; link_ptr = &link_array [dir_ptr->Link ()]; if (dir_ptr->Dir () == 0) { node = link_ptr->Bnode (); } else { node = link_ptr->Anode (); } node_ptr = &node_array [node]; x3 = node_ptr->X (); y3 = node_ptr->Y (); dx = x - x3; dy = y - y3; diff2 = diff + (dx * dx + dy * dy) * 2.0; if (diff2 < best_diff2) { best_diff2 = diff2; } } if (best < 0 || best_diff2 < best_diff) { best = i; best_diff = best_diff2; } } if (best < 0) { look_ahead = false; continue; } //---- stop at the gas station ---- Time_Index new_index = plan.Get_Time_Index (); plan.Reroute_Time (tod); plan.Stop_Location (best); plan.Activity (fuel_duration); plan.Constraint (START_TIME); plan.Priority (CRITICAL); //---- save and update iterator ----- MAIN_LOCK if (reserve) { fuel_ptr = &loc_fuel_array [best]; fuel_ptr->consumed += veh_type_ptr->Fuel_Cap (); } Time_Index index = time_itr->first; if (tod <= index.Start ()) { new_index.Start (index.Start () + 10); } else { new_index.Start (tod); } if (!plan_time_map.insert (Time_Map_Data (new_index, plan.Index ())).second) { Warning (String ("Fuel Time Index Problem Plan %d-%d-%d-%d") % plan.Household () % plan.Person () % plan.Tour () % plan.Trip ()); } time_itr = plan_time_map.find (index); END_LOCK plan.Problem (FUEL_PROBLEM); break; } }
[ "davidroden@7728d46c-9721-0410-b1ea-f014b4b56054" ]
davidroden@7728d46c-9721-0410-b1ea-f014b4b56054
8a97bc9927be19784dc1459086dd3c89cee46335
9240ceb15f7b5abb1e4e4644f59d209b83d70066
/sp/src/game/server/sdk/sdk_player.h
efac7ec14105184433f8e0e2dd4e2cb656620036
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Margen67/blamod
13e5cd9f7f94d1612eb3f44a2803bf2f02a3dcbe
d59b5f968264121d013a81ae1ba1f51432030170
refs/heads/master
2023-04-16T12:05:12.130933
2019-02-20T10:23:04
2019-02-20T10:23:04
264,556,156
2
0
NOASSERTION
2020-05-17T00:47:56
2020-05-17T00:47:55
null
UTF-8
C++
false
false
2,757
h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Player for SDK Game // // $NoKeywords: $ //=============================================================================// #ifndef SDK_PLAYER_H #define SDK_PLAYER_H #pragma once #include "player.h" #include "server_class.h" #include "sdk_playeranimstate.h" #include "sdk_shareddefs.h" //============================================================================= // >> SDK Game player //============================================================================= class CSDKPlayer : public CBasePlayer, public ISDKPlayerAnimStateHelpers { public: DECLARE_CLASS( CSDKPlayer, CBasePlayer ); DECLARE_SERVERCLASS(); DECLARE_PREDICTABLE(); DECLARE_DATADESC(); CSDKPlayer(); ~CSDKPlayer(); static CSDKPlayer *CreatePlayer( const char *className, edict_t *ed ); static CSDKPlayer* Instance( int iEnt ); // This passes the event to the client's and server's CPlayerAnimState. void DoAnimationEvent( PlayerAnimEvent_t event, int nData = 0 ); virtual void FlashlightTurnOn( void ); virtual void FlashlightTurnOff( void ); virtual int FlashlightIsOn( void ); virtual void PreThink(); virtual void PostThink(); virtual void Spawn(); virtual void InitialSpawn(); virtual void Precache(); virtual void Event_Killed( const CTakeDamageInfo &info ); virtual void LeaveVehicle( const Vector &vecExitPoint, const QAngle &vecExitAngles ); CWeaponSDKBase* GetActiveSDKWeapon() const; virtual void CreateViewModel( int viewmodelindex = 0 ); virtual void CheatImpulseCommands( int iImpulse ); CNetworkVar( int, m_iThrowGrenadeCounter ); // used to trigger grenade throw animations. CNetworkQAngle( m_angEyeAngles ); // Copied from EyeAngles() so we can send it to the client. CNetworkVar( int, m_iShotsFired ); // number of shots fired recently // Tracks our ragdoll entity. CNetworkHandle( CBaseEntity, m_hRagdoll ); // networked entity handle // In shared code. public: // ISDKPlayerAnimState overrides. virtual CWeaponSDKBase* SDKAnim_GetActiveWeapon(); virtual bool SDKAnim_CanMove(); void FireBullet( Vector vecSrc, const QAngle &shootAngles, float vecSpread, int iDamage, int iBulletType, CBaseEntity *pevAttacker, bool bDoEffects, float x, float y ); private: void CreateRagdollEntity(); ISDKPlayerAnimState *m_PlayerAnimState; }; inline CSDKPlayer *ToSDKPlayer( CBaseEntity *pEntity ) { if ( !pEntity || !pEntity->IsPlayer() ) return NULL; #ifdef _DEBUG Assert( dynamic_cast<CSDKPlayer*>( pEntity ) != 0 ); #endif return static_cast< CSDKPlayer* >( pEntity ); } #endif // SDK_PLAYER_H
[ "joe@valvesoftware.com" ]
joe@valvesoftware.com
05579139d95851e549675beacd8901baae6df3a1
f6439b5ed1614fd8db05fa963b47765eae225eb5
/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
ffbad82ed9b9291cc6c91839f17155209f792126
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
22,211
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <list> #include <set> #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/download/download_browsertest.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_controller.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_throttle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/context_menu_params.h" #include "content/public/common/resource_type.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/extension_system.h" #include "extensions/common/switches.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "third_party/WebKit/public/web/WebInputEvent.h" using content::ResourceType; using content::WebContents; namespace extensions { namespace { // This class can defer requests for arbitrary URLs. class TestNavigationListener : public base::RefCountedThreadSafe<TestNavigationListener> { public: TestNavigationListener() {} // Add |url| to the set of URLs we should delay. void DelayRequestsForURL(const GURL& url) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&TestNavigationListener::DelayRequestsForURL, this, url)); return; } urls_to_delay_.insert(url); } // Resume all deferred requests. void ResumeAll() { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&TestNavigationListener::ResumeAll, this)); return; } WeakThrottleList::const_iterator it; for (it = throttles_.begin(); it != throttles_.end(); ++it) { if (it->get()) (*it)->Resume(); } throttles_.clear(); } // Constructs a ResourceThrottle if the request for |url| should be held. // // Needs to be invoked on the IO thread. content::ResourceThrottle* CreateResourceThrottle( const GURL& url, ResourceType::Type resource_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (urls_to_delay_.find(url) == urls_to_delay_.end()) return NULL; Throttle* throttle = new Throttle(); throttles_.push_back(throttle->AsWeakPtr()); return throttle; } private: friend class base::RefCountedThreadSafe<TestNavigationListener>; virtual ~TestNavigationListener() {} // Stores a throttle per URL request that we have delayed. class Throttle : public content::ResourceThrottle, public base::SupportsWeakPtr<Throttle> { public: void Resume() { controller()->Resume(); } // content::ResourceThrottle implementation. virtual void WillStartRequest(bool* defer) OVERRIDE { *defer = true; } virtual const char* GetNameForLogging() const OVERRIDE { return "TestNavigationListener::Throttle"; } }; typedef base::WeakPtr<Throttle> WeakThrottle; typedef std::list<WeakThrottle> WeakThrottleList; WeakThrottleList throttles_; // The set of URLs to be delayed. std::set<GURL> urls_to_delay_; DISALLOW_COPY_AND_ASSIGN(TestNavigationListener); }; // Waits for a WC to be created. Once it starts loading |delay_url| (after at // least the first navigation has committed), it delays the load, executes // |script| in the last committed RVH and resumes the load when a URL ending in // |until_url_suffix| commits. This class expects |script| to trigger the load // of an URL ending in |until_url_suffix|. class DelayLoadStartAndExecuteJavascript : public content::NotificationObserver, public content::WebContentsObserver { public: DelayLoadStartAndExecuteJavascript( TestNavigationListener* test_navigation_listener, const GURL& delay_url, const std::string& script, const std::string& until_url_suffix) : content::WebContentsObserver(), test_navigation_listener_(test_navigation_listener), delay_url_(delay_url), until_url_suffix_(until_url_suffix), script_(script), script_was_executed_(false), rvh_(NULL) { registrar_.Add(this, chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); test_navigation_listener_->DelayRequestsForURL(delay_url_); } virtual ~DelayLoadStartAndExecuteJavascript() {} virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { if (type != chrome::NOTIFICATION_TAB_ADDED) { NOTREACHED(); return; } content::WebContentsObserver::Observe( content::Details<content::WebContents>(details).ptr()); registrar_.RemoveAll(); } virtual void DidStartProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& validated_url, bool is_error_page, bool is_iframe_srcdoc) OVERRIDE { if (validated_url != delay_url_ || !rvh_) return; rvh_->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(script_)); script_was_executed_ = true; } virtual void DidCommitProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& url, content::PageTransition transition_type) OVERRIDE { if (script_was_executed_ && EndsWith(url.spec(), until_url_suffix_, true)) { content::WebContentsObserver::Observe(NULL); test_navigation_listener_->ResumeAll(); } rvh_ = render_frame_host->GetRenderViewHost(); } private: content::NotificationRegistrar registrar_; scoped_refptr<TestNavigationListener> test_navigation_listener_; GURL delay_url_; std::string until_url_suffix_; std::string script_; bool script_was_executed_; content::RenderViewHost* rvh_; DISALLOW_COPY_AND_ASSIGN(DelayLoadStartAndExecuteJavascript); }; // A ResourceDispatcherHostDelegate that adds a TestNavigationObserver. class TestResourceDispatcherHostDelegate : public ChromeResourceDispatcherHostDelegate { public: TestResourceDispatcherHostDelegate( prerender::PrerenderTracker* prerender_tracker, TestNavigationListener* test_navigation_listener) : ChromeResourceDispatcherHostDelegate(prerender_tracker), test_navigation_listener_(test_navigation_listener) { } virtual ~TestResourceDispatcherHostDelegate() {} virtual void RequestBeginning( net::URLRequest* request, content::ResourceContext* resource_context, content::AppCacheService* appcache_service, ResourceType::Type resource_type, int child_id, int route_id, ScopedVector<content::ResourceThrottle>* throttles) OVERRIDE { ChromeResourceDispatcherHostDelegate::RequestBeginning( request, resource_context, appcache_service, resource_type, child_id, route_id, throttles); content::ResourceThrottle* throttle = test_navigation_listener_->CreateResourceThrottle(request->url(), resource_type); if (throttle) throttles->push_back(throttle); } private: scoped_refptr<TestNavigationListener> test_navigation_listener_; DISALLOW_COPY_AND_ASSIGN(TestResourceDispatcherHostDelegate); }; } // namespace class WebNavigationApiTest : public ExtensionApiTest { public: WebNavigationApiTest() {} virtual ~WebNavigationApiTest() {} virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); FrameNavigationState::set_allow_extension_scheme(true); CommandLine::ForCurrentProcess()->AppendSwitch( switches::kAllowLegacyExtensionManifests); host_resolver()->AddRule("*", "127.0.0.1"); } virtual void SetUpOnMainThread() OVERRIDE { ExtensionApiTest::SetUpOnMainThread(); test_navigation_listener_ = new TestNavigationListener(); resource_dispatcher_host_delegate_.reset( new TestResourceDispatcherHostDelegate( g_browser_process->prerender_tracker(), test_navigation_listener_.get())); content::ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } TestNavigationListener* test_navigation_listener() { return test_navigation_listener_.get(); } private: scoped_refptr<TestNavigationListener> test_navigation_listener_; scoped_ptr<TestResourceDispatcherHostDelegate> resource_dispatcher_host_delegate_; DISALLOW_COPY_AND_ASSIGN(WebNavigationApiTest); }; IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Api) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, GetFrame) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/getFrame")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ClientRedirect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/clientRedirect")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirect) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/serverRedirect")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Download) { base::ScopedTempDir download_directory; ASSERT_TRUE(download_directory.CreateUniqueTempDir()); DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(browser()->profile()); download_prefs->SetDownloadPath(download_directory.path()); DownloadTestObserverNotInProgress download_observer( content::BrowserContext::GetDownloadManager(profile()), 1); download_observer.StartObserving(); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/download")) << message_; download_observer.WaitForFinished(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirectSingleProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); // Set max renderers to 1 to force running out of processes. content::RenderProcessHost::SetMaxRendererProcessCount(1); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE( RunExtensionTest("webnavigation/serverRedirectSingleProcess")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/serverRedirectSingleProcess/a.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); url = GURL(base::StringPrintf( "http://www.b.com:%d/server-redirect?http://www.b.com:%d/", embedded_test_server()->port(), embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ForwardBack) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/forwardBack")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, IFrame) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/iframe")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, SrcDoc) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/srcdoc")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, OpenTab) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/openTab")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ReferenceFragment) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/referenceFragment")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, SimpleLoad) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/simpleLoad")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Failures) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/failures")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, FilteredTest) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/filtered")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, UserAction) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/userAction")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; ExtensionService* service = extensions::ExtensionSystem::Get( browser()->profile())->extension_service(); const extensions::Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), url); // This corresponds to "Open link in new tab". content::ContextMenuParams params; params.is_editable = false; params.media_type = blink::WebContextMenuData::MediaTypeNone; params.page_url = url; params.link_url = extension->GetResourceURL("b.html"); TestRenderViewContextMenu menu(tab->GetMainFrame(), params); menu.Init(); menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB, 0); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/requestOpenTab")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; ExtensionService* service = extensions::ExtensionSystem::Get( browser()->profile())->extension_service(); const extensions::Extension* extension = service->GetExtensionById(last_loaded_extension_id(), false); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html. Middle-click on it to open it in a new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonMiddle; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlank) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/targetBlank")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webnavigation/targetBlank/a.html"); chrome::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK); ui_test_utils::NavigateToURL(&params); // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlankIncognito) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTestIncognito("webnavigation/targetBlank")) << message_; ResultCatcher catcher; GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webnavigation/targetBlank/a.html"); Browser* otr_browser = ui_test_utils::OpenURLOffTheRecord( browser()->profile(), url); WebContents* tab = otr_browser->tab_strip_model()->GetActiveWebContents(); // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. blink::WebMouseEvent mouse_event; mouse_event.type = blink::WebInputEvent::MouseDown; mouse_event.button = blink::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); mouse_event.type = blink::WebInputEvent::MouseUp; tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, History) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("webnavigation/history")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); LoadExtension(test_data_dir_.AppendASCII("webnavigation").AppendASCII("app")); // See crossProcess/d.html. DelayLoadStartAndExecuteJavascript call_script( test_navigation_listener(), embedded_test_server()->GetURL("/test1"), "navigate2()", "empty.html"); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcess")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessFragment) { ASSERT_TRUE(StartEmbeddedTestServer()); // See crossProcessFragment/f.html. DelayLoadStartAndExecuteJavascript call_script3( test_navigation_listener(), embedded_test_server()->GetURL("/test3"), "updateFragment()", base::StringPrintf("f.html?%d#foo", embedded_test_server()->port())); // See crossProcessFragment/g.html. DelayLoadStartAndExecuteJavascript call_script4( test_navigation_listener(), embedded_test_server()->GetURL("/test4"), "updateFragment()", base::StringPrintf("g.html?%d#foo", embedded_test_server()->port())); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessFragment")) << message_; } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcessHistory) { ASSERT_TRUE(StartEmbeddedTestServer()); // See crossProcessHistory/e.html. DelayLoadStartAndExecuteJavascript call_script2( test_navigation_listener(), embedded_test_server()->GetURL("/test2"), "updateHistory()", "empty.html"); // See crossProcessHistory/h.html. DelayLoadStartAndExecuteJavascript call_script5( test_navigation_listener(), embedded_test_server()->GetURL("/test5"), "updateHistory()", "empty.html"); // See crossProcessHistory/i.html. DelayLoadStartAndExecuteJavascript call_script6( test_navigation_listener(), embedded_test_server()->GetURL("/test6"), "updateHistory()", "empty.html"); ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessHistory")) << message_; } // TODO(jam): http://crbug.com/350550 #if !(defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER)) IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, Crash) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionTest("webnavigation/crash")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForLoadStop(tab); ResultCatcher catcher; GURL url(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/crash/a.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ui_test_utils::NavigateToURL(browser(), GURL(content::kChromeUICrashURL)); url = GURL(base::StringPrintf( "http://www.a.com:%d/" "extensions/api_test/webnavigation/crash/b.html", embedded_test_server()->port())); ui_test_utils::NavigateToURL(browser(), url); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } #endif } // namespace extensions
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
e36d2cf1a869617128c0c3e1b4f790a60273caf8
ee6c236ba07ddd2f1328e38f3b0a00c3eaf3a38a
/Code/server/FindingTreasure_Test_Blending_20170529/IOCP_Client.cpp
c174715e0dc501099de4667a840526a728aff394
[]
no_license
GreeeeeShot/Graduation-Work
b01b4662813a1a25a0ed82f0a43af92c38801bbc
53e2c000241b71da222d065d0697ec79b0ded65c
refs/heads/master
2021-01-11T01:55:47.025089
2017-10-18T10:25:06
2017-10-18T10:25:06
70,653,275
0
1
null
null
null
null
UTF-8
C++
false
false
6,663
cpp
#include "stdafx.h" #include "IOCP_Init.h" #include "IOCP_Client.h" #include "GameManager.h" #include "GameFramework.h" //CPlayer player; #pragma comment (lib, "ws2_32.lib") SOCKET g_mysocket; WSABUF send_wsabuf; char send_buffer[BUF_SIZE]; WSABUF recv_wsabuf; char recv_buffer[BUF_SIZE]; char packet_buffer[BUF_SIZE]; DWORD in_packet_size = 0; int saved_packet_size = 0; int g_myid; int g_left_x = 0; int g_top_y = 0; Client_Data player; void clienterror() { exit(-1); } void ProcessPacket(char *ptr) { static bool first_time = true; float x = 0, y = 0, z = 0; int id=-1; float px=0.0, py = 0.0, pz = 0.0; switch (ptr[1]) { case SC_PUT_PLAYER: { sc_packet_put_player *my_packet = reinterpret_cast<sc_packet_put_player *>(ptr); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); break; } case SC_POS: { sc_packet_pos *my_packet = reinterpret_cast<sc_packet_pos *>(ptr); //CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); x = my_packet->x; z = my_packet->z; id = my_packet->id; y = my_packet->y; //y = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->GetPosition().y; //std::cout<<"Position: " << x<<", " << y << ", " << z << std::endl; //CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->SetMove(x, y, z); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[id]->SetPosition(D3DXVECTOR3(x,y, z)); break; } case SC_REMOVE_PLAYER: { sc_packet_remove_player *my_packet = reinterpret_cast<sc_packet_remove_player *>(ptr); break; } case SC_INIT: { sc_packet_init *my_packet = reinterpret_cast<sc_packet_init *>(ptr); CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_iMyPlayerID = my_packet->id; CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_ppPlayers[my_packet->id]->SetPosition(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z)); } /* case SC_CHAT: { sc_packet_chat *my_packet = reinterpret_cast<sc_packet_chat *>(ptr); int other_id = my_packet->id; if (other_id == g_myid) { wcsncpy_s(player.message, my_packet->message, 256); player.message_time = GetTickCount(); } else if (other_id < NPC_START) { wcsncpy_s(skelaton[other_id].message, my_packet->message, 256); skelaton[other_id].message_time = GetTickCount(); } else { wcsncpy_s(npc[other_id - NPC_START].message, my_packet->message, 256); npc[other_id - NPC_START].message_time = GetTickCount(); } break; }*/ default: printf("Unknown PACKET type [%d]\n", ptr[1]); } } void ReadPacket(SOCKET sock) { DWORD io_byte, io_flag = 0; int ret = WSARecv(sock, &recv_wsabuf, 1, &io_byte, &io_flag, NULL, NULL); if (ret) { int err_code = WSAGetLastError(); printf("Recv Error [%d]\n", err_code); } BYTE *ptr = reinterpret_cast<BYTE *>(recv_buffer); while (0 != io_byte) { if (0 == in_packet_size) in_packet_size = ptr[0]; if (io_byte + saved_packet_size >= in_packet_size) { memcpy(packet_buffer + saved_packet_size, ptr, in_packet_size - saved_packet_size); ProcessPacket(packet_buffer); ptr += in_packet_size - saved_packet_size; io_byte -= in_packet_size - saved_packet_size; in_packet_size = 0; saved_packet_size = 0; } else { memcpy(packet_buffer + saved_packet_size, ptr, io_byte); saved_packet_size += io_byte; io_byte = 0; } } } void ClientMain(HWND main_window_handle,const char* serverip) { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); g_mysocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0); SOCKADDR_IN ServerAddr; ZeroMemory(&ServerAddr, sizeof(SOCKADDR_IN)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(MY_SERVER_PORT); ServerAddr.sin_addr.s_addr = inet_addr(serverip); int Result = WSAConnect(g_mysocket, (sockaddr *)&ServerAddr, sizeof(ServerAddr), NULL, NULL, NULL, NULL); WSAAsyncSelect(g_mysocket, main_window_handle, WM_SOCKET, FD_CLOSE | FD_READ); send_wsabuf.buf = send_buffer; send_wsabuf.len = BUF_SIZE; recv_wsabuf.buf = recv_buffer; recv_wsabuf.len = BUF_SIZE; } void SetPacket(int x,int y, int z) { cs_packet_up *my_packet = reinterpret_cast<cs_packet_up *>(send_buffer); int id = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->m_iMyPlayerID; my_packet->size = sizeof(my_packet); send_wsabuf.len = sizeof(my_packet); DWORD iobyte; my_packet->Lookx = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->GetMyPlayer()->m_CameraOperator.GetLook().x; my_packet->Lookz = CGameManager::GetInstance()->m_pGameFramework->m_pPlayersMgrInform->GetMyPlayer()->m_CameraOperator.GetLook().z; //std::cout<<"Client Look" << (float)my_packet->Lookx << ", " <<(float)my_packet->Lookz << std::endl; if (x>0) { my_packet->type = CS_RIGHT; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (x<0) { my_packet->type = CS_LEFT; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (z>0) { my_packet->type = CS_UP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (z<0) { my_packet->type = CS_DOWN; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (y>0) { my_packet->type = CS_JUMP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } /* if (move == X_STOP) { my_packet->type = CS_XSTOP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } } if (move == Z_STOP) { my_packet->type = CS_ZSTOP; int ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); printf("Error while sending packet [%d]", error_code); } }*/ }
[ "joonbum638@naver.com" ]
joonbum638@naver.com
e1108471b13ff8785215765da1c3049ca962daf2
eab36cd36644c062a9ba43fe9cfd2dfc2ad5bfe8
/codeforces/Discounts.cpp
d73e4c10394ec1f70883ebe7ffbd7b765ba6f955
[]
no_license
yashraj1120/CodeForces
e10037eed737adce65b28c5ce02b11bbbb0eee08
8396ccd426975dcf788c595d596b246e4adac305
refs/heads/master
2020-04-29T18:10:17.933070
2019-03-18T15:37:08
2019-03-18T15:37:08
176,316,485
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; long long arr[n]; long long s=0; for(int i=0;i<n;i++) { cin>>arr[i]; s+=arr[i]; } long m; sort(arr,arr+n); cin>>m; while(m!=0) { int temp; cin>>temp; cout<<s-arr[n-temp]<<"\n"; m--; } }
[ "noreply@github.com" ]
yashraj1120.noreply@github.com
89be1651a09bf91158875ccb522ae2db5962999e
fb399b4b4afe86194e4d3d996ea6b9ee4bed674c
/subtask3/code/Extra_SparseOpticalFlow.cpp
1ca881435ddad1c5f53a02a8c307ca3b6c379264
[]
no_license
ShreyaGupta8/cop290-assignment-1
238a3d774f9e867b3be11bce0adaca89190361cb
f447f459e3a2ffaaabde5dacd8b06fb072b0e26d
refs/heads/main
2023-06-29T17:04:52.614300
2021-07-29T22:43:53
2021-07-29T22:43:53
341,635,618
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
cpp
#include <iostream> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <opencv2/video.hpp> #include <fstream> using namespace cv; using namespace std; int main(int argc, char **argv) { ofstream method("extra.txt"); clock_t start, end; double time; start=clock(); //taking input from user string video; cout<<"path of video: "; cin>> video; VideoCapture capture(video); if (!capture.isOpened()){ //error in opening the video input cerr << "Unable to open file!" << endl; return 0; } // Create some random colors vector<Scalar> colors; RNG rng; for(int i = 0; i < 100; i++) { int r = rng.uniform(0, 256); int g = rng.uniform(0, 256); int b = rng.uniform(0, 256); colors.push_back(Scalar(r,g,b)); } Mat prev_frame, prev_gray; vector<Point2f> p0, p1; // Take first frame and find corners in it capture >> prev_frame; cvtColor(prev_frame, prev_gray, COLOR_BGR2GRAY); goodFeaturesToTrack(prev_gray, p0, 100, 0.3, 7, Mat(), 7, false, 0.04); // Create a mask image for drawing purposes Mat mask = Mat::zeros(prev_frame.size(), prev_frame.type()); float dynamic_density; while(true){ int pixelcount=0; Mat frame, grayframe; capture >> frame; if (frame.empty()) break; cvtColor(frame, grayframe, COLOR_BGR2GRAY); // calculate optical flow vector<uchar> stat; vector<float> errs; TermCriteria criteria = TermCriteria((TermCriteria::COUNT) + (TermCriteria::EPS), 10, 0.03); calcOpticalFlowPyrLK(prev_gray, grayframe, p0, p1, stat, errs, Size(15,15), 2, criteria); vector<Point2f> goodpts; for(uint i = 0; i < p0.size(); i++) { // Select good points if(stat[i] == 1) { goodpts.push_back(p1[i]); // draw the tracks line(mask,p1[i], p0[i], colors[i], 2); circle(frame, p1[i], 5, colors[i], -1); } } Mat img; Mat buf = mask.clone(); for (int i = 0; i < buf.rows; i++) { for (int j = 0; j < buf.cols; j++) { uchar pixelval; buf.at<uchar>(i, j) = pixelval; if ((int)pixelval>0){ pixelcount++; } } } dynamic_density = (float)pixelcount / (float)255184; method << dynamic_density << endl; add(frame, mask, img); // imshow("Frame", mask); int keyboard = waitKey(30); if (keyboard == 'q' || keyboard == 27) break; // Updation of the previous frame prev_frame and the corresponding previous point prev_gray = grayframe.clone(); p0 = goodpts; } end=clock(); time=((double)(end-start))/ CLOCKS_PER_SEC; cout<<"time taken: "<< time << endl; method.close(); }
[ "noreply@github.com" ]
ShreyaGupta8.noreply@github.com
b3bd6dd44be2d655306a106ce69bafae36280f5a
0208776bfede55763e03a08c80b79c28564cfb04
/src/cpu.cpp
bc67327cb5a04fafae5736446ab78696258682cd
[ "MIT" ]
permissive
mikefeneley/mechanicus-emulator
cda239387bdbf291487d796338186bd34515a13b
949946de02b8346c4654baaf6946b3a15da51d5b
refs/heads/master
2021-06-09T19:36:51.329209
2016-12-23T13:43:14
2016-12-23T13:43:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
/* * CPU Simulator */ class CPU { public: CPU(void); void reset(void); void set_program(void *program); void fetch(void); void decode(void); void execute(void); private: void *program; int zero_flag; int sign_flag; int overflow_flag; int break_flag; int decimal_flag; int interrupt_flag; int carry_flag; };
[ "michael.j.feneley@gmail.com" ]
michael.j.feneley@gmail.com
2c064cb569c3e2789098a813f1c039e89f2e819f
b067b1fc5239eaf4354871dcb9d64f10901af2a8
/Labor_4/L4_A4/Circle.cpp
9220fc9696c532b5bcbe51b79b2318fc4b79b73f
[]
no_license
Dream-Dev-Team/Labor_OOS1
37d9282de9da0d87745a63ac91d917e06d74e45b
cf6c6679acaf4a4844f8955896af16e2b2b7229d
refs/heads/master
2022-11-26T01:44:59.534960
2020-07-24T08:39:20
2020-07-24T08:39:20
261,707,092
2
1
null
null
null
null
UTF-8
C++
false
false
1,225
cpp
#include "Circle.hpp" extern bool debugConstructor; Circle::Circle(Point p, double r) { if (debugConstructor) { cout << "Konstruktor der Klasse Circle(param), Objekt:" << this->getID() << endl; } centre = p; radius = r; } Circle::Circle(string str) { if (debugConstructor) { cout << "Konstruktor der Klasse Circle(convert), Objekt:" << this->getID() << endl; } radius = 0; istringstream ss(str); ss >> *this; } const Point& Circle::getCentre() const { return centre; } double Circle::getRadius() const { return radius; } void Circle::setCentre(Point p) { centre = p; } // setzt den Radius void Circle::setRadius(double r) { radius = r; } void Circle::move(double dx, double dy) { centre.move(dx, dy); } void Circle::print(bool nl) const { cout << "<"; centre.print(false); cout << ", " << radius << ">"; if (nl) cout << endl; } string Circle::toString() const { stringstream ss; ss << "<" << centre.toString() << ", " << radius << ">"; return ss.str(); } istream& operator>>(istream& is, Circle& circ) { char c; is >> c >> circ.centre >> c >> circ.radius >> c; return is; } ostream& operator<<(ostream& os, Circle& c) { os << c.toString(); return os; } Circle::~Circle() { }
[ "aamuit00@hs-esslingen.de" ]
aamuit00@hs-esslingen.de
d981dc1bb0cc27d14d2f321be6cbf914f21d21b7
66deb611781cae17567efc4fd3717426d7df5e85
/pcmanager/src/src_kclear/trackcleaner/src/regopt.cpp
4a1578dc0595bfb175eceb65e2ea0e21bcc452df
[ "Apache-2.0" ]
permissive
heguoxing98/knoss-pcmanager
4671548e14b8b080f2d3a9f678327b06bf9660c9
283ca2e3b671caa85590b0f80da2440a3fab7205
refs/heads/master
2023-03-19T02:11:01.833194
2020-01-03T01:45:24
2020-01-03T01:45:24
504,422,245
1
0
null
2022-06-17T06:40:03
2022-06-17T06:40:02
null
GB18030
C++
false
false
17,003
cpp
#include "stdafx.h" #include "regopt.h" /************************************************************************/ //枚举当前所有值可递归 /************************************************************************/ void CRegOpt::DoRegEnumeration(HKEY rootKey,LPCTSTR lpItemPath,EnumerateRegFun fnRegFun,void* pUserData/* =NULL */) { if(s_bUserBreak) return; HKEY hKey = NULL; LONG lResult; LPTSTR lpName = new TCHAR[MAX_PATH]; LPBYTE lpValue = new BYTE[MAX_PATH * 20]; if (lpValue == NULL) { goto clean0; } if (lpName == NULL) { goto clean0; } lResult = RegOpenKeyEx(rootKey, lpItemPath, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = ::GetLastError(); goto clean0; } /************************************************************************/ /*枚举值 /************************************************************************/ BEGIN DWORD dwIndex=0; do { if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ::GetLastError(); goto clean0; } memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); DWORD dwName = MAX_PATH; DWORD dwValue = MAX_PATH * 20; DWORD dwType; lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); if (lResult == ERROR_MORE_DATA) { //delete[] lpName; delete[] lpValue; //lpName = NULL; lpValue = NULL; //lpName = new TCHAR[dwName+2]; lpValue = new BYTE [dwValue+10]; //memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue) + 10); if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ::GetLastError(); goto clean0; } lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); } if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { break; } else { m_iErrCode = GetLastError(); goto clean0; } } if(0==wcscmp(lpName,_T(""))) { wcscpy(lpName,_T("默认值")); } BOOL bRet= fnRegFun(rootKey, lpItemPath, lpName, dwName ,lpValue,dwValue, dwType, pUserData); //是否继续枚举 if (bRet == FALSE) { s_bUserBreak = TRUE; goto clean0; } dwIndex++; } while (1); END /************************************************************************/ /*枚举键 /************************************************************************/ BEGIN DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { // RegCloseKey(hKey); // return ; goto clean0; } else { m_iErrCode = GetLastError(); // RegCloseKey(hKey); // return ; goto clean0; } } //!!由于递归过深有可能溢出 //#define MAX_REGPATH 2048 //TCHAR szRoot[MAX_REGPATH]={0}; CString strRoot; if (wcscmp(lpItemPath,_T("")) == 0 ) { strRoot.Format(_T("%s"),szKey); //wsprintf(szRoot,_T("%s"),szKey); } else { strRoot.Format(_T("%s\\%s"),lpItemPath,szKey); //wsprintf(szRoot,_T("%s\\%s"),lpItemPath,szKey); } if (fnRegFun(rootKey, strRoot.GetBuffer(), NULL,NULL,NULL,NULL, -1, pUserData)) { DoRegEnumeration(rootKey, strRoot.GetBuffer(), fnRegFun, pUserData); } } while (1); END clean0: if (hKey) { RegCloseKey(hKey); hKey = NULL; } if (lpName) { delete[] lpName; lpName = NULL; } if (lpValue) { delete[] lpValue; lpValue = NULL; } return ; } /************************************************************************/ /* 递归枚举所有子键 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetSubKeyEx(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<CString>& vec_Key,BOOL bRes,BOOL bFullPath) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } if(bFullPath == TRUE) { CString strRegFullPath; strRegFullPath = lpcKey; strRegFullPath.Append(_T("\\")); strRegFullPath.Append(szKey); vec_Key.Add(strRegFullPath); } else vec_Key.Add(szKey); if (TRUE == bRes) { CString strSub=lpcKey; strSub.Append(_T("\\")); strSub.Append(szKey); DoEnumCurrnetSubKeyEx(hRootKey,strSub,vec_Key,bRes,bFullPath); } } while (1); RegCloseKey(hKey); return bRet; } /************************************************************************/ //获得当前键下的所有子键 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetSubKey(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<CString>& vec_Key) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } vec_Key.Add(szKey); } while (1); RegCloseKey(hKey); return bRet; } BOOL CRegOpt::DoEnumCurrnetSubKey(HKEY hRootKey,LPCTSTR lpcKey,CAtlMap<CString,char>& vec_Key) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = lResult; return FALSE; } //枚举键名 BOOL bRet = TRUE; DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } else { bRet = FALSE; m_iErrCode = lResult; break; } } vec_Key.SetAt(szKey,'1'); dwIndex++; } while (1); RegCloseKey(hKey); return bRet; } /************************************************************************/ //获得当前键下的所有值名 /************************************************************************/ BOOL CRegOpt::DoEnumCurrnetValue(HKEY hRootKey,LPCTSTR lpcKey,CSimpleArray<REGVALUE>& vec_Value,BOOL bRes) { HKEY hKey; LONG lResult; //打开键 lResult = RegOpenKeyEx(hRootKey, lpcKey, NULL, KEY_READ, &hKey ); if(lResult != ERROR_SUCCESS) { m_iErrCode = ::GetLastError(); return FALSE; } BOOL bRet = TRUE; DWORD dwIndex=0; do { LPTSTR lpName = new TCHAR[MAX_PATH]; LPBYTE lpValue = new BYTE[MAX_PATH]; if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY bRet = FALSE; break; } memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); DWORD dwName = MAX_PATH; DWORD dwValue = MAX_PATH; DWORD dwType; lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); if (lResult == ERROR_MORE_DATA) { delete[] lpName; delete[] lpValue; lpName = NULL; lpValue = NULL; lpName = new TCHAR[dwName+1]; lpValue = new BYTE [dwValue+1]; memset(lpName,0,sizeof(lpName)); memset(lpValue,0,sizeof(lpValue)); if (lpName == NULL||lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY bRet = FALSE; break; } lResult = RegEnumValue( hKey, dwIndex, lpName, &dwName, NULL, &dwType, lpValue, &dwValue ); } if (lResult == ERROR_NO_MORE_ITEMS) { bRet = TRUE; break; } if (dwName == 0) { wcscpy(lpName,_T("默认值")); } REGVALUE regValue; regValue.strValueName = lpName; regValue.dwType = dwType; switch (dwType) { case REG_SZ: case REG_EXPAND_SZ: { regValue.strValue = (wchar_t*) lpValue; } break; case REG_BINARY: case REG_DWORD_LITTLE_ENDIAN: case REG_DWORD_BIG_ENDIAN: case REG_LINK: case REG_MULTI_SZ: case REG_NONE: case REG_QWORD_LITTLE_ENDIAN: regValue.strValue = _T(""); break; } vec_Value.Add(regValue); //释放相应空间 delete[] lpName; delete[] lpValue; lpName = NULL; lpValue = NULL; dwIndex++; } while (1); if (bRes == FALSE) { RegCloseKey(hKey); return TRUE; } //向下层枚举 BEGIN DWORD dwIndex=0; do { TCHAR szKey[MAX_PATH]={0}; DWORD dwKey = sizeof(szKey); lResult =RegEnumKey(hKey,dwIndex,szKey,dwKey); dwIndex++; if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_NO_MORE_ITEMS) { RegCloseKey(hKey); return TRUE; } else { m_iErrCode = GetLastError(); RegCloseKey(hKey); return TRUE; } } // //!!由于递归过深有可能溢出 //#define MAX_REGPATH 2048 // // TCHAR szRoot[MAX_REGPATH]={0}; // // // if (wcscmp(lpcKey,_T("")) == 0 ) // wsprintf(szRoot,_T("%s"),szKey); // else // wsprintf(szRoot,_T("%s\\%s"),lpcKey,szKey); CString strRoot; if (wcscmp(lpcKey,_T("")) == 0 ) { strRoot.Format(_T("%s"),szKey); //wsprintf(szRoot,_T("%s"),szKey); } else { strRoot.Format(_T("%s\\%s"),lpcKey,szKey); //wsprintf(szRoot,_T("%s\\%s"),lpItemPath,szKey); } DoEnumCurrnetValue(hRootKey, strRoot.GetBuffer(), vec_Value, bRes); } while (1); END RegCloseKey(hKey); return TRUE; } /************************************************************************/ //删除子键 /************************************************************************/ BOOL CRegOpt::RegDelnode(HKEY hKeyRoot, LPCTSTR lpSubKey) { TCHAR szDelKey[2 * MAX_PATH]; lstrcpy (szDelKey, lpSubKey); return RegDelnodeRecurse(hKeyRoot, szDelKey); } BOOL CRegOpt::RegDelnodeRecurse(HKEY hKeyRoot, LPTSTR lpSubKey) { LPTSTR lpEnd; LONG lResult; DWORD dwSize; TCHAR szName[MAX_PATH]; HKEY hKey; FILETIME ftWrite; lResult = RegDeleteKey(hKeyRoot, lpSubKey); if (lResult == ERROR_SUCCESS) { m_iErrCode = GetLastError(); return TRUE; } lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey); if (lResult != ERROR_SUCCESS) { if (lResult == ERROR_FILE_NOT_FOUND) { return TRUE; } else { m_iErrCode = GetLastError(); return FALSE; } } lpEnd = lpSubKey + lstrlen(lpSubKey); if (*(lpEnd - 1) != '\\') { *lpEnd = '\\'; lpEnd++; *lpEnd = '\0'; } dwSize = MAX_PATH; lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL, NULL, NULL, &ftWrite); if (lResult == ERROR_SUCCESS) { do { lstrcpy (lpEnd, szName); if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) { break; } dwSize = MAX_PATH; lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,NULL, NULL, &ftWrite); } while (lResult == ERROR_SUCCESS); } lpEnd--; *lpEnd = TEXT('\0'); RegCloseKey (hKey); lResult = RegDeleteKey(hKeyRoot, lpSubKey); if (lResult == ERROR_SUCCESS) return TRUE; return FALSE; } BOOL CRegOpt::RegDelValue (HKEY hKeyRoot,LPCTSTR lpSubKey,LPCTSTR lpValue) { HKEY hKey = NULL; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))==ERROR_SUCCESS) { DWORD cbdata; if ((dwRet=RegQueryValueEx(hKey,lpValue,NULL,NULL,NULL,&cbdata))==ERROR_SUCCESS) { if (RegDeleteValue(hKey,lpValue)==ERROR_SUCCESS) { bRet = TRUE; goto clean0; } } else { m_iErrCode = dwRet; bRet = FALSE; goto clean0; } } else { m_iErrCode = dwRet; bRet = FALSE; } clean0: if (hKey) { RegCloseKey(hKey); hKey = NULL; } return TRUE; } /************************************************************************/ //是否存键 /************************************************************************/ BOOL CRegOpt::FindKey(HKEY hKeyRoot,LPCTSTR lpSubKey) { HKEY hKey = NULL; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))==ERROR_SUCCESS) { bRet = TRUE; goto clean0; } if (dwRet == ERROR_FILE_NOT_FOUND ) //找不到指定文件 { bRet = FALSE; dwRet = GetLastError(); goto clean0; } clean0: m_iErrCode = dwRet; return TRUE; } /************************************************************************/ //获得错误代码 /************************************************************************/ DWORD CRegOpt::GetErrorCode() { return m_iErrCode; } BOOL CRegOpt::CrackRegKey(wchar_t* regstring,HKEY& root, wchar_t*& subkey,wchar_t*& value) { if (!(subkey = wcsstr(regstring,L"\\"))) { return FALSE; //No valid root key } *subkey = 0; ++subkey; if (!lstrcmpi(regstring,L"HKEY_CURRENT_USER"))root = HKEY_CURRENT_USER; else if (!lstrcmpi(regstring,L"HKEY_LOCAL_MACHINE"))root = HKEY_LOCAL_MACHINE; else if (!lstrcmpi(regstring,L"HKEY_USERS")) root = HKEY_USERS; else if (!lstrcmpi(regstring,L"HKEY_CLASSES_ROOT")) root = HKEY_CLASSES_ROOT; else //No valid root key { m_iErrCode = ERROR_NOFAILKEY; return FALSE; } //value = wcsstr(subkey,L"\\"); //if (value) //{ // //value can point to real value or to '\0', meaning empty std::wstring // *value = 0; // ++value; //} ////value points to NULL return TRUE; } BOOL CRegOpt::CrackRegKey(CString& strRegPath,HKEY& root,CString& strSubKey) { int nInx = strRegPath.Find(_T("\\")); if (nInx == -1) return FALSE; strSubKey = strRegPath.Mid(nInx+1); CString strRootKey = strRegPath.Mid(0,nInx); if (-1!=strRootKey.Find(L"HKEY_CURRENT_USER")) root = HKEY_CURRENT_USER; else if(-1!=strRootKey.Find(L"HKEY_LOCAL_MACHINE")) root = HKEY_LOCAL_MACHINE; else if(-1!=strRootKey.Find(L"HKEY_USERS")) root = HKEY_USERS; else if(-1!=strRootKey.Find(L"HKEY_CLASSES_ROOT")) root = HKEY_CLASSES_ROOT; else { m_iErrCode = ERROR_NOFAILKEY; return FALSE; } return TRUE; } //获得指定键的默认值 BOOL CRegOpt::GetDefValue(HKEY hKeyRoot,LPCTSTR lpSubKey,CString& strValueName,CString& strValue) { HKEY hKey; DWORD dwRet; BOOL bRet = FALSE; if ((dwRet=RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_ALL_ACCESS,&hKey))!=ERROR_SUCCESS) { m_iErrCode = dwRet; bRet = FALSE; goto clean0; } DWORD cbData =MAX_PATH; LPBYTE lpValue = new BYTE[MAX_PATH]; memset(lpValue,0,MAX_PATH); DWORD dwType; dwRet = RegQueryValueEx(hKey, strValueName.GetBuffer(), NULL, &dwType, (LPBYTE) lpValue, &cbData ); if ( dwRet== ERROR_MORE_DATA ) { lpValue = new BYTE[cbData+2]; if (lpValue ==NULL) { m_iErrCode = ERROR_NOMEMOEY; bRet = FALSE; goto clean0; } dwRet = RegQueryValueEx(hKey, strValueName.GetBuffer(), NULL, NULL, (LPBYTE) lpValue, &cbData ); } if (dwRet != ERROR_SUCCESS) { m_iErrCode = ERROR_NODEF; bRet = FALSE; goto clean0; } if (REG_SZ == dwType|| REG_EXPAND_SZ== dwType) { strValue = (TCHAR*)lpValue; } else strValue = _T(""); bRet = TRUE; clean0: RegCloseKey(hKey); return bRet; } BOOL CRegOpt::GetHKEYToString(HKEY hRootKey,LPCTSTR lpszSubKey,CString& strRegFullPath) { strRegFullPath = _T(""); if (hRootKey == HKEY_CURRENT_USER) { strRegFullPath.Append(L"HKEY_CURRENT_USER\\"); } else if (hRootKey == HKEY_LOCAL_MACHINE) { strRegFullPath.Append(L"HKEY_LOCAL_MACHINE\\"); } else if (hRootKey == HKEY_USERS) { strRegFullPath.Append(L"HKEY_USERS\\"); } else if (hRootKey == HKEY_CLASSES_ROOT) { strRegFullPath.Append(L"HKEY_CLASSES_ROOT\\"); } else { return FALSE; } strRegFullPath.Append(lpszSubKey); return TRUE; }
[ "dreamsxin@qq.com" ]
dreamsxin@qq.com
fc32791069a41db370419b62bb451c6aa3862531
84bb32d553cfa97cfa8803091382645f76bc255f
/Stack using two queues.cpp
3e9e87d2a3d9821b959d95be71eadde2b20feaf3
[ "Unlicense" ]
permissive
trun-k/GeeksForGeeks_Final450
2e55c8b62d669463d87973083f9c0b0de56bbf8a
473fd336a81fdbe66d05bf25f54a61bc994d890e
refs/heads/main
2023-08-01T22:44:38.620859
2021-10-01T17:44:03
2021-10-01T17:44:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,630
cpp
#include<bits/stdc++.h> using namespace std; class QueueStack{ private: queue<int> q1; queue<int> q2; public: void push(int); int pop(); }; int main() { int T; cin>>T; while(T--) { QueueStack *qs = new QueueStack(); int Q; cin>>Q; while(Q--){ int QueryType=0; cin>>QueryType; if(QueryType==1) { int a; cin>>a; qs->push(a); }else if(QueryType==2){ cout<<qs->pop()<<" "; } } cout<<endl; } } // } Driver Code Ends /* The structure of the class is class QueueStack{ private: queue<int> q1; queue<int> q2; public: void push(int); int pop(); }; */ /* The method push to push element into the stack */ void QueueStack :: push(int x) { // Your Code if(q1.empty()) { q1.push(x); while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } } else { q2.push(x); while(!q1.empty()) { q2.push(q1.front()); q1.pop(); } } } /*The method pop which return the element poped out of the stack*/ int QueueStack :: pop() { // Your Code int x=-1; if(q1.empty() && q2.empty()) { return x; } if(q1.empty()) { x = q2.front(); q2.pop(); } else { x = q1.front(); q1.pop(); } return x; }
[ "noreply@github.com" ]
trun-k.noreply@github.com
39ef0be40668f9ae72bda45c43d33a60f1508b3e
0f252a72f9c464bc4e38d8b18c4d03717d84acf2
/laptop/SPOJ/LARMY.cpp
31254d9d45c9b893c2ae619c0cdadea0d2dce3b1
[]
no_license
ZikXewen/Submissions
e5286f1a94f1108eaa43c30fe6d12cec8537f066
ec6efc8f92440e43850b8d094927958c5533eb05
refs/heads/master
2023-07-24T11:59:16.460972
2021-05-24T13:02:43
2021-05-24T13:02:43
220,632,852
1
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define vi vector<int> using namespace std; int main(){ ios::sync_with_stdio(0), cin.tie(0); int N, K; cin >> N >> K; vi in(N), mp(N); for(int i = 0; i < N; ++i) cin >> in[i], mp[i] = in[i]; sort(all(mp)); mp.resize(unique(all(mp)) - mp.begin()); vector<vi> sm(N, vi(mp.size() + 1)), dp(N, vi(N)), an(N, vi(K + 1, 1e9)), ct(N, vi(K)); for(auto &i: in) i = lower_bound(all(mp), i) - mp.begin(); for(int i = 0; i < N; ++i) ++sm[i][in[i]]; for(int i = 0; i < N; ++i) for(int j = mp.size() - 1; j >= 0; --j) sm[i][j] += sm[i][j + 1] + (i? sm[i - 1][j] : 0) - (i? sm[i - 1][j + 1] : 0); for(int i = 0; i < N; ++i) for(int j = i + 1; j < N; ++j) dp[i][j] = dp[i][j - 1] + sm[j - 1][in[j] + 1] - (i? sm[i - 1][in[j] + 1] : 0); for(int i = 0; i < N; ++i) an[i][0] = dp[0][i]; for(int i = 1; i < N; ++i) for(int j = min(i, K - 1), ck = 0; j; --j, ck = 1) for(int k = max(ct[i - 1][j], j - 1); k <= (ck? ct[i][j + 1] : i - 1); ++k) if(an[i][j] >= an[k][j - 1] + dp[k + 1][i]) an[i][j] = an[k][j - 1] + dp[k + 1][i], ct[i][j] = k; cout << an[N - 1][K - 1]; }
[ "datasup12@gmail.com" ]
datasup12@gmail.com
b48fbfef673cdef5f3ab4f21c1e9cb6cc05959b7
c3bbdbbbc5f47577e332a280f81bd905617423c9
/Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_MethodImpl.cpp
757871880768abc7e96d23a552e4516a6a9f379c
[ "MIT" ]
permissive
DeanRoddey/CIDLib
65850f56cb60b16a63bbe7d6d67e4fddd3ecce57
82014e064eef51cad998bf2c694ed9c1c8cceac6
refs/heads/develop
2023-03-11T03:08:59.207530
2021-11-06T16:40:44
2021-11-06T16:40:44
174,652,391
227
33
MIT
2020-09-16T11:33:26
2019-03-09T05:26:26
C++
UTF-8
C++
false
false
83,514
cpp
// // FILE NAME: CIDMacroEng_MethodImpl.cpp // // AUTHOR: Dean Roddey // // CREATED: 01/12/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements TMEngMethodImpl class. This class represents the // actual implementation of a 'method' in the macro engine system. External // methods (those handled by C++ code) can each provide a derivative of // this class and override the Invoke() method. We provide a single, generic // one that is used to do all native (opcode based) methods. It's Invoke() // override is the one that interprets opcodes. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // Magic RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TMEngMethodImpl,TMEngNamedItem) RTTIDecls(TMEngOpMethodImpl,TMEngMethodImpl) // --------------------------------------------------------------------------- // CLASS: TMEngJumpTableItem // PREFIX: jtbli // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTableItem: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTableItem:: TMEngJumpTableItem( const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) : m_c4IP(c4IPToSet) , m_pmecvCase(pmecvToAdopt) { } TMEngJumpTableItem::~TMEngJumpTableItem() { delete m_pmecvCase; } // --------------------------------------------------------------------------- // TMEngJumpTableItem: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::ESortComps TMEngJumpTableItem::eComp( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { #if CID_DEBUG_ON if (m_pmecvCase->c2ClassId() != mecvToCheck.c2ClassId()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_DifferentCaseTypes , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(m_pmecvCase->c2ClassId()) , TCardinal(mecvToCheck.c2ClassId()) ); } #endif tCIDLib::ESortComps eRet = tCIDLib::ESortComps::Equal; switch(tCIDMacroEng::EIntrinsics(mecvToCheck.c2ClassId())) { case tCIDMacroEng::EIntrinsics::Card1 : { const TMEngCard1Val& mecvThis = *static_cast<const TMEngCard1Val*>(m_pmecvCase); const TMEngCard1Val& mecvThat = static_cast<const TMEngCard1Val&>(mecvToCheck); if (mecvThis.c1Value() < mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c1Value() > mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card2 : { const TMEngCard2Val& mecvThis = *static_cast<const TMEngCard2Val*>(m_pmecvCase); const TMEngCard2Val& mecvThat = static_cast<const TMEngCard2Val&>(mecvToCheck); if (mecvThis.c2Value() < mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c2Value() > mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card4 : { const TMEngCard4Val& mecvThis = *static_cast<const TMEngCard4Val*>(m_pmecvCase); const TMEngCard4Val& mecvThat = static_cast<const TMEngCard4Val&>(mecvToCheck); if (mecvThis.c4Value() < mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Value() > mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int1 : { const TMEngInt1Val& mecvThis = *static_cast<const TMEngInt1Val*>(m_pmecvCase); const TMEngInt1Val& mecvThat= static_cast<const TMEngInt1Val&>(mecvToCheck); if (mecvThis.i1Value() < mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i1Value() > mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int2 : { const TMEngInt2Val& mecvThis = *static_cast<const TMEngInt2Val*>(m_pmecvCase); const TMEngInt2Val& mecvThat= static_cast<const TMEngInt2Val&>(mecvToCheck); if (mecvThis.i2Value() < mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i2Value() > mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int4 : { const TMEngInt4Val& mecvThis = *static_cast<const TMEngInt4Val*>(m_pmecvCase); const TMEngInt4Val& mecvThat= static_cast<const TMEngInt4Val&>(mecvToCheck); if (mecvThis.i4Value() < mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i4Value() > mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Char : { const TMEngCharVal& mecvThis = *static_cast<const TMEngCharVal*>(m_pmecvCase); const TMEngCharVal& mecvThat= static_cast<const TMEngCharVal&>(mecvToCheck); if (mecvThis.chValue() < mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.chValue() > mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstGreater; break; } default : { // // It should be some enum derivative. If debugging, then use our C++ // level RTTI to insure it is. // #if CID_DEBUG_ON if (!mecvToCheck.bIsDescendantOf(TMEngEnumVal::clsThis())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_UnknownSwitchType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(mecvToCheck.c2ClassId()) ); } #endif const TMEngEnumVal& mecvThis = *static_cast<const TMEngEnumVal*>(m_pmecvCase); const TMEngEnumVal& mecvThat= static_cast<const TMEngEnumVal&>(mecvToCheck); if (mecvThis.c4Ordinal() < mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Ordinal() > mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstGreater; break; } } if (eRet == tCIDLib::ESortComps::Equal) c4IP = m_c4IP; return eRet; } // --------------------------------------------------------------------------- // CLASS: TMEngJumpTable // PREFIX: jtbl // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTable: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTable::TMEngJumpTable() : m_c4DefIP(kCIDLib::c4MaxCard) , m_colCases(tCIDLib::EAdoptOpts::Adopt) { } TMEngJumpTable::~TMEngJumpTable() { } // --------------------------------------------------------------------------- // TMEngJumpTable: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngJumpTable::AddDefaultItem(const tCIDLib::TCard4 c4IPToSet) { m_c4DefIP = c4IPToSet; } tCIDLib::TVoid TMEngJumpTable::AddItem(const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) { m_colCases.Add(new TMEngJumpTableItem(c4IPToSet, pmecvToAdopt)); } tCIDLib::TBoolean TMEngJumpTable::bFindMatch( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { const tCIDLib::TCard4 c4Count = m_colCases.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_colCases[c4Index]->eComp(mecvToCheck, c4IP) == tCIDLib::ESortComps::Equal) return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TMEngJumpTable::bHasRequiredItems() const { return (!m_colCases.bIsEmpty() && (m_c4DefIP != kCIDLib::c4MaxCard)); } tCIDLib::TCard4 TMEngJumpTable::c4DefCaseIP() const { return m_c4DefIP; } TMEngJumpTableItem& TMEngJumpTable::jtbliAt(const tCIDLib::TCard4 c4At) { #if CID_DEBUG_ON if (c4At >= m_colCases.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_BadJmpTableIndex , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c4At) ); } #endif return *m_colCases[c4At]; } // --------------------------------------------------------------------------- // CLASS: TMEngMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, static methods // --------------------------------------------------------------------------- const TString& TMEngMethodImpl::strKey(const TMEngMethodImpl& memethSrc) { return memethSrc.strName(); } // --------------------------------------------------------------------------- // TMEngMethodImpl: Destructor // --------------------------------------------------------------------------- TMEngMethodImpl::~TMEngMethodImpl() { // Clean up the locals and string pool collections delete m_pcolLocalList; delete m_pcolStringPool; } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TCard2 TMEngMethodImpl::c2AddLocal(const TMEngLocalInfo& meliToAdd) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_pcolLocalList->objAt(c4Index).strName() == meliToAdd.strName()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_DupLocalName , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , meliToAdd.strName() ); } } facCIDMacroEng().CheckIdOverflow(c4Count, L"Locals"); // Looks ok, so take it const tCIDLib::TCard2 c2Id = tCIDLib::TCard2(c4Count); TMEngLocalInfo& meliNew = m_pcolLocalList->objAdd(meliToAdd); meliNew.c2Id(c2Id); return c2Id; } tCIDLib::TCard2 TMEngMethodImpl::c2AddString(const TString& strToAdd , const tCIDLib::TBoolean bFindDups) { // Allocate the pool collection if not already if (!m_pcolStringPool) m_pcolStringPool = new TStringPool(tCIDLib::EAdoptOpts::Adopt, 8); // // If we are to find dups, then see if we already have this string in // the pool and don't add a new copy, just give back the existing id. // if (bFindDups && !m_pcolStringPool->bIsEmpty()) { const tCIDLib::TCard4 c4Count = m_pcolStringPool->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (strToAdd == m_pcolStringPool->pobjAt(c4Index)->strValue()) return tCIDLib::TCard2(c4Index); } } // Create a string value object with the passed value const tCIDLib::TCard2 c2NewId(tCIDLib::TCard2(m_pcolStringPool->c4ElemCount())); TString strName(L"PoolItem"); strName.AppendFormatted(c2NewId); TMEngStringVal* pmecvNew = new TMEngStringVal ( strName , tCIDMacroEng::EConstTypes::Const , strToAdd ); // Add it, and set it's id to the next id pmecvNew->c2Id(c2NewId); m_pcolStringPool->Add(pmecvNew); return pmecvNew->c2Id(); } tCIDLib::TCard4 TMEngMethodImpl::c4LocalCount() const { // If not allocated yet, then zero definitely if (!m_pcolLocalList) return 0; return m_pcolLocalList->c4ElemCount(); } tCIDLib::TCard4 TMEngMethodImpl::c4StringCount() const { // If not allocated yet, then zero definitely if (!m_pcolStringPool) return 0; return m_pcolStringPool->c4ElemCount(); } const TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) const { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } const TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) const { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } const TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) const { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } tCIDLib::TVoid TMEngMethodImpl::PushLocals(TCIDMacroEngine& meOwner) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); // // Look up the type of this parm and create a value. // // <TBD> We cannot use pool values for locals, because the negate // opcode will convert a non-const pool value in place instead // of replacing it. We have to have some way to say it's a pool // value, so it get's cleaned up ok, but also say it's a local // so that it get's treated correctly. // // For now, we just create a new object for all locals. // const tCIDLib::TCard2 c2Id = meliCur.c2ClassId(); TMEngClassVal* pmecvLocal = meOwner.meciFind(c2Id).pmecvMakeStorage ( meliCur.strName(), meOwner, meliCur.eConst() ); meOwner.PushValue(pmecvLocal, tCIDMacroEng::EStackItems::Local); } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Hidden Constructors // --------------------------------------------------------------------------- TMEngMethodImpl::TMEngMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngNamedItem(strName, c2MethodId) , m_pcolLocalList(nullptr) , m_pcolStringPool(nullptr) { } // --------------------------------------------------------------------------- // CLASS: TMEngOpMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- TMEngOpMethodImpl::TMEngOpMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngMethodImpl(strName, c2MethodId) , m_colOpCodes(128) , m_pjtblSwitches(nullptr) { } TMEngOpMethodImpl::~TMEngOpMethodImpl() { // Delete the jump table list if we have one try { delete m_pjtblSwitches; } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } catch(...) { } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public operators // --------------------------------------------------------------------------- const TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) const { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, inherited methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::Invoke( TMEngClassVal& mecvInstance , const TMEngClassInfo& meciTarget , const TMEngMethodInfo& methiThis , TCIDMacroEngine& meOwner) { // // Remember the stack top upon entry. If we throw out of here, we have // to remember to clean up back to there again. // const tCIDLib::TCard4 c4BasePointer = meOwner.c4StackTop(); // // We have two levels of exception handling, one for exceptions coming out of // a called method and one that occurs within the current method. We need // to know that the inner one was done, so that we don't do some redundant // work on the second one after the inner rethrows. // tCIDLib::TBoolean bThrowReported = kCIDLib::False; // // Get a pointer to the debugger interface. The macro engine owns this, // so we just get a pointer to avoid having to call his getter over and // over. We'll call back on this every time we hit a line opcode. It will // usually be zero, in which case we do nothing with it. // MMEngDebugIntf* pmedbgToCall = meOwner.pmedbgToUse(); #if CID_DEBUG_ON tCIDLib::TBoolean bDoDump = kCIDLib::False; if (bDoDump) { DumpOpCodes(*meOwner.pstrmConsole(), meOwner); meOwner.pstrmConsole()->Flush(); } #endif // // If we have any locals, then push them now. Their ids are relative // to the base pointer we stored above. // if (c4LocalCount()) { PushLocals(meOwner); // If we have a debug callback, tell him new locals were created if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::True); } // // And now let's enter the opcode processing loop. We process opcodes // in the order found, except when we hit jump opcodes. If we hit the // end of the opcodes or we hit a return opcode, we will break out. // try { // We need an index, which is our 'instruction pointer' tCIDLib::TCard4 c4IP = 0; // // Remember the opcode count. If we get to this, then we are at // the end of the method. // const tCIDLib::TCard4 c4EndIndex = m_colOpCodes.c4ElemCount(); tCIDLib::TBoolean bDone = kCIDLib::False; tCIDLib::TBoolean bNoIncIP = kCIDLib::False; while (!bDone) { // Get the current opcode const TMEngOpCode& meopCur = m_colOpCodes[c4IP]; switch(meopCur.eOpCode()) { case tCIDMacroEng::EOpCodes::CallExcept : case tCIDMacroEng::EOpCodes::CallLocal : case tCIDMacroEng::EOpCodes::CallMember : case tCIDMacroEng::EOpCodes::CallParent : case tCIDMacroEng::EOpCodes::CallParm : case tCIDMacroEng::EOpCodes::CallStack : case tCIDMacroEng::EOpCodes::CallThis : { TMEngClassVal* pmecvTarget = nullptr; const TMEngClassInfo* pmeciTarget = nullptr; tCIDLib::TCard2 c2MethId = kCIDMacroEng::c2BadId; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallExcept) { pmecvTarget = &meOwner.mecvExceptionThrown(); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallStack) { pmecvTarget = &meOwner.mecvStackAt ( meOwner.c4StackTop() - meopCur[0] ); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallThis) { pmecvTarget = &mecvInstance; pmeciTarget = &meciTarget; c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) { pmecvTarget = &mecvInstance; pmeciTarget = &meOwner.meciFind(meciTarget.c2ParentClassId()); c2MethId = meopCur[0]; } else { // // The first index is the id of the member, local, or // parm that the call is being made against. So, // according to the opcode, look up the target value // object. // if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallLocal) { // // The local ids are relative to the base pointer // for our stack frame. // pmecvTarget = &meOwner.mecvStackAt ( c4BasePointer + meopCur[0] ); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallMember) { // Get the indicated member, in the first index pmecvTarget = &mecvInstance.mecvFind(meopCur[0], meOwner); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParm) { // It's a parm already on the stack pmecvTarget = &meOwner.mecvStackAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); } else { // Not a known target type, so throw facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownCallType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Unknown , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) ); // Won't happen but makes analyzer happy break; } // Get the class info for the class of the target pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } // // And invoke it. The parameters are on the call stack, // but we have to push the method onto the call stack // before invoking it. // try { // // Push a call item on the stack and if we have a debugger // installed, let it know about the change. // meOwner.meciPushMethodCall ( pmeciTarget->c2Id() , c2MethId , &meciTarget , this , &methiThis , &mecvInstance , meOwner.c4CurLine() , c4IP ); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // // Looks ok, so call the class with the instance and // method info. It will pass it on to the appropriate // method. // // If we are doing a parent call, that's a monomorphic // dispatch, else do polymorphic to go to the most // derived. // tCIDMacroEng::EDispatch eDispatch = tCIDMacroEng::EDispatch::Poly; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) eDispatch = tCIDMacroEng::EDispatch::Mono; pmeciTarget->Invoke(meOwner, *pmecvTarget, c2MethId, eDispatch); // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } catch(TError& errToCatch) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures() && !meOwner.bInIDE()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionFrom , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the error handler know about it, if not already if (!errToCatch.bReported()) meOwner.Exception(errToCatch); bThrowReported = kCIDLib::True; errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // Just rethrow. We are being forced down throw; } catch(const TExceptException&) { // // The called method threw a macro level exception // and didn't handle it. So we need to see if we // have a handler. If so, jump to the catch block, // else, rethrow. // tCIDLib::TCard4 c4New = 0; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } catch(...) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptFrom , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // Tell the engine about it meOwner.UnknownException(); bThrowReported = kCIDLib::True; throw; } break; } case tCIDMacroEng::EOpCodes::ColIndex : { // // The top of stack is an index value, and the one before // that is a collection object. // const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvIndex = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvCollect = meOwner.mecvStackAt(c4Top - 2); #if CID_DEBUG_ON if (!mecvCollect.bIsDescendantOf(TMEngCollectVal::clsThis())) { TMEngClassInfo& meciCol = meOwner.meciFind(mecvCollect.c2ClassId()); facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_NotCollectionType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciCol.strClassPath() ); } #endif // // Cast the value object to the (C++ level) base collection // value class, and ask it to get us the object at the // indicated index. // // It will throw a macro level index error if the index is // not good. // try { TMEngCollectVal& mecvActual ( static_cast<TMEngCollectVal&>(mecvCollect) ); TMEngClassVal* pmecvElem ( mecvActual.pmecvGetAt(meOwner, mecvIndex) ); // Pop the two values off the stack top meOwner.MultiPop(2); // And push the new value meOwner.PushValue(pmecvElem, tCIDMacroEng::EStackItems::ColElem); } catch(const TExceptException&) { // Do the macro level try/catch handling tCIDLib::TCard4 c4New = 0; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; }; case tCIDMacroEng::EOpCodes::Copy : { const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvSrc = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvTar = meOwner.mecvStackAt(c4Top - 2); if (meOwner.bValidation()) { TMEngClassInfo& meciSrc = meOwner.meciFind(mecvSrc.c2ClassId()); TMEngClassInfo& meciTar = meOwner.meciFind(mecvTar.c2ClassId()); if (!meciSrc.bIsCopyable() || !meciTar.bIsCopyable()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcRT_BadCopyOpParms , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciSrc.strClassPath() , meciTar.strClassPath() ); } } // If the source and target are not the same, do the copy if (&mecvSrc != &mecvTar) mecvTar.CopyFrom(mecvSrc, meOwner); // And pop them both off meOwner.MultiPop(2); break; } case tCIDMacroEng::EOpCodes::CondEnumInc : case tCIDMacroEng::EOpCodes::ResetEnum : { // // The top of stack must be an enumerated object. We will // look at it and if it is not at it's max, we will // increment it, else we'll do nothing. We leave a boolean // value on the stack to indicate whether we incremented // it or not. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); // If validating, make sure it's an enum if (meOwner.bValidation()) { if (!meOwner.bIsDerivedFrom(mecvTop.c2ClassId() , tCIDMacroEng::EIntrinsics::Enum)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_WrongStackTopType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") , meOwner.strClassPathForId(mecvTop.c2ClassId()) ); } if (mecvTop.bIsConst()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotNConstStackItem , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") ); } } TMEngEnumVal& mecvEnum = static_cast<TMEngEnumVal&>(mecvTop); if (tCIDMacroEng::EOpCodes::CondEnumInc == meopCur.eOpCode()) { if (mecvEnum.bAtMax()) { meOwner.PushBoolean(kCIDLib::False, tCIDMacroEng::EConstTypes::Const); } else { mecvEnum.Increment(); meOwner.PushBoolean(kCIDLib::True, tCIDMacroEng::EConstTypes::Const); } } else { mecvEnum.c4Ordinal(0); } break; } case tCIDMacroEng::EOpCodes::CondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CondJumpNP : { // If we need to jump, the new IP is in an immedate if (meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CurLine : { // Just store the line number stored meOwner.c4CurLine(meopCur.c4Immediate()); // // If we have a debugger installed, then we need to // call it and take action based on what it returns. // if (pmedbgToCall) { tCIDMacroEng::EDbgActs eAct = pmedbgToCall->eAtLine ( meciTarget , methiThis , *this , mecvInstance , meopCur.c4Immediate() , c4IP ); // // If he tells us to exit, then throw an exception // that will dump us back to the top level, who will // tell the debugger we've exited. // if ((eAct == tCIDMacroEng::EDbgActs::CloseSession) || (eAct == tCIDMacroEng::EDbgActs::Exit)) { throw TDbgExitException(eAct); } } break; } case tCIDMacroEng::EOpCodes::EndTry : { // // The top of stack must be a try item, which we want // to pop. If validating, then check it. // if (meOwner.bValidation()) { if (meOwner.mecsiTop().eType() != tCIDMacroEng::EStackItems::Try) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExpectedTry , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() ); } } meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::FlipTop : { // Just ask the engine to flip the top two stack items meOwner.FlipStackTop(); break; } case tCIDMacroEng::EOpCodes::Jump : { // Get the new IP out const tCIDLib::TCard4 c4New = meopCur.c4Immediate(); // // If debugging, make sure that we aren't going to jump // out of the valid range. // if (c4New >= c4EndIndex) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJump , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(c4IP) , meciTarget.strClassPath() , strName() ); } // Looks ok, so set it c4IP = c4New; bNoIncIP = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::LogicalAnd : case tCIDMacroEng::EOpCodes::LogicalOr : case tCIDMacroEng::EOpCodes::LogicalXor : { // Get the two top items as booleans tCIDLib::TBoolean bFirst = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); tCIDLib::TBoolean bSecond = meOwner.bStackValAt ( meOwner.c4StackTop() - 2 ); // Do the indicated operation if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalAnd) bFirst &= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalOr) bFirst |= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalXor) bFirst ^= bSecond; // Now pop the top two items off meOwner.MultiPop(2); // And put our new result on the top meOwner.PushBoolean(bFirst, tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::MultiPop : { meOwner.MultiPop(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::Negate : { // // The top of stack must be a boolean value. We have // to pop it and push back the negated version We // cannot modify the value on the stack itself, even if // a temp, since it may be referred to again later. // TMEngCallStackItem& mecsiTop = meOwner.mecsiTop(); if (meOwner.bValidation()) { if (mecsiTop.mecvPushed().c2ClassId() != tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Boolean)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotStackItemType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(tCIDMacroEng::EIntrinsics::Boolean) ); } } TMEngBooleanVal& mecvTop = static_cast<TMEngBooleanVal&> ( mecsiTop.mecvPushed() ); const tCIDMacroEng::EConstTypes eConst = mecvTop.eConst(); const tCIDLib::TBoolean bSave = !mecvTop.bValue(); meOwner.PopTop(); meOwner.PushBoolean(bSave, eConst); break; } case tCIDMacroEng::EOpCodes::NoOp : // Do nothing break; case tCIDMacroEng::EOpCodes::NotCondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (!bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::NotCondJumpNP : { if (!meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::PopTop : { // Just pop the stack meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PopToReturn : { // // Get the value on the top of the stack, and copy it to // the return value object. If debugging, make sure that // the types are the same and that the type is copyable. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); TMEngClassVal& mecvRet = meOwner.mecvStackAt ( c4BasePointer - (methiThis.c4ParmCount() + 2) ); mecvRet.CopyFrom(mecvTop, meOwner); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PushCurLine : { meOwner.PushCard4(meOwner.c4CurLine(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushEnum : { meOwner.PushEnum(meopCur[0], meopCur[1], tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushException : { meOwner.PushException(); break; } case tCIDMacroEng::EOpCodes::PushImBoolean : { meOwner.PushBoolean(meopCur.bImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard1 : { meOwner.PushCard1(meopCur.c1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard2 : { meOwner.PushCard2(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard4 : { meOwner.PushCard4(meopCur.c4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard8 : { meOwner.PushCard8(meopCur.c8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImChar : { meOwner.PushChar(meopCur.chImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat4 : { meOwner.PushFloat4(meopCur.f4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat8 : { meOwner.PushFloat8(meopCur.f8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt1 : { meOwner.PushInt1(meopCur.i1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt2 : { meOwner.PushInt2(meopCur.i2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt4 : { meOwner.PushInt4(meopCur.i4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushLocal : { // // The first index is the index of the local. In this // case, we are repushing a value already on the stack. // The offset of the local relative to the base pointer // is in the immediate field. // meOwner.RepushAt(c4BasePointer + meopCur[0]); break; } case tCIDMacroEng::EOpCodes::PushMember : { // The first index is the index of the member meOwner.PushValue ( &mecvInstance.mecvFind(meopCur[0], meOwner) , tCIDMacroEng::EStackItems::Member ); break; } case tCIDMacroEng::EOpCodes::PushParm : { // // The first index is the id of the parameter. In this // case, we are just repushing a value already on the // stack as a parameter. Subtracting the parm count plus // one get's us to the first parm. Then we add the parm // id minus one (they are 1 based) to get to the actual // value. // meOwner.RepushAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); break; } case tCIDMacroEng::EOpCodes::PushStrPoolItem : { // Just push the pool item meOwner.PushValue ( &mecvFindPoolItem(meopCur[0]) , tCIDMacroEng::EStackItems::StringPool ); break; } case tCIDMacroEng::EOpCodes::PushTempConst : { // // The c2Immediate field holds the id of the type to push. // meOwner.PushPoolValue(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushTempVar : { // // The c2Immediate field holds the id of the type to push. // The context object has a method to push a value of a // give type id onto the stack from the temp pool. // meOwner.PushPoolValue ( meopCur.c2Immediate() , tCIDMacroEng::EConstTypes::NonConst ); break; } case tCIDMacroEng::EOpCodes::PushThis : { meOwner.PushValue(&mecvInstance, tCIDMacroEng::EStackItems::This); break; } case tCIDMacroEng::EOpCodes::Return : { // // There can be try blocks still on the stack at this // point, so we have to remove them. Any return value has // been extracted at this point, so there should only be // tries above the current base pointer. // tCIDLib::TCard4 c4New = 0; while (kCIDLib::True) { const tCIDLib::TCard4 c4PopTo = meOwner.c4FindNextTry(c4New); if ((c4PopTo == kCIDLib::c4MaxCard) || (c4PopTo < c4BasePointer)) { break; } // We found one in our method scope, so pop back to there meOwner.PopBackTo(c4PopTo); } // Break out of this method bDone = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::TableJump : { // // This is an indirect table jump, probably for a switch // statement. The first index indicates index of the // jump table that we are to use. // TMEngJumpTable& jtblToUse = jtblById(meopCur[0]); // // The value to switch on must be no the top of the stack, // so get it and ask the table which one matches it. // TMEngClassVal& mecvCase = meOwner.mecvStackAtTop(); // // Look this guy up. Note that if it doesn't match, // we will use the deafult. // tCIDLib::TCard4 c4New; if (!jtblToUse.bFindMatch(mecvCase, c4New)) c4New = jtblToUse.c4DefCaseIP(); // We can trash the stack top now meOwner.PopTop(); // And set the IP to the IP of the target case block bNoIncIP = kCIDLib::True; c4IP = c4New; break; } case tCIDMacroEng::EOpCodes::Throw : { // // This can be either a throw, or a rethrow, according // to the immediate boolean value. If a throw, then // get the exception info set. // // There must be an enumerated type on the stack, which // is the error to throw. We will use this to set up an // exception instance that we keep around for this // purpose. // if (!meopCur.bImmediate()) { TMEngEnumVal& mecvErr = meOwner.mecvStackAtTopAs<TMEngEnumVal>(); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , meciErr.strTextValue(mecvErr) , meOwner.c4CurLine() ); } // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::ThrowFmt : { // // This is a special form of throw that is used to // pass in values to be used to replace tokens in the // error text. c4Immediate indicates how many of them // there are, pushed after the error enum. So start // off by getting the error enum out, and get the // text that we will format tokens into. // TMEngEnumVal& mecvErr = meOwner.mecvStackAtAs<TMEngEnumVal> ( meOwner.c4StackTop() - (1 + meopCur.c4Immediate()) ); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); TString strText(meciErr.strTextValue(mecvErr), 128); // // Now, according to how many tokens indicated in the // immediate value, work down and format each one and // replace that tokens. This requires a bit of code to // do, so we call a helper method to do it. // FormatErrTokens ( meOwner , meopCur.c4Immediate() , strText ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , strText , meOwner.c4CurLine() ); // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::Try : { // // We need to push a try block on the stack. The opcode // has the IP of the start of the catch block in the // c4Immediate field, which we need to push along with it. // meOwner.PushTry(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::TypeCast : { // // The first index is the type to cast to. The value to // cast is on the top of stack, and must be a numeric or // enumerated type, as must be the type to cast to. // // So we need to get the value on the top of the stack, // convert it to the cast type, pop the old value off, // and replace it with a new value from the temp pool. // TMEngClassVal& mecvToCast = meOwner.mecvStackAtTop(); // Push a temp pool value of the target type meOwner.PushPoolValue ( meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const ); TMEngClassVal& mecvTmp = meOwner.mecvStackAtTop(); // And ask the temp object to cast from the stack top value TMEngClassInfo& meciTarType = meOwner.meciFind(meopCur.c2Immediate()); const tCIDMacroEng::ECastRes eRes = meciTarType.eCastFrom ( meOwner, mecvToCast, mecvTmp ); if (eRes == tCIDMacroEng::ECastRes::Incompatible) { // This should have been checked up front facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcPrs_CannotCast , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(mecvToCast.c2ClassId()) , meciTarType.strClassPath() ); } // Flip and pop the original off meOwner.FlipStackTop(); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::None : { // // We shouldn't be see this one in the opcode stream // because it's just a place holder for internal use. // facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_NoneOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } default : { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_UnknownOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } } // Move forward to the next opcode if (bNoIncIP) bNoIncIP = kCIDLib::False; else c4IP++; // If at the end, we are done if (c4IP == c4EndIndex) break; } } catch(TError& errToCatch) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the engine know about it, if not already, then rethrow if (errToCatch.bReported()) meOwner.Exception(errToCatch); } errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(const TExceptException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(...) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // Tell the engine about it and then rethrow meOwner.UnknownException(); } throw; } // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TMEngOpMethodImpl::bMoreLines(const tCIDLib::TCard4 c4LastIP) const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = c4LastIP + 1; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) { // // Check to see if the next opcode is the last one and a no-op. // If so, then this line is the one on the EndMethod, which is // really past the end of the method from a call stack point of // view, so we'll return false if so. // if ((c4Index + 2 == c4Count) && (m_colOpCodes[c4Index + 1].eOpCode() == tCIDMacroEng::EOpCodes::NoOp)) { return kCIDLib::False; } return kCIDLib::True; } } return kCIDLib::False; } tCIDLib::TCard2 TMEngOpMethodImpl::c2AddJumpTable() { if (!m_pjtblSwitches) m_pjtblSwitches = new TMEngJumpTableTable(tCIDLib::EAdoptOpts::Adopt); const tCIDLib::TCard4 c4Ret = m_pjtblSwitches->c4ElemCount(); m_pjtblSwitches->Add(new TMEngJumpTable); return tCIDLib::TCard2(c4Ret); } tCIDLib::TCard4 TMEngOpMethodImpl::c4AddOpCode(const TMEngOpCode& meopToAdd) { // // Add this opcode and return the index of the opcode, which is the // current (pre-addition) count. // tCIDLib::TCard4 c4Ret = m_colOpCodes.c4ElemCount(); m_colOpCodes.objAdd(meopToAdd); return c4Ret; } tCIDLib::TCard4 TMEngOpMethodImpl::c4CurOffset() const { return m_colOpCodes.c4ElemCount(); } tCIDLib::TCard4 TMEngOpMethodImpl::c4FirstLineNum() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) return meopCur.c4Immediate(); } // Just return 1, since we didn't find any current line opcodes return 1; } tCIDLib::TVoid TMEngOpMethodImpl::DumpOpCodes( TTextOutStream& strmTarget , const TCIDMacroEngine& meOwner) const { const TTextOutStream::Width widNums(4); const TTextOutStream::Width widZero(0); TStreamJanitor janStream(&strmTarget); const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmTarget << widNums << c4Index << widZero << L"- "; m_colOpCodes[c4Index].Format(strmTarget, meOwner); strmTarget << kCIDLib::NewLn; } } TMEngJumpTable& TMEngOpMethodImpl::jtblById(const tCIDLib::TCard2 c2Id) { // Make sure this index is valid if (!m_pjtblSwitches || (c2Id >= m_pjtblSwitches->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJumpTableId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pjtblSwitches->pobjAt(c2Id); } const TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) const { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } const TMEngOpCode& TMEngOpMethodImpl::meopLast() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } TMEngOpCode& TMEngOpMethodImpl::meopLast() { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::FormatErrTokens( TCIDMacroEngine& meOwner , const tCIDLib::TCard4 c4Tokens , TString& strToFill) { // Create a macro level string out stream TMEngClassInfo& meciStrm = meOwner.meciFind ( tCIDMacroEng::EIntrinsics::StringOutStream ); TMEngTextOutStreamVal* pmecvStrm = static_cast<TMEngTextOutStreamVal*> ( meciStrm.pmecvMakeStorage ( L"TempStream" , meOwner , tCIDMacroEng::EConstTypes::NonConst ) ); TJanitor<TMEngTextOutStreamVal> janStream(pmecvStrm); // // Give it a stream, since we won't be constructing it at the macro // language level, which normally is how it gets one. // TTextStringOutStream* pstrmTarget = new TTextStringOutStream(1024UL); pmecvStrm->SetStream(pstrmTarget, tCIDLib::EAdoptOpts::Adopt); tCIDLib::TCh chToken(kCIDLib::chDigit1); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Tokens; c4Index++) { // // Get the current formattable object. One gets us down to the actual // top item, then add the current index to get to the current one. // TMEngFormattableVal& mecvCur = meOwner.mecvStackAtAs<TMEngFormattableVal> ( (meOwner.c4StackTop() - c4Tokens) + c4Index ); TMEngClassInfo& meciTarget = meOwner.meciFind(mecvCur.c2ClassId()); // // Generate a macro level call to format this guy to the stream. Tell // the call stack that the stream is a 'repush', though its not, so // that it won't try to delete it on us. // meOwner.PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const); meOwner.PushValue(pmecvStrm, tCIDMacroEng::EStackItems::Parm, kCIDLib::True); meOwner.meciPushMethodCall ( meciTarget.c2Id() , TMEngFormattableInfo::c2FormatToId() ); meciTarget.Invoke ( meOwner , mecvCur , TMEngFormattableInfo::c2FormatToId() , tCIDMacroEng::EDispatch::Poly ); // // We cheated this one, so we have to pop the method item as well // the parm and return! // meOwner.MultiPop(3); // And now replace the current token with this result. Flush first! pmecvStrm->Flush(); strToFill.eReplaceToken(pstrmTarget->strData(), chToken); // And reset it for the next round pstrmTarget->Reset(); // Move up to the next token digit chToken++; } }
[ "droddey@charmedquark.com" ]
droddey@charmedquark.com
56e617b004faee96d11dafc9165b6e986adeece0
79ce7b21cb9eead164c6df9355014d33ba9f702a
/caffe2/utils/filler.h
6dadfa69bcbed227f11a7d3c5d63769970562bbd
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
FDecaYed/pytorch
7c7d3fb762c1aae3d41ec214b44dc0b28c0e7353
a5e9500a5672595f5ee8a242a411d80adb265dd7
refs/heads/master
2021-11-18T18:21:47.397464
2018-08-29T23:38:07
2018-08-29T23:38:07
131,061,037
1
0
NOASSERTION
2021-11-09T02:58:16
2018-04-25T20:40:00
C++
UTF-8
C++
false
false
2,980
h
#ifndef CAFFE2_FILLER_H_ #define CAFFE2_FILLER_H_ #include <sstream> #include "caffe2/core/logging.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/math.h" namespace caffe2 { class TensorFiller { public: template <class Type, class Context> void Fill(Tensor* tensor, Context* context) const { CAFFE_ENFORCE(context, "context is null"); CAFFE_ENFORCE(tensor, "tensor is null"); auto min = static_cast<Type>(min_); auto max = static_cast<Type>(max_); CAFFE_ENFORCE_LE(min, max); Tensor temp_tensor(shape_, Context::GetDeviceType()); tensor->swap(temp_tensor); Type* data = tensor->template mutable_data<Type>(); // TODO: Come up with a good distribution abstraction so that // the users could plug in their own distribution. if (has_fixed_sum_) { auto fixed_sum = static_cast<Type>(fixed_sum_); CAFFE_ENFORCE_LE(min * tensor->size(), fixed_sum); CAFFE_ENFORCE_GE(max * tensor->size(), fixed_sum); math::RandFixedSum<Type, Context>( tensor->size(), min, max, fixed_sum_, data, context); } else { math::RandUniform<Type, Context>(tensor->size(), min, max, data, context); } } template <class Type> TensorFiller& Min(Type min) { min_ = (double)min; return *this; } template <class Type> TensorFiller& Max(Type max) { max_ = (double)max; return *this; } template <class Type> TensorFiller& FixedSum(Type fixed_sum) { has_fixed_sum_ = true; fixed_sum_ = (double)fixed_sum; return *this; } // a helper function to construct the lengths vector for sparse features template <class Type> TensorFiller& SparseLengths(Type total_length) { return FixedSum(total_length).Min(0).Max(total_length); } // a helper function to construct the segments vector for sparse features template <class Type> TensorFiller& SparseSegments(Type max_segment) { CAFFE_ENFORCE(!has_fixed_sum_); return Min(0).Max(max_segment); } TensorFiller& Shape(const std::vector<TIndex>& shape) { shape_ = shape; return *this; } template <class Type> TensorFiller(const std::vector<TIndex>& shape, Type fixed_sum) : shape_(shape), has_fixed_sum_(true), fixed_sum_((double)fixed_sum) {} TensorFiller(const std::vector<TIndex>& shape) : shape_(shape), has_fixed_sum_(false), fixed_sum_(0) {} TensorFiller() : TensorFiller(std::vector<TIndex>()) {} std::string DebugString() const { std::stringstream stream; stream << "shape = [" << shape_ << "]; min = " << min_ << "; max = " << max_; if (has_fixed_sum_) { stream << "; fixed sum = " << fixed_sum_; } return stream.str(); } private: std::vector<TIndex> shape_; // TODO: type is unknown until a user starts to fill data; // cast everything to double for now. double min_ = 0.0; double max_ = 1.0; bool has_fixed_sum_; double fixed_sum_; }; } // namespace caffe2 #endif // CAFFE2_FILLER_H_
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
7175cb755112deaeebe37ea2a665802f632b66ef
a15ad75b81dd175322cebc49a3f4f30604c5c819
/Scenario3_ServicingCompleteTask.xaml.h
47ecb38779818ad6cc5d254a65cd55143567da81
[]
no_license
BraydenFolk/BackgroundTasks
c3b1645a4a34e3002a8b79f1408fa0f5137ccc9f
f260c6103a6b0df0bd57909a2f2a97c9ab06653e
refs/heads/master
2021-05-01T01:44:12.322108
2017-01-23T20:36:32
2017-01-23T20:36:32
79,844,970
0
0
null
null
null
null
UTF-8
C++
false
false
1,819
h
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario3_ServicingCompleteTask.xaml.h // Declaration of the ServicingCompleteTask class // #pragma once #include "pch.h" #include "Scenario3_ServicingCompleteTask.g.h" #include "MainPage.xaml.h" namespace SDKTemplate { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> [Windows::Foundation::Metadata::WebHostHidden] public ref class ServicingCompleteTask sealed { public: ServicingCompleteTask(); protected: virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; private: SDKTemplate::MainPage^ rootPage; void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task); void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args); void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args); void UpdateUI(); }; }
[ "noreply@github.com" ]
BraydenFolk.noreply@github.com
672e494ccd23432ae64d7bf860354a9f58349334
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/process/detail/windows/start_dir.hpp
09fdbbccf0337a971fb1e63ac819ff1807dc7de4
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
hpp
// Copyright (c) 2006, 2007 Julio M. Merino Vidal // Copyright (c) 2008 Ilya Sokolov, Boris Schaeling // Copyright (c) 2009 Boris Schaeling // Copyright (c) 2010 Felipe Tanus, Boris Schaeling // Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PROCESS_DETAIL_WINDOWS_START_DIR_HPP #define BOOST_PROCESS_DETAIL_WINDOWS_START_DIR_HPP #include <string> #include <sstd/boost/process/detail/windows/handler.hpp> namespace boost { namespace process { namespace detail { namespace windows { template<typename Char> struct start_dir_init : handler_base_ext { start_dir_init(const std::basic_string<Char> &s) : s_(s) {} template <class Executor> void on_setup(Executor& exec) const { exec.work_dir = s_.c_str(); } const std::basic_string<Char> &str() const {return s_;} private: std::basic_string<Char> s_; }; }}}} #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com