max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
703
<reponame>Tekh-ops/ezEngine #include <ToolsFoundationTest/ToolsFoundationTestPCH.h>
32
964
[ { "queryName": "Schema with 'additionalProperties' set as Boolean", "severity": "INFO", "line": 28, "filename": "positive1.json" }, { "queryName": "Schema with 'additionalProperties' set as Boolean", "severity": "INFO", "line": 22, "filename": "positive2.yaml" }, { "queryName": "Schema with 'additionalProperties' set as Boolean", "severity": "INFO", "line": 51, "filename": "positive3.json" }, { "queryName": "Schema with 'additionalProperties' set as Boolean", "severity": "INFO", "line": 34, "filename": "positive4.yaml" } ]
250
392
/* * Point 3D. */ #include "io/serialization/serial_input_stream.hh" #include "io/serialization/serial_output_stream.hh" #include "io/streams/ostream.hh" #include "lang/pointers/auto_ptr.hh" #include "math/exact.hh" #include "math/geometry/point_3D.hh" #include "math/math.hh" namespace math { namespace geometry { /* * Imports. */ using io::serialization::serial_input_stream; using io::serialization::serial_output_stream; using io::streams::ostream; using math::exact; using lang::pointers::auto_ptr; /*************************************************************************** * Constructors and destructor. ***************************************************************************/ /* * Default constructor. * Return the origin. */ point_3D::point_3D() : _x(0), _y(0), _z(0) { } /* * Constructor. * Return the point with the given coordinates. */ point_3D::point_3D(const double& x, const double& y, const double& z) : _x(x), _y(y), _z(z) { } /* * Copy constructor. */ point_3D::point_3D(const point_3D& p) : _x(p._x), _y(p._y), _z(p._z) { } /* * Destructor. */ point_3D::~point_3D() { /* do nothing */ } /*************************************************************************** * Named constructors. ***************************************************************************/ /* * Polar form. * Return the point at the given radius from the origin, theta radians from * the positive x-axis, and psi radians above the xy-plane. */ point_3D point_3D::polar( const double& r, const double& theta, const double& psi) { double r_xy = r*math::cos(psi); return point_3D( r_xy*math::cos(theta), r_xy*math::sin(theta), r*math::sin(psi) ); } /*************************************************************************** * Serialization. ***************************************************************************/ /* * Serialize. */ void point_3D::serialize(serial_output_stream& s) const { s << _x << _y << _z; } /* * Deserialize. */ auto_ptr<point_3D> point_3D::deserialize(serial_input_stream& s) { auto_ptr<point_3D> p(new point_3D()); s >> p->_x >> p->_y >> p->_z; return p; } /*************************************************************************** * I/O. ***************************************************************************/ /* * Formatted output to stream. */ ostream& operator<<(ostream& os, const point_3D& p) { os << "(" << p._x << ", " << p._y << ", " << p._z << ")"; return os; } /*************************************************************************** * Assignment operator. ***************************************************************************/ point_3D& point_3D::operator=(const point_3D& p) { _x = p._x; _y = p._y; _z = p._z; return *this; } /*************************************************************************** * Binary operators. ***************************************************************************/ point_3D operator*(const double& s, const point_3D& p) { return point_3D(s*p._x, s*p._y, s*p._z); } point_3D operator*(const point_3D& p, const double& s) { return point_3D(p._x*s, p._y*s, p._z*s); } point_3D operator/(const point_3D& p, const double& s) { return point_3D(p._x/s, p._y/s, p._z/s); } point_3D operator+(const point_3D& p0, const point_3D& p1) { return point_3D(p0._x + p1._x, p0._y + p1._y, p0._z + p1._z); } point_3D operator-(const point_3D& p0, const point_3D& p1) { return point_3D(p0._x - p1._x, p0._y - p1._y, p0._z - p1._z); } /*************************************************************************** * Unary operators. ***************************************************************************/ point_3D point_3D::operator+() const { return *this; } point_3D point_3D::operator-() const { return point_3D(-_x, -_y, -_z); } /*************************************************************************** * Binary equality tests. ***************************************************************************/ bool operator==(const point_3D& p0, const point_3D& p1) { return ((p0._x == p1._x) && (p0._y == p1._y) && (p0._z == p1._z)); } bool operator!=(const point_3D& p0, const point_3D& p1) { return ((p0._x != p1._x) || (p0._y != p1._y) || (p0._z != p1._z)); } /*************************************************************************** * Comparators. ***************************************************************************/ /* * Binary comparators. * These comparators enforce a lexicographic ordering on points. */ bool operator<(const point_3D& p0, const point_3D& p1) { return ( (p0._x < p1._x) || ((p0._x == p1._x) && ((p0._y < p1._y) || ((p0._y == p1._y) && (p0._z < p1._z)))) ); } bool operator>(const point_3D& p0, const point_3D& p1) { return ( (p0._x > p1._x) || ((p0._x == p1._x) && ((p0._y > p1._y) || ((p0._y == p1._y) && (p0._z > p1._z)))) ); } bool operator<=(const point_3D& p0, const point_3D& p1) { return ( (p0._x < p1._x) || ((p0._x == p1._x) && ((p0._y < p1._y) || ((p0._y == p1._y) && (p0._z <= p1._z)))) ); } bool operator>=(const point_3D& p0, const point_3D& p1) { return ( (p0._x > p1._x) || ((p0._x == p1._x) && ((p0._y > p1._y) || ((p0._y == p1._y) && (p0._z >= p1._z)))) ); } /* * Comparison method (for lexicographic ordering on points). */ int point_3D::compare_to(const point_3D& p) const { int cmp_x = (_x < p._x) ? -1 : ((_x > p._x) ? 1 : 0); int cmp_y = (_y < p._y) ? -1 : ((_y > p._y) ? 1 : 0); int cmp_z = (_z < p._z) ? -1 : ((_z > p._z) ? 1 : 0); return ((cmp_x == 0) ? ((cmp_y == 0) ? cmp_z : cmp_y) : cmp_x); } /*************************************************************************** * Polar coordinates. ***************************************************************************/ /* * Magnitude (distance from origin). */ double abs(const point_3D& p) { return math::sqrt(p._x*p._x + p._y*p._y + p._z*p._z); } /* * Argument (angle in radians from positive x-axis). */ double arg(const point_3D& p) { return math::atan2(p._y, p._x); } /* * Elevation (angle in radians from the xy-plane). */ double elev(const point_3D& p) { double r_xy = math::sqrt(p._x*p._x + p._y*p._y); return math::atan2(p._z, r_xy); } /*************************************************************************** * Dot product. ***************************************************************************/ /* * Dot product. */ double dot(const point_3D& p0, const point_3D& p1) { return (p0._x * p1._x + p0._y * p1._y + p0._z * p1._z); } /*************************************************************************** * Distance from point to line/segment. ***************************************************************************/ /* * Distance from the point to the line passing through the specified points. */ double point_3D::distance_to_line( const point_3D& p, const point_3D& q) const { /* compute vectors between points */ point_3D a = q - p; point_3D b = *this - p; /* compute distance */ double mag_a_sq = a._x*a._x + a._y*a._y + a._z*a._z; double mag_b_sq = b._x*b._x + b._y*b._y + b._z*b._z; double a_dot_b = dot(a, b); return (mag_a_sq*mag_b_sq - a_dot_b*a_dot_b)/mag_a_sq; } /* * Distance from the point to the line segment with the specified endpoints. */ double point_3D::distance_to_segment( const point_3D& p, const point_3D& q) const { /* compute vectors between points */ point_3D a = q - p; point_3D b = *this - p; point_3D c = *this - q; /* compute distance to segment */ if (dot(a, c) >= 0) { /* q is closest point */ return abs(c); } else if (dot(-a, b) >= 0) { /* p is closest point */ return abs(b); } else { /* compute distance from point to line */ return this->distance_to_line(p, q); } } /*************************************************************************** * Geometric predicates. ***************************************************************************/ /* * Robust geometric orientation test (using exact arithmetic). * Return -1 if the point is above plane pqr, * 0 if the points are coplanar, and * 1 if the point is below plane pqr. * * Note that "below" and "above" are defined so that p, q, and r appear * in counterclockwise order when viewed from above plane pqr. */ int point_3D::orientation( const point_3D& p, const point_3D& q, const point_3D& r) const { /* compute error bound beyond which exact arithmetic is needed */ static const double error_bound = (7.0 + 56.0 * exact<>::epsilon()) * exact<>::epsilon(); /* perform approximate orientation test */ double ax = p.x() - _x; double ay = p.y() - _y; double az = p.z() - _z; double bx = q.x() - _x; double by = q.y() - _y; double bz = q.z() - _z; double cx = r.x() - _x; double cy = r.y() - _y; double cz = r.z() - _z; double ax_by = ax * by; double bx_ay = bx * ay; double ax_cy = ax * cy; double cx_ay = cx * ay; double bx_cy = bx * cy; double cx_by = cx * by; double det = az * (bx_cy - cx_by) + bz * (cx_ay - ax_cy) + cz * (ax_by - bx_ay); /* check if error cannot change result */ double permanent = math::abs(az) * (math::abs(bx_cy) + math::abs(cx_by)) + math::abs(bz) * (math::abs(cx_ay) + math::abs(ax_cy)) + math::abs(cz) * (math::abs(ax_by) + math::abs(bx_ay)); double max_error = error_bound * permanent; if ((-det) < max_error) { return -1; } else if (det > max_error) { return 1; } else { /* perform exact orientation test */ exact<> ax_e = exact<>(p.x()) - _x; exact<> ay_e = exact<>(p.y()) - _y; exact<> az_e = exact<>(p.z()) - _z; exact<> bx_e = exact<>(q.x()) - _x; exact<> by_e = exact<>(q.y()) - _y; exact<> bz_e = exact<>(q.z()) - _z; exact<> cx_e = exact<>(r.x()) - _x; exact<> cy_e = exact<>(r.y()) - _y; exact<> cz_e = exact<>(r.z()) - _z; exact<> ax_by_e = ax_e * by_e; exact<> bx_ay_e = bx_e * ay_e; exact<> ax_cy_e = ax_e * cy_e; exact<> cx_ay_e = cx_e * ay_e; exact<> bx_cy_e = bx_e * cy_e; exact<> cx_by_e = cx_e * by_e; exact<> det_exact = az_e * (bx_cy_e - cx_by_e) + bz_e * (cx_ay_e - ax_cy_e) + cz_e * (ax_by_e - bx_ay_e); return det_exact.sign(); } } /* * Robust geometric in-sphere test (using exact arithmetic). * Return -1 if the point is outside the sphere, * 0 if the point is on the sphere, and * 1 if the point is inside the sphere. * * The four points defining the sphere must appear in order so that the * fourth point is below the plane defined by the first three (positive * orientation), or the sign of the result will be reversed. */ int point_3D::in_sphere( const point_3D& p0, const point_3D& p1, const point_3D& p2, const point_3D& p3) const { /* compute error bound beyond which exact arithmetic is needed */ static const double error_bound = (16.0 + 224.0 * exact<>::epsilon()) * exact<>::epsilon(); /* perform approximate in-sphere test */ double ax = p0.x() - _x; double ay = p0.y() - _y; double az = p0.z() - _z; double bx = p1.x() - _x; double by = p1.y() - _y; double bz = p1.z() - _z; double cx = p2.x() - _x; double cy = p2.y() - _y; double cz = p2.z() - _z; double dx = p3.x() - _x; double dy = p3.y() - _y; double dz = p3.z() - _z; double ax_by = ax * by; double bx_ay = bx * ay; double bx_cy = bx * cy; double cx_by = cx * by; double cx_dy = cx * dy; double dx_cy = dx * cy; double dx_ay = dx * ay; double ax_dy = ax * dy; double ax_cy = ax * cy; double cx_ay = cx * ay; double bx_dy = bx * dy; double dx_by = dx * by; double ab_diff = ax_by - bx_ay; double bc_diff = bx_cy - cx_by; double cd_diff = cx_dy - dx_cy; double da_diff = dx_ay - ax_dy; double ac_diff = ax_cy - cx_ay; double bd_diff = bx_dy - dx_by; double abc = az * bc_diff - bz * ac_diff + cz * ab_diff; double bcd = bz * cd_diff - cz * bd_diff + dz * bc_diff; double cda = cz * da_diff + dz * ac_diff + az * cd_diff; double dab = dz * ab_diff + az * bd_diff + bz * da_diff; double a_sq = ax * ax + ay * ay + az * az; double b_sq = bx * bx + by * by + bz * bz; double c_sq = cx * cx + cy * cy + cz * cz; double d_sq = dx * dx + dy * dy + dz * dz; double det = (d_sq * abc - c_sq * dab) + (b_sq * cda - a_sq * bcd); /* check if error cannot change result */ double permanent = ((math::abs(cx_dy) + math::abs(dx_cy)) * math::abs(bz) + (math::abs(dx_by) + math::abs(bx_dy)) * math::abs(cz) + (math::abs(bx_cy) + math::abs(cx_by)) * math::abs(dz)) * a_sq + ((math::abs(dx_ay) + math::abs(ax_dy)) * math::abs(cz) + (math::abs(ax_cy) + math::abs(cx_ay)) * math::abs(dz) + (math::abs(cx_dy) + math::abs(dx_cy)) * math::abs(az)) * b_sq + ((math::abs(ax_by) + math::abs(bx_ay)) * math::abs(dz) + (math::abs(bx_dy) + math::abs(dx_by)) * math::abs(az) + (math::abs(dx_ay) + math::abs(ax_dy)) * math::abs(bz)) * c_sq + ((math::abs(bx_cy) + math::abs(cx_by)) * math::abs(az) + (math::abs(cx_ay) + math::abs(ax_cy)) * math::abs(bz) + (math::abs(ax_by) + math::abs(bx_ay)) * math::abs(cz)) * d_sq; double max_error = error_bound * permanent; if ((-det) < max_error) { return -1; } else if (det > max_error) { return 1; } else { /* perform exact in-sphere test */ exact<> ax_e = exact<>(p0.x()) - _x; exact<> ay_e = exact<>(p0.y()) - _y; exact<> az_e = exact<>(p0.z()) - _z; exact<> bx_e = exact<>(p1.x()) - _x; exact<> by_e = exact<>(p1.y()) - _y; exact<> bz_e = exact<>(p1.z()) - _z; exact<> cx_e = exact<>(p2.x()) - _x; exact<> cy_e = exact<>(p2.y()) - _y; exact<> cz_e = exact<>(p2.z()) - _z; exact<> dx_e = exact<>(p3.x()) - _x; exact<> dy_e = exact<>(p3.y()) - _y; exact<> dz_e = exact<>(p3.z()) - _z; exact<> ab_diff_e = ax_e * by_e - bx_e * ay_e; exact<> bc_diff_e = bx_e * cy_e - cx_e * by_e; exact<> cd_diff_e = cx_e * dy_e - dx_e * cy_e; exact<> da_diff_e = dx_e * ay_e - ax_e * dy_e; exact<> ac_diff_e = ax_e * cy_e - cx_e * ay_e; exact<> bd_diff_e = bx_e * dy_e - dx_e * by_e; exact<> abc_e = az_e * bc_diff_e - bz_e * ac_diff_e + cz_e * ab_diff_e; exact<> bcd_e = bz_e * cd_diff_e - cz_e * bd_diff_e + dz_e * bc_diff_e; exact<> cda_e = cz_e * da_diff_e + dz_e * ac_diff_e + az_e * cd_diff_e; exact<> dab_e = dz_e * ab_diff_e + az_e * bd_diff_e + bz_e * da_diff_e; exact<> a_sq_e = ax_e * ax_e + ay_e * ay_e + az_e * az_e; exact<> b_sq_e = bx_e * bx_e + by_e * by_e + bz_e * bz_e; exact<> c_sq_e = cx_e * cx_e + cy_e * cy_e + cz_e * cz_e; exact<> d_sq_e = dx_e * dx_e + dy_e * dy_e + dz_e * dz_e; exact<> det_exact = (d_sq_e * abc_e - c_sq_e * dab_e) + (b_sq_e * cda_e - a_sq_e * bcd_e); return det_exact.sign(); } } } /* namespace geometry */ } /* namespace math */
6,396
2,868
<gh_stars>1000+ /* * Copyright (c) 2015-2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Unit tests for serialization functions. */ #include "config.h" #include "gtest/gtest.h" #include "hs.h" #include "hs_internal.h" #include "test_util.h" #include <cstring> #include <string> #include <vector> namespace { using namespace std; using namespace testing; static const unsigned validModes[] = { HS_MODE_NOSTREAM, HS_MODE_STREAM | HS_MODE_SOM_HORIZON_LARGE, HS_MODE_VECTORED }; static const pattern testPatterns[] = { pattern("hatstand.*teakettle.*badgerbrush", HS_FLAG_CASELESS, 1000), pattern("hatstand.*teakettle.*badgerbrush", HS_FLAG_DOTALL, 1001), pattern("hatstand|teakettle|badgerbrush", 0, 1002), pattern("^hatstand|teakettle|badgerbrush$", 0, 1003), pattern("foobar.{10,1000}xyzzy", HS_FLAG_DOTALL, 1004), pattern("foobar.{2,501}roobar", 0, 1005), pattern("abc.*def.*ghi", HS_FLAG_SOM_LEFTMOST, 1006), pattern("(\\p{L}){4}", HS_FLAG_UTF8|HS_FLAG_UCP, 1007), pattern("\\.(exe|pdf|gif|jpg|png|wav|riff|mp4)\\z", 0, 1008) }; class SerializeP : public TestWithParam<tuple<unsigned, pattern>> {}; static const char *getModeString(unsigned mode) { if (mode & HS_MODE_STREAM) { return "STREAM"; } if (mode & HS_MODE_BLOCK) { return "BLOCK"; } if (mode & HS_MODE_VECTORED) { return "VECTORED"; } return "UNKNOWN"; } // Check that we can deserialize from a char array at any alignment and the info // is consistent TEST_P(SerializeP, DeserializeFromAnyAlignment) { const unsigned mode = get<0>(GetParam()); const pattern &pat = get<1>(GetParam()); SCOPED_TRACE(mode); SCOPED_TRACE(pat); hs_error_t err; hs_database_t *db = buildDB(pat, mode); ASSERT_TRUE(db != nullptr) << "database build failed."; char *original_info = nullptr; err = hs_database_info(db, &original_info); ASSERT_EQ(HS_SUCCESS, err); const char *mode_string = getModeString(mode); ASSERT_NE(nullptr, original_info) << "hs_serialized_database_info returned null."; ASSERT_STREQ("Version:", string(original_info).substr(0, 8).c_str()); ASSERT_TRUE(strstr(original_info, mode_string) != nullptr) << "Original info \"" << original_info << "\" does not contain " << mode_string; char *bytes = nullptr; size_t length = 0; err = hs_serialize_database(db, &bytes, &length); ASSERT_EQ(HS_SUCCESS, err) << "serialize failed."; ASSERT_NE(nullptr, bytes); ASSERT_LT(0U, length); hs_free_database(db); db = nullptr; const size_t maxalign = 16; char *copy = new char[length + maxalign]; // Deserialize from char arrays at a range of alignments. for (size_t i = 0; i < maxalign; i++) { SCOPED_TRACE(i); memset(copy, 0, length + maxalign); char *mycopy = copy + i; memcpy(mycopy, bytes, length); // We should be able to call hs_serialized_database_info and get back a // reasonable string. char *info; err = hs_serialized_database_info(mycopy, length, &info); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(nullptr, original_info); ASSERT_STREQ(original_info, info); free(info); // We should be able to deserialize as well. err = hs_deserialize_database(mycopy, length, &db); ASSERT_EQ(HS_SUCCESS, err) << "deserialize failed."; ASSERT_TRUE(db != nullptr); // And the info there should match. err = hs_database_info(db, &info); ASSERT_EQ(HS_SUCCESS, err); ASSERT_STREQ(original_info, info); free(info); hs_free_database(db); db = nullptr; } free(original_info); free(bytes); delete[] copy; } // Check that we can deserialize_at from a char array at any alignment and the // info is consistent TEST_P(SerializeP, DeserializeAtFromAnyAlignment) { const unsigned mode = get<0>(GetParam()); const pattern &pat = get<1>(GetParam()); SCOPED_TRACE(mode); SCOPED_TRACE(pat); hs_error_t err; hs_database_t *db = buildDB(pat, mode); ASSERT_TRUE(db != nullptr) << "database build failed."; char *original_info; err = hs_database_info(db, &original_info); ASSERT_EQ(HS_SUCCESS, err); const char *mode_string = getModeString(mode); ASSERT_NE(nullptr, original_info) << "hs_serialized_database_info returned null."; ASSERT_STREQ("Version:", string(original_info).substr(0, 8).c_str()); ASSERT_TRUE(strstr(original_info, mode_string) != nullptr) << "Original info \"" << original_info << "\" does not contain " << mode_string; char *bytes = nullptr; size_t length = 0; err = hs_serialize_database(db, &bytes, &length); ASSERT_EQ(HS_SUCCESS, err) << "serialize failed."; ASSERT_NE(nullptr, bytes); ASSERT_LT(0U, length); hs_free_database(db); db = nullptr; size_t slength; err = hs_serialized_database_size(bytes, length, &slength); ASSERT_EQ(HS_SUCCESS, err); const size_t maxalign = 16; char *copy = new char[length + maxalign]; char *mem = new char[slength]; db = (hs_database_t *)mem; // Deserialize from char arrays at a range of alignments. for (size_t i = 0; i < maxalign; i++) { SCOPED_TRACE(i); memset(copy, 0, length + maxalign); char *mycopy = copy + i; memcpy(mycopy, bytes, length); // We should be able to call hs_serialized_database_info and get back a // reasonable string. char *info; err = hs_serialized_database_info(mycopy, length, &info); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(nullptr, original_info); ASSERT_STREQ(original_info, info); free(info); // Scrub target memory. memset(mem, 0xff, length); // We should be able to deserialize as well. err = hs_deserialize_database_at(mycopy, length, db); ASSERT_EQ(HS_SUCCESS, err) << "deserialize failed."; ASSERT_TRUE(db != nullptr); // And the info there should match. err = hs_database_info(db, &info); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(info != nullptr); ASSERT_STREQ(original_info, info); free(info); } free(original_info); free(bytes); delete[] copy; delete[] mem; } INSTANTIATE_TEST_CASE_P(Serialize, SerializeP, Combine(ValuesIn(validModes), ValuesIn(testPatterns))); // Attempt to reproduce the scenario in UE-1946. TEST(Serialize, CrossCompileSom) { hs_platform_info plat; plat.cpu_features = 0; plat.tune = HS_TUNE_FAMILY_GENERIC; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; const unsigned mode = HS_MODE_STREAM | HS_MODE_SOM_HORIZON_LARGE; hs_database_t *db = buildDB(pat, HS_FLAG_SOM_LEFTMOST, 1000, mode, &plat); ASSERT_TRUE(db != nullptr) << "database build failed."; size_t db_len; hs_error_t err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); char *bytes = nullptr; size_t bytes_len = 0; err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, bytes_len); hs_free_database(db); // Relocate to misaligned block. char *copy = (char *)malloc(bytes_len + 1); ASSERT_TRUE(copy != nullptr); memcpy(copy + 1, bytes, bytes_len); free(bytes); size_t ser_len; err = hs_serialized_database_size(copy + 1, bytes_len, &ser_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, ser_len); ASSERT_EQ(db_len, ser_len); free(copy); } static void *null_malloc(size_t) { return nullptr; } static void *misaligned_malloc(size_t s) { char *c = (char *)malloc(s + 1); return (void *)(c + 1); } static void misaligned_free(void *p) { char *c = (char *)p; free(c - 1); } // make sure that serializing/deserializing to null or an unaligned address // fails TEST(Serialize, CompileNullMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; // mallocing null should fail compile hs_set_allocator(null_malloc, nullptr); hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_NE(HS_SUCCESS, err); ASSERT_TRUE(db == nullptr); ASSERT_TRUE(c_err != nullptr); hs_free_compile_error(c_err); hs_set_allocator(nullptr, nullptr); } TEST(Serialize, CompileErrorAllocator) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatsta^nd.*(badgerbrush|teakettle)"; // failing to compile should use the misc allocator allocated_count = 0; allocated_count_b = 0; hs_set_allocator(count_malloc_b, count_free_b); hs_set_misc_allocator(count_malloc, count_free); hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_NE(HS_SUCCESS, err); ASSERT_TRUE(db == nullptr); ASSERT_TRUE(c_err != nullptr); ASSERT_EQ(0, allocated_count_b); ASSERT_NE(0, allocated_count); hs_free_compile_error(c_err); hs_set_allocator(nullptr, nullptr); ASSERT_EQ(0, allocated_count); } TEST(Serialize, AllocatorsUsed) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; allocated_count = 0; allocated_count_b = 0; hs_set_allocator(count_malloc_b, count_free_b); hs_set_database_allocator(count_malloc, count_free); hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); ASSERT_TRUE(c_err == nullptr); ASSERT_EQ(0, allocated_count_b); ASSERT_NE(0, allocated_count); /* serialize should use the misc allocator */ char *bytes = nullptr; size_t bytes_len = 0; err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, bytes_len); ASSERT_EQ(bytes_len, allocated_count_b); count_free_b(bytes); hs_free_database(db); hs_set_allocator(nullptr, nullptr); ASSERT_EQ(0, allocated_count); ASSERT_EQ(0, allocated_count_b); } TEST(Serialize, CompileUnalignedMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; // unaligned malloc should fail compile hs_set_allocator(misaligned_malloc, misaligned_free); hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_NE(HS_SUCCESS, err); ASSERT_TRUE(db == nullptr); ASSERT_TRUE(c_err != nullptr); hs_free_compile_error(c_err); hs_set_allocator(nullptr, nullptr); } TEST(Serialize, SerializeNullMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); size_t db_len; err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); char *bytes = nullptr; size_t bytes_len = 0; // fail when serialize gets a null malloc hs_set_allocator(null_malloc, nullptr); err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_NE(HS_SUCCESS, err); hs_set_allocator(nullptr, nullptr); hs_free_database(db); } // make sure that serializing/deserializing to null or an unaligned address // fails TEST(Serialize, SerializeUnalignedMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat= "hatstand.*(badgerbrush|teakettle)"; hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); size_t db_len; err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); char *bytes = nullptr; size_t bytes_len = 0; // fail when serialize gets a misaligned malloc hs_set_allocator(misaligned_malloc, misaligned_free); err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_NE(HS_SUCCESS, err); hs_set_allocator(nullptr, nullptr); hs_free_database(db); } TEST(Serialize, DeserializeNullMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); size_t db_len; err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); char *bytes = nullptr; size_t bytes_len = 0; err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, bytes_len); hs_free_database(db); size_t ser_len; err = hs_serialized_database_size(bytes, bytes_len, &ser_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, ser_len); err = hs_deserialize_database_at(bytes, ser_len, nullptr); ASSERT_NE(HS_SUCCESS, err); free(bytes); } TEST(Serialize, DeserializeUnalignedMalloc) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); size_t db_len; err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); char *bytes = nullptr; size_t bytes_len = 0; err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, bytes_len); hs_free_database(db); size_t ser_len; err = hs_serialized_database_size(bytes, bytes_len, &ser_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, ser_len); // and now fail when deserialize addr is unaligned char *new_db = (char *)malloc(ser_len + 8); for (int i = 1; i < 8; i++) { err = hs_deserialize_database_at(bytes, ser_len, (hs_database_t *)(new_db + i)); ASSERT_NE(HS_SUCCESS, err); } free(new_db); free(bytes); } TEST(Serialize, DeserializeGarbage) { hs_database_t *db; hs_compile_error_t *c_err; static const char *pat = "hatstand.*(badgerbrush|teakettle)"; hs_error_t err = hs_compile(pat, 0, HS_MODE_BLOCK, nullptr, &db, &c_err); ASSERT_EQ(HS_SUCCESS, err); ASSERT_TRUE(db != nullptr); // determine database size for subsequent hs_deserialize_database_at size_t db_len; err = hs_database_size(db, &db_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, db_len); // serialize char *bytes = nullptr; size_t bytes_len = 0; err = hs_serialize_database(db, &bytes, &bytes_len); ASSERT_EQ(HS_SUCCESS, err); ASSERT_NE(0, bytes_len); hs_free_database(db); // append '\0' byte to the serialized string to spoil it bytes = (char *)realloc(bytes, bytes_len + 1); ASSERT_NE(nullptr, bytes); bytes[bytes_len] = '\0'; // create set of invalid serializations struct Arg { char *start; size_t len; }; const Arg invalid_args[] = { {bytes + 1, bytes_len}, {bytes + 1, bytes_len - 1}, {bytes, bytes_len - 1}, {bytes, bytes_len + 1}, }; for (const Arg &arg : invalid_args) { hs_database_t *a_db; err = hs_deserialize_database(arg.start, arg.len, &a_db); ASSERT_NE(HS_SUCCESS, err); char *new_db = (char *)malloc(db_len); ASSERT_NE(nullptr, new_db); err = hs_deserialize_database_at(arg.start, arg.len, (hs_database_t *)(new_db)); ASSERT_NE(HS_SUCCESS, err); free(new_db); char *info; err = hs_serialized_database_info(arg.start, arg.len, &info); ASSERT_NE(HS_SUCCESS, err); size_t ser_len; err = hs_serialized_database_size(arg.start, arg.len, &ser_len); ASSERT_NE(HS_SUCCESS, err); } free(bytes); } }
7,783
2,129
<gh_stars>1000+ // Copyright 2014 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // YUV->RGB conversion functions // // Author: Skal (<EMAIL>) #include "src/dsp/yuv.h" #if defined(WEBP_USE_SSE2) #include "src/dsp/common_sse2.h" #include <stdlib.h> #include <emmintrin.h> //----------------------------------------------------------------------------- // Convert spans of 32 pixels to various RGB formats for the fancy upsampler. // These constants are 14b fixed-point version of ITU-R BT.601 constants. // R = (19077 * y + 26149 * v - 14234) >> 6 // G = (19077 * y - 6419 * u - 13320 * v + 8708) >> 6 // B = (19077 * y + 33050 * u - 17685) >> 6 static void ConvertYUV444ToRGB_SSE2(const __m128i* const Y0, const __m128i* const U0, const __m128i* const V0, __m128i* const R, __m128i* const G, __m128i* const B) { const __m128i k19077 = _mm_set1_epi16(19077); const __m128i k26149 = _mm_set1_epi16(26149); const __m128i k14234 = _mm_set1_epi16(14234); // 33050 doesn't fit in a signed short: only use this with unsigned arithmetic const __m128i k33050 = _mm_set1_epi16((short)33050); const __m128i k17685 = _mm_set1_epi16(17685); const __m128i k6419 = _mm_set1_epi16(6419); const __m128i k13320 = _mm_set1_epi16(13320); const __m128i k8708 = _mm_set1_epi16(8708); const __m128i Y1 = _mm_mulhi_epu16(*Y0, k19077); const __m128i R0 = _mm_mulhi_epu16(*V0, k26149); const __m128i R1 = _mm_sub_epi16(Y1, k14234); const __m128i R2 = _mm_add_epi16(R1, R0); const __m128i G0 = _mm_mulhi_epu16(*U0, k6419); const __m128i G1 = _mm_mulhi_epu16(*V0, k13320); const __m128i G2 = _mm_add_epi16(Y1, k8708); const __m128i G3 = _mm_add_epi16(G0, G1); const __m128i G4 = _mm_sub_epi16(G2, G3); // be careful with the saturated *unsigned* arithmetic here! const __m128i B0 = _mm_mulhi_epu16(*U0, k33050); const __m128i B1 = _mm_adds_epu16(B0, Y1); const __m128i B2 = _mm_subs_epu16(B1, k17685); // use logical shift for B2, which can be larger than 32767 *R = _mm_srai_epi16(R2, 6); // range: [-14234, 30815] *G = _mm_srai_epi16(G4, 6); // range: [-10953, 27710] *B = _mm_srli_epi16(B2, 6); // range: [0, 34238] } // Load the bytes into the *upper* part of 16b words. That's "<< 8", basically. static WEBP_INLINE __m128i Load_HI_16_SSE2(const uint8_t* src) { const __m128i zero = _mm_setzero_si128(); return _mm_unpacklo_epi8(zero, _mm_loadl_epi64((const __m128i*)src)); } // Load and replicate the U/V samples static WEBP_INLINE __m128i Load_UV_HI_8_SSE2(const uint8_t* src) { const __m128i zero = _mm_setzero_si128(); const __m128i tmp0 = _mm_cvtsi32_si128(*(const uint32_t*)src); const __m128i tmp1 = _mm_unpacklo_epi8(zero, tmp0); return _mm_unpacklo_epi16(tmp1, tmp1); // replicate samples } // Convert 32 samples of YUV444 to R/G/B static void YUV444ToRGB_SSE2(const uint8_t* const y, const uint8_t* const u, const uint8_t* const v, __m128i* const R, __m128i* const G, __m128i* const B) { const __m128i Y0 = Load_HI_16_SSE2(y), U0 = Load_HI_16_SSE2(u), V0 = Load_HI_16_SSE2(v); ConvertYUV444ToRGB_SSE2(&Y0, &U0, &V0, R, G, B); } // Convert 32 samples of YUV420 to R/G/B static void YUV420ToRGB_SSE2(const uint8_t* const y, const uint8_t* const u, const uint8_t* const v, __m128i* const R, __m128i* const G, __m128i* const B) { const __m128i Y0 = Load_HI_16_SSE2(y), U0 = Load_UV_HI_8_SSE2(u), V0 = Load_UV_HI_8_SSE2(v); ConvertYUV444ToRGB_SSE2(&Y0, &U0, &V0, R, G, B); } // Pack R/G/B/A results into 32b output. static WEBP_INLINE void PackAndStore4_SSE2(const __m128i* const R, const __m128i* const G, const __m128i* const B, const __m128i* const A, uint8_t* const dst) { const __m128i rb = _mm_packus_epi16(*R, *B); const __m128i ga = _mm_packus_epi16(*G, *A); const __m128i rg = _mm_unpacklo_epi8(rb, ga); const __m128i ba = _mm_unpackhi_epi8(rb, ga); const __m128i RGBA_lo = _mm_unpacklo_epi16(rg, ba); const __m128i RGBA_hi = _mm_unpackhi_epi16(rg, ba); _mm_storeu_si128((__m128i*)(dst + 0), RGBA_lo); _mm_storeu_si128((__m128i*)(dst + 16), RGBA_hi); } // Pack R/G/B/A results into 16b output. static WEBP_INLINE void PackAndStore4444_SSE2(const __m128i* const R, const __m128i* const G, const __m128i* const B, const __m128i* const A, uint8_t* const dst) { #if (WEBP_SWAP_16BIT_CSP == 0) const __m128i rg0 = _mm_packus_epi16(*R, *G); const __m128i ba0 = _mm_packus_epi16(*B, *A); #else const __m128i rg0 = _mm_packus_epi16(*B, *A); const __m128i ba0 = _mm_packus_epi16(*R, *G); #endif const __m128i mask_0xf0 = _mm_set1_epi8(0xf0); const __m128i rb1 = _mm_unpacklo_epi8(rg0, ba0); // rbrbrbrbrb... const __m128i ga1 = _mm_unpackhi_epi8(rg0, ba0); // gagagagaga... const __m128i rb2 = _mm_and_si128(rb1, mask_0xf0); const __m128i ga2 = _mm_srli_epi16(_mm_and_si128(ga1, mask_0xf0), 4); const __m128i rgba4444 = _mm_or_si128(rb2, ga2); _mm_storeu_si128((__m128i*)dst, rgba4444); } // Pack R/G/B results into 16b output. static WEBP_INLINE void PackAndStore565_SSE2(const __m128i* const R, const __m128i* const G, const __m128i* const B, uint8_t* const dst) { const __m128i r0 = _mm_packus_epi16(*R, *R); const __m128i g0 = _mm_packus_epi16(*G, *G); const __m128i b0 = _mm_packus_epi16(*B, *B); const __m128i r1 = _mm_and_si128(r0, _mm_set1_epi8(0xf8)); const __m128i b1 = _mm_and_si128(_mm_srli_epi16(b0, 3), _mm_set1_epi8(0x1f)); const __m128i g1 = _mm_srli_epi16(_mm_and_si128(g0, _mm_set1_epi8(0xe0)), 5); const __m128i g2 = _mm_slli_epi16(_mm_and_si128(g0, _mm_set1_epi8(0x1c)), 3); const __m128i rg = _mm_or_si128(r1, g1); const __m128i gb = _mm_or_si128(g2, b1); #if (WEBP_SWAP_16BIT_CSP == 0) const __m128i rgb565 = _mm_unpacklo_epi8(rg, gb); #else const __m128i rgb565 = _mm_unpacklo_epi8(gb, rg); #endif _mm_storeu_si128((__m128i*)dst, rgb565); } // Pack the planar buffers // rrrr... rrrr... gggg... gggg... bbbb... bbbb.... // triplet by triplet in the output buffer rgb as rgbrgbrgbrgb ... static WEBP_INLINE void PlanarTo24b_SSE2(__m128i* const in0, __m128i* const in1, __m128i* const in2, __m128i* const in3, __m128i* const in4, __m128i* const in5, uint8_t* const rgb) { // The input is 6 registers of sixteen 8b but for the sake of explanation, // let's take 6 registers of four 8b values. // To pack, we will keep taking one every two 8b integer and move it // around as follows: // Input: // r0r1r2r3 | r4r5r6r7 | g0g1g2g3 | g4g5g6g7 | b0b1b2b3 | b4b5b6b7 // Split the 6 registers in two sets of 3 registers: the first set as the even // 8b bytes, the second the odd ones: // r0r2r4r6 | g0g2g4g6 | b0b2b4b6 | r1r3r5r7 | g1g3g5g7 | b1b3b5b7 // Repeat the same permutations twice more: // r0r4g0g4 | b0b4r1r5 | g1g5b1b5 | r2r6g2g6 | b2b6r3r7 | g3g7b3b7 // r0g0b0r1 | g1b1r2g2 | b2r3g3b3 | r4g4b4r5 | g5b5r6g6 | b6r7g7b7 VP8PlanarTo24b(in0, in1, in2, in3, in4, in5); _mm_storeu_si128((__m128i*)(rgb + 0), *in0); _mm_storeu_si128((__m128i*)(rgb + 16), *in1); _mm_storeu_si128((__m128i*)(rgb + 32), *in2); _mm_storeu_si128((__m128i*)(rgb + 48), *in3); _mm_storeu_si128((__m128i*)(rgb + 64), *in4); _mm_storeu_si128((__m128i*)(rgb + 80), *in5); } void VP8YuvToRgba32_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n < 32; n += 8, dst += 32) { __m128i R, G, B; YUV444ToRGB_SSE2(y + n, u + n, v + n, &R, &G, &B); PackAndStore4_SSE2(&R, &G, &B, &kAlpha, dst); } } void VP8YuvToBgra32_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n < 32; n += 8, dst += 32) { __m128i R, G, B; YUV444ToRGB_SSE2(y + n, u + n, v + n, &R, &G, &B); PackAndStore4_SSE2(&B, &G, &R, &kAlpha, dst); } } void VP8YuvToArgb32_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n < 32; n += 8, dst += 32) { __m128i R, G, B; YUV444ToRGB_SSE2(y + n, u + n, v + n, &R, &G, &B); PackAndStore4_SSE2(&kAlpha, &R, &G, &B, dst); } } void VP8YuvToRgba444432_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n < 32; n += 8, dst += 16) { __m128i R, G, B; YUV444ToRGB_SSE2(y + n, u + n, v + n, &R, &G, &B); PackAndStore4444_SSE2(&R, &G, &B, &kAlpha, dst); } } void VP8YuvToRgb56532_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { int n; for (n = 0; n < 32; n += 8, dst += 16) { __m128i R, G, B; YUV444ToRGB_SSE2(y + n, u + n, v + n, &R, &G, &B); PackAndStore565_SSE2(&R, &G, &B, dst); } } void VP8YuvToRgb32_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { __m128i R0, R1, R2, R3, G0, G1, G2, G3, B0, B1, B2, B3; __m128i rgb0, rgb1, rgb2, rgb3, rgb4, rgb5; YUV444ToRGB_SSE2(y + 0, u + 0, v + 0, &R0, &G0, &B0); YUV444ToRGB_SSE2(y + 8, u + 8, v + 8, &R1, &G1, &B1); YUV444ToRGB_SSE2(y + 16, u + 16, v + 16, &R2, &G2, &B2); YUV444ToRGB_SSE2(y + 24, u + 24, v + 24, &R3, &G3, &B3); // Cast to 8b and store as RRRRGGGGBBBB. rgb0 = _mm_packus_epi16(R0, R1); rgb1 = _mm_packus_epi16(R2, R3); rgb2 = _mm_packus_epi16(G0, G1); rgb3 = _mm_packus_epi16(G2, G3); rgb4 = _mm_packus_epi16(B0, B1); rgb5 = _mm_packus_epi16(B2, B3); // Pack as RGBRGBRGBRGB. PlanarTo24b_SSE2(&rgb0, &rgb1, &rgb2, &rgb3, &rgb4, &rgb5, dst); } void VP8YuvToBgr32_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst) { __m128i R0, R1, R2, R3, G0, G1, G2, G3, B0, B1, B2, B3; __m128i bgr0, bgr1, bgr2, bgr3, bgr4, bgr5; YUV444ToRGB_SSE2(y + 0, u + 0, v + 0, &R0, &G0, &B0); YUV444ToRGB_SSE2(y + 8, u + 8, v + 8, &R1, &G1, &B1); YUV444ToRGB_SSE2(y + 16, u + 16, v + 16, &R2, &G2, &B2); YUV444ToRGB_SSE2(y + 24, u + 24, v + 24, &R3, &G3, &B3); // Cast to 8b and store as BBBBGGGGRRRR. bgr0 = _mm_packus_epi16(B0, B1); bgr1 = _mm_packus_epi16(B2, B3); bgr2 = _mm_packus_epi16(G0, G1); bgr3 = _mm_packus_epi16(G2, G3); bgr4 = _mm_packus_epi16(R0, R1); bgr5= _mm_packus_epi16(R2, R3); // Pack as BGRBGRBGRBGR. PlanarTo24b_SSE2(&bgr0, &bgr1, &bgr2, &bgr3, &bgr4, &bgr5, dst); } //----------------------------------------------------------------------------- // Arbitrary-length row conversion functions static void YuvToRgbaRow_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst, int len) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n + 8 <= len; n += 8, dst += 32) { __m128i R, G, B; YUV420ToRGB_SSE2(y, u, v, &R, &G, &B); PackAndStore4_SSE2(&R, &G, &B, &kAlpha, dst); y += 8; u += 4; v += 4; } for (; n < len; ++n) { // Finish off VP8YuvToRgba(y[0], u[0], v[0], dst); dst += 4; y += 1; u += (n & 1); v += (n & 1); } } static void YuvToBgraRow_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst, int len) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n + 8 <= len; n += 8, dst += 32) { __m128i R, G, B; YUV420ToRGB_SSE2(y, u, v, &R, &G, &B); PackAndStore4_SSE2(&B, &G, &R, &kAlpha, dst); y += 8; u += 4; v += 4; } for (; n < len; ++n) { // Finish off VP8YuvToBgra(y[0], u[0], v[0], dst); dst += 4; y += 1; u += (n & 1); v += (n & 1); } } static void YuvToArgbRow_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst, int len) { const __m128i kAlpha = _mm_set1_epi16(255); int n; for (n = 0; n + 8 <= len; n += 8, dst += 32) { __m128i R, G, B; YUV420ToRGB_SSE2(y, u, v, &R, &G, &B); PackAndStore4_SSE2(&kAlpha, &R, &G, &B, dst); y += 8; u += 4; v += 4; } for (; n < len; ++n) { // Finish off VP8YuvToArgb(y[0], u[0], v[0], dst); dst += 4; y += 1; u += (n & 1); v += (n & 1); } } static void YuvToRgbRow_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst, int len) { int n; for (n = 0; n + 32 <= len; n += 32, dst += 32 * 3) { __m128i R0, R1, R2, R3, G0, G1, G2, G3, B0, B1, B2, B3; __m128i rgb0, rgb1, rgb2, rgb3, rgb4, rgb5; YUV420ToRGB_SSE2(y + 0, u + 0, v + 0, &R0, &G0, &B0); YUV420ToRGB_SSE2(y + 8, u + 4, v + 4, &R1, &G1, &B1); YUV420ToRGB_SSE2(y + 16, u + 8, v + 8, &R2, &G2, &B2); YUV420ToRGB_SSE2(y + 24, u + 12, v + 12, &R3, &G3, &B3); // Cast to 8b and store as RRRRGGGGBBBB. rgb0 = _mm_packus_epi16(R0, R1); rgb1 = _mm_packus_epi16(R2, R3); rgb2 = _mm_packus_epi16(G0, G1); rgb3 = _mm_packus_epi16(G2, G3); rgb4 = _mm_packus_epi16(B0, B1); rgb5 = _mm_packus_epi16(B2, B3); // Pack as RGBRGBRGBRGB. PlanarTo24b_SSE2(&rgb0, &rgb1, &rgb2, &rgb3, &rgb4, &rgb5, dst); y += 32; u += 16; v += 16; } for (; n < len; ++n) { // Finish off VP8YuvToRgb(y[0], u[0], v[0], dst); dst += 3; y += 1; u += (n & 1); v += (n & 1); } } static void YuvToBgrRow_SSE2(const uint8_t* y, const uint8_t* u, const uint8_t* v, uint8_t* dst, int len) { int n; for (n = 0; n + 32 <= len; n += 32, dst += 32 * 3) { __m128i R0, R1, R2, R3, G0, G1, G2, G3, B0, B1, B2, B3; __m128i bgr0, bgr1, bgr2, bgr3, bgr4, bgr5; YUV420ToRGB_SSE2(y + 0, u + 0, v + 0, &R0, &G0, &B0); YUV420ToRGB_SSE2(y + 8, u + 4, v + 4, &R1, &G1, &B1); YUV420ToRGB_SSE2(y + 16, u + 8, v + 8, &R2, &G2, &B2); YUV420ToRGB_SSE2(y + 24, u + 12, v + 12, &R3, &G3, &B3); // Cast to 8b and store as BBBBGGGGRRRR. bgr0 = _mm_packus_epi16(B0, B1); bgr1 = _mm_packus_epi16(B2, B3); bgr2 = _mm_packus_epi16(G0, G1); bgr3 = _mm_packus_epi16(G2, G3); bgr4 = _mm_packus_epi16(R0, R1); bgr5 = _mm_packus_epi16(R2, R3); // Pack as BGRBGRBGRBGR. PlanarTo24b_SSE2(&bgr0, &bgr1, &bgr2, &bgr3, &bgr4, &bgr5, dst); y += 32; u += 16; v += 16; } for (; n < len; ++n) { // Finish off VP8YuvToBgr(y[0], u[0], v[0], dst); dst += 3; y += 1; u += (n & 1); v += (n & 1); } } //------------------------------------------------------------------------------ // Entry point extern void WebPInitSamplersSSE2(void); WEBP_TSAN_IGNORE_FUNCTION void WebPInitSamplersSSE2(void) { WebPSamplers[MODE_RGB] = YuvToRgbRow_SSE2; WebPSamplers[MODE_RGBA] = YuvToRgbaRow_SSE2; WebPSamplers[MODE_BGR] = YuvToBgrRow_SSE2; WebPSamplers[MODE_BGRA] = YuvToBgraRow_SSE2; WebPSamplers[MODE_ARGB] = YuvToArgbRow_SSE2; } //------------------------------------------------------------------------------ // RGB24/32 -> YUV converters // Load eight 16b-words from *src. #define LOAD_16(src) _mm_loadu_si128((const __m128i*)(src)) // Store either 16b-words into *dst #define STORE_16(V, dst) _mm_storeu_si128((__m128i*)(dst), (V)) // Function that inserts a value of the second half of the in buffer in between // every two char of the first half. static WEBP_INLINE void RGB24PackedToPlanarHelper_SSE2( const __m128i* const in /*in[6]*/, __m128i* const out /*out[6]*/) { out[0] = _mm_unpacklo_epi8(in[0], in[3]); out[1] = _mm_unpackhi_epi8(in[0], in[3]); out[2] = _mm_unpacklo_epi8(in[1], in[4]); out[3] = _mm_unpackhi_epi8(in[1], in[4]); out[4] = _mm_unpacklo_epi8(in[2], in[5]); out[5] = _mm_unpackhi_epi8(in[2], in[5]); } // Unpack the 8b input rgbrgbrgbrgb ... as contiguous registers: // rrrr... rrrr... gggg... gggg... bbbb... bbbb.... // Similar to PlanarTo24bHelper(), but in reverse order. static WEBP_INLINE void RGB24PackedToPlanar_SSE2( const uint8_t* const rgb, __m128i* const out /*out[6]*/) { __m128i tmp[6]; tmp[0] = _mm_loadu_si128((const __m128i*)(rgb + 0)); tmp[1] = _mm_loadu_si128((const __m128i*)(rgb + 16)); tmp[2] = _mm_loadu_si128((const __m128i*)(rgb + 32)); tmp[3] = _mm_loadu_si128((const __m128i*)(rgb + 48)); tmp[4] = _mm_loadu_si128((const __m128i*)(rgb + 64)); tmp[5] = _mm_loadu_si128((const __m128i*)(rgb + 80)); RGB24PackedToPlanarHelper_SSE2(tmp, out); RGB24PackedToPlanarHelper_SSE2(out, tmp); RGB24PackedToPlanarHelper_SSE2(tmp, out); RGB24PackedToPlanarHelper_SSE2(out, tmp); RGB24PackedToPlanarHelper_SSE2(tmp, out); } // Convert 8 packed ARGB to r[], g[], b[] static WEBP_INLINE void RGB32PackedToPlanar_SSE2(const uint32_t* const argb, __m128i* const rgb /*in[6]*/) { const __m128i zero = _mm_setzero_si128(); __m128i a0 = LOAD_16(argb + 0); __m128i a1 = LOAD_16(argb + 4); __m128i a2 = LOAD_16(argb + 8); __m128i a3 = LOAD_16(argb + 12); VP8L32bToPlanar(&a0, &a1, &a2, &a3); rgb[0] = _mm_unpacklo_epi8(a1, zero); rgb[1] = _mm_unpackhi_epi8(a1, zero); rgb[2] = _mm_unpacklo_epi8(a2, zero); rgb[3] = _mm_unpackhi_epi8(a2, zero); rgb[4] = _mm_unpacklo_epi8(a3, zero); rgb[5] = _mm_unpackhi_epi8(a3, zero); } // This macro computes (RG * MULT_RG + GB * MULT_GB + ROUNDER) >> DESCALE_FIX // It's a macro and not a function because we need to use immediate values with // srai_epi32, e.g. #define TRANSFORM(RG_LO, RG_HI, GB_LO, GB_HI, MULT_RG, MULT_GB, \ ROUNDER, DESCALE_FIX, OUT) do { \ const __m128i V0_lo = _mm_madd_epi16(RG_LO, MULT_RG); \ const __m128i V0_hi = _mm_madd_epi16(RG_HI, MULT_RG); \ const __m128i V1_lo = _mm_madd_epi16(GB_LO, MULT_GB); \ const __m128i V1_hi = _mm_madd_epi16(GB_HI, MULT_GB); \ const __m128i V2_lo = _mm_add_epi32(V0_lo, V1_lo); \ const __m128i V2_hi = _mm_add_epi32(V0_hi, V1_hi); \ const __m128i V3_lo = _mm_add_epi32(V2_lo, ROUNDER); \ const __m128i V3_hi = _mm_add_epi32(V2_hi, ROUNDER); \ const __m128i V5_lo = _mm_srai_epi32(V3_lo, DESCALE_FIX); \ const __m128i V5_hi = _mm_srai_epi32(V3_hi, DESCALE_FIX); \ (OUT) = _mm_packs_epi32(V5_lo, V5_hi); \ } while (0) #define MK_CST_16(A, B) _mm_set_epi16((B), (A), (B), (A), (B), (A), (B), (A)) static WEBP_INLINE void ConvertRGBToY_SSE2(const __m128i* const R, const __m128i* const G, const __m128i* const B, __m128i* const Y) { const __m128i kRG_y = MK_CST_16(16839, 33059 - 16384); const __m128i kGB_y = MK_CST_16(16384, 6420); const __m128i kHALF_Y = _mm_set1_epi32((16 << YUV_FIX) + YUV_HALF); const __m128i RG_lo = _mm_unpacklo_epi16(*R, *G); const __m128i RG_hi = _mm_unpackhi_epi16(*R, *G); const __m128i GB_lo = _mm_unpacklo_epi16(*G, *B); const __m128i GB_hi = _mm_unpackhi_epi16(*G, *B); TRANSFORM(RG_lo, RG_hi, GB_lo, GB_hi, kRG_y, kGB_y, kHALF_Y, YUV_FIX, *Y); } static WEBP_INLINE void ConvertRGBToUV_SSE2(const __m128i* const R, const __m128i* const G, const __m128i* const B, __m128i* const U, __m128i* const V) { const __m128i kRG_u = MK_CST_16(-9719, -19081); const __m128i kGB_u = MK_CST_16(0, 28800); const __m128i kRG_v = MK_CST_16(28800, 0); const __m128i kGB_v = MK_CST_16(-24116, -4684); const __m128i kHALF_UV = _mm_set1_epi32(((128 << YUV_FIX) + YUV_HALF) << 2); const __m128i RG_lo = _mm_unpacklo_epi16(*R, *G); const __m128i RG_hi = _mm_unpackhi_epi16(*R, *G); const __m128i GB_lo = _mm_unpacklo_epi16(*G, *B); const __m128i GB_hi = _mm_unpackhi_epi16(*G, *B); TRANSFORM(RG_lo, RG_hi, GB_lo, GB_hi, kRG_u, kGB_u, kHALF_UV, YUV_FIX + 2, *U); TRANSFORM(RG_lo, RG_hi, GB_lo, GB_hi, kRG_v, kGB_v, kHALF_UV, YUV_FIX + 2, *V); } #undef MK_CST_16 #undef TRANSFORM static void ConvertRGB24ToY_SSE2(const uint8_t* rgb, uint8_t* y, int width) { const int max_width = width & ~31; int i; for (i = 0; i < max_width; rgb += 3 * 16 * 2) { __m128i rgb_plane[6]; int j; RGB24PackedToPlanar_SSE2(rgb, rgb_plane); for (j = 0; j < 2; ++j, i += 16) { const __m128i zero = _mm_setzero_si128(); __m128i r, g, b, Y0, Y1; // Convert to 16-bit Y. r = _mm_unpacklo_epi8(rgb_plane[0 + j], zero); g = _mm_unpacklo_epi8(rgb_plane[2 + j], zero); b = _mm_unpacklo_epi8(rgb_plane[4 + j], zero); ConvertRGBToY_SSE2(&r, &g, &b, &Y0); // Convert to 16-bit Y. r = _mm_unpackhi_epi8(rgb_plane[0 + j], zero); g = _mm_unpackhi_epi8(rgb_plane[2 + j], zero); b = _mm_unpackhi_epi8(rgb_plane[4 + j], zero); ConvertRGBToY_SSE2(&r, &g, &b, &Y1); // Cast to 8-bit and store. STORE_16(_mm_packus_epi16(Y0, Y1), y + i); } } for (; i < width; ++i, rgb += 3) { // left-over y[i] = VP8RGBToY(rgb[0], rgb[1], rgb[2], YUV_HALF); } } static void ConvertBGR24ToY_SSE2(const uint8_t* bgr, uint8_t* y, int width) { const int max_width = width & ~31; int i; for (i = 0; i < max_width; bgr += 3 * 16 * 2) { __m128i bgr_plane[6]; int j; RGB24PackedToPlanar_SSE2(bgr, bgr_plane); for (j = 0; j < 2; ++j, i += 16) { const __m128i zero = _mm_setzero_si128(); __m128i r, g, b, Y0, Y1; // Convert to 16-bit Y. b = _mm_unpacklo_epi8(bgr_plane[0 + j], zero); g = _mm_unpacklo_epi8(bgr_plane[2 + j], zero); r = _mm_unpacklo_epi8(bgr_plane[4 + j], zero); ConvertRGBToY_SSE2(&r, &g, &b, &Y0); // Convert to 16-bit Y. b = _mm_unpackhi_epi8(bgr_plane[0 + j], zero); g = _mm_unpackhi_epi8(bgr_plane[2 + j], zero); r = _mm_unpackhi_epi8(bgr_plane[4 + j], zero); ConvertRGBToY_SSE2(&r, &g, &b, &Y1); // Cast to 8-bit and store. STORE_16(_mm_packus_epi16(Y0, Y1), y + i); } } for (; i < width; ++i, bgr += 3) { // left-over y[i] = VP8RGBToY(bgr[2], bgr[1], bgr[0], YUV_HALF); } } static void ConvertARGBToY_SSE2(const uint32_t* argb, uint8_t* y, int width) { const int max_width = width & ~15; int i; for (i = 0; i < max_width; i += 16) { __m128i Y0, Y1, rgb[6]; RGB32PackedToPlanar_SSE2(&argb[i], rgb); ConvertRGBToY_SSE2(&rgb[0], &rgb[2], &rgb[4], &Y0); ConvertRGBToY_SSE2(&rgb[1], &rgb[3], &rgb[5], &Y1); STORE_16(_mm_packus_epi16(Y0, Y1), y + i); } for (; i < width; ++i) { // left-over const uint32_t p = argb[i]; y[i] = VP8RGBToY((p >> 16) & 0xff, (p >> 8) & 0xff, (p >> 0) & 0xff, YUV_HALF); } } // Horizontal add (doubled) of two 16b values, result is 16b. // in: A | B | C | D | ... -> out: 2*(A+B) | 2*(C+D) | ... static void HorizontalAddPack_SSE2(const __m128i* const A, const __m128i* const B, __m128i* const out) { const __m128i k2 = _mm_set1_epi16(2); const __m128i C = _mm_madd_epi16(*A, k2); const __m128i D = _mm_madd_epi16(*B, k2); *out = _mm_packs_epi32(C, D); } static void ConvertARGBToUV_SSE2(const uint32_t* argb, uint8_t* u, uint8_t* v, int src_width, int do_store) { const int max_width = src_width & ~31; int i; for (i = 0; i < max_width; i += 32, u += 16, v += 16) { __m128i rgb[6], U0, V0, U1, V1; RGB32PackedToPlanar_SSE2(&argb[i], rgb); HorizontalAddPack_SSE2(&rgb[0], &rgb[1], &rgb[0]); HorizontalAddPack_SSE2(&rgb[2], &rgb[3], &rgb[2]); HorizontalAddPack_SSE2(&rgb[4], &rgb[5], &rgb[4]); ConvertRGBToUV_SSE2(&rgb[0], &rgb[2], &rgb[4], &U0, &V0); RGB32PackedToPlanar_SSE2(&argb[i + 16], rgb); HorizontalAddPack_SSE2(&rgb[0], &rgb[1], &rgb[0]); HorizontalAddPack_SSE2(&rgb[2], &rgb[3], &rgb[2]); HorizontalAddPack_SSE2(&rgb[4], &rgb[5], &rgb[4]); ConvertRGBToUV_SSE2(&rgb[0], &rgb[2], &rgb[4], &U1, &V1); U0 = _mm_packus_epi16(U0, U1); V0 = _mm_packus_epi16(V0, V1); if (!do_store) { const __m128i prev_u = LOAD_16(u); const __m128i prev_v = LOAD_16(v); U0 = _mm_avg_epu8(U0, prev_u); V0 = _mm_avg_epu8(V0, prev_v); } STORE_16(U0, u); STORE_16(V0, v); } if (i < src_width) { // left-over WebPConvertARGBToUV_C(argb + i, u, v, src_width - i, do_store); } } // Convert 16 packed ARGB 16b-values to r[], g[], b[] static WEBP_INLINE void RGBA32PackedToPlanar_16b_SSE2( const uint16_t* const rgbx, __m128i* const r, __m128i* const g, __m128i* const b) { const __m128i in0 = LOAD_16(rgbx + 0); // r0 | g0 | b0 |x| r1 | g1 | b1 |x const __m128i in1 = LOAD_16(rgbx + 8); // r2 | g2 | b2 |x| r3 | g3 | b3 |x const __m128i in2 = LOAD_16(rgbx + 16); // r4 | ... const __m128i in3 = LOAD_16(rgbx + 24); // r6 | ... // column-wise transpose const __m128i A0 = _mm_unpacklo_epi16(in0, in1); const __m128i A1 = _mm_unpackhi_epi16(in0, in1); const __m128i A2 = _mm_unpacklo_epi16(in2, in3); const __m128i A3 = _mm_unpackhi_epi16(in2, in3); const __m128i B0 = _mm_unpacklo_epi16(A0, A1); // r0 r1 r2 r3 | g0 g1 .. const __m128i B1 = _mm_unpackhi_epi16(A0, A1); // b0 b1 b2 b3 | x x x x const __m128i B2 = _mm_unpacklo_epi16(A2, A3); // r4 r5 r6 r7 | g4 g5 .. const __m128i B3 = _mm_unpackhi_epi16(A2, A3); // b4 b5 b6 b7 | x x x x *r = _mm_unpacklo_epi64(B0, B2); *g = _mm_unpackhi_epi64(B0, B2); *b = _mm_unpacklo_epi64(B1, B3); } static void ConvertRGBA32ToUV_SSE2(const uint16_t* rgb, uint8_t* u, uint8_t* v, int width) { const int max_width = width & ~15; const uint16_t* const last_rgb = rgb + 4 * max_width; while (rgb < last_rgb) { __m128i r, g, b, U0, V0, U1, V1; RGBA32PackedToPlanar_16b_SSE2(rgb + 0, &r, &g, &b); ConvertRGBToUV_SSE2(&r, &g, &b, &U0, &V0); RGBA32PackedToPlanar_16b_SSE2(rgb + 32, &r, &g, &b); ConvertRGBToUV_SSE2(&r, &g, &b, &U1, &V1); STORE_16(_mm_packus_epi16(U0, U1), u); STORE_16(_mm_packus_epi16(V0, V1), v); u += 16; v += 16; rgb += 2 * 32; } if (max_width < width) { // left-over WebPConvertRGBA32ToUV_C(rgb, u, v, width - max_width); } } //------------------------------------------------------------------------------ extern void WebPInitConvertARGBToYUVSSE2(void); WEBP_TSAN_IGNORE_FUNCTION void WebPInitConvertARGBToYUVSSE2(void) { WebPConvertARGBToY = ConvertARGBToY_SSE2; WebPConvertARGBToUV = ConvertARGBToUV_SSE2; WebPConvertRGB24ToY = ConvertRGB24ToY_SSE2; WebPConvertBGR24ToY = ConvertBGR24ToY_SSE2; WebPConvertRGBA32ToUV = ConvertRGBA32ToUV_SSE2; } //------------------------------------------------------------------------------ #define MAX_Y ((1 << 10) - 1) // 10b precision over 16b-arithmetic static uint16_t clip_y(int v) { return (v < 0) ? 0 : (v > MAX_Y) ? MAX_Y : (uint16_t)v; } static uint64_t SharpYUVUpdateY_SSE2(const uint16_t* ref, const uint16_t* src, uint16_t* dst, int len) { uint64_t diff = 0; uint32_t tmp[4]; int i; const __m128i zero = _mm_setzero_si128(); const __m128i max = _mm_set1_epi16(MAX_Y); const __m128i one = _mm_set1_epi16(1); __m128i sum = zero; for (i = 0; i + 8 <= len; i += 8) { const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i)); const __m128i B = _mm_loadu_si128((const __m128i*)(src + i)); const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i)); const __m128i D = _mm_sub_epi16(A, B); // diff_y const __m128i E = _mm_cmpgt_epi16(zero, D); // sign (-1 or 0) const __m128i F = _mm_add_epi16(C, D); // new_y const __m128i G = _mm_or_si128(E, one); // -1 or 1 const __m128i H = _mm_max_epi16(_mm_min_epi16(F, max), zero); const __m128i I = _mm_madd_epi16(D, G); // sum(abs(...)) _mm_storeu_si128((__m128i*)(dst + i), H); sum = _mm_add_epi32(sum, I); } _mm_storeu_si128((__m128i*)tmp, sum); diff = tmp[3] + tmp[2] + tmp[1] + tmp[0]; for (; i < len; ++i) { const int diff_y = ref[i] - src[i]; const int new_y = (int)dst[i] + diff_y; dst[i] = clip_y(new_y); diff += (uint64_t)abs(diff_y); } return diff; } static void SharpYUVUpdateRGB_SSE2(const int16_t* ref, const int16_t* src, int16_t* dst, int len) { int i = 0; for (i = 0; i + 8 <= len; i += 8) { const __m128i A = _mm_loadu_si128((const __m128i*)(ref + i)); const __m128i B = _mm_loadu_si128((const __m128i*)(src + i)); const __m128i C = _mm_loadu_si128((const __m128i*)(dst + i)); const __m128i D = _mm_sub_epi16(A, B); // diff_uv const __m128i E = _mm_add_epi16(C, D); // new_uv _mm_storeu_si128((__m128i*)(dst + i), E); } for (; i < len; ++i) { const int diff_uv = ref[i] - src[i]; dst[i] += diff_uv; } } static void SharpYUVFilterRow_SSE2(const int16_t* A, const int16_t* B, int len, const uint16_t* best_y, uint16_t* out) { int i; const __m128i kCst8 = _mm_set1_epi16(8); const __m128i max = _mm_set1_epi16(MAX_Y); const __m128i zero = _mm_setzero_si128(); for (i = 0; i + 8 <= len; i += 8) { const __m128i a0 = _mm_loadu_si128((const __m128i*)(A + i + 0)); const __m128i a1 = _mm_loadu_si128((const __m128i*)(A + i + 1)); const __m128i b0 = _mm_loadu_si128((const __m128i*)(B + i + 0)); const __m128i b1 = _mm_loadu_si128((const __m128i*)(B + i + 1)); const __m128i a0b1 = _mm_add_epi16(a0, b1); const __m128i a1b0 = _mm_add_epi16(a1, b0); const __m128i a0a1b0b1 = _mm_add_epi16(a0b1, a1b0); // A0+A1+B0+B1 const __m128i a0a1b0b1_8 = _mm_add_epi16(a0a1b0b1, kCst8); const __m128i a0b1_2 = _mm_add_epi16(a0b1, a0b1); // 2*(A0+B1) const __m128i a1b0_2 = _mm_add_epi16(a1b0, a1b0); // 2*(A1+B0) const __m128i c0 = _mm_srai_epi16(_mm_add_epi16(a0b1_2, a0a1b0b1_8), 3); const __m128i c1 = _mm_srai_epi16(_mm_add_epi16(a1b0_2, a0a1b0b1_8), 3); const __m128i d0 = _mm_add_epi16(c1, a0); const __m128i d1 = _mm_add_epi16(c0, a1); const __m128i e0 = _mm_srai_epi16(d0, 1); const __m128i e1 = _mm_srai_epi16(d1, 1); const __m128i f0 = _mm_unpacklo_epi16(e0, e1); const __m128i f1 = _mm_unpackhi_epi16(e0, e1); const __m128i g0 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 0)); const __m128i g1 = _mm_loadu_si128((const __m128i*)(best_y + 2 * i + 8)); const __m128i h0 = _mm_add_epi16(g0, f0); const __m128i h1 = _mm_add_epi16(g1, f1); const __m128i i0 = _mm_max_epi16(_mm_min_epi16(h0, max), zero); const __m128i i1 = _mm_max_epi16(_mm_min_epi16(h1, max), zero); _mm_storeu_si128((__m128i*)(out + 2 * i + 0), i0); _mm_storeu_si128((__m128i*)(out + 2 * i + 8), i1); } for (; i < len; ++i) { // (9 * A0 + 3 * A1 + 3 * B0 + B1 + 8) >> 4 = // = (8 * A0 + 2 * (A1 + B0) + (A0 + A1 + B0 + B1 + 8)) >> 4 // We reuse the common sub-expressions. const int a0b1 = A[i + 0] + B[i + 1]; const int a1b0 = A[i + 1] + B[i + 0]; const int a0a1b0b1 = a0b1 + a1b0 + 8; const int v0 = (8 * A[i + 0] + 2 * a1b0 + a0a1b0b1) >> 4; const int v1 = (8 * A[i + 1] + 2 * a0b1 + a0a1b0b1) >> 4; out[2 * i + 0] = clip_y(best_y[2 * i + 0] + v0); out[2 * i + 1] = clip_y(best_y[2 * i + 1] + v1); } } #undef MAX_Y //------------------------------------------------------------------------------ extern void WebPInitSharpYUVSSE2(void); WEBP_TSAN_IGNORE_FUNCTION void WebPInitSharpYUVSSE2(void) { WebPSharpYUVUpdateY = SharpYUVUpdateY_SSE2; WebPSharpYUVUpdateRGB = SharpYUVUpdateRGB_SSE2; WebPSharpYUVFilterRow = SharpYUVFilterRow_SSE2; } #else // !WEBP_USE_SSE2 WEBP_DSP_INIT_STUB(WebPInitSamplersSSE2) WEBP_DSP_INIT_STUB(WebPInitConvertARGBToYUVSSE2) WEBP_DSP_INIT_STUB(WebPInitSharpYUVSSE2) #endif // WEBP_USE_SSE2
18,313
1,232
<reponame>congduy/gopropyapi from goprocam import GoProCamera from goprocam import constants import time gpCam = GoProCamera.GoPro(constants.auth) gpCam.overview() gpCam.listMedia(True)
65
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.quota.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.quota.fluent.models.QuotaRequestDetailsInner; /** An instance of this class provides access to all the operations defined in QuotaRequestStatusClient. */ public interface QuotaRequestStatusClient { /** * Get the quota request details and status by quota request ID for the resources of the resource provider at a * specific location. The quota request ID **id** is returned in the response of the PUT operation. * * @param id Quota request ID. * @param scope The target Azure resource URI. For example, * `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`. * This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after * `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the quota request details and status by quota request ID for the resources of the resource provider at a * specific location. */ @ServiceMethod(returns = ReturnType.SINGLE) QuotaRequestDetailsInner get(String id, String scope); /** * Get the quota request details and status by quota request ID for the resources of the resource provider at a * specific location. The quota request ID **id** is returned in the response of the PUT operation. * * @param id Quota request ID. * @param scope The target Azure resource URI. For example, * `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`. * This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after * `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the quota request details and status by quota request ID for the resources of the resource provider at a * specific location. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<QuotaRequestDetailsInner> getWithResponse(String id, String scope, Context context); /** * For the specified scope, get the current quota requests for a one year period ending at the time is made. Use the * **oData** filter to select quota requests. * * @param scope The target Azure resource URI. For example, * `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`. * This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after * `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return quota request information. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<QuotaRequestDetailsInner> list(String scope); /** * For the specified scope, get the current quota requests for a one year period ending at the time is made. Use the * **oData** filter to select quota requests. * * @param scope The target Azure resource URI. For example, * `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`. * This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after * `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource. * @param filter | Field | Supported operators |---------------------|------------------------ * <p>|requestSubmitTime | ge, le, eq, gt, lt |provisioningState eq {QuotaRequestState} |resourceName eq * {resourceName}. * @param top Number of records to return. * @param skiptoken The **Skiptoken** parameter is used only if a previous operation returned a partial result. If a * previous response contains a **nextLink** element, its value includes a **skiptoken** parameter that * specifies a starting point to use for subsequent calls. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return quota request information. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<QuotaRequestDetailsInner> list( String scope, String filter, Integer top, String skiptoken, Context context); }
1,828
1,099
package com.example.chat.bean; import com.example.commonlibrary.bean.chat.User; import cn.bmob.v3.BmobObject; /** * 项目名称: NewFastFrame * 创建人: 陈锦军 * 创建时间: 2018/6/18 12:16 * QQ:1981367757 */ public class StepBean extends BmobObject{ private User user; private String time; private Integer stepCount; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void setStepCount(Integer stepCount) { this.stepCount = stepCount; } public Integer getStepCount() { return stepCount; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
347
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.models; import com.azure.core.util.Context; import com.azure.resourcemanager.datafactory.fluent.models.ManagedVirtualNetworkResourceInner; /** An immutable client-side representation of ManagedVirtualNetworkResource. */ public interface ManagedVirtualNetworkResource { /** * Gets the id property: Fully qualified resource Id for the resource. * * @return the id value. */ String id(); /** * Gets the properties property: Managed Virtual Network properties. * * @return the properties value. */ ManagedVirtualNetwork properties(); /** * Gets the name property: The resource name. * * @return the name value. */ String name(); /** * Gets the type property: The resource type. * * @return the type value. */ String type(); /** * Gets the etag property: Etag identifies change in the resource. * * @return the etag value. */ String etag(); /** * Gets the inner com.azure.resourcemanager.datafactory.fluent.models.ManagedVirtualNetworkResourceInner object. * * @return the inner object. */ ManagedVirtualNetworkResourceInner innerModel(); /** The entirety of the ManagedVirtualNetworkResource definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithProperties, DefinitionStages.WithCreate { } /** The ManagedVirtualNetworkResource definition stages. */ interface DefinitionStages { /** The first stage of the ManagedVirtualNetworkResource definition. */ interface Blank extends WithParentResource { } /** The stage of the ManagedVirtualNetworkResource definition allowing to specify parent resource. */ interface WithParentResource { /** * Specifies resourceGroupName, factoryName. * * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @return the next definition stage. */ WithProperties withExistingFactory(String resourceGroupName, String factoryName); } /** The stage of the ManagedVirtualNetworkResource definition allowing to specify properties. */ interface WithProperties { /** * Specifies the properties property: Managed Virtual Network properties.. * * @param properties Managed Virtual Network properties. * @return the next definition stage. */ WithCreate withProperties(ManagedVirtualNetwork properties); } /** * The stage of the ManagedVirtualNetworkResource definition which contains all the minimum required properties * for the resource to be created, but also allows for any other optional properties to be specified. */ interface WithCreate extends DefinitionStages.WithIfMatch { /** * Executes the create request. * * @return the created resource. */ ManagedVirtualNetworkResource create(); /** * Executes the create request. * * @param context The context to associate with this operation. * @return the created resource. */ ManagedVirtualNetworkResource create(Context context); } /** The stage of the ManagedVirtualNetworkResource definition allowing to specify ifMatch. */ interface WithIfMatch { /** * Specifies the ifMatch property: ETag of the managed Virtual Network entity. Should only be specified for * update, for which it should match existing entity or can be * for unconditional update.. * * @param ifMatch ETag of the managed Virtual Network entity. Should only be specified for update, for which * it should match existing entity or can be * for unconditional update. * @return the next definition stage. */ WithCreate withIfMatch(String ifMatch); } } /** * Begins update for the ManagedVirtualNetworkResource resource. * * @return the stage of resource update. */ ManagedVirtualNetworkResource.Update update(); /** The template for ManagedVirtualNetworkResource update. */ interface Update extends UpdateStages.WithProperties, UpdateStages.WithIfMatch { /** * Executes the update request. * * @return the updated resource. */ ManagedVirtualNetworkResource apply(); /** * Executes the update request. * * @param context The context to associate with this operation. * @return the updated resource. */ ManagedVirtualNetworkResource apply(Context context); } /** The ManagedVirtualNetworkResource update stages. */ interface UpdateStages { /** The stage of the ManagedVirtualNetworkResource update allowing to specify properties. */ interface WithProperties { /** * Specifies the properties property: Managed Virtual Network properties.. * * @param properties Managed Virtual Network properties. * @return the next definition stage. */ Update withProperties(ManagedVirtualNetwork properties); } /** The stage of the ManagedVirtualNetworkResource update allowing to specify ifMatch. */ interface WithIfMatch { /** * Specifies the ifMatch property: ETag of the managed Virtual Network entity. Should only be specified for * update, for which it should match existing entity or can be * for unconditional update.. * * @param ifMatch ETag of the managed Virtual Network entity. Should only be specified for update, for which * it should match existing entity or can be * for unconditional update. * @return the next definition stage. */ Update withIfMatch(String ifMatch); } } /** * Refreshes the resource to sync with Azure. * * @return the refreshed resource. */ ManagedVirtualNetworkResource refresh(); /** * Refreshes the resource to sync with Azure. * * @param context The context to associate with this operation. * @return the refreshed resource. */ ManagedVirtualNetworkResource refresh(Context context); }
2,522
645
// 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. package org.chromium.distiller.document; /** * Provides shallow statistics on a given TextDocument. */ public final class TextDocumentStatistics { /** * @return the sum of number of words in content blocks. */ public static int countWordsInContent(TextDocument document) { int numWords = 0; for (TextBlock tb : document.getTextBlocks()) { if (tb.isContent()) numWords += tb.getNumWords(); } return numWords; } private TextDocumentStatistics() { } }
233
3,337
#include "universe.h" #include <tbb/task_scheduler_init.h> #include <tbb/flow_graph.h> #include <tbb/partitioner.h> #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> struct UpdateStressBody { Universe & u_; UpdateStressBody(Universe & u):u_(u){} void operator()( const tbb::blocked_range<int>& range ) const { u_.UpdateStress(Universe::Rectangle(0, range.begin(), u_.UniverseWidth-1, range.size())); } }; struct UpdateVelocityBody { Universe & u_; UpdateVelocityBody(Universe & u):u_(u){} void operator()( const tbb::blocked_range<int>& y_range ) const { u_.UpdateVelocity(Universe::Rectangle(1, y_range.begin(), u_.UniverseWidth-1, y_range.size())); } }; // the wavefront computation void seismic_tbb(unsigned num_threads, unsigned num_frames, Universe& u) { using namespace tbb; using namespace tbb::flow; tbb::task_scheduler_init init(num_threads); static tbb::affinity_partitioner affinity; for(unsigned i=0u; i<num_frames; ++i ) { u.UpdatePulse(); tbb::parallel_for(tbb::blocked_range<int>( 0, u.UniverseHeight-1 ), // Index space for loop UpdateStressBody(u), // Body of loop affinity); // Affinity hint tbb::parallel_for(tbb::blocked_range<int>( 1, u.UniverseHeight ), // Index space for loop UpdateVelocityBody(u), // Body of loop affinity); // Affinity hint } } std::chrono::microseconds measure_time_tbb(unsigned num_threads, unsigned num_frames, Universe& u) { auto beg = std::chrono::high_resolution_clock::now(); seismic_tbb(num_threads, num_frames, u); auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>(end - beg); }
820
7,407
<gh_stars>1000+ /* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ //open a log file void Log_Open(char *filename); //close the current log file void Log_Close(void); //close log file if present void Log_Shutdown(void); //print on stdout and write to the current opened log file void Log_Print(char *fmt, ...); //write to the current opened log file void Log_Write(char *fmt, ...); //write to the current opened log file with a time stamp void Log_WriteTimeStamped(char *fmt, ...); //returns the log file structure FILE *Log_FileStruct(void); //flush log file void Log_Flush(void); #ifdef WINBSPC void WinBSPCPrint(char *str); #endif //WINBSPC
408
688
<reponame>AhmedLeithy/Recognizers-Text # ------------------------------------------------------------------------------ # <auto-generated> # This code was generated by a tool. # Changes to this file may cause incorrect behavior and will be lost if # the code is regenerated. # </auto-generated> # # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ # pylint: disable=line-too-long class BaseGUID: GUIDRegexElement = f'(([a-f0-9]{{8}}(-[a-f0-9]{{4}}){{3}}-[a-f0-9]{{12}})|([a-f0-9]{{32}}))' GUIDRegex = f'(\\b{GUIDRegexElement}\\b|\\{{{GUIDRegexElement}\\}}|urn:uuid:{GUIDRegexElement}\\b|%7[b]{GUIDRegexElement}%7[d]|[x]\\\'{GUIDRegexElement}\\\')' # pylint: enable=line-too-long
290
6,450
{ "title": { "zh": "中文分类", "en": "Category" }, "demos": [ { "filename": "gold.jsx", "title": "某黄金实时金价走势图", "screenshot": "https://gw.alipayobjects.com/zos/rmsportal/nhKcpmYFRYcSeQgTQSZW.png" }, { "filename": "dynamic.jsx", "title": "实时折线", "screenshot": "https://gw.alipayobjects.com/zos/rmsportal/McevuIUuSZcUbkBEOGRc.gif" } ] }
251
18,450
<reponame>shanyao19940801/Java-Interview package com.crossoverjie.algorithm; import com.crossoverjie.algorithm.MergeTwoSortedLists.ListNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class MergeTwoSortedListsTest { MergeTwoSortedLists mergeTwoSortedLists ; @Before public void setUp() throws Exception { mergeTwoSortedLists = new MergeTwoSortedLists(); } @Test public void mergeTwoLists() throws Exception { ListNode l1 = new ListNode(1) ; ListNode l1_2 = new ListNode(4); l1.next = l1_2 ; ListNode l1_3 = new ListNode(5) ; l1_2.next = l1_3 ; ListNode l2 = new ListNode(1) ; ListNode l2_2 = new ListNode(3) ; l2.next = l2_2 ; ListNode l2_3 = new ListNode(6) ; l2_2.next = l2_3 ; ListNode l2_4 = new ListNode(9) ; l2_3.next = l2_4 ; ListNode listNode = mergeTwoSortedLists.mergeTwoLists(l1, l2); ListNode node1 = new ListNode(1) ; ListNode node2 = new ListNode(1); node1.next = node2; ListNode node3 = new ListNode(3) ; node2.next= node3 ; ListNode node4 = new ListNode(4) ; node3.next = node4 ; ListNode node5 = new ListNode(5) ; node4.next = node5 ; ListNode node6 = new ListNode(6) ; node5.next = node6 ; ListNode node7 = new ListNode(9) ; node6.next = node7 ; Assert.assertEquals(node1.toString(),listNode.toString()); } @Test public void mergeTwoLists2() throws Exception { ListNode l2 = new ListNode(1) ; ListNode l2_2 = new ListNode(3) ; l2.next = l2_2 ; ListNode l2_3 = new ListNode(6) ; l2_2.next = l2_3 ; ListNode l2_4 = new ListNode(9) ; l2_3.next = l2_4 ; ListNode listNode = mergeTwoSortedLists.mergeTwoLists(null, l2); System.out.println(listNode.toString()); } @Test public void mergeTwoLists3() throws Exception { ListNode l2 = new ListNode(1) ; ListNode l2_2 = new ListNode(3) ; l2.next = l2_2 ; ListNode l2_3 = new ListNode(6) ; l2_2.next = l2_3 ; ListNode l2_4 = new ListNode(9) ; l2_3.next = l2_4 ; ListNode listNode = mergeTwoSortedLists.mergeTwoLists(l2, null); ListNode node1 = new ListNode(1) ; ListNode node2 = new ListNode(3); node1.next = node2; ListNode node3 = new ListNode(6) ; node2.next= node3 ; ListNode node4 = new ListNode(9) ; node3.next = node4 ; Assert.assertEquals(node1.toString(),listNode.toString()); } }
1,301
435
<filename>europython-2013/videos/a-mleczko-lost-in-oauth-learn-velruse-and-get-your-life-back.json { "copyright_text": null, "description": "", "duration": 1608, "language": "eng", "recorded": "2013-07-03", "related_urls": [ { "label": "Conference schedule", "url": "https://www.pycon.it/en/ep2013/" } ], "speakers": [ "<NAME>" ], "tags": [ "web", "pyramid", "HTTP", "open-source", "case-study" ], "thumbnail_url": "https://i.ytimg.com/vi/a-mzJ7wFIcA/hqdefault.jpg", "title": "Lost in OAuth? Learn Velruse And Get Your Life Back!", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=a-mzJ7wFIcA" } ] }
339
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_NAVIGATION_CONTROLLER_CONSTANTS_H_ #define IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_NAVIGATION_CONTROLLER_CONSTANTS_H_ #import <Foundation/Foundation.h> // Vertical offset from the top, to center search bar and cancel button in the // header. extern const float kTableViewNavigationVerticalOffsetForSearchHeader; // The Alpha value used by the SearchBar when disabled. extern const float kTableViewNavigationAlphaForDisabledSearchBar; // The duration for scrim to fade in or out. extern const NSTimeInterval kTableViewNavigationScrimFadeDuration; // Accessibility ID for the "Done" button on TableView NavigationController bar. extern NSString* const kTableViewNavigationDismissButtonId; #endif // IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_NAVIGATION_CONTROLLER_CONSTANTS_H_
341
416
package org.simpleflatmapper.util.date; public interface DateFormatSupplier { String get(); }
31
716
<gh_stars>100-1000 /* * * Copyright 2011 Netflix, 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. * */ package com.netflix.exhibitor.application; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.netflix.exhibitor.servlet.ExhibitorServletFilter; import com.sun.jersey.spi.container.servlet.ServletContainer; import com.netflix.exhibitor.core.Exhibitor; import com.netflix.exhibitor.core.ExhibitorArguments; import com.netflix.exhibitor.core.RemoteConnectionConfiguration; import com.netflix.exhibitor.core.backup.BackupProvider; import com.netflix.exhibitor.core.config.ConfigProvider; import com.netflix.exhibitor.core.rest.UIContext; import com.netflix.exhibitor.core.rest.jersey.JerseySupport; import com.netflix.exhibitor.standalone.ExhibitorCreator; import com.netflix.exhibitor.standalone.ExhibitorCreatorExit; import com.netflix.exhibitor.standalone.SecurityArguments; import com.sun.jersey.api.client.filter.ClientFilter; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter; import com.sun.jersey.api.core.DefaultResourceConfig; import org.apache.curator.utils.CloseableUtils; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.handler.ContextHandler; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.SecurityHandler; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.jetty.webapp.WebXmlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; public class ExhibitorMain implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final Server server; private final AtomicBoolean isClosed = new AtomicBoolean(false); private final Exhibitor exhibitor; private final AtomicBoolean shutdownSignaled = new AtomicBoolean(false); private final Map<String, String> users = Maps.newHashMap(); public static void main(String[] args) throws Exception { ExhibitorCreator creator; try { creator = new ExhibitorCreator(args); } catch ( ExhibitorCreatorExit exit ) { if ( exit.getError() != null ) { System.err.println(exit.getError()); } exit.getCli().printHelp(); return; } SecurityArguments securityArguments = new SecurityArguments(creator.getSecurityFile(), creator.getRealmSpec(), creator.getRemoteAuthSpec()); ExhibitorMain exhibitorMain = new ExhibitorMain ( creator.getBackupProvider(), creator.getConfigProvider(), creator.getBuilder(), creator.getHttpPort(), creator.getListenAddress(), creator.getSecurityHandler(), securityArguments ); setShutdown(exhibitorMain); try { exhibitorMain.start(); } catch (Exception ex) { ex.printStackTrace(System.err); System.err.println(String.format("Failed to start HTTP server on address %s, port %d. Exiting", creator.getListenAddress(), creator.getHttpPort())); Runtime.getRuntime().exit(1); } try { exhibitorMain.join(); } finally { exhibitorMain.close(); for ( Closeable closeable : creator.getCloseables() ) { CloseableUtils.closeQuietly(closeable); } } } public ExhibitorMain(BackupProvider backupProvider, ConfigProvider configProvider, ExhibitorArguments.Builder builder, int httpPort, String listenAddress, SecurityHandler security, SecurityArguments securityArguments) throws Exception { HashUserRealm realm = makeRealm(securityArguments); if ( securityArguments.getRemoteAuthSpec() != null ) { addRemoteAuth(builder, securityArguments.getRemoteAuthSpec()); } builder.shutdownProc(makeShutdownProc(this)); exhibitor = new Exhibitor(configProvider, null, backupProvider, builder.build()); exhibitor.start(); DefaultResourceConfig application = JerseySupport.newApplicationConfig(new UIContext(exhibitor)); ServletContainer container = new ServletContainer(application); server = new Server(); SocketConnector http = new SocketConnector(); http.setHost(listenAddress); http.setPort(httpPort); server.addConnector(http); Context root = new Context(server, "/", Context.SESSIONS); root.addFilter(ExhibitorServletFilter.class, "/", Handler.ALL); root.addServlet(new ServletHolder(container), "/*"); if ( security != null ) { root.setSecurityHandler(security); } else if ( securityArguments.getSecurityFile() != null ) { addSecurityFile(realm, securityArguments.getSecurityFile(), root); } } private void addRemoteAuth(ExhibitorArguments.Builder builder, String remoteAuthSpec) { String[] parts = remoteAuthSpec.split(":"); Preconditions.checkArgument(parts.length == 2, "Badly formed remote client authorization: " + remoteAuthSpec); String type = parts[0].trim(); String userName = parts[1].trim(); String password = Preconditions.checkNotNull(users.get(userName), "Realm user not found: " + userName); ClientFilter filter; if ( type.equals("basic") ) { filter = new HTTPBasicAuthFilter(userName, password); } else if ( type.equals("digest") ) { filter = new HTTPDigestAuthFilter(userName, password); } else { throw new IllegalStateException("Unknown remote client authorization type: " + type); } builder.remoteConnectionConfiguration(new RemoteConnectionConfiguration(Arrays.asList(filter))); } public void start() throws Exception { server.start(); } public void join() { try { while ( !shutdownSignaled.get() && !Thread.currentThread().isInterrupted() ) { Thread.sleep(5000); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } @Override public void close() throws IOException { if ( isClosed.compareAndSet(false, true) ) { log.info("Shutting down"); CloseableUtils.closeQuietly(exhibitor); try { server.stop(); } catch ( Exception e ) { log.error("Error shutting down Jetty", e); } server.destroy(); } } private static void setShutdown(final ExhibitorMain exhibitorMain) { Runtime.getRuntime().addShutdownHook ( new Thread ( makeShutdownProc(exhibitorMain) ) ); } private static Runnable makeShutdownProc(final ExhibitorMain exhibitorMain) { return new Runnable() { @Override public void run() { exhibitorMain.shutdownSignaled.set(true); } }; } private void addSecurityFile(HashUserRealm realm, String securityFile, Context root) throws Exception { // create a temp Jetty context to parse the security portion of the web.xml file /* TODO This code assumes far too much internal knowledge of Jetty. I don't know of simple way to parse the web.xml though and don't want to write it myself. */ final URL url = new URL("file", null, securityFile); final WebXmlConfiguration webXmlConfiguration = new WebXmlConfiguration(); WebAppContext context = new WebAppContext(); context.setServer(server); webXmlConfiguration.setWebAppContext(context); ContextHandler contextHandler = new ContextHandler("/") { @Override protected void startContext() throws Exception { super.startContext(); setServer(server); webXmlConfiguration.configure(url.toString()); } }; try { SecurityHandler securityHandler = webXmlConfiguration.getWebAppContext().getSecurityHandler(); if ( realm != null ) { securityHandler.setUserRealm(realm); } root.setSecurityHandler(securityHandler); contextHandler.start(); } finally { contextHandler.stop(); } } private HashUserRealm makeRealm(SecurityArguments securityArguments) throws Exception { if ( securityArguments.getRealmSpec() == null ) { return null; } String[] parts = securityArguments.getRealmSpec().split(":"); if ( parts.length != 2 ) { throw new Exception("Bad realm spec: " + securityArguments.getRealmSpec()); } return new HashUserRealm(parts[0].trim(), parts[1].trim()) { @Override public Object put(Object name, Object credentials) { users.put(String.valueOf(name), String.valueOf(credentials)); return super.put(name, credentials); } }; } }
4,361
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SITE_AFFILIATION_AFFILIATION_FETCHER_BASE_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SITE_AFFILIATION_AFFILIATION_FETCHER_BASE_H_ #include <string> #include "base/memory/raw_ptr.h" #include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher_interface.h" #include "base/memory/ref_counted.h" #include "base/timer/elapsed_timer.h" #include "components/password_manager/core/browser/android_affiliation/affiliation_api.pb.h" namespace net { struct NetworkTrafficAnnotationTag; } namespace network { class SharedURLLoaderFactory; class SimpleURLLoader; } // namespace network namespace password_manager { // Creates lookup mask based on |request_info|. affiliation_pb::LookupAffiliationMask CreateLookupMask( const AffiliationFetcherInterface::RequestInfo& request_info); // A base class for affiliation fetcher. Should not be used directly. // // Fetches authoritative information regarding which facets are affiliated with // each other, that is, which facets belong to the same logical application. // Apart from affiliations the service also supports groups and other details, // all of which have to be specified when starting a request. // See affiliation_utils.h for the definitions. // // An instance is good for exactly one fetch, and may be used from any thread // that runs a message loop (i.e. not a worker pool thread). class AffiliationFetcherBase : public virtual AffiliationFetcherInterface { public: ~AffiliationFetcherBase() override; AffiliationFetcherDelegate* delegate() const; protected: AffiliationFetcherBase( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, AffiliationFetcherDelegate* delegate); // Actually starts the request to retrieve affiliations and optionally // groupings for each facet in |facet_uris| along with the details based on // |request_info|. Calls the delegate with the results on the same thread when // done. If |this| is destroyed before completion, the in-flight request is // cancelled, and the delegate will not be called. Further details: // * No cookies are sent/saved with the request. // * In case of network/server errors, the request will not be retried. // * Results are guaranteed to be always fresh and will never be cached. void FinalizeRequest(const std::string& payload, const GURL& query_url, net::NetworkTrafficAnnotationTag traffic_annotation); private: // Parses and validates the response protocol buffer message for a list of // equivalence classes, stores them into |result| and returns true on success. // It is guaranteed that every one of the requested Facet URIs will be a // member of exactly one returned equivalence class. // Returns false if the response was gravely ill-formed or self-inconsistent. // Unknown kinds of facet URIs and new protocol buffer fields will be ignored. bool ParseResponse(const std::string& serialized_response, AffiliationFetcherDelegate::Result* result) const; void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const raw_ptr<AffiliationFetcherDelegate> delegate_; base::ElapsedTimer fetch_timer_; std::unique_ptr<network::SimpleURLLoader> simple_url_loader_; }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_SITE_AFFILIATION_AFFILIATION_FETCHER_BASE_H_
1,138
325
<gh_stars>100-1000 from AlphaGo.go import GameState, BLACK, WHITE def parse(boardstr): '''Parses a board into a gamestate, and returns the location of any moves marked with anything other than 'B', 'X', '#', 'W', 'O', or '.' Rows are separated by '|', spaces are ignored. ''' boardstr = boardstr.replace(' ', '') board_size = max(boardstr.index('|'), boardstr.count('|')) st = GameState(size=board_size) moves = {} for row, rowstr in enumerate(boardstr.split('|')): for col, c in enumerate(rowstr): if c == '.': continue # ignore empty spaces elif c in 'BX#': st.do_move((row, col), color=BLACK) elif c in 'WO': st.do_move((row, col), color=WHITE) else: # move reference assert c not in moves, "{} already used as a move marker".format(c) moves[c] = (row, col) return st, moves
449
3,212
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.web.api.dto.provenance.lineage; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlType; import java.util.List; import java.util.Set; /** * Represents the lineage results. */ @XmlType(name = "lineage") public class LineageResultsDTO { private Set<String> errors; private List<ProvenanceNodeDTO> nodes; private List<ProvenanceLinkDTO> links; /** * @return any error messages */ @ApiModelProperty( value = "Any errors that occurred while generating the lineage." ) public Set<String> getErrors() { return errors; } public void setErrors(Set<String> errors) { this.errors = errors; } /** * @return the nodes */ @ApiModelProperty( value = "The nodes in the lineage." ) public List<ProvenanceNodeDTO> getNodes() { return nodes; } public void setNodes(List<ProvenanceNodeDTO> nodes) { this.nodes = nodes; } /** * @return the links */ @ApiModelProperty( value = "The links between the nodes in the lineage." ) public List<ProvenanceLinkDTO> getLinks() { return links; } public void setLinks(List<ProvenanceLinkDTO> links) { this.links = links; } }
739
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Discipline", "definitions": [ "The practice of training people to obey rules or a code of behaviour, using punishment to correct disobedience.", "The controlled behaviour resulting from such training.", "Activity that provides mental or physical training.", "A system of rules of conduct.", "A branch of knowledge, typically one studied in higher education." ], "parts-of-speech": "Noun" }
160
1,338
/* * Copyright 2009-2012, <NAME>, <EMAIL>. * Copyright 2010-2017, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "controllers/TeamDebugger.h" #include <stdarg.h> #include <stdio.h> #include <new> #include <Entry.h> #include <InterfaceDefs.h> #include <Message.h> #include <StringList.h> #include <AutoDeleter.h> #include <AutoLocker.h> #include "debug_utils.h" #include "syscall_numbers.h" #include "Architecture.h" #include "BreakpointManager.h" #include "BreakpointSetting.h" #include "CpuState.h" #include "DebugEvent.h" #include "DebuggerInterface.h" #include "DebugReportGenerator.h" #include "ExpressionInfo.h" #include "FileManager.h" #include "Function.h" #include "FunctionID.h" #include "ImageDebugInfo.h" #include "ImageDebugInfoLoadingState.h" #include "ImageDebugLoadingStateHandler.h" #include "ImageDebugLoadingStateHandlerRoster.h" #include "Jobs.h" #include "LocatableFile.h" #include "MessageCodes.h" #include "NoOpSettingsManager.h" #include "SettingsManager.h" #include "SourceCode.h" #include "SourceLanguage.h" #include "SpecificImageDebugInfo.h" #include "SpecificImageDebugInfoLoadingState.h" #include "StackFrame.h" #include "StackFrameValues.h" #include "Statement.h" #include "SymbolInfo.h" #include "TeamDebugInfo.h" #include "TeamInfo.h" #include "TeamMemoryBlock.h" #include "TeamMemoryBlockManager.h" #include "TeamSettings.h" #include "TeamSignalSettings.h" #include "TeamUiSettings.h" #include "Tracing.h" #include "ValueNode.h" #include "ValueNodeContainer.h" #include "Variable.h" #include "WatchpointManager.h" // #pragma mark - ImageHandler struct TeamDebugger::ImageHandler : public BReferenceable, private LocatableFile::Listener { public: ImageHandler(TeamDebugger* teamDebugger, Image* image) : fTeamDebugger(teamDebugger), fImage(image) { fImage->AcquireReference(); if (fImage->ImageFile() != NULL) fImage->ImageFile()->AddListener(this); } ~ImageHandler() { if (fImage->ImageFile() != NULL) fImage->ImageFile()->RemoveListener(this); fImage->ReleaseReference(); } Image* GetImage() const { return fImage; } image_id ImageID() const { return fImage->ID(); } private: // LocatableFile::Listener virtual void LocatableFileChanged(LocatableFile* file) { BMessage message(MSG_IMAGE_FILE_CHANGED); message.AddInt32("image", fImage->ID()); fTeamDebugger->PostMessage(&message); } private: TeamDebugger* fTeamDebugger; Image* fImage; public: ImageHandler* fNext; }; // #pragma mark - ImageHandlerHashDefinition struct TeamDebugger::ImageHandlerHashDefinition { typedef image_id KeyType; typedef ImageHandler ValueType; size_t HashKey(image_id key) const { return (size_t)key; } size_t Hash(const ImageHandler* value) const { return HashKey(value->ImageID()); } bool Compare(image_id key, const ImageHandler* value) const { return value->ImageID() == key; } ImageHandler*& GetLink(ImageHandler* value) const { return value->fNext; } }; // #pragma mark - ImageInfoPendingThread struct TeamDebugger::ImageInfoPendingThread { public: ImageInfoPendingThread(image_id image, thread_id thread) : fImage(image), fThread(thread) { } ~ImageInfoPendingThread() { } image_id ImageID() const { return fImage; } thread_id ThreadID() const { return fThread; } private: image_id fImage; thread_id fThread; public: ImageInfoPendingThread* fNext; }; // #pragma mark - ImageHandlerHashDefinition struct TeamDebugger::ImageInfoPendingThreadHashDefinition { typedef image_id KeyType; typedef ImageInfoPendingThread ValueType; size_t HashKey(image_id key) const { return (size_t)key; } size_t Hash(const ImageInfoPendingThread* value) const { return HashKey(value->ImageID()); } bool Compare(image_id key, const ImageInfoPendingThread* value) const { return value->ImageID() == key; } ImageInfoPendingThread*& GetLink(ImageInfoPendingThread* value) const { return value->fNext; } }; // #pragma mark - TeamDebugger TeamDebugger::TeamDebugger(Listener* listener, UserInterface* userInterface, SettingsManager* settingsManager) : BLooper("team debugger"), fListener(listener), fSettingsManager(settingsManager), fTeam(NULL), fTeamID(-1), fIsPostMortem(false), fImageHandlers(NULL), fImageInfoPendingThreads(NULL), fDebuggerInterface(NULL), fFileManager(NULL), fWorker(NULL), fBreakpointManager(NULL), fWatchpointManager(NULL), fMemoryBlockManager(NULL), fReportGenerator(NULL), fDebugEventListener(-1), fUserInterface(userInterface), fTerminating(false), fKillTeamOnQuit(false), fCommandLineArgc(0), fCommandLineArgv(NULL), fExecPending(false) { fUserInterface->AcquireReference(); } TeamDebugger::~TeamDebugger() { if (fTeam != NULL) _SaveSettings(); AutoLocker<BLooper> locker(this); fTerminating = true; if (fDebuggerInterface != NULL) { fDebuggerInterface->Close(fKillTeamOnQuit); fDebuggerInterface->ReleaseReference(); } if (fWorker != NULL) fWorker->ShutDown(); locker.Unlock(); if (fDebugEventListener >= 0) wait_for_thread(fDebugEventListener, NULL); // terminate UI if (fUserInterface != NULL) { fUserInterface->Terminate(); fUserInterface->ReleaseReference(); } ThreadHandler* threadHandler = fThreadHandlers.Clear(true); while (threadHandler != NULL) { ThreadHandler* next = threadHandler->fNext; threadHandler->ReleaseReference(); threadHandler = next; } if (fImageHandlers != NULL) { ImageHandler* imageHandler = fImageHandlers->Clear(true); while (imageHandler != NULL) { ImageHandler* next = imageHandler->fNext; imageHandler->ReleaseReference(); imageHandler = next; } } delete fImageHandlers; if (fImageInfoPendingThreads != NULL) { ImageInfoPendingThread* thread = fImageInfoPendingThreads->Clear(true); while (thread != NULL) { ImageInfoPendingThread* next = thread->fNext; delete thread; thread = next; } } if (fReportGenerator != NULL) { fReportGenerator->Lock(); fReportGenerator->Quit(); } delete fWorker; delete fImageInfoPendingThreads; delete fBreakpointManager; delete fWatchpointManager; delete fMemoryBlockManager; delete fTeam; delete fFileManager; for (int i = 0; i < fCommandLineArgc; i++) { if (fCommandLineArgv[i] != NULL) free(const_cast<char*>(fCommandLineArgv[i])); } delete [] fCommandLineArgv; fListener->TeamDebuggerQuit(this); } status_t TeamDebugger::Init(DebuggerInterface* interface, thread_id threadID, int argc, const char* const* argv, bool stopInMain) { bool targetIsLocal = true; // TODO: Support non-local targets! // the first thing we want to do when running PostMessage(MSG_LOAD_SETTINGS); status_t error = _HandleSetArguments(argc, argv); if (error != B_OK) return error; if (fSettingsManager == NULL) { // if we have not been provided with a settings manager, // simply use the no-op manager by default. fSettingsManager = new(std::nothrow) NoOpSettingsManager; if (fSettingsManager == NULL) return B_NO_MEMORY; } fDebuggerInterface = interface; fDebuggerInterface->AcquireReference(); fTeamID = interface->TeamID(); fIsPostMortem = interface->IsPostMortem(); // create file manager fFileManager = new(std::nothrow) FileManager; if (fFileManager == NULL) return B_NO_MEMORY; error = fFileManager->Init(targetIsLocal); if (error != B_OK) return error; // create team debug info TeamDebugInfo* teamDebugInfo = new(std::nothrow) TeamDebugInfo( fDebuggerInterface, fDebuggerInterface->GetArchitecture(), fFileManager); if (teamDebugInfo == NULL) return B_NO_MEMORY; BReference<TeamDebugInfo> teamDebugInfoReference(teamDebugInfo, true); error = teamDebugInfo->Init(); if (error != B_OK) return error; // check whether the team exists at all TeamInfo teamInfo; error = fDebuggerInterface->GetTeamInfo(teamInfo); if (error != B_OK) return error; // create a team object fTeam = new(std::nothrow) ::Team(fTeamID, fDebuggerInterface, fDebuggerInterface->GetArchitecture(), teamDebugInfo, teamDebugInfo); if (fTeam == NULL) return B_NO_MEMORY; error = fTeam->Init(); if (error != B_OK) return error; fTeam->SetName(teamInfo.Arguments()); // TODO: Set a better name! fTeam->AddListener(this); // init thread handler table error = fThreadHandlers.Init(); if (error != B_OK) return error; // create image handler table fImageHandlers = new(std::nothrow) ImageHandlerTable; if (fImageHandlers == NULL) return B_NO_MEMORY; error = fImageHandlers->Init(); if (error != B_OK) return error; fImageInfoPendingThreads = new(std::nothrow) ImageInfoPendingThreadTable; if (fImageInfoPendingThreads == NULL) return B_NO_MEMORY; // create our worker fWorker = new(std::nothrow) Worker; if (fWorker == NULL) return B_NO_MEMORY; error = fWorker->Init(); if (error != B_OK) return error; // create the breakpoint manager fBreakpointManager = new(std::nothrow) BreakpointManager(fTeam, fDebuggerInterface); if (fBreakpointManager == NULL) return B_NO_MEMORY; error = fBreakpointManager->Init(); if (error != B_OK) return error; // create the watchpoint manager fWatchpointManager = new(std::nothrow) WatchpointManager(fTeam, fDebuggerInterface); if (fWatchpointManager == NULL) return B_NO_MEMORY; error = fWatchpointManager->Init(); if (error != B_OK) return error; // create the memory block manager fMemoryBlockManager = new(std::nothrow) TeamMemoryBlockManager(); if (fMemoryBlockManager == NULL) return B_NO_MEMORY; error = fMemoryBlockManager->Init(); if (error != B_OK) return error; // create the debug report generator fReportGenerator = new(std::nothrow) DebugReportGenerator(fTeam, this, fDebuggerInterface); if (fReportGenerator == NULL) return B_NO_MEMORY; error = fReportGenerator->Init(); if (error != B_OK) return error; // set team debugging flags fDebuggerInterface->SetTeamDebuggingFlags( B_TEAM_DEBUG_THREADS | B_TEAM_DEBUG_IMAGES | B_TEAM_DEBUG_POST_SYSCALL | B_TEAM_DEBUG_SIGNALS | B_TEAM_DEBUG_TEAM_CREATION); // get the initial state of the team AutoLocker< ::Team> teamLocker(fTeam); ThreadHandler* mainThreadHandler = NULL; { BObjectList<ThreadInfo> threadInfos(20, true); status_t error = fDebuggerInterface->GetThreadInfos(threadInfos); for (int32 i = 0; ThreadInfo* info = threadInfos.ItemAt(i); i++) { ::Thread* thread; error = fTeam->AddThread(*info, &thread); if (error != B_OK) return error; ThreadHandler* handler = new(std::nothrow) ThreadHandler(thread, fWorker, fDebuggerInterface, this, fBreakpointManager); if (handler == NULL) return B_NO_MEMORY; fThreadHandlers.Insert(handler); if (thread->IsMainThread()) mainThreadHandler = handler; handler->Init(); } } Image* appImage = NULL; { BObjectList<ImageInfo> imageInfos(20, true); status_t error = fDebuggerInterface->GetImageInfos(imageInfos); for (int32 i = 0; ImageInfo* info = imageInfos.ItemAt(i); i++) { Image* image; error = _AddImage(*info, &image); if (error != B_OK) return error; if (image->Type() == B_APP_IMAGE) appImage = image; ImageDebugInfoRequested(image); } } // create the debug event listener (for live debugging only) if (!fDebuggerInterface->IsPostMortem()) { char buffer[128]; snprintf(buffer, sizeof(buffer), "team %" B_PRId32 " debug listener", fTeamID); fDebugEventListener = spawn_thread(_DebugEventListenerEntry, buffer, B_NORMAL_PRIORITY, this); if (fDebugEventListener < 0) return fDebugEventListener; resume_thread(fDebugEventListener); } // run looper thread_id looperThread = Run(); if (looperThread < 0) return looperThread; // init the UI error = fUserInterface->Init(fTeam, this); if (error != B_OK) { ERROR("Error: Failed to init the UI: %s\n", strerror(error)); return error; } // if requested, stop the given thread if (threadID >= 0 && !fDebuggerInterface->IsPostMortem()) { if (stopInMain) { SymbolInfo symbolInfo; if (appImage != NULL && mainThreadHandler != NULL && fDebuggerInterface->GetSymbolInfo( fTeam->ID(), appImage->ID(), "main", B_SYMBOL_TYPE_TEXT, symbolInfo) == B_OK) { mainThreadHandler->SetBreakpointAndRun(symbolInfo.Address()); } } else { debug_thread(threadID); // TODO: Superfluous, if the thread is already stopped. } } fListener->TeamDebuggerStarted(this); return B_OK; } void TeamDebugger::Activate() { fUserInterface->Show(); } void TeamDebugger::MessageReceived(BMessage* message) { switch (message->what) { case MSG_THREAD_RUN: case MSG_THREAD_SET_ADDRESS: case MSG_THREAD_STOP: case MSG_THREAD_STEP_OVER: case MSG_THREAD_STEP_INTO: case MSG_THREAD_STEP_OUT: { int32 threadID; target_addr_t address; if (message->FindInt32("thread", &threadID) != B_OK) break; if (message->FindUInt64("address", &address) != B_OK) address = 0; if (ThreadHandler* handler = _GetThreadHandler(threadID)) { handler->HandleThreadAction(message->what, address); handler->ReleaseReference(); } break; } case MSG_SET_BREAKPOINT: case MSG_CLEAR_BREAKPOINT: { UserBreakpoint* breakpoint = NULL; BReference<UserBreakpoint> breakpointReference; uint64 address = 0; if (message->FindPointer("breakpoint", (void**)&breakpoint) == B_OK) { breakpointReference.SetTo(breakpoint, true); } else if (message->FindUInt64("address", &address) != B_OK) break; if (message->what == MSG_SET_BREAKPOINT) { bool enabled; if (message->FindBool("enabled", &enabled) != B_OK) enabled = true; bool hidden; if (message->FindBool("hidden", &hidden) != B_OK) hidden = false; if (breakpoint != NULL) _HandleSetUserBreakpoint(breakpoint, enabled); else _HandleSetUserBreakpoint(address, enabled, hidden); } else { if (breakpoint != NULL) _HandleClearUserBreakpoint(breakpoint); else _HandleClearUserBreakpoint(address); } break; } case MSG_SET_BREAKPOINT_CONDITION: { UserBreakpoint* breakpoint = NULL; BReference<UserBreakpoint> breakpointReference; if (message->FindPointer("breakpoint", (void**)&breakpoint) != B_OK) { break; } breakpointReference.SetTo(breakpoint, true); const char* condition; if (message->FindString("condition", &condition) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); breakpoint->SetCondition(condition); fTeam->NotifyUserBreakpointChanged(breakpoint); break; } case MSG_CLEAR_BREAKPOINT_CONDITION: { UserBreakpoint* breakpoint = NULL; BReference<UserBreakpoint> breakpointReference; if (message->FindPointer("breakpoint", (void**)&breakpoint) != B_OK) break; breakpointReference.SetTo(breakpoint, true); AutoLocker< ::Team> teamLocker(fTeam); breakpoint->SetCondition(NULL); fTeam->NotifyUserBreakpointChanged(breakpoint); break; } case MSG_STOP_ON_IMAGE_LOAD: { bool enabled; bool useNames; if (message->FindBool("enabled", &enabled) != B_OK) break; if (message->FindBool("useNames", &useNames) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); fTeam->SetStopOnImageLoad(enabled, useNames); break; } case MSG_ADD_STOP_IMAGE_NAME: { BString imageName; if (message->FindString("name", &imageName) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); fTeam->AddStopImageName(imageName); break; } case MSG_REMOVE_STOP_IMAGE_NAME: { BString imageName; if (message->FindString("name", &imageName) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); fTeam->RemoveStopImageName(imageName); break; } case MSG_SET_DEFAULT_SIGNAL_DISPOSITION: { int32 disposition; if (message->FindInt32("disposition", &disposition) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); fTeam->SetDefaultSignalDisposition(disposition); break; } case MSG_SET_CUSTOM_SIGNAL_DISPOSITION: { int32 signal; int32 disposition; if (message->FindInt32("signal", &signal) != B_OK || message->FindInt32("disposition", &disposition) != B_OK) { break; } AutoLocker< ::Team> teamLocker(fTeam); fTeam->SetCustomSignalDisposition(signal, disposition); break; } case MSG_REMOVE_CUSTOM_SIGNAL_DISPOSITION: { int32 signal; if (message->FindInt32("signal", &signal) != B_OK) break; AutoLocker< ::Team> teamLocker(fTeam); fTeam->RemoveCustomSignalDisposition(signal); break; } case MSG_SET_WATCHPOINT: case MSG_CLEAR_WATCHPOINT: { Watchpoint* watchpoint = NULL; BReference<Watchpoint> watchpointReference; uint64 address = 0; uint32 type = 0; int32 length = 0; if (message->FindPointer("watchpoint", (void**)&watchpoint) == B_OK) { watchpointReference.SetTo(watchpoint, true); } else if (message->FindUInt64("address", &address) != B_OK) break; if (message->what == MSG_SET_WATCHPOINT) { if (watchpoint == NULL && (message->FindUInt32("type", &type) != B_OK || message->FindInt32("length", &length) != B_OK)) { break; } bool enabled; if (message->FindBool("enabled", &enabled) != B_OK) enabled = true; if (watchpoint != NULL) _HandleSetWatchpoint(watchpoint, enabled); else _HandleSetWatchpoint(address, type, length, enabled); } else { if (watchpoint != NULL) _HandleClearWatchpoint(watchpoint); else _HandleClearWatchpoint(address); } break; } case MSG_INSPECT_ADDRESS: { TeamMemoryBlock::Listener* listener; if (message->FindPointer("listener", reinterpret_cast<void **>(&listener)) != B_OK) { break; } target_addr_t address; if (message->FindUInt64("address", &address) == B_OK) { _HandleInspectAddress(address, listener); } break; } case MSG_WRITE_TARGET_MEMORY: { target_addr_t address; if (message->FindUInt64("address", &address) != B_OK) break; void* data; if (message->FindPointer("data", &data) != B_OK) break; target_size_t size; if (message->FindUInt64("size", &size) != B_OK) break; _HandleWriteMemory(address, data, size); break; } case MSG_EVALUATE_EXPRESSION: { SourceLanguage* language; if (message->FindPointer("language", reinterpret_cast<void**>(&language)) != B_OK) { break; } // ExpressionEvaluationRequested() acquires a reference // to both the language and the expression info on our behalf. BReference<SourceLanguage> reference(language, true); ExpressionInfo* info; if (message->FindPointer("info", reinterpret_cast<void**>(&info)) != B_OK) { break; } BReference<ExpressionInfo> infoReference(info, true); StackFrame* frame; if (message->FindPointer("frame", reinterpret_cast<void**>(&frame)) != B_OK) { // the stack frame isn't needed, unless variable // evaluation is desired. frame = NULL; } ::Thread* thread; if (message->FindPointer("thread", reinterpret_cast<void**>(&thread)) != B_OK) { // the thread isn't needed, unless variable // evaluation is desired. thread = NULL; } _HandleEvaluateExpression(language, info, frame, thread); break; } case MSG_GENERATE_DEBUG_REPORT: { fReportGenerator->PostMessage(message); break; } case MSG_WRITE_CORE_FILE: { entry_ref ref; if (message->FindRef("target", &ref) != B_OK) break; _HandleWriteCoreFile(ref); break; } case MSG_THREAD_STATE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; if (ThreadHandler* handler = _GetThreadHandler(threadID)) { handler->HandleThreadStateChanged(); handler->ReleaseReference(); } break; } case MSG_THREAD_CPU_STATE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; if (ThreadHandler* handler = _GetThreadHandler(threadID)) { handler->HandleCpuStateChanged(); handler->ReleaseReference(); } break; } case MSG_THREAD_STACK_TRACE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; if (ThreadHandler* handler = _GetThreadHandler(threadID)) { handler->HandleStackTraceChanged(); handler->ReleaseReference(); } break; } case MSG_IMAGE_DEBUG_INFO_CHANGED: { int32 imageID; if (message->FindInt32("image", &imageID) != B_OK) break; _HandleImageDebugInfoChanged(imageID); break; } case MSG_IMAGE_FILE_CHANGED: { int32 imageID; if (message->FindInt32("image", &imageID) != B_OK) break; _HandleImageFileChanged(imageID); break; } case MSG_DEBUGGER_EVENT: { DebugEvent* event; if (message->FindPointer("event", (void**)&event) != B_OK) break; _HandleDebuggerMessage(event); delete event; break; } case MSG_LOAD_SETTINGS: _LoadSettings(); Activate(); break; case MSG_TEAM_RESTART_REQUESTED: { if (fCommandLineArgc == 0) break; _SaveSettings(); fListener->TeamDebuggerRestartRequested(this); break; } case MSG_DEBUG_INFO_NEEDS_USER_INPUT: { Job* job; ImageDebugInfoLoadingState* state; if (message->FindPointer("job", (void**)&job) != B_OK) break; if (message->FindPointer("state", (void**)&state) != B_OK) break; _HandleDebugInfoJobUserInput(state); fWorker->ResumeJob(job); break; } case MSG_RESET_USER_BACKGROUND_STATUS: { fUserInterface->NotifyBackgroundWorkStatus("Ready."); break; } default: BLooper::MessageReceived(message); break; } } void TeamDebugger::SourceEntryLocateRequested(const char* sourcePath, const char* locatedPath) { AutoLocker<FileManager> locker(fFileManager); fFileManager->SourceEntryLocated(sourcePath, locatedPath); } void TeamDebugger::SourceEntryInvalidateRequested(LocatableFile* sourceFile) { AutoLocker< ::Team> locker(fTeam); fTeam->DebugInfo()->ClearSourceCode(sourceFile); } void TeamDebugger::FunctionSourceCodeRequested(FunctionInstance* functionInstance, bool forceDisassembly) { Function* function = functionInstance->GetFunction(); // mark loading AutoLocker< ::Team> locker(fTeam); if (forceDisassembly && functionInstance->SourceCodeState() != FUNCTION_SOURCE_NOT_LOADED) { return; } else if (!forceDisassembly && function->SourceCodeState() == FUNCTION_SOURCE_LOADED) { return; } functionInstance->SetSourceCode(NULL, FUNCTION_SOURCE_LOADING); bool loadForFunction = false; if (!forceDisassembly && (function->SourceCodeState() == FUNCTION_SOURCE_NOT_LOADED || function->SourceCodeState() == FUNCTION_SOURCE_SUPPRESSED)) { loadForFunction = true; function->SetSourceCode(NULL, FUNCTION_SOURCE_LOADING); } locker.Unlock(); // schedule the job if (fWorker->ScheduleJob( new(std::nothrow) LoadSourceCodeJob(fDebuggerInterface, fDebuggerInterface->GetArchitecture(), fTeam, functionInstance, loadForFunction), this) != B_OK) { // scheduling failed -- mark unavailable locker.Lock(); function->SetSourceCode(NULL, FUNCTION_SOURCE_UNAVAILABLE); locker.Unlock(); } } void TeamDebugger::ImageDebugInfoRequested(Image* image) { LoadImageDebugInfoJob::ScheduleIfNecessary(fWorker, image, this); } void TeamDebugger::ValueNodeValueRequested(CpuState* cpuState, ValueNodeContainer* container, ValueNode* valueNode) { AutoLocker<ValueNodeContainer> containerLocker(container); if (valueNode->Container() != container) return; // check whether a job is already in progress AutoLocker<Worker> workerLocker(fWorker); SimpleJobKey jobKey(valueNode, JOB_TYPE_RESOLVE_VALUE_NODE_VALUE); if (fWorker->GetJob(jobKey) != NULL) return; workerLocker.Unlock(); // schedule the job status_t error = fWorker->ScheduleJob( new(std::nothrow) ResolveValueNodeValueJob(fDebuggerInterface, fDebuggerInterface->GetArchitecture(), cpuState, fTeam->GetTeamTypeInformation(), container, valueNode), this); if (error != B_OK) { // scheduling failed -- set the value to invalid valueNode->SetLocationAndValue(NULL, NULL, error); } } void TeamDebugger::ValueNodeWriteRequested(ValueNode* node, CpuState* state, Value* newValue) { // schedule the job status_t error = fWorker->ScheduleJob( new(std::nothrow) WriteValueNodeValueJob(fDebuggerInterface, fDebuggerInterface->GetArchitecture(), state, fTeam->GetTeamTypeInformation(), node, newValue), this); if (error != B_OK) { BString message; message.SetToFormat("Request to write new value for variable %s " "failed: %s.\n", node->Name().String(), strerror(error)); fUserInterface->NotifyUser("Error", message.String(), USER_NOTIFICATION_ERROR); } } void TeamDebugger::ThreadActionRequested(thread_id threadID, uint32 action, target_addr_t address) { BMessage message(action); message.AddInt32("thread", threadID); message.AddUInt64("address", address); PostMessage(&message); } void TeamDebugger::SetBreakpointRequested(target_addr_t address, bool enabled, bool hidden) { BMessage message(MSG_SET_BREAKPOINT); message.AddUInt64("address", (uint64)address); message.AddBool("enabled", enabled); message.AddBool("hidden", hidden); PostMessage(&message); } void TeamDebugger::SetBreakpointEnabledRequested(UserBreakpoint* breakpoint, bool enabled) { BMessage message(MSG_SET_BREAKPOINT); BReference<UserBreakpoint> breakpointReference(breakpoint); if (message.AddPointer("breakpoint", breakpoint) == B_OK && message.AddBool("enabled", enabled) == B_OK && PostMessage(&message) == B_OK) { breakpointReference.Detach(); } } void TeamDebugger::SetBreakpointConditionRequested(UserBreakpoint* breakpoint, const char* condition) { BMessage message(MSG_SET_BREAKPOINT_CONDITION); BReference<UserBreakpoint> breakpointReference(breakpoint); if (message.AddPointer("breakpoint", breakpoint) == B_OK && message.AddString("condition", condition) == B_OK && PostMessage(&message) == B_OK) { breakpointReference.Detach(); } } void TeamDebugger::ClearBreakpointConditionRequested(UserBreakpoint* breakpoint) { BMessage message(MSG_CLEAR_BREAKPOINT_CONDITION); BReference<UserBreakpoint> breakpointReference(breakpoint); if (message.AddPointer("breakpoint", breakpoint) == B_OK && PostMessage(&message) == B_OK) { breakpointReference.Detach(); } } void TeamDebugger::ClearBreakpointRequested(target_addr_t address) { BMessage message(MSG_CLEAR_BREAKPOINT); message.AddUInt64("address", (uint64)address); PostMessage(&message); } void TeamDebugger::SetStopOnImageLoadRequested(bool enabled, bool useImageNames) { BMessage message(MSG_STOP_ON_IMAGE_LOAD); message.AddBool("enabled", enabled); message.AddBool("useNames", useImageNames); PostMessage(&message); } void TeamDebugger::AddStopImageNameRequested(const char* name) { BMessage message(MSG_ADD_STOP_IMAGE_NAME); message.AddString("name", name); PostMessage(&message); } void TeamDebugger::RemoveStopImageNameRequested(const char* name) { BMessage message(MSG_REMOVE_STOP_IMAGE_NAME); message.AddString("name", name); PostMessage(&message); } void TeamDebugger::SetDefaultSignalDispositionRequested(int32 disposition) { BMessage message(MSG_SET_DEFAULT_SIGNAL_DISPOSITION); message.AddInt32("disposition", disposition); PostMessage(&message); } void TeamDebugger::SetCustomSignalDispositionRequested(int32 signal, int32 disposition) { BMessage message(MSG_SET_CUSTOM_SIGNAL_DISPOSITION); message.AddInt32("signal", signal); message.AddInt32("disposition", disposition); PostMessage(&message); } void TeamDebugger::RemoveCustomSignalDispositionRequested(int32 signal) { BMessage message(MSG_REMOVE_CUSTOM_SIGNAL_DISPOSITION); message.AddInt32("signal", signal); PostMessage(&message); } void TeamDebugger::ClearBreakpointRequested(UserBreakpoint* breakpoint) { BMessage message(MSG_CLEAR_BREAKPOINT); BReference<UserBreakpoint> breakpointReference(breakpoint); if (message.AddPointer("breakpoint", breakpoint) == B_OK && PostMessage(&message) == B_OK) { breakpointReference.Detach(); } } void TeamDebugger::SetWatchpointRequested(target_addr_t address, uint32 type, int32 length, bool enabled) { BMessage message(MSG_SET_WATCHPOINT); message.AddUInt64("address", (uint64)address); message.AddUInt32("type", type); message.AddInt32("length", length); message.AddBool("enabled", enabled); PostMessage(&message); } void TeamDebugger::SetWatchpointEnabledRequested(Watchpoint* watchpoint, bool enabled) { BMessage message(MSG_SET_WATCHPOINT); BReference<Watchpoint> watchpointReference(watchpoint); if (message.AddPointer("watchpoint", watchpoint) == B_OK && message.AddBool("enabled", enabled) == B_OK && PostMessage(&message) == B_OK) { watchpointReference.Detach(); } } void TeamDebugger::ClearWatchpointRequested(target_addr_t address) { BMessage message(MSG_CLEAR_WATCHPOINT); message.AddUInt64("address", (uint64)address); PostMessage(&message); } void TeamDebugger::ClearWatchpointRequested(Watchpoint* watchpoint) { BMessage message(MSG_CLEAR_WATCHPOINT); BReference<Watchpoint> watchpointReference(watchpoint); if (message.AddPointer("watchpoint", watchpoint) == B_OK && PostMessage(&message) == B_OK) { watchpointReference.Detach(); } } void TeamDebugger::InspectRequested(target_addr_t address, TeamMemoryBlock::Listener *listener) { BMessage message(MSG_INSPECT_ADDRESS); message.AddUInt64("address", address); message.AddPointer("listener", listener); PostMessage(&message); } void TeamDebugger::MemoryWriteRequested(target_addr_t address, const void* data, target_size_t size) { BMessage message(MSG_WRITE_TARGET_MEMORY); message.AddUInt64("address", address); message.AddPointer("data", data); message.AddUInt64("size", size); PostMessage(&message); } void TeamDebugger::ExpressionEvaluationRequested(SourceLanguage* language, ExpressionInfo* info, StackFrame* frame, ::Thread* thread) { BMessage message(MSG_EVALUATE_EXPRESSION); message.AddPointer("language", language); message.AddPointer("info", info); if (frame != NULL) message.AddPointer("frame", frame); if (thread != NULL) message.AddPointer("thread", thread); BReference<SourceLanguage> languageReference(language); BReference<ExpressionInfo> infoReference(info); if (PostMessage(&message) == B_OK) { languageReference.Detach(); infoReference.Detach(); } } void TeamDebugger::DebugReportRequested(entry_ref* targetPath) { BMessage message(MSG_GENERATE_DEBUG_REPORT); message.AddRef("target", targetPath); PostMessage(&message); } void TeamDebugger::WriteCoreFileRequested(entry_ref* targetPath) { BMessage message(MSG_WRITE_CORE_FILE); message.AddRef("target", targetPath); PostMessage(&message); } void TeamDebugger::TeamRestartRequested() { PostMessage(MSG_TEAM_RESTART_REQUESTED); } bool TeamDebugger::UserInterfaceQuitRequested(QuitOption quitOption) { bool askUser = false; switch (quitOption) { case QUIT_OPTION_ASK_USER: askUser = true; break; case QUIT_OPTION_ASK_KILL_TEAM: fKillTeamOnQuit = true; break; case QUIT_OPTION_ASK_RESUME_TEAM: break; } if (askUser) { AutoLocker< ::Team> locker(fTeam); BString name(fTeam->Name()); locker.Unlock(); BString message; message << "What shall be done about the debugged team '"; message << name; message << "'?"; name.Remove(0, name.FindLast('/') + 1); BString killLabel("Kill "); killLabel << name; BString resumeLabel("Resume "); resumeLabel << name; int32 choice = fUserInterface->SynchronouslyAskUser("Quit Debugger", message, killLabel, "Cancel", resumeLabel); switch (choice) { case 0: fKillTeamOnQuit = true; break; case 1: case -1: return false; case 2: // Detach from the team and resume and stopped threads. break; } } PostMessage(B_QUIT_REQUESTED); return true; } void TeamDebugger::JobStarted(Job* job) { BString description(job->GetDescription()); if (!description.IsEmpty()) { description.Append(B_UTF8_ELLIPSIS); fUserInterface->NotifyBackgroundWorkStatus(description.String()); } } void TeamDebugger::JobDone(Job* job) { TRACE_JOBS("TeamDebugger::JobDone(%p)\n", job); _ResetUserBackgroundStatusIfNeeded(); } void TeamDebugger::JobWaitingForInput(Job* job) { LoadImageDebugInfoJob* infoJob = dynamic_cast<LoadImageDebugInfoJob*>(job); if (infoJob == NULL) return; BMessage message(MSG_DEBUG_INFO_NEEDS_USER_INPUT); message.AddPointer("job", infoJob); message.AddPointer("state", infoJob->GetLoadingState()); PostMessage(&message); } void TeamDebugger::JobFailed(Job* job) { TRACE_JOBS("TeamDebugger::JobFailed(%p)\n", job); // TODO: notify user _ResetUserBackgroundStatusIfNeeded(); } void TeamDebugger::JobAborted(Job* job) { TRACE_JOBS("TeamDebugger::JobAborted(%p)\n", job); // TODO: For a stack frame source loader thread we should reset the // loading state! Asynchronously due to locking order. _ResetUserBackgroundStatusIfNeeded(); } void TeamDebugger::ThreadStateChanged(const ::Team::ThreadEvent& event) { BMessage message(MSG_THREAD_STATE_CHANGED); message.AddInt32("thread", event.GetThread()->ID()); PostMessage(&message); } void TeamDebugger::ThreadCpuStateChanged(const ::Team::ThreadEvent& event) { BMessage message(MSG_THREAD_CPU_STATE_CHANGED); message.AddInt32("thread", event.GetThread()->ID()); PostMessage(&message); } void TeamDebugger::ThreadStackTraceChanged(const ::Team::ThreadEvent& event) { BMessage message(MSG_THREAD_STACK_TRACE_CHANGED); message.AddInt32("thread", event.GetThread()->ID()); PostMessage(&message); } void TeamDebugger::ImageDebugInfoChanged(const ::Team::ImageEvent& event) { BMessage message(MSG_IMAGE_DEBUG_INFO_CHANGED); message.AddInt32("image", event.GetImage()->ID()); PostMessage(&message); } /*static*/ status_t TeamDebugger::_DebugEventListenerEntry(void* data) { return ((TeamDebugger*)data)->_DebugEventListener(); } status_t TeamDebugger::_DebugEventListener() { while (!fTerminating) { // get the next event DebugEvent* event; status_t error = fDebuggerInterface->GetNextDebugEvent(event); if (error != B_OK) break; // TODO: Error handling! if (event->Team() != fTeamID) { TRACE_EVENTS("TeamDebugger for team %" B_PRId32 ": received event " "from team %" B_PRId32 "!\n", fTeamID, event->Team()); continue; } BMessage message(MSG_DEBUGGER_EVENT); if (message.AddPointer("event", event) != B_OK || PostMessage(&message) != B_OK) { // TODO: Continue thread if necessary! delete event; } } return B_OK; } void TeamDebugger::_HandleDebuggerMessage(DebugEvent* event) { TRACE_EVENTS("TeamDebugger::_HandleDebuggerMessage(): %" B_PRId32 "\n", event->EventType()); bool handled = false; ThreadHandler* handler = _GetThreadHandler(event->Thread()); BReference<ThreadHandler> handlerReference(handler, true); switch (event->EventType()) { case B_DEBUGGER_MESSAGE_THREAD_DEBUGGED: TRACE_EVENTS("B_DEBUGGER_MESSAGE_THREAD_DEBUGGED: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleThreadDebugged( dynamic_cast<ThreadDebuggedEvent*>(event)); } break; case B_DEBUGGER_MESSAGE_DEBUGGER_CALL: TRACE_EVENTS("B_DEBUGGER_MESSAGE_DEBUGGER_CALL: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleDebuggerCall( dynamic_cast<DebuggerCallEvent*>(event)); } break; case B_DEBUGGER_MESSAGE_BREAKPOINT_HIT: TRACE_EVENTS("B_DEBUGGER_MESSAGE_BREAKPOINT_HIT: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleBreakpointHit( dynamic_cast<BreakpointHitEvent*>(event)); } break; case B_DEBUGGER_MESSAGE_WATCHPOINT_HIT: TRACE_EVENTS("B_DEBUGGER_MESSAGE_WATCHPOINT_HIT: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleWatchpointHit( dynamic_cast<WatchpointHitEvent*>(event)); } break; case B_DEBUGGER_MESSAGE_SINGLE_STEP: TRACE_EVENTS("B_DEBUGGER_MESSAGE_SINGLE_STEP: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleSingleStep( dynamic_cast<SingleStepEvent*>(event)); } break; case B_DEBUGGER_MESSAGE_EXCEPTION_OCCURRED: TRACE_EVENTS("B_DEBUGGER_MESSAGE_EXCEPTION_OCCURRED: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleExceptionOccurred( dynamic_cast<ExceptionOccurredEvent*>(event)); } break; // case B_DEBUGGER_MESSAGE_TEAM_CREATED: //printf("B_DEBUGGER_MESSAGE_TEAM_CREATED: team: %ld\n", message.team_created.new_team); // break; case B_DEBUGGER_MESSAGE_TEAM_DELETED: { TRACE_EVENTS("B_DEBUGGER_MESSAGE_TEAM_DELETED: team: %" B_PRId32 "\n", event->Team()); TeamDeletedEvent* teamEvent = dynamic_cast<TeamDeletedEvent*>(event); handled = _HandleTeamDeleted(teamEvent); break; } case B_DEBUGGER_MESSAGE_TEAM_EXEC: { TRACE_EVENTS("B_DEBUGGER_MESSAGE_TEAM_EXEC: team: %" B_PRId32 "\n", event->Team()); TeamExecEvent* teamEvent = dynamic_cast<TeamExecEvent*>(event); _PrepareForTeamExec(teamEvent); break; } case B_DEBUGGER_MESSAGE_THREAD_CREATED: { ThreadCreatedEvent* threadEvent = dynamic_cast<ThreadCreatedEvent*>(event); TRACE_EVENTS("B_DEBUGGER_MESSAGE_THREAD_CREATED: thread: %" B_PRId32 "\n", threadEvent->NewThread()); handled = _HandleThreadCreated(threadEvent); break; } case DEBUGGER_MESSAGE_THREAD_RENAMED: { ThreadRenamedEvent* threadEvent = dynamic_cast<ThreadRenamedEvent*>(event); TRACE_EVENTS("DEBUGGER_MESSAGE_THREAD_RENAMED: thread: %" B_PRId32 " (\"%s\")\n", threadEvent->RenamedThread(), threadEvent->NewName()); handled = _HandleThreadRenamed(threadEvent); break; } case DEBUGGER_MESSAGE_THREAD_PRIORITY_CHANGED: { ThreadPriorityChangedEvent* threadEvent = dynamic_cast<ThreadPriorityChangedEvent*>(event); TRACE_EVENTS("B_DEBUGGER_MESSAGE_THREAD_PRIORITY_CHANGED: thread:" " %" B_PRId32 "\n", threadEvent->ChangedThread()); handled = _HandleThreadPriorityChanged(threadEvent); break; } case B_DEBUGGER_MESSAGE_THREAD_DELETED: TRACE_EVENTS("B_DEBUGGER_MESSAGE_THREAD_DELETED: thread: %" B_PRId32 "\n", event->Thread()); handled = _HandleThreadDeleted( dynamic_cast<ThreadDeletedEvent*>(event)); break; case B_DEBUGGER_MESSAGE_IMAGE_CREATED: { ImageCreatedEvent* imageEvent = dynamic_cast<ImageCreatedEvent*>(event); TRACE_EVENTS("B_DEBUGGER_MESSAGE_IMAGE_CREATED: image: \"%s\" " "(%" B_PRId32 ")\n", imageEvent->GetImageInfo().Name().String(), imageEvent->GetImageInfo().ImageID()); handled = _HandleImageCreated(imageEvent); break; } case B_DEBUGGER_MESSAGE_IMAGE_DELETED: { ImageDeletedEvent* imageEvent = dynamic_cast<ImageDeletedEvent*>(event); TRACE_EVENTS("B_DEBUGGER_MESSAGE_IMAGE_DELETED: image: \"%s\" " "(%" B_PRId32 ")\n", imageEvent->GetImageInfo().Name().String(), imageEvent->GetImageInfo().ImageID()); handled = _HandleImageDeleted(imageEvent); break; } case B_DEBUGGER_MESSAGE_POST_SYSCALL: { PostSyscallEvent* postSyscallEvent = dynamic_cast<PostSyscallEvent*>(event); TRACE_EVENTS("B_DEBUGGER_MESSAGE_POST_SYSCALL: syscall: %" B_PRIu32 "\n", postSyscallEvent->GetSyscallInfo().Syscall()); handled = _HandlePostSyscall(postSyscallEvent); // if a thread was blocked in a syscall when we requested to // stop it for debugging, then that request will interrupt // said call, and the post syscall event will be all we get // in response. Consequently, we need to treat this case as // equivalent to having received a thread debugged event. AutoLocker< ::Team> teamLocker(fTeam); ::Thread* thread = fTeam->ThreadByID(event->Thread()); if (handler != NULL && thread != NULL && thread->StopRequestPending()) { handled = handler->HandleThreadDebugged(NULL); } break; } case B_DEBUGGER_MESSAGE_SIGNAL_RECEIVED: { TRACE_EVENTS("B_DEBUGGER_MESSAGE_SIGNAL_RECEIVED: thread: %" B_PRId32 "\n", event->Thread()); if (handler != NULL) { handled = handler->HandleSignalReceived( dynamic_cast<SignalReceivedEvent*>(event)); } break; } case B_DEBUGGER_MESSAGE_PRE_SYSCALL: case B_DEBUGGER_MESSAGE_PROFILER_UPDATE: case B_DEBUGGER_MESSAGE_HANDED_OVER: // not interested break; default: WARNING("TeamDebugger for team %" B_PRId32 ": unknown event type: " "%" B_PRId32 "\n", fTeamID, event->EventType()); break; } if (!handled && event->ThreadStopped()) fDebuggerInterface->ContinueThread(event->Thread()); } bool TeamDebugger::_HandleTeamDeleted(TeamDeletedEvent* event) { char message[64]; fDebuggerInterface->Close(false); snprintf(message, sizeof(message), "Team %" B_PRId32 " has terminated. ", event->Team()); int32 result = fUserInterface->SynchronouslyAskUser("Team terminated", message, "Do nothing", "Quit", fCommandLineArgc != 0 ? "Restart team" : NULL); switch (result) { case 1: case -1: { PostMessage(B_QUIT_REQUESTED); break; } case 2: { _SaveSettings(); fListener->TeamDebuggerRestartRequested(this); break; } default: break; } return true; } bool TeamDebugger::_HandleThreadCreated(ThreadCreatedEvent* event) { AutoLocker< ::Team> locker(fTeam); ThreadInfo info; status_t error = fDebuggerInterface->GetThreadInfo(event->NewThread(), info); if (error == B_OK) { ::Thread* thread; fTeam->AddThread(info, &thread); ThreadHandler* handler = new(std::nothrow) ThreadHandler(thread, fWorker, fDebuggerInterface, this, fBreakpointManager); if (handler != NULL) { fThreadHandlers.Insert(handler); handler->Init(); } } return false; } bool TeamDebugger::_HandleThreadRenamed(ThreadRenamedEvent* event) { AutoLocker< ::Team> locker(fTeam); ::Thread* thread = fTeam->ThreadByID(event->RenamedThread()); if (thread != NULL) thread->SetName(event->NewName()); return false; } bool TeamDebugger::_HandleThreadPriorityChanged(ThreadPriorityChangedEvent*) { // TODO: implement once we actually track thread priorities return false; } bool TeamDebugger::_HandleThreadDeleted(ThreadDeletedEvent* event) { AutoLocker< ::Team> locker(fTeam); if (ThreadHandler* handler = fThreadHandlers.Lookup(event->Thread())) { fThreadHandlers.Remove(handler); handler->ReleaseReference(); } fTeam->RemoveThread(event->Thread()); return false; } bool TeamDebugger::_HandleImageCreated(ImageCreatedEvent* event) { AutoLocker< ::Team> locker(fTeam); _AddImage(event->GetImageInfo()); ImageInfoPendingThread* info = new(std::nothrow) ImageInfoPendingThread( event->GetImageInfo().ImageID(), event->Thread()); if (info == NULL) return false; fImageInfoPendingThreads->Insert(info); return true; } bool TeamDebugger::_HandleImageDeleted(ImageDeletedEvent* event) { AutoLocker< ::Team> locker(fTeam); fTeam->RemoveImage(event->GetImageInfo().ImageID()); ImageHandler* imageHandler = fImageHandlers->Lookup( event->GetImageInfo().ImageID()); if (imageHandler == NULL) return false; fImageHandlers->Remove(imageHandler); BReference<ImageHandler> imageHandlerReference(imageHandler, true); locker.Unlock(); // remove breakpoints in the image fBreakpointManager->RemoveImageBreakpoints(imageHandler->GetImage()); return false; } bool TeamDebugger::_HandlePostSyscall(PostSyscallEvent* event) { const SyscallInfo& info = event->GetSyscallInfo(); switch (info.Syscall()) { case SYSCALL_WRITE: { if ((ssize_t)info.ReturnValue() <= 0) break; int32 fd; target_addr_t address; size_t size; // TODO: decoding the syscall arguments should probably be // factored out into an Architecture method of its own, since // there's no guarantee the target architecture has the same // endianness as the host. This could re-use the syscall // argument parser that strace uses, though that would need to // be adapted to handle the aforementioned endian differences. // This works for x86{-64} for now though. if (fTeam->GetArchitecture()->AddressSize() == 4) { const uint32* args = (const uint32*)info.Arguments(); fd = args[0]; address = args[3]; size = args[4]; } else { const uint64* args = (const uint64*)info.Arguments(); fd = args[0]; address = args[2]; size = args[3]; } if (fd == 1 || fd == 2) { BString data; ssize_t result = fDebuggerInterface->ReadMemoryString( address, size, data); if (result >= 0) fTeam->NotifyConsoleOutputReceived(fd, data); } break; } case SYSCALL_WRITEV: { // TODO: handle } default: break; } return false; } void TeamDebugger::_PrepareForTeamExec(TeamExecEvent* event) { // NB: must be called with team lock held. _SaveSettings(); // when notified of exec, we need to clear out data related // to the old team. const ImageList& images = fTeam->Images(); for (ImageList::ConstIterator it = images.GetIterator(); Image* image = it.Next();) { fBreakpointManager->RemoveImageBreakpoints(image); } BObjectList<UserBreakpoint> breakpointsToRemove(20, false); const UserBreakpointList& breakpoints = fTeam->UserBreakpoints(); for (UserBreakpointList::ConstIterator it = breakpoints.GetIterator(); UserBreakpoint* breakpoint = it.Next();) { breakpointsToRemove.AddItem(breakpoint); breakpoint->AcquireReference(); } for (int32 i = 0; i < breakpointsToRemove.CountItems(); i++) { UserBreakpoint* breakpoint = breakpointsToRemove.ItemAt(i); fTeam->RemoveUserBreakpoint(breakpoint); fTeam->NotifyUserBreakpointChanged(breakpoint); breakpoint->ReleaseReference(); } fTeam->ClearImages(); fTeam->ClearSignalDispositionMappings(); fExecPending = true; } void TeamDebugger::_HandleImageDebugInfoChanged(image_id imageID) { // get the image (via the image handler) AutoLocker< ::Team> locker(fTeam); ImageHandler* imageHandler = fImageHandlers->Lookup(imageID); if (imageHandler == NULL) return; Image* image = imageHandler->GetImage(); BReference<Image> imageReference(image); image_debug_info_state state = image->ImageDebugInfoState(); bool handlePostExecSetup = fExecPending && image->Type() == B_APP_IMAGE && state != IMAGE_DEBUG_INFO_LOADING; // this needs to be done first so that breakpoints are loaded. // otherwise, UpdateImageBreakpoints() won't find the appropriate // UserBreakpoints to create/install instances for. if (handlePostExecSetup) { fTeam->SetName(image->Name()); _LoadSettings(); fExecPending = false; } locker.Unlock(); if (state == IMAGE_DEBUG_INFO_LOADED || state == IMAGE_DEBUG_INFO_UNAVAILABLE) { // update breakpoints in the image fBreakpointManager->UpdateImageBreakpoints(image); ImageInfoPendingThread* thread = fImageInfoPendingThreads ->Lookup(imageID); if (thread != NULL) { fImageInfoPendingThreads->Remove(thread); ObjectDeleter<ImageInfoPendingThread> threadDeleter(thread); locker.Lock(); ThreadHandler* handler = _GetThreadHandler(thread->ThreadID()); BReference<ThreadHandler> handlerReference(handler, true); if (fTeam->StopOnImageLoad()) { bool stop = true; const BString& imageName = image->Name(); // only match on the image filename itself const char* rawImageName = imageName.String() + imageName.FindLast('/') + 1; if (fTeam->StopImageNameListEnabled()) { const BStringList& nameList = fTeam->StopImageNames(); stop = nameList.HasString(rawImageName); } if (stop && handler != NULL) { BString stopReason; stopReason.SetToFormat("Image '%s' loaded.", rawImageName); locker.Unlock(); if (handler->HandleThreadDebugged(NULL, stopReason)) return; } else locker.Unlock(); } else if (handlePostExecSetup) { // in the case of an exec(), we can't stop in main() until // the new app image has been loaded, so we know where to // set the main breakpoint at. SymbolInfo symbolInfo; if (fDebuggerInterface->GetSymbolInfo(fTeam->ID(), image->ID(), "main", B_SYMBOL_TYPE_TEXT, symbolInfo) == B_OK) { handler->SetBreakpointAndRun(symbolInfo.Address()); } } else { locker.Unlock(); fDebuggerInterface->ContinueThread(thread->ThreadID()); } } } } void TeamDebugger::_HandleImageFileChanged(image_id imageID) { TRACE_IMAGES("TeamDebugger::_HandleImageFileChanged(%" B_PRId32 ")\n", imageID); // TODO: Reload the debug info! } void TeamDebugger::_HandleSetUserBreakpoint(target_addr_t address, bool enabled, bool hidden) { TRACE_CONTROL("TeamDebugger::_HandleSetUserBreakpoint(%#" B_PRIx64 ", %d, %d)\n", address, enabled, hidden); // check whether there already is a breakpoint AutoLocker< ::Team> locker(fTeam); Breakpoint* breakpoint = fTeam->BreakpointAtAddress(address); UserBreakpoint* userBreakpoint = NULL; if (breakpoint != NULL && breakpoint->FirstUserBreakpoint() != NULL) userBreakpoint = breakpoint->FirstUserBreakpoint()->GetUserBreakpoint(); BReference<UserBreakpoint> userBreakpointReference(userBreakpoint); if (userBreakpoint == NULL) { TRACE_CONTROL(" no breakpoint yet\n"); // get the function at the address Image* image = fTeam->ImageByAddress(address); TRACE_CONTROL(" image: %p\n", image); if (image == NULL) return; ImageDebugInfo* imageDebugInfo = image->GetImageDebugInfo(); TRACE_CONTROL(" image debug info: %p\n", imageDebugInfo); if (imageDebugInfo == NULL) return; // TODO: Handle this case by loading the debug info, if possible! FunctionInstance* functionInstance = imageDebugInfo->FunctionAtAddress(address); TRACE_CONTROL(" function instance: %p\n", functionInstance); if (functionInstance == NULL) return; Function* function = functionInstance->GetFunction(); TRACE_CONTROL(" function: %p\n", function); // get the source location for the address FunctionDebugInfo* functionDebugInfo = functionInstance->GetFunctionDebugInfo(); SourceLocation sourceLocation; Statement* breakpointStatement = NULL; if (functionDebugInfo->GetSpecificImageDebugInfo()->GetStatement( functionDebugInfo, address, breakpointStatement) != B_OK) { return; } sourceLocation = breakpointStatement->StartSourceLocation(); breakpointStatement->ReleaseReference(); target_addr_t relativeAddress = address - functionInstance->Address(); TRACE_CONTROL(" relative address: %#" B_PRIx64 ", source location: " "(%" B_PRId32 ", %" B_PRId32 ")\n", relativeAddress, sourceLocation.Line(), sourceLocation.Column()); // get function id FunctionID* functionID = functionInstance->GetFunctionID(); if (functionID == NULL) return; BReference<FunctionID> functionIDReference(functionID, true); // create the user breakpoint userBreakpoint = new(std::nothrow) UserBreakpoint( UserBreakpointLocation(functionID, function->SourceFile(), sourceLocation, relativeAddress)); if (userBreakpoint == NULL) return; userBreakpointReference.SetTo(userBreakpoint, true); userBreakpoint->SetHidden(hidden); TRACE_CONTROL(" created user breakpoint: %p\n", userBreakpoint); // iterate through all function instances and create // UserBreakpointInstances for (FunctionInstanceList::ConstIterator it = function->Instances().GetIterator(); FunctionInstance* instance = it.Next();) { TRACE_CONTROL(" function instance %p: range: %#" B_PRIx64 " - %#" B_PRIx64 "\n", instance, instance->Address(), instance->Address() + instance->Size()); // get the breakpoint address for the instance target_addr_t instanceAddress = 0; if (instance == functionInstance) { instanceAddress = address; } else if (functionInstance->SourceFile() != NULL) { // We have a source file, so get the address for the source // location. Statement* statement = NULL; functionDebugInfo = instance->GetFunctionDebugInfo(); functionDebugInfo->GetSpecificImageDebugInfo() ->GetStatementAtSourceLocation(functionDebugInfo, sourceLocation, statement); if (statement != NULL) { instanceAddress = statement->CoveringAddressRange().Start(); // TODO: What about BreakpointAllowed()? statement->ReleaseReference(); } } TRACE_CONTROL(" breakpoint address using source info: %" B_PRIx64 "\n", instanceAddress); if (instanceAddress == 0) { // No source file (or we failed getting the statement), so try // to use the same relative address. if (relativeAddress > instance->Size()) continue; instanceAddress = instance->Address() + relativeAddress; } TRACE_CONTROL(" final breakpoint address: %" B_PRIx64 "\n", instanceAddress); UserBreakpointInstance* breakpointInstance = new(std::nothrow) UserBreakpointInstance(userBreakpoint, instanceAddress); if (breakpointInstance == NULL || !userBreakpoint->AddInstance(breakpointInstance)) { delete breakpointInstance; return; } TRACE_CONTROL(" breakpoint instance: %p\n", breakpointInstance); } } locker.Unlock(); _HandleSetUserBreakpoint(userBreakpoint, enabled); } void TeamDebugger::_HandleSetUserBreakpoint(UserBreakpoint* breakpoint, bool enabled) { status_t error = fBreakpointManager->InstallUserBreakpoint(breakpoint, enabled); if (error != B_OK) { _NotifyUser("Install Breakpoint", "Failed to install breakpoint: %s", strerror(error)); } } void TeamDebugger::_HandleClearUserBreakpoint(target_addr_t address) { TRACE_CONTROL("TeamDebugger::_HandleClearUserBreakpoint(%#" B_PRIx64 ")\n", address); AutoLocker< ::Team> locker(fTeam); Breakpoint* breakpoint = fTeam->BreakpointAtAddress(address); if (breakpoint == NULL || breakpoint->FirstUserBreakpoint() == NULL) return; UserBreakpoint* userBreakpoint = breakpoint->FirstUserBreakpoint()->GetUserBreakpoint(); BReference<UserBreakpoint> userBreakpointReference(userBreakpoint); locker.Unlock(); _HandleClearUserBreakpoint(userBreakpoint); } void TeamDebugger::_HandleClearUserBreakpoint(UserBreakpoint* breakpoint) { fBreakpointManager->UninstallUserBreakpoint(breakpoint); } void TeamDebugger::_HandleSetWatchpoint(target_addr_t address, uint32 type, int32 length, bool enabled) { Watchpoint* watchpoint = new(std::nothrow) Watchpoint(address, type, length); if (watchpoint == NULL) return; BReference<Watchpoint> watchpointRef(watchpoint, true); _HandleSetWatchpoint(watchpoint, enabled); } void TeamDebugger::_HandleSetWatchpoint(Watchpoint* watchpoint, bool enabled) { status_t error = fWatchpointManager->InstallWatchpoint(watchpoint, enabled); if (error != B_OK) { _NotifyUser("Install Watchpoint", "Failed to install watchpoint: %s", strerror(error)); } } void TeamDebugger::_HandleClearWatchpoint(target_addr_t address) { TRACE_CONTROL("TeamDebugger::_HandleClearWatchpoint(%#" B_PRIx64 ")\n", address); AutoLocker< ::Team> locker(fTeam); Watchpoint* watchpoint = fTeam->WatchpointAtAddress(address); if (watchpoint == NULL) return; BReference<Watchpoint> watchpointReference(watchpoint); locker.Unlock(); _HandleClearWatchpoint(watchpoint); } void TeamDebugger::_HandleClearWatchpoint(Watchpoint* watchpoint) { fWatchpointManager->UninstallWatchpoint(watchpoint); } void TeamDebugger::_HandleInspectAddress(target_addr_t address, TeamMemoryBlock::Listener* listener) { TRACE_CONTROL("TeamDebugger::_HandleInspectAddress(%" B_PRIx64 ", %p)\n", address, listener); TeamMemoryBlock* memoryBlock = fMemoryBlockManager ->GetMemoryBlock(address); if (memoryBlock == NULL) { _NotifyUser("Inspect Address", "Failed to allocate memory block"); return; } if (!memoryBlock->IsValid()) { AutoLocker< ::Team> teamLocker(fTeam); if (!memoryBlock->HasListener(listener)) memoryBlock->AddListener(listener); TeamMemory* memory = fTeam->GetTeamMemory(); // schedule the job status_t result; if ((result = fWorker->ScheduleJob( new(std::nothrow) RetrieveMemoryBlockJob(fTeam, memory, memoryBlock), this)) != B_OK) { memoryBlock->NotifyDataRetrieved(result); memoryBlock->ReleaseReference(); _NotifyUser("Inspect Address", "Failed to retrieve memory data: %s", strerror(result)); } } else memoryBlock->NotifyDataRetrieved(); } void TeamDebugger::_HandleWriteMemory(target_addr_t address, void* data, target_size_t size) { TRACE_CONTROL("TeamDebugger::_HandleWriteTargetMemory(%" B_PRIx64 ", %p, " "%" B_PRIu64 ")\n", address, data, size); AutoLocker< ::Team> teamLocker(fTeam); TeamMemory* memory = fTeam->GetTeamMemory(); // schedule the job status_t result; if ((result = fWorker->ScheduleJob( new(std::nothrow) WriteMemoryJob(fTeam, memory, address, data, size), this)) != B_OK) { _NotifyUser("Write Memory", "Failed to write memory data: %s", strerror(result)); } } void TeamDebugger::_HandleEvaluateExpression(SourceLanguage* language, ExpressionInfo* info, StackFrame* frame, ::Thread* thread) { status_t result = fWorker->ScheduleJob( new(std::nothrow) ExpressionEvaluationJob(fTeam, fDebuggerInterface, language, info, frame, thread)); if (result != B_OK) { _NotifyUser("Evaluate Expression", "Failed to evaluate expression: %s", strerror(result)); } } void TeamDebugger::_HandleWriteCoreFile(const entry_ref& targetPath) { status_t result = fWorker->ScheduleJob( new(std::nothrow) WriteCoreFileJob(fTeam, fDebuggerInterface, targetPath)); if (result != B_OK) { _NotifyUser("Write Core File", "Failed to write core file: %s", strerror(result)); } } status_t TeamDebugger::_HandleSetArguments(int argc, const char* const* argv) { fCommandLineArgc = argc; fCommandLineArgv = new(std::nothrow) const char*[argc]; if (fCommandLineArgv == NULL) return B_NO_MEMORY; memset(const_cast<char **>(fCommandLineArgv), 0, sizeof(char*) * argc); for (int i = 0; i < argc; i++) { fCommandLineArgv[i] = strdup(argv[i]); if (fCommandLineArgv[i] == NULL) return B_NO_MEMORY; } return B_OK; } void TeamDebugger::_HandleDebugInfoJobUserInput(ImageDebugInfoLoadingState* state) { SpecificImageDebugInfoLoadingState* specificState = state->GetSpecificDebugInfoLoadingState(); ImageDebugLoadingStateHandler* handler; if (ImageDebugLoadingStateHandlerRoster::Default() ->FindStateHandler(specificState, handler) != B_OK) { TRACE_JOBS("TeamDebugger::_HandleDebugInfoJobUserInput(): " "Failed to find appropriate information handler, aborting."); return; } handler->HandleState(specificState, fUserInterface); } ThreadHandler* TeamDebugger::_GetThreadHandler(thread_id threadID) { AutoLocker< ::Team> locker(fTeam); ThreadHandler* handler = fThreadHandlers.Lookup(threadID); if (handler != NULL) handler->AcquireReference(); return handler; } status_t TeamDebugger::_AddImage(const ImageInfo& imageInfo, Image** _image) { LocatableFile* file = NULL; if (strchr(imageInfo.Name(), '/') != NULL) file = fFileManager->GetTargetFile(imageInfo.Name()); BReference<LocatableFile> imageFileReference(file, true); Image* image; status_t error = fTeam->AddImage(imageInfo, file, &image); if (error != B_OK) return error; ImageDebugInfoRequested(image); ImageHandler* imageHandler = new(std::nothrow) ImageHandler(this, image); if (imageHandler != NULL) fImageHandlers->Insert(imageHandler); if (_image != NULL) *_image = image; return B_OK; } void TeamDebugger::_LoadSettings() { // get the team name AutoLocker< ::Team> locker(fTeam); BString teamName = fTeam->Name(); locker.Unlock(); // load the settings if (fSettingsManager->LoadTeamSettings(teamName, fTeamSettings) != B_OK) return; // create the saved breakpoints for (int32 i = 0; const BreakpointSetting* breakpointSetting = fTeamSettings.BreakpointAt(i); i++) { if (breakpointSetting->GetFunctionID() == NULL) continue; // get the source file, if any LocatableFile* sourceFile = NULL; if (breakpointSetting->SourceFile().Length() > 0) { sourceFile = fFileManager->GetSourceFile( breakpointSetting->SourceFile()); if (sourceFile == NULL) continue; } BReference<LocatableFile> sourceFileReference(sourceFile, true); // create the breakpoint UserBreakpointLocation location(breakpointSetting->GetFunctionID(), sourceFile, breakpointSetting->GetSourceLocation(), breakpointSetting->RelativeAddress()); UserBreakpoint* breakpoint = new(std::nothrow) UserBreakpoint(location); if (breakpoint == NULL) return; BReference<UserBreakpoint> breakpointReference(breakpoint, true); breakpoint->SetHidden(breakpointSetting->IsHidden()); breakpoint->SetCondition(breakpointSetting->Condition()); // install it fBreakpointManager->InstallUserBreakpoint(breakpoint, breakpointSetting->IsEnabled()); } fFileManager->LoadLocationMappings(fTeamSettings.FileManagerSettings()); const TeamUiSettings* uiSettings = fTeamSettings.UiSettingFor( fUserInterface->ID()); if (uiSettings != NULL) fUserInterface->LoadSettings(uiSettings); const TeamSignalSettings* signalSettings = fTeamSettings.SignalSettings(); if (signalSettings != NULL) { fTeam->SetDefaultSignalDisposition( signalSettings->DefaultSignalDisposition()); int32 signal; int32 disposition; for (int32 i = 0; i < signalSettings->CountCustomSignalDispositions(); i++) { if (signalSettings->GetCustomSignalDispositionAt(i, signal, disposition) == B_OK) { fTeam->SetCustomSignalDisposition(signal, disposition); } } } } void TeamDebugger::_SaveSettings() { // get the settings AutoLocker< ::Team> locker(fTeam); TeamSettings settings; if (settings.SetTo(fTeam) != B_OK) return; TeamUiSettings* uiSettings = NULL; if (fUserInterface->SaveSettings(uiSettings) != B_OK) return; if (uiSettings != NULL) settings.AddUiSettings(uiSettings); // preserve the UI settings from our cached copy. for (int32 i = 0; i < fTeamSettings.CountUiSettings(); i++) { const TeamUiSettings* oldUiSettings = fTeamSettings.UiSettingAt(i); if (strcmp(oldUiSettings->ID(), fUserInterface->ID()) != 0) { TeamUiSettings* clonedSettings = oldUiSettings->Clone(); if (clonedSettings != NULL) settings.AddUiSettings(clonedSettings); } } fFileManager->SaveLocationMappings(settings.FileManagerSettings()); locker.Unlock(); // save the settings fSettingsManager->SaveTeamSettings(settings); } void TeamDebugger::_NotifyUser(const char* title, const char* text,...) { // print the message char buffer[1024]; va_list args; va_start(args, text); vsnprintf(buffer, sizeof(buffer), text, args); va_end(args); // notify the user fUserInterface->NotifyUser(title, buffer, USER_NOTIFICATION_WARNING); } void TeamDebugger::_ResetUserBackgroundStatusIfNeeded() { if (!fTerminating && !fWorker->HasPendingJobs()) PostMessage(MSG_RESET_USER_BACKGROUND_STATUS); } // #pragma mark - Listener TeamDebugger::Listener::~Listener() { }
23,381
3,102
<reponame>medismailben/llvm-project typedef struct { int x; } TypedefStructHidden_t;
33
4,845
<reponame>gaozining/Sa-Token package com.pj; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import cn.dev33.satoken.SaManager; /** * Sa-Token整合SpringBoot 示例 * @author kong * */ @SpringBootApplication public class SaTokenAloneRedisApplication { public static void main(String[] args) throws ClassNotFoundException { SpringApplication.run(SaTokenAloneRedisApplication.class, args); System.out.println("\n启动成功:Sa-Token配置如下:" + SaManager.getConfig()); } }
201
2,329
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.common.timer; import java.util.Iterator; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; /** * TimerTaskList . */ public class TimerTaskList implements Delayed, Iterable<TimerTask> { private final TimerTaskEntry root; private final AtomicInteger taskCounter; private final AtomicLong expiration = new AtomicLong(-1L); /** * Instantiates a new Timer task list. * * @param taskCounter the task counter */ public TimerTaskList(final AtomicInteger taskCounter) { this.taskCounter = taskCounter; root = new TimerTaskEntry(null, null, -1L); root.next = root; root.prev = root; } /** * Sets expiration. * * @param expirationMs the expiration ms * @return the expiration */ public boolean setExpiration(final long expirationMs) { return expiration.getAndSet(expirationMs) != expirationMs; } /** * Get the bucket's expiration time. * * @return the expiration */ public long getExpiration() { return expiration.get(); } /** * Flush. * * @param consumer the consumer */ synchronized void flush(final Consumer<TimerTaskEntry> consumer) { TimerTaskEntry head = root.next; while (head != root) { this.remove(head); consumer.accept(head); head = root.next; } expiration.set(-1L); } /** * Add. * * @param timerTaskEntry the timer task entry */ public void add(final TimerTaskEntry timerTaskEntry) { boolean done = false; while (!done) { timerTaskEntry.remove(); synchronized (this) { if (timerTaskEntry.list == null) { TimerTaskEntry tail = root.prev; timerTaskEntry.next = root; timerTaskEntry.prev = tail; timerTaskEntry.list = this; tail.next = timerTaskEntry; root.prev = timerTaskEntry; taskCounter.incrementAndGet(); done = true; } } } } /** * Traversing using this is thread-safe. * * @param consumer the consumer */ public synchronized void foreach(final Consumer<TimerTask> consumer) { TimerTaskEntry entry = root.next; while (entry != root) { TimerTaskEntry next = entry.next; if (!entry.cancelled()) { consumer.accept(entry.timerTask); } entry = next; } } @Override public long getDelay(final TimeUnit unit) { long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); return unit.convert(Math.max(getExpiration() - millis, 0), TimeUnit.MILLISECONDS); } @Override public int compareTo(final Delayed delayed) { boolean other = delayed instanceof TimerTaskList; if (other) { long expiration = ((TimerTaskList) delayed).getExpiration(); return Long.compare(getExpiration(), expiration); } else { return -1; } } /** * Remove. * * @param timerTaskEntry the timer task entry */ public void remove(final TimerTaskEntry timerTaskEntry) { synchronized (this) { if (timerTaskEntry.list == this) { timerTaskEntry.next.prev = timerTaskEntry.prev; timerTaskEntry.prev.next = timerTaskEntry.next; timerTaskEntry.next = null; timerTaskEntry.prev = null; timerTaskEntry.list = null; taskCounter.decrementAndGet(); } } } /** * Using Iterator is not thread safe. * * @return an Iterator. */ @Override public Iterator<TimerTask> iterator() { return new Itr(root.next); } /** * The type Timer task entry. */ public static class TimerTaskEntry implements TaskEntity, Comparable<TimerTaskEntry> { private final Timer timer; private final TimerTask timerTask; private final Long expirationMs; /** * The List. */ private TimerTaskList list; /** * The Next. */ private TimerTaskEntry next; /** * The Prev. */ private TimerTaskEntry prev; /** * Instantiates a new Timer task entry. * * @param timer the timer * @param timerTask the timer task * @param expirationMs the expiration ms */ public TimerTaskEntry(final Timer timer, final TimerTask timerTask, final Long expirationMs) { this.timerTask = timerTask; this.expirationMs = expirationMs; this.timer = timer; if (timerTask != null) { timerTask.setTimerTaskEntry(this); } } /** * Has the current task been cancelled. * * @return the boolean */ @Override public boolean cancelled() { return this.timerTask.getTimerTaskEntry() != this; } /** * Cancel boolean. */ @Override public void cancel() { this.timerTask.cancel(); } /** * Gets expiration ms. * * @return the expiration ms */ public Long getExpirationMs() { return expirationMs; } /** * Gets timer. * * @return the timer */ @Override public Timer getTimer() { return this.timer; } /** * Gets timer task. * * @return the timer task */ @Override public TimerTask getTimerTask() { return timerTask; } /** * Remove. */ void remove() { TimerTaskList currentList = list; while (currentList != null) { currentList.remove(this); currentList = list; } } @Override public int compareTo(final TimerTaskEntry timerTaskEntry) { return Long.compare(expirationMs, timerTaskEntry.expirationMs); } } /** * The type Itr. */ private class Itr implements Iterator<TimerTask> { private TimerTaskEntry entry; /** * Instantiates a new Itr. * * @param entry the entry */ Itr(final TimerTaskEntry entry) { this.entry = entry; } @Override public boolean hasNext() { if (entry != root) { return !entry.cancelled(); } return false; } @Override public TimerTask next() { TimerTask timerTask = null; if (entry != root) { TimerTaskEntry nextEntry = entry.next; if (!entry.cancelled()) { timerTask = entry.timerTask; } entry = nextEntry; } return timerTask; } @Override public void remove() { entry.remove(); } } }
4,077
651
package net.serenitybdd.integration.jenkins.process; import org.jdeferred.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.Charset; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Matcher; public class JenkinsLogWatcher implements AutoCloseable, Runnable { private static final Logger Log = LoggerFactory.getLogger(JenkinsLogWatcher.class); private final InputStream jenkinsOutput; private final List<JenkinsLogLineWatcher> watchers = new CopyOnWriteArrayList<>(); private boolean stop = false; public JenkinsLogWatcher(InputStream jenkinsOutput) { this.jenkinsOutput = jenkinsOutput; } public Promise<Matcher, ?, ?> watchFor(String patternToMatchAgainstALogLine) { JenkinsLogLineWatcher watcher = new JenkinsLogLineWatcher(patternToMatchAgainstALogLine); watchers.add(watcher); return watcher.promise(); } @Override public void close() throws Exception { stop = true; jenkinsOutput.close(); watchers.clear(); } @Override public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(jenkinsOutput, Charset.forName("UTF-8")))) { String line; while ((line = reader.readLine()) != null) { Log.debug(line); for (JenkinsLogLineWatcher watcher : watchers) { if (watcher.matches(line)) { watchers.remove(watcher); } } } } catch (IOException e) { if (stop && "Stream closed".equals(e.getMessage())) { Log.debug("Jenkins OutputStream was closed, but that was expected since we're stopping the log watcher."); } else { throw new RuntimeException("Jenkins output stream is already closed", e); } } } }
830
8,747
<gh_stars>1000+ /* TWAI Network Slave Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* * The following example demonstrates a slave node in a TWAI network. The slave * node is responsible for sending data messages to the master. The example will * execute multiple iterations, with each iteration the slave node will do the * following: * 1) Start the TWAI driver * 2) Listen for ping messages from master, and send ping response * 3) Listen for start command from master * 4) Send data messages to master and listen for stop command * 5) Send stop response to master * 6) Stop the TWAI driver */ #include <stdio.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "esp_err.h" #include "esp_log.h" #include "driver/twai.h" /* --------------------- Definitions and static variables ------------------ */ //Example Configuration #define DATA_PERIOD_MS 50 #define NO_OF_ITERS 3 #define ITER_DELAY_MS 1000 #define RX_TASK_PRIO 8 //Receiving task priority #define TX_TASK_PRIO 9 //Sending task priority #define CTRL_TSK_PRIO 10 //Control task priority #define TX_GPIO_NUM CONFIG_EXAMPLE_TX_GPIO_NUM #define RX_GPIO_NUM CONFIG_EXAMPLE_RX_GPIO_NUM #define EXAMPLE_TAG "TWAI Slave" #define ID_MASTER_STOP_CMD 0x0A0 #define ID_MASTER_START_CMD 0x0A1 #define ID_MASTER_PING 0x0A2 #define ID_SLAVE_STOP_RESP 0x0B0 #define ID_SLAVE_DATA 0x0B1 #define ID_SLAVE_PING_RESP 0x0B2 typedef enum { TX_SEND_PING_RESP, TX_SEND_DATA, TX_SEND_STOP_RESP, TX_TASK_EXIT, } tx_task_action_t; typedef enum { RX_RECEIVE_PING, RX_RECEIVE_START_CMD, RX_RECEIVE_STOP_CMD, RX_TASK_EXIT, } rx_task_action_t; static const twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(TX_GPIO_NUM, RX_GPIO_NUM, TWAI_MODE_NORMAL); static const twai_timing_config_t t_config = TWAI_TIMING_CONFIG_25KBITS(); static const twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); static const twai_message_t ping_resp = {.identifier = ID_SLAVE_PING_RESP, .data_length_code = 0, .data = {0, 0 , 0 , 0 ,0 ,0 ,0 ,0}}; static const twai_message_t stop_resp = {.identifier = ID_SLAVE_STOP_RESP, .data_length_code = 0, .data = {0, 0 , 0 , 0 ,0 ,0 ,0 ,0}}; //Data bytes of data message will be initialized in the transmit task static twai_message_t data_message = {.identifier = ID_SLAVE_DATA, .data_length_code = 4, .data = {0, 0 , 0 , 0 ,0 ,0 ,0 ,0}}; static QueueHandle_t tx_task_queue; static QueueHandle_t rx_task_queue; static SemaphoreHandle_t ctrl_task_sem; static SemaphoreHandle_t stop_data_sem; static SemaphoreHandle_t done_sem; /* --------------------------- Tasks and Functions -------------------------- */ static void twai_receive_task(void *arg) { while (1) { rx_task_action_t action; xQueueReceive(rx_task_queue, &action, portMAX_DELAY); if (action == RX_RECEIVE_PING) { //Listen for pings from master twai_message_t rx_msg; while (1) { twai_receive(&rx_msg, portMAX_DELAY); if (rx_msg.identifier == ID_MASTER_PING) { xSemaphoreGive(ctrl_task_sem); break; } } } else if (action == RX_RECEIVE_START_CMD) { //Listen for start command from master twai_message_t rx_msg; while (1) { twai_receive(&rx_msg, portMAX_DELAY); if (rx_msg.identifier == ID_MASTER_START_CMD) { xSemaphoreGive(ctrl_task_sem); break; } } } else if (action == RX_RECEIVE_STOP_CMD) { //Listen for stop command from master twai_message_t rx_msg; while (1) { twai_receive(&rx_msg, portMAX_DELAY); if (rx_msg.identifier == ID_MASTER_STOP_CMD) { xSemaphoreGive(stop_data_sem); xSemaphoreGive(ctrl_task_sem); break; } } } else if (action == RX_TASK_EXIT) { break; } } vTaskDelete(NULL); } static void twai_transmit_task(void *arg) { while (1) { tx_task_action_t action; xQueueReceive(tx_task_queue, &action, portMAX_DELAY); if (action == TX_SEND_PING_RESP) { //Transmit ping response to master twai_transmit(&ping_resp, portMAX_DELAY); ESP_LOGI(EXAMPLE_TAG, "Transmitted ping response"); xSemaphoreGive(ctrl_task_sem); } else if (action == TX_SEND_DATA) { //Transmit data messages until stop command is received ESP_LOGI(EXAMPLE_TAG, "Start transmitting data"); while (1) { //FreeRTOS tick count used to simulate sensor data uint32_t sensor_data = xTaskGetTickCount(); for (int i = 0; i < 4; i++) { data_message.data[i] = (sensor_data >> (i * 8)) & 0xFF; } twai_transmit(&data_message, portMAX_DELAY); ESP_LOGI(EXAMPLE_TAG, "Transmitted data value %d", sensor_data); vTaskDelay(pdMS_TO_TICKS(DATA_PERIOD_MS)); if (xSemaphoreTake(stop_data_sem, 0) == pdTRUE) { break; } } } else if (action == TX_SEND_STOP_RESP) { //Transmit stop response to master twai_transmit(&stop_resp, portMAX_DELAY); ESP_LOGI(EXAMPLE_TAG, "Transmitted stop response"); xSemaphoreGive(ctrl_task_sem); } else if (action == TX_TASK_EXIT) { break; } } vTaskDelete(NULL); } static void twai_control_task(void *arg) { xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); tx_task_action_t tx_action; rx_task_action_t rx_action; for (int iter = 0; iter < NO_OF_ITERS; iter++) { ESP_ERROR_CHECK(twai_start()); ESP_LOGI(EXAMPLE_TAG, "Driver started"); //Listen of pings from master rx_action = RX_RECEIVE_PING; xQueueSend(rx_task_queue, &rx_action, portMAX_DELAY); xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); //Send ping response tx_action = TX_SEND_PING_RESP; xQueueSend(tx_task_queue, &tx_action, portMAX_DELAY); xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); //Listen for start command rx_action = RX_RECEIVE_START_CMD; xQueueSend(rx_task_queue, &rx_action, portMAX_DELAY); xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); //Start sending data messages and listen for stop command tx_action = TX_SEND_DATA; rx_action = RX_RECEIVE_STOP_CMD; xQueueSend(tx_task_queue, &tx_action, portMAX_DELAY); xQueueSend(rx_task_queue, &rx_action, portMAX_DELAY); xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); //Send stop response tx_action = TX_SEND_STOP_RESP; xQueueSend(tx_task_queue, &tx_action, portMAX_DELAY); xSemaphoreTake(ctrl_task_sem, portMAX_DELAY); //Wait for bus to become free twai_status_info_t status_info; twai_get_status_info(&status_info); while (status_info.msgs_to_tx > 0) { vTaskDelay(pdMS_TO_TICKS(100)); twai_get_status_info(&status_info); } ESP_ERROR_CHECK(twai_stop()); ESP_LOGI(EXAMPLE_TAG, "Driver stopped"); vTaskDelay(pdMS_TO_TICKS(ITER_DELAY_MS)); } //Stop TX and RX tasks tx_action = TX_TASK_EXIT; rx_action = RX_TASK_EXIT; xQueueSend(tx_task_queue, &tx_action, portMAX_DELAY); xQueueSend(rx_task_queue, &rx_action, portMAX_DELAY); //Delete Control task xSemaphoreGive(done_sem); vTaskDelete(NULL); } void app_main(void) { //Add short delay to allow master it to initialize first for (int i = 3; i > 0; i--) { printf("Slave starting in %d\n", i); vTaskDelay(pdMS_TO_TICKS(1000)); } //Create semaphores and tasks tx_task_queue = xQueueCreate(1, sizeof(tx_task_action_t)); rx_task_queue = xQueueCreate(1, sizeof(rx_task_action_t)); ctrl_task_sem = xSemaphoreCreateBinary(); stop_data_sem = xSemaphoreCreateBinary();; done_sem = xSemaphoreCreateBinary();; xTaskCreatePinnedToCore(twai_receive_task, "TWAI_rx", 4096, NULL, RX_TASK_PRIO, NULL, tskNO_AFFINITY); xTaskCreatePinnedToCore(twai_transmit_task, "TWAI_tx", 4096, NULL, TX_TASK_PRIO, NULL, tskNO_AFFINITY); xTaskCreatePinnedToCore(twai_control_task, "TWAI_ctrl", 4096, NULL, CTRL_TSK_PRIO, NULL, tskNO_AFFINITY); //Install TWAI driver, trigger tasks to start ESP_ERROR_CHECK(twai_driver_install(&g_config, &t_config, &f_config)); ESP_LOGI(EXAMPLE_TAG, "Driver installed"); xSemaphoreGive(ctrl_task_sem); //Start Control task xSemaphoreTake(done_sem, portMAX_DELAY); //Wait for tasks to complete //Uninstall TWAI driver ESP_ERROR_CHECK(twai_driver_uninstall()); ESP_LOGI(EXAMPLE_TAG, "Driver uninstalled"); //Cleanup vSemaphoreDelete(ctrl_task_sem); vSemaphoreDelete(stop_data_sem); vSemaphoreDelete(done_sem); vQueueDelete(tx_task_queue); vQueueDelete(rx_task_queue); }
4,850
808
<reponame>carllhw/dddplus package io.github.dddplus.runtime; import org.junit.Test; import static org.junit.Assert.*; public class ExtTimeoutExceptionTest { @Test public void getMessage() { ExtTimeoutException extTimeoutException = new ExtTimeoutException(5000); assertEquals("timeout:5000ms", extTimeoutException.getMessage()); } }
126
992
<filename>Src/MarchingCubes.h /* Copyright (c) 2006, <NAME> and <NAME> 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 Johns Hopkins University 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 MARCHING_CUBES_INCLUDED #define MARCHING_CUBES_INCLUDED #include <stdio.h> #include <type_traits> #include "Geometry.h" #include "Window.h" namespace HyperCube { enum Direction{ BACK , CROSS , FRONT }; inline Direction Opposite( Direction dir ){ return dir==BACK ? FRONT : ( dir==FRONT ? BACK : CROSS ); } // The number of k-dimensional elements in a d-dimensional cube is equal to // the number of (k-1)-dimensional elements in a (d-1)-dimensional hypercube plus twice the number of k-dimensional elements in a (d-1)-dimensional hypercube // Number of elements of dimension K in a cube of dimension D template< unsigned int D , unsigned int K > struct ElementNum { static const unsigned int Value = 2 * ElementNum< D-1 , K >::Value + ElementNum< D-1 , K-1 >::Value; }; template< unsigned int D > struct ElementNum< D , 0 >{ static const unsigned int Value = 2 * ElementNum< D-1 , 0 >::Value; }; template< unsigned int D > struct ElementNum< D , D >{ static const unsigned int Value = 1; }; template< > struct ElementNum< 0 , 0 >{ static const unsigned int Value = 1; }; // [WARNING] This shouldn't really happen, but we need to support the definition of OverlapElementNum template< unsigned int K > struct ElementNum< 0 , K >{ static const unsigned int Value = K==0 ? 1 : 0; }; template< unsigned int D , unsigned int K1 , unsigned int K2 > struct OverlapElementNum { static const unsigned int Value = K1>=K2 ? ElementNum< K1 , K2 >::Value : OverlapElementNum< D-1 , K1 , K2 >::Value + OverlapElementNum< D-1 , K1 , K2-1 >::Value; }; template< unsigned int D , unsigned int K > struct OverlapElementNum< D , D , K >{ static const unsigned int Value = ElementNum< D , K >::Value; }; template< unsigned int D > struct OverlapElementNum< D , D , 0 >{ static const unsigned int Value = ElementNum< D , 0 >::Value; }; template< unsigned int D , unsigned int K > struct OverlapElementNum< D , K , 0 >{ static const unsigned int Value = ElementNum< K , 0 >::Value; }; template< unsigned int D , unsigned int K > struct OverlapElementNum< D , K , K >{ static const unsigned int Value = 1; }; template< unsigned int D , unsigned int K > struct OverlapElementNum< D , K , D >{ static const unsigned int Value = 1; }; template< unsigned int D > struct OverlapElementNum< D , D , D >{ static const unsigned int Value = 1; }; template< unsigned int D > struct OverlapElementNum< D , 0 , 0 >{ static const unsigned int Value = 1; }; template< unsigned int D > struct Cube { // Corner index (x,y,z,...) -> x + 2*y + 4*z + ... // CROSS -> the D-th axis // Representation of a K-dimensional element of the cube template< unsigned int K > struct Element { static_assert( D>=K , "[ERROR] Element dimension exceeds cube dimension" ); // The index of the element, sorted as: // 1. All K-dimensional elements contained in the back face // 2. All K-dimensional elements spanning the D-th axis // 3. All K-dimensional elements contained in the front face unsigned int index; // Initialize by index Element( unsigned int idx=0 ); // Initialize by co-index: // 1. A K-dimensional element in either BACK or FRONT // 2. A (K-1)-dimensional element extruded across the D-th axis Element( Direction dir , unsigned int coIndex ); // Given a K-Dimensional sub-element living inside a DK-dimensional sub-cube, get the element relative to the D-dimensional cube template< unsigned int DK > Element( Element< DK > subCube , typename Cube< DK >::template Element< K > subElement ); // Initialize by setting the directions Element( const Direction dirs[D] ); // Print the element to the specified stream void print( FILE* fp=stdout ) const; // Sets the direction and co-index of the element void factor( Direction& dir , unsigned int& coIndex ) const; // Returns the direction along which the element lives Direction direction( void ) const; // Returns the co-index of the element unsigned int coIndex( void ) const; // Compute the directions of the element void directions( Direction* dirs ) const; // Returns the antipodal element typename Cube< D >::template Element< K > antipodal( void ) const; // Comparison operators bool operator < ( Element e ) const { return index< e.index; } bool operator <= ( Element e ) const { return index<=e.index; } bool operator > ( Element e ) const { return index> e.index; } bool operator >= ( Element e ) const { return index>=e.index; } bool operator == ( Element e ) const { return index==e.index; } bool operator != ( Element e ) const { return index!=e.index; } bool operator < ( unsigned int i ) const { return index< i; } bool operator <= ( unsigned int i ) const { return index<=i; } bool operator > ( unsigned int i ) const { return index> i; } bool operator >= ( unsigned int i ) const { return index>=i; } bool operator == ( unsigned int i ) const { return index==i; } bool operator != ( unsigned int i ) const { return index!=i; } // Increment operators Element& operator ++ ( void ) { index++ ; return *this; } Element operator ++ ( int ) { index++ ; return Element(index-1); } protected: template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D!=0 && _K!=0 >::type _setElement( Direction dir , unsigned int coIndex ); template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D!=0 && _K==0 >::type _setElement( Direction dir , unsigned int coIndex ); template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D==0 && _K==0 >::type _setElement( Direction dir , unsigned int coIndex ); template< unsigned int KD > typename std::enable_if< (D> KD) && (KD>K) && K!=0 >::type _setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ); template< unsigned int KD > typename std::enable_if< (D> KD) && (KD>K) && K==0 >::type _setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ); template< unsigned int KD > typename std::enable_if< (D==KD) && (KD>K) >::type _setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ); template< unsigned int KD > typename std::enable_if< (KD==K) >::type _setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ); template< unsigned int _D=D > typename std::enable_if< _D!=0 >::type _setElement( const Direction* dirs ); template< unsigned int _D=D > typename std::enable_if< _D==0 >::type _setElement( const Direction* dirs ); template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D==_K >::type _factor( Direction& dir , unsigned int& coIndex ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D!=_K && _K!=0 >::type _factor( Direction& dir , unsigned int& coIndex ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D!=_K && _K==0 >::type _factor( Direction& dir , unsigned int& coIndex ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< (_D>_K) && _K!=0 >::type _directions( Direction* dirs ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< (_D>_K) && _K==0 >::type _directions( Direction* dirs ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D==_K >::type _directions( Direction* dirs ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< (_D>_K) && _K!=0 , Element >::type _antipodal( void ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< (_D>_K) && _K==0 , Element >::type _antipodal( void ) const; template< unsigned int _D=D , unsigned int _K=K > typename std::enable_if< _D==_K , Element >::type _antipodal( void ) const; }; // A way of indexing the cubes incident on an element template< unsigned int K > using IncidentCubeIndex = typename Cube< D-K >::template Element< 0 >; // Number of elements of dimension K template< unsigned int K > static constexpr unsigned int ElementNum( void ){ return HyperCube::ElementNum< D , K >::Value; } // Number of cubes incident to an element of dimension K template< unsigned int K > static constexpr unsigned int IncidentCubeNum( void ){ return HyperCube::ElementNum< D-K , 0 >::Value; } // Number of overlapping elements of dimension K1 / K2 template< unsigned int K1 , unsigned int K2 > static constexpr unsigned int OverlapElementNum( void ){ return HyperCube::OverlapElementNum< D , K1 , K2 >::Value; } // Is the face outward-facing static bool IsOriented( Element< D-1 > e ); // Is one element contained in the other? template< unsigned int K1 , unsigned int K2 > static bool Overlap( Element< K1 > e1 , Element< K2 > e2 ); // If K1>K2: returns all elements contained in e // Else: returns all elements containing e template< unsigned int K1 , unsigned int K2 > static void OverlapElements( Element< K1 > e , Element< K2 >* es ); // Returns the marching-cubes index for the set of values template< typename Real > static unsigned int MCIndex( const Real values[ Cube::ElementNum< 0 >() ] , Real iso ); // Extracts the marching-cubes sub-index for the associated element template< unsigned int K > static unsigned int ElementMCIndex( Element< K > element , unsigned int mcIndex ); // Does the marching cubes index have a zero-crossing static bool HasMCRoots( unsigned int mcIndex ); // Sets the offset of the incident cube relative to the center cube, x[i] \in {-1,0,1} template< unsigned int K > static void CellOffset( Element< K > e , IncidentCubeIndex< K > d , int x[D] ); // Returns the linearized offset of the incident cube relative to the center cube, \in [0,3^D) template< unsigned int K > static unsigned int CellOffset( Element< K > e , IncidentCubeIndex< K > d ); // Returns the index of the incident cube that is the source template< unsigned int K > static typename Cube< D >::template IncidentCubeIndex< K > IncidentCube( Element< K > e ); // Returns the corresponding element in the incident cube template< unsigned int K > static typename Cube< D >::template Element< K > IncidentElement( Element< K > e , IncidentCubeIndex< K > d ); protected: template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1>=K2) , bool >::type _Overlap( Element< K1 > e1 , Element< K2 > e2 ); template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1< K2) , bool >::type _Overlap( Element< K1 > e1 , Element< K2 > e2 ); template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1>=K2) >::type _OverlapElements( Element< K1 > e , Element< K2 >* es ); template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1< K2) && D==K2 >::type _OverlapElements( Element< K1 > e , Element< K2 >* es ); template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1< K2) && D!=K2 && K1!=0 >::type _OverlapElements( Element< K1 > e , Element< K2 >* es ); template< unsigned int K1 , unsigned int K2 > static typename std::enable_if< (K1< K2) && D!=K2 && K1==0 >::type _OverlapElements( Element< K1 > e , Element< K2 >* es ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K , IncidentCubeIndex< K > >::type _IncidentCube( Element< K > e ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && _D!=0 && K!=0 , IncidentCubeIndex< K > >::type _IncidentCube( Element< K > e ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && _D!=0 && K==0 , IncidentCubeIndex< K > >::type _IncidentCube( Element< K > e ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d , int* x ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K!=0 >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d , int* x ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K==0 >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d , int* x ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K && K==0 , unsigned int >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K && K!=0 , unsigned int >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K!=0 , unsigned int >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K==0 , unsigned int >::type _CellOffset( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K , Element< K > >::type _IncidentElement( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && _D!=0 && K!=0 , Element< K > >::type _IncidentElement( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && _D!=0 && K==0 , Element< K > >::type _IncidentElement( Element< K > e , IncidentCubeIndex< K > d ); template< unsigned int _D=D > static typename std::enable_if< _D!=1 >::type _FactorOrientation( Element< D-1 > e , unsigned int& dim , Direction& dir ); template< unsigned int _D=D > static typename std::enable_if< _D==1 >::type _FactorOrientation( Element< D-1 > e , unsigned int& dim , Direction& dir ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K!=0 , unsigned int >::type _ElementMCIndex( Element< K > element , unsigned int mcIndex ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D!=K && K==0 , unsigned int >::type _ElementMCIndex( Element< K > element , unsigned int mcIndex ); template< unsigned int K , unsigned int _D=D > static typename std::enable_if< _D==K , unsigned int >::type _ElementMCIndex( Element< K > element , unsigned int mcIndex ); template< unsigned int DD > friend struct Cube; }; // Specialized class for extracting iso-curves from a square struct MarchingSquares { const static unsigned int MAX_EDGES=2; static const int edges[1<<HyperCube::Cube< 2 >::ElementNum< 0 >()][2*MAX_EDGES+1]; static int AddEdgeIndices( unsigned char mcIndex , int* edges); }; /////////////////// // Cube::Element // /////////////////// template< unsigned int D > template< unsigned int K > Cube< D >::Element< K >::Element( unsigned int idx ) : index( idx ){} template< unsigned int D > template< unsigned int K > Cube< D >::Element< K >::Element( Direction dir , unsigned int coIndex ){ _setElement( dir , coIndex ); } template< unsigned int D > template< unsigned int K > template< unsigned int DK > Cube< D >::Element< K >::Element( Element< DK > subCube , typename Cube< DK >::template Element< K > subElement ) { static_assert( DK>=K , "[ERROR] Element::Element: sub-cube dimension cannot be smaller than the sub-element dimension" ); static_assert( DK<=D , "[ERROR] Element::Element: sub-cube dimension cannot be larger than the cube dimension" ); _setElement( subCube , subElement ); } template< unsigned int D > template< unsigned int K > Cube< D >::Element< K >::Element( const Direction dirs[D] ){ _setElement( dirs ); } template< unsigned int D > template< unsigned int K > template< unsigned int KD > typename std::enable_if< (D>KD) && (KD>K) && K!=0 >::type Cube< D >::Element< K >::_setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ) { Direction dir ; unsigned int coIndex; subCube.factor( dir , coIndex ); // If the sub-cube lies entirely in the back/front, we can compute the element in the smaller cube. if( dir==BACK || dir==FRONT ) { typename Cube< D-1 >::template Element< KD > _subCube( coIndex ); typename Cube< D-1 >::template Element< K > _element( _subCube , subElement ); *this = Element( dir , _element.index ); } else { typename Cube< D-1 >::template Element< KD-1 > _subCube( coIndex ); Direction _dir ; unsigned int _coIndex; subElement.factor( _dir , _coIndex ); // If the sub-element lies entirely in the back/front, we can compute the element in the smaller cube. if( _dir==BACK || _dir==FRONT ) { typename Cube< KD-1 >::template Element< K > _subElement( _coIndex ); typename Cube< D-1 >::template Element< K > _element( _subCube , _subElement ); *this = Element( _dir , _element.index ); } // Otherwise else { typename Cube< KD-1 >::template Element< K-1 > _subElement( _coIndex ); typename Cube< D-1 >::template Element< K-1 > _element( _subCube , _subElement ); *this = Element( _dir , _element.index ); } } } template< unsigned int D > template< unsigned int K > template< unsigned int KD > typename std::enable_if< (D>KD) && (KD>K) && K==0 >::type Cube< D >::Element< K >::_setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ) { Direction dir ; unsigned int coIndex; subCube.factor( dir , coIndex ); // If the sub-cube lies entirely in the back/front, we can compute the element in the smaller cube. if( dir==BACK || dir==FRONT ) { typename Cube< D-1 >::template Element< KD > _subCube( coIndex ); typename Cube< D-1 >::template Element< K > _element( _subCube , subElement ); *this = Element( dir , _element.index ); } else { typename Cube< D-1 >::template Element< KD-1 > _subCube( coIndex ); Direction _dir ; unsigned int _coIndex; subElement.factor( _dir , _coIndex ); // If the sub-element lies entirely in the back/front, we can compute the element in the smaller cube. if( _dir==BACK || _dir==FRONT ) { typename Cube< KD-1 >::template Element< K > _subElement( _coIndex ); typename Cube< D-1 >::template Element< K > _element( _subCube , _subElement ); *this = Element( _dir , _element.index ); } } } template< unsigned int D > template< unsigned int K > template< unsigned int KD > typename std::enable_if< (D==KD) && (KD>K) >::type Cube< D >::Element< K >::_setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ){ *this = subElement; } template< unsigned int D > template< unsigned int K > template< unsigned int KD > typename std::enable_if< (KD==K) >::type Cube< D >::Element< K >::_setElement( typename Cube< D >::template Element< KD > subCube , typename Cube< KD >::template Element< K > subElement ){ *this = subCube; } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D!=0 && _K!=0 >::type Cube< D >::Element< K >::_setElement( Direction dir , unsigned int coIndex ) { switch( dir ) { case BACK: index = coIndex ; break; case CROSS: index = coIndex + HyperCube::ElementNum< D-1 , K >::Value ; break; case FRONT: index = coIndex + HyperCube::ElementNum< D-1 , K >::Value + HyperCube::ElementNum< D-1 , K-1 >::Value ; break; default: ERROR_OUT( "Bad direction: " , dir ); } } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D!=0 && _K==0 >::type Cube< D >::Element< K >::_setElement( Direction dir , unsigned int coIndex ) { switch( dir ) { case BACK: index = coIndex ; break; case FRONT: index = coIndex + HyperCube::ElementNum< D-1 , K >::Value ; break; default: ERROR_OUT( "Bad direction: " , dir ); } } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D==0 && _K==0 >::type Cube< D >::Element< K >::_setElement( Direction dir , unsigned int coIndex ){ index = coIndex; } template< unsigned int D > template< unsigned int K > template< unsigned int _D > typename std::enable_if< _D!=0 >::type Cube< D >::Element< K>::_setElement( const Direction* dirs ) { if( dirs[D-1]==CROSS ) *this = Element( dirs[D-1] , typename Cube< D-1 >::template Element< K-1 >( dirs ).index ); else *this = Element( dirs[D-1] , typename Cube< D-1 >::template Element< K >( dirs ).index ); } template< unsigned int D > template< unsigned int K > template< unsigned int _D > typename std::enable_if< _D==0 >::type Cube< D >::Element< K>::_setElement( const Direction* dirs ){} template< unsigned int D > template< unsigned int K > void Cube< D >::Element< K >::print( FILE* fp ) const { Direction dirs[D==0?1:D]; directions( dirs ); for( int d=0 ; d<D ; d++ ) fprintf( fp , "%c" , dirs[d]==BACK ? 'B' : ( dirs[d]==CROSS ? 'C' : 'F' ) ); } template< unsigned int D > template< unsigned int K > void Cube< D >::Element< K >::factor( Direction& dir , unsigned int& coIndex ) const { _factor( dir , coIndex ); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D!=_K && _K!=0 >::type Cube< D >::Element< K >::_factor( Direction& dir , unsigned int& coIndex ) const { if ( index<HyperCube::ElementNum< D-1 , K >::Value ) dir = BACK , coIndex = index; else if( index<HyperCube::ElementNum< D-1 , K >::Value + HyperCube::ElementNum< D-1 , K-1 >::Value ) dir = CROSS , coIndex = index - HyperCube::ElementNum< D-1 , K >::Value; else dir = FRONT , coIndex = index - HyperCube::ElementNum< D-1 , K >::Value - HyperCube::ElementNum< D-1 , K-1 >::Value; } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D!=_K && _K==0 >::type Cube< D >::Element< K >::_factor( Direction& dir , unsigned int& coIndex ) const { if ( index<HyperCube::ElementNum< D-1 , K >::Value ) dir = BACK , coIndex = index; else dir = FRONT , coIndex = index - HyperCube::ElementNum< D-1 , K >::Value; } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D==_K >::type Cube< D >::Element< K >::_factor( Direction& dir , unsigned int& coIndex ) const { dir=CROSS , coIndex=0; } template< unsigned int D > template< unsigned int K > Direction Cube< D >::Element< K >::direction( void ) const { Direction dir ; unsigned int coIndex; factor( dir , coIndex ); return dir; } template< unsigned int D > template< unsigned int K > unsigned int Cube< D >::Element< K >::coIndex( void ) const { Direction dir ; unsigned int coIndex; factor( dir , coIndex ); return coIndex; } template< unsigned int D > template< unsigned int K > void Cube< D >::Element< K >::directions( Direction* dirs ) const { _directions( dirs ); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< (_D>_K) && _K!=0 >::type Cube< D >::Element< K >::_directions( Direction* dirs ) const { unsigned int coIndex; factor( dirs[D-1] , coIndex ); if( dirs[D-1]==CROSS ) typename Cube< D-1 >::template Element< K-1 >( coIndex ).directions( dirs ); else typename Cube< D-1 >::template Element< K >( coIndex ).directions( dirs ); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< (_D>_K) && _K==0 >::type Cube< D >::Element< K >::_directions( Direction* dirs ) const { unsigned int coIndex; factor( dirs[D-1] , coIndex ); if( dirs[D-1]==FRONT || dirs[D-1]==BACK ) typename Cube< D-1 >::template Element< K >( coIndex ).directions( dirs ); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > typename std::enable_if< _D==_K >::type Cube< D >::Element< K >::_directions( Direction* dirs ) const { for( int d=0 ; d<D ; d++ ) dirs[d] = CROSS; } template< unsigned int D > template< unsigned int K > typename Cube< D >::template Element< K > Cube< D >::Element< K >::antipodal( void ) const { return _antipodal(); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > #ifdef _MSC_VER typename std::enable_if< (_D>_K) && _K!=0 , typename Cube< D >::Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const #else // !_MSC_VER typename std::enable_if< (_D>_K) && _K!=0 , typename Cube< D >::template Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const #endif // _MSC_VER { Direction dir ; unsigned int coIndex; factor( dir , coIndex ); if ( dir==CROSS ) return Element< K >( CROSS , typename Cube< D-1 >::template Element< K-1 >( coIndex ).antipodal().index ); else if( dir==FRONT ) return Element< K >( BACK , typename Cube< D-1 >::template Element< K >( coIndex ).antipodal().index ); else if( dir==BACK ) return Element< K >( FRONT , typename Cube< D-1 >::template Element< K >( coIndex ).antipodal().index ); return Element< K >(); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > #ifdef _MSC_VER typename std::enable_if< (_D>_K) && _K==0 , typename Cube< D >::Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const #else // !_MSC_VER typename std::enable_if< (_D>_K) && _K==0 , typename Cube< D >::template Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const #endif // _MSC_VER { Direction dir ; unsigned int coIndex; factor( dir , coIndex ); if ( dir==FRONT ) return Element< K >( BACK , typename Cube< D-1 >::template Element< K >( coIndex ).antipodal().index ); else if( dir==BACK ) return Element< K >( FRONT , typename Cube< D-1 >::template Element< K >( coIndex ).antipodal().index ); return Element< K >(); } template< unsigned int D > template< unsigned int K > template< unsigned int _D , unsigned int _K > #ifdef _MSC_VER typename std::enable_if< _D==_K , typename Cube< D >::Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const { return *this; } #else // !_MSC_VER typename std::enable_if< _D==_K , typename Cube< D >::template Element< K > >::type Cube< D >::Element< K >::_antipodal( void ) const { return *this; } #endif // _MSC_VER ////////// // Cube // ////////// template< unsigned int D > template< unsigned int K1 , unsigned int K2 > bool Cube< D >::Overlap( Element< K1 > e1 , Element< K2 > e2 ){ return _Overlap( e1 , e2 ); } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1>=K2) , bool >::type Cube< D >::_Overlap( Element< K1 > e1 , Element< K2 > e2 ) { Direction dir1[ D ] , dir2[ D ]; e1.directions( dir1 ) , e2.directions( dir2 ); for( int d=0 ; d<D ; d++ ) if( dir1[d]!=CROSS && dir1[d]!=dir2[d] ) return false; return true; } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1< K2) , bool >::type Cube< D >::_Overlap( Element< K1 > e1 , Element< K2 > e2 ){ return _Overlap( e2 , e1 ); } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > void Cube< D >::OverlapElements( Element< K1 > e , Element< K2 >* es ){ _OverlapElements( e , es ); } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1>=K2) >::type Cube< D >::_OverlapElements( Element< K1 > e , Element< K2 >* es ) { for( typename Cube< K1 >::template Element< K2 > _e ; _e<Cube< K1 >::template ElementNum< K2 >() ; _e++ ) es[_e.index] = Element< K2 >( e , _e ); } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1< K2) && D==K2 >::type Cube< D >::_OverlapElements( Element< K1 > e , Element< K2 >* es ) { es[0] = Element< D >(); } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1< K2) && D!=K2 && K1!=0 >::type Cube< D >::_OverlapElements( Element< K1 > e , Element< K2 >* es ) { Direction dir = e.direction() ; unsigned int coIndex; e.factor( dir , coIndex ); if( dir==FRONT || dir==BACK ) { typename Cube< D-1 >::template Element< K2 > _es1[ HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value ]; typename Cube< D-1 >::template Element< K2-1 > _es2[ HyperCube::OverlapElementNum< D-1 , K1 , K2-1 >::Value ]; Cube< D-1 >::OverlapElements( typename Cube< D-1 >::template Element< K1 >( coIndex ) , _es1 ); Cube< D-1 >::OverlapElements( typename Cube< D-1 >::template Element< K1 >( coIndex ) , _es2 ); for( unsigned int i=0 ; i<HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value ; i++ ) es[i] = typename Cube< D >::template Element< K2 >( dir , _es1[i].index ); es += HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value; for( unsigned int i=0 ; i<HyperCube::OverlapElementNum< D-1 , K1 , K2-1 >::Value ; i++ ) es[i] = typename Cube< D >::template Element< K2 >( CROSS , _es2[i].index ); } else if( dir==CROSS ) { typename Cube< D-1 >::template Element< K2-1 > _es1[ HyperCube::OverlapElementNum< D-1 , K1-1 , K2-1 >::Value ]; Cube< D-1 >::OverlapElements( typename Cube< D-1 >::template Element< K1-1 >( coIndex ) , _es1 ); for( unsigned int i=0 ; i<HyperCube::OverlapElementNum< D-1 , K1-1 , K2-1 >::Value ; i++ ) es[i] = typename Cube< D >::template Element< K2 >( CROSS , _es1[i].index ); } } template< unsigned int D > template< unsigned int K1 , unsigned int K2 > typename std::enable_if< (K1< K2) && D!=K2 && K1==0 >::type Cube< D >::_OverlapElements( Element< K1 > e , Element< K2 >* es ) { Direction dir = e.direction() ; unsigned int coIndex; e.factor( dir , coIndex ); if( dir==FRONT || dir==BACK ) { typename Cube< D-1 >::template Element< K2 > _es1[ HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value ]; typename Cube< D-1 >::template Element< K2-1 > _es2[ HyperCube::OverlapElementNum< D-1 , K1 , K2-1 >::Value ]; Cube< D-1 >::OverlapElements( typename Cube< D-1 >::template Element< K1 >( coIndex ) , _es1 ); Cube< D-1 >::OverlapElements( typename Cube< D-1 >::template Element< K1 >( coIndex ) , _es2 ); for( unsigned int i=0 ; i<HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value ; i++ ) es[i] = typename Cube< D >::template Element< K2 >( dir , _es1[i].index ); es += HyperCube::OverlapElementNum< D-1 , K1 , K2 >::Value; for( unsigned int i=0 ; i<HyperCube::OverlapElementNum< D-1 , K1 , K2-1 >::Value ; i++ ) es[i] = typename Cube< D >::template Element< K2 >( CROSS , _es2[i].index ); } } template< unsigned int D > template< unsigned int K > typename Cube< D >::template IncidentCubeIndex< K > Cube< D >::IncidentCube( Element< K > e ){ return _IncidentCube( e ); } template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D==K , typename Cube< D >::IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ){ return IncidentCubeIndex< D >(); } #else // !_MSC_VER typename std::enable_if< _D==K , typename Cube< D >::template IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ){ return IncidentCubeIndex< D >(); } #endif // _MSC_VER template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D!=K && _D!=0 && K!=0 , typename Cube< D >::IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ) #else // !_MSC_VER typename std::enable_if< _D!=K && _D!=0 && K!=0 , typename Cube< D >::template IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ) #endif // _MSC_VER { Direction dir ; unsigned int coIndex; e.factor( dir , coIndex ); if ( dir==CROSS ) return Cube< D-1 >::IncidentCube( typename Cube< D-1 >::template Element< K-1 >( coIndex ) ); else if( dir==FRONT ) return IncidentCubeIndex< K >( BACK , Cube< D-1 >::IncidentCube( typename Cube< D-1 >::template Element< K >( coIndex ) ).index ); else return IncidentCubeIndex< K >( FRONT , Cube< D-1 >::IncidentCube( typename Cube< D-1 >::template Element< K >( coIndex ) ).index ); } template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D!=K && _D!=0 && K==0 , typename Cube< D >::IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ) #else // !_MSC_VER typename std::enable_if< _D!=K && _D!=0 && K==0 , typename Cube< D >::template IncidentCubeIndex< K > >::type Cube< D >::_IncidentCube( Element< K > e ) #endif // _MSC_VER { Direction dir ; unsigned int coIndex; e.factor( dir , coIndex ); if( dir==FRONT ) return IncidentCubeIndex< K >( BACK , Cube< D-1 >::IncidentCube( typename Cube< D-1 >::template Element< K >( coIndex ) ).index ); else return IncidentCubeIndex< K >( FRONT , Cube< D-1 >::IncidentCube( typename Cube< D-1 >::template Element< K >( coIndex ) ).index ); } template< unsigned int D > bool Cube< D >::IsOriented( Element< D-1 > e ) { unsigned int dim ; Direction dir; _FactorOrientation( e , dim , dir ); return (dir==FRONT) ^ ((D-dim-1)&1); } template< unsigned int D > template< unsigned int _D > typename std::enable_if< _D!=1 >::type Cube< D >::_FactorOrientation( Element< D-1 > e , unsigned int& dim , Direction& dir ) { unsigned int coIndex; e.factor( dir , coIndex ); if( dir==CROSS ) Cube< D-1 >::template _FactorOrientation( typename Cube< D-1 >::template Element< D-2 >( coIndex ) , dim , dir ); else dim = D-1; } template< unsigned int D > template< unsigned int _D > typename std::enable_if< _D==1 >::type Cube< D >::_FactorOrientation( Element< D-1 > e , unsigned int& dim , Direction& dir ) { unsigned int coIndex; e.factor( dir , coIndex ); dim = 0; } template< unsigned int D > template< typename Real > unsigned int Cube< D >::MCIndex( const Real values[ Cube< D >::ElementNum< 0 >() ] , Real iso ) { unsigned int mcIdx = 0; for( unsigned int c=0 ; c<ElementNum< 0 >() ; c++ ) if( values[c]<iso ) mcIdx |= (1<<c); return mcIdx; } template< unsigned int D > template< unsigned int K > unsigned int Cube< D >::ElementMCIndex( Element< K > element , unsigned int mcIndex ){ return _ElementMCIndex( element , mcIndex ); } template< unsigned int D > bool Cube< D >::HasMCRoots( unsigned int mcIndex ) { static const unsigned int Mask = (1<<(1<<D)) - 1; return mcIndex!=0 && ( mcIndex & Mask )!=Mask; } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K!=0 , unsigned int >::type Cube< D >::_ElementMCIndex( Element< K > element , unsigned int mcIndex ) { static const unsigned int Mask = ( 1<<( ElementNum< 0 >() / 2 ) ) - 1; static const unsigned int Shift = ElementNum< 0 >() / 2 , _Shift = Cube< K >::template ElementNum< 0 >() / 2; unsigned int mcIndex0 = mcIndex & Mask , mcIndex1 = ( mcIndex>>Shift ) & Mask; Direction dir ; unsigned int coIndex; element.factor( dir , coIndex ); if( dir==CROSS ) return Cube< D-1 >::template ElementMCIndex< K-1 >( coIndex , mcIndex0 ) | ( Cube< D-1 >::template ElementMCIndex< K-1 >( coIndex , mcIndex1 )<<_Shift ); else return Cube< D-1 >::template ElementMCIndex< K >( coIndex , dir==BACK ? mcIndex0 : mcIndex1 ); } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K==0 , unsigned int >::type Cube< D >::_ElementMCIndex( Element< K > element , unsigned int mcIndex ) { static const unsigned int Mask = ( 1<<( ElementNum< 0 >() / 2 ) ) - 1; static const unsigned int Shift = ElementNum< 0 >() / 2 , _Shift = Cube< K >::template ElementNum< 0 >() / 2; unsigned int mcIndex0 = mcIndex & Mask , mcIndex1 = ( mcIndex>>Shift ) & Mask; Direction dir ; unsigned int coIndex; element.factor( dir , coIndex ); return Cube< D-1 >::template ElementMCIndex< K >( typename Cube< D-1 >::template Element< K >( coIndex ) , dir==BACK ? mcIndex0 : mcIndex1 ); } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D==K , unsigned int >::type Cube< D >::_ElementMCIndex( Element< K > element , unsigned int mcIndex ){ return mcIndex; } template< unsigned int D > template< unsigned int K > void Cube< D >::CellOffset( Element< K > e , IncidentCubeIndex< K > d , int x[D] ){ _CellOffset( e , d , x ); } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D==K >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d , int *x ){ for( int d=0 ; d<D ; d++ ) x[d] = 0; } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K!=0 >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d , int *x ) { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if ( eDir==CROSS ){ x[D-1] = 0 ; Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K-1 >( eCoIndex ) , d , x ); } else if( eDir==BACK ){ x[D-1] = -1 + ( dDir==BACK ? 0 : 1 ) ; Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) , x ); } else if( eDir==FRONT ){ x[D-1] = 0 + ( dDir==BACK ? 0 : 1 ) ; Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) , x ); } } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K==0 >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d , int *x ) { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if ( eDir==BACK ){ x[D-1] = -1 + ( dDir==BACK ? 0 : 1 ) ; Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) , x ); } else if( eDir==FRONT ){ x[D-1] = 0 + ( dDir==BACK ? 0 : 1 ) ; Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) , x ); } } template< unsigned int D > template< unsigned int K > unsigned int Cube< D >::CellOffset( Element< K > e , IncidentCubeIndex< K > d ){ return _CellOffset( e , d ); } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D==K && K==0 , unsigned int >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d ){ return 0; } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D==K && K!=0 , unsigned int >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d ){ return WindowIndex< IsotropicUIntPack< D , 3 > , IsotropicUIntPack< D , 1 > >::Index; } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K!=0 , unsigned int >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d ) { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if ( eDir==CROSS ){ return 1 + Cube< D-1 >::template CellOffset( typename Cube< D-1 >::template Element< K-1 >( eCoIndex ) , d ) * 3; } else if( eDir==BACK ){ return 0 + ( dDir==BACK ? 0 : 1 ) + Cube< D-1 >::template CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ) * 3; } else if( eDir==FRONT ){ return 1 + ( dDir==BACK ? 0 : 1 ) + Cube< D-1 >::template CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ) * 3; } return 0; } template< unsigned int D > template< unsigned int K , unsigned int _D > typename std::enable_if< _D!=K && K==0 , unsigned int >::type Cube< D >::_CellOffset( Element< K > e , IncidentCubeIndex< K > d ) { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if ( eDir==BACK ){ return 0 + ( dDir==BACK ? 0 : 1 ) + Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ) * 3; } else if( eDir==FRONT ){ return 1 + ( dDir==BACK ? 0 : 1 ) + Cube< D-1 >::CellOffset( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ) * 3; } return 0; } template< unsigned int D > template< unsigned int K > typename Cube< D >::template Element< K > Cube< D >::IncidentElement( Element< K > e , IncidentCubeIndex< K > d ){ return _IncidentElement( e , d ); } template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D==K , typename Cube< D >::Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ){ return e; } #else // !_MSC_VER typename std::enable_if< _D==K , typename Cube< D >::template Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ){ return e; } #endif // _MSC_VER template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D!=K && _D!=0 && K!=0 , typename Cube< D >::Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ) #else // !_MSC_VER typename std::enable_if< _D!=K && _D!=0 && K!=0 , typename Cube< D >::template Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ) #endif // _MSC_VER { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if ( eDir==CROSS ) return Element< K >( eDir , Cube< D-1 >::template IncidentElement( typename Cube< D-1 >::template Element< K-1 >( eCoIndex ) , d ).index ); else if( eDir==dDir ) return Element< K >( Opposite( eDir ) , Cube< D-1 >::template IncidentElement( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ).index ); else return Element< K >( eDir , Cube< D-1 >::template IncidentElement( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ).index ); } template< unsigned int D > template< unsigned int K , unsigned int _D > #ifdef _MSC_VER typename std::enable_if< _D!=K && _D!=0 && K==0 , typename Cube< D >::Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ) #else // !_MSC_VER typename std::enable_if< _D!=K && _D!=0 && K==0 , typename Cube< D >::template Element< K > >::type Cube< D >::_IncidentElement( Element< K > e , IncidentCubeIndex< K > d ) #endif // _MSC_VER { Direction eDir , dDir ; unsigned int eCoIndex , dCoIndex; e.factor( eDir , eCoIndex ) , d.factor( dDir , dCoIndex ); if( eDir==dDir ) return Element< K >( Opposite( eDir ) , Cube< D-1 >::template IncidentElement( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ).index ); else return Element< K >( eDir , Cube< D-1 >::template IncidentElement( typename Cube< D-1 >::template Element< K >( eCoIndex ) , typename Cube< D-1 >::template IncidentCubeIndex< K >( dCoIndex ) ).index ); } ///////////////////// // MarchingSquares // ///////////////////// const int MarchingSquares::edges[][MAX_EDGES*2+1] = { // Positive to the right // Positive in center /////////////////////////////////// (0,0) (1,0) (0,1) (1,1) { -1 , -1 , -1 , -1 , -1 } , // - - - - // { 1 , 0 , -1 , -1 , -1 } , // + - - - // (0,0) - (0,1) | (0,0) - (1,0) { 0 , 2 , -1 , -1 , -1 } , // - + - - // (0,0) - (1,0) | (1,0) - (1,1) { 1 , 2 , -1 , -1 , -1 } , // + + - - // (0,0) - (0,1) | (1,0) - (1,1) { 3 , 1 , -1 , -1 , -1 } , // - - + - // (0,1) - (1,1) | (0,0) - (0,1) { 3 , 0 , -1 , -1 , -1 } , // + - + - // (0,1) - (1,1) | (0,0) - (1,0) { 0 , 1 , 3 , 2 , -1 } , // - + + - // (0,0) - (1,0) | (0,0) - (0,1) & (0,1) - (1,1) | (1,0) - (1,1) { 3 , 2 , -1 , -1 , -1 } , // + + + - // (0,1) - (1,1) | (1,0) - (1,1) { 2 , 3 , -1 , -1 , -1 } , // - - - + // (1,0) - (1,1) | (0,1) - (1,1) { 1 , 3 , 2 , 0 , -1 } , // + - - + // (0,0) - (0,1) | (0,1) - (1,1) & (1,0) - (1,1) | (0,0) - (1,0) { 0 , 3 , -1 , -1 , -1 } , // - + - + // (0,0) - (1,0) | (0,1) - (1,1) { 1 , 3 , -1 , -1 , -1 } , // + + - + // (0,0) - (0,1) | (0,1) - (1,1) { 2 , 1 , -1 , -1 , -1 } , // - - + + // (1,0) - (1,1) | (0,0) - (0,1) { 2 , 0 , -1 , -1 , -1 } , // + - + + // (1,0) - (1,1) | (0,0) - (1,0) { 0 , 1 , -1 , -1 , -1 } , // - + + + // (0,0) - (1,0) | (0,0) - (0,1) { -1 , -1 , -1 , -1 , -1 } , // + + + + // }; inline int MarchingSquares::AddEdgeIndices( unsigned char mcIndex , int* isoIndices ) { int nEdges = 0; /* Square is entirely in/out of the surface */ if( mcIndex==0 || mcIndex==15 ) return 0; /* Create the edges */ for( int i=0 ; edges[mcIndex][i]!=-1 ; i+=2 ) { for( int j=0 ; j<2 ; j++ ) isoIndices[i+j] = edges[mcIndex][i+j]; nEdges++; } return nEdges; } } #endif //MARCHING_CUBES_INCLUDED
18,364
1,690
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. # language governing permissions and limitations under the License. from __future__ import absolute_import from sagemaker.workflow import _repack_model from pathlib import Path import shutil import tarfile import os import pytest import time @pytest.mark.skip( reason="""This test operates on the root file system and will likely fail due to permission errors. Temporarily remove this skip decorator and run the test after making changes to _repack_model.py""" ) def test_repack_entry_point_only(tmp): model_name = "xg-boost-model" fake_model_path = os.path.join(tmp, model_name) # create a fake model open(fake_model_path, "w") # create model.tar.gz model_tar_name = "model-%s.tar.gz" % time.time() model_tar_location = os.path.join(tmp, model_tar_name) with tarfile.open(model_tar_location, mode="w:gz") as t: t.add(fake_model_path, arcname=model_name) # move model.tar.gz to /opt/ml/input/data/training Path("/opt/ml/input/data/training").mkdir(parents=True, exist_ok=True) shutil.move(model_tar_location, os.path.join("/opt/ml/input/data/training", model_tar_name)) # create files that will be added to model.tar.gz create_file_tree( "/opt/ml/code", [ "inference.py", ], ) # repack _repack_model.repack(inference_script="inference.py", model_archive=model_tar_name) # /opt/ml/model should now have the original model and the inference script assert os.path.exists(os.path.join("/opt/ml/model", model_name)) assert os.path.exists(os.path.join("/opt/ml/model/code", "inference.py")) @pytest.mark.skip( reason="""This test operates on the root file system and will likely fail due to permission errors. Temporarily remove this skip decorator and run the test after making changes to _repack_model.py""" ) def test_repack_with_dependencies(tmp): model_name = "xg-boost-model" fake_model_path = os.path.join(tmp, model_name) # create a fake model open(fake_model_path, "w") # create model.tar.gz model_tar_name = "model-%s.tar.gz" % time.time() model_tar_location = os.path.join(tmp, model_tar_name) with tarfile.open(model_tar_location, mode="w:gz") as t: t.add(fake_model_path, arcname=model_name) # move model.tar.gz to /opt/ml/input/data/training Path("/opt/ml/input/data/training").mkdir(parents=True, exist_ok=True) shutil.move(model_tar_location, os.path.join("/opt/ml/input/data/training", model_tar_name)) # create files that will be added to model.tar.gz create_file_tree( "/opt/ml/code", ["inference.py", "dependencies/a", "bb", "dependencies/some/dir/b"], ) # repack _repack_model.repack( inference_script="inference.py", model_archive=model_tar_name, dependencies=["dependencies/a", "bb", "dependencies/some/dir"], ) # /opt/ml/model should now have the original model and the inference script assert os.path.exists(os.path.join("/opt/ml/model", model_name)) assert os.path.exists(os.path.join("/opt/ml/model/code", "inference.py")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib", "a")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib", "bb")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib/dir", "b")) @pytest.mark.skip( reason="""This test operates on the root file system and will likely fail due to permission errors. Temporarily remove this skip decorator and run the test after making changes to _repack_model.py""" ) def test_repack_with_source_dir_and_dependencies(tmp): model_name = "xg-boost-model" fake_model_path = os.path.join(tmp, model_name) # create a fake model open(fake_model_path, "w") # create model.tar.gz model_tar_name = "model-%s.tar.gz" % time.time() model_tar_location = os.path.join(tmp, model_tar_name) with tarfile.open(model_tar_location, mode="w:gz") as t: t.add(fake_model_path, arcname=model_name) # move model.tar.gz to /opt/ml/input/data/training Path("/opt/ml/input/data/training").mkdir(parents=True, exist_ok=True) shutil.move(model_tar_location, os.path.join("/opt/ml/input/data/training", model_tar_name)) # create files that will be added to model.tar.gz create_file_tree( "/opt/ml/code", [ "inference.py", "dependencies/a", "bb", "dependencies/some/dir/b", "sourcedir/foo.py", "sourcedir/some/dir/a", ], ) # repack _repack_model.repack( inference_script="inference.py", model_archive=model_tar_name, dependencies=["dependencies/a", "bb", "dependencies/some/dir"], source_dir="sourcedir", ) # /opt/ml/model should now have the original model and the inference script assert os.path.exists(os.path.join("/opt/ml/model", model_name)) assert os.path.exists(os.path.join("/opt/ml/model/code", "inference.py")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib", "a")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib", "bb")) assert os.path.exists(os.path.join("/opt/ml/model/code/lib/dir", "b")) assert os.path.exists(os.path.join("/opt/ml/model/code/", "foo.py")) assert os.path.exists(os.path.join("/opt/ml/model/code/some/dir", "a")) def create_file_tree(root, tree): for file in tree: try: os.makedirs(os.path.join(root, os.path.dirname(file))) except: # noqa: E722 Using bare except because p2/3 incompatibility issues. pass with open(os.path.join(root, file), "a") as f: f.write(file) @pytest.fixture() def tmp(tmpdir): yield str(tmpdir)
2,741
444
<reponame>code-review-doctor/orchestra<filename>orchestra/todos/views.py<gh_stars>100-1000 import logging import copy from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import redirect from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View from rest_framework import generics from rest_framework import permissions from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.decorators import action from jsonview.exceptions import BadRequest from django.db.models.query import QuerySet from orchestra.core.errors import TodoListTemplateValidationError from orchestra.models import Task from orchestra.models import Todo from orchestra.models import TodoQA from orchestra.models import TodoListTemplate from orchestra.todos.forms import ImportTodoListTemplateFromSpreadsheetForm from orchestra.todos.filters import QueryParamsFilterBackend from orchestra.todos.serializers import BulkTodoSerializer from orchestra.todos.serializers import BulkTodoSerializerWithoutQA from orchestra.todos.serializers import BulkTodoSerializerWithQA from orchestra.todos.serializers import TodoQASerializer from orchestra.todos.serializers import TodoListTemplateSerializer from orchestra.utils.common_helpers import notify_todo_created from orchestra.utils.common_helpers import notify_single_todo_update from orchestra.todos.api import add_todolist_template from orchestra.utils.decorators import api_endpoint from orchestra.todos.auth import IsAssociatedWithTodosProject from orchestra.todos.auth import IsAssociatedWithProject from orchestra.todos.auth import IsAssociatedWithTask from orchestra.todos.import_export import import_from_spreadsheet logger = logging.getLogger(__name__) @api_endpoint(methods=['POST'], permissions=(IsAssociatedWithProject,), logger=logger) def update_todos_from_todolist_template(request): todolist_template_slug = request.data.get('todolist_template') project_id = request.data.get('project') step_slug = request.data.get('step') try: add_todolist_template(todolist_template_slug, project_id, step_slug) todos = Todo.objects.filter( project__id=project_id).order_by('-created_at') serializer = BulkTodoSerializerWithoutQA(todos, many=True) return Response(serializer.data) except TodoListTemplate.DoesNotExist: raise BadRequest('TodoList Template not found for the given slug.') @api_endpoint(methods=['GET'], permissions=(permissions.IsAuthenticated, IsAssociatedWithTask), logger=logger) def worker_task_recent_todo_qas(request): """ Returns TodoQA recommendations for the requesting user and task. The TodoQAs for the recommendation are selected using the following logic: 1. If the given task has TodoQAs, use them. 2. Otherwise, use the TodoQAs from the requesting user's most recent task with matching task slug. """ task_id = request.query_params.get('task') task_todo_qas = TodoQA.objects.filter(todo__project__tasks__id=task_id) if task_todo_qas.exists(): todo_qas = task_todo_qas else: task = Task.objects.get(pk=task_id) most_recent_worker_task_todo_qa = TodoQA.objects.filter( todo__project__tasks__assignments__worker__user=request.user, todo__step__slug=task.step.slug ).order_by('-created_at').first() if most_recent_worker_task_todo_qa: project = most_recent_worker_task_todo_qa.todo.project step = most_recent_worker_task_todo_qa.todo.step todo_qas = TodoQA.objects.filter( todo__project=project, todo__step=step, approved=False) else: todo_qas = TodoQA.objects.none() todos_recommendation = {todo_qa.todo.title: TodoQASerializer( todo_qa).data for todo_qa in todo_qas} return Response(todos_recommendation) class TodoQADetail(generics.UpdateAPIView): permission_classes = (permissions.IsAuthenticated, IsAssociatedWithTodosProject) serializer_class = TodoQASerializer queryset = TodoQA.objects.all() class TodoQAList(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated, IsAssociatedWithProject) serializer_class = TodoQASerializer queryset = TodoQA.objects.all() class TodoListTemplateDetail(generics.RetrieveUpdateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = TodoListTemplateSerializer queryset = TodoListTemplate.objects.all() class TodoListTemplateList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = TodoListTemplateSerializer queryset = TodoListTemplate.objects.all() class GenericTodoViewset(ModelViewSet): """ A base viewset inherited by multiple viewsets, created to de-duplicate Todo-related views. It lacks permission and auth classes, so that child classes can select their own. """ serializer_class = BulkTodoSerializer filter_backends = (QueryParamsFilterBackend,) # Note: additional_data__nested_field is not supported in filterset_fields # This issue can be fixed when we migrate to Django 3.1 # and convert additional_data from django-jsonfields to the native one. filterset_fields = ('project__id', 'step__slug', 'id__in') queryset = Todo.objects.select_related('step', 'qa').all() def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) def get_queryset(self, ids=None): queryset = super().get_queryset() if ids is not None: queryset = queryset.filter(id__in=ids) return queryset.order_by('-created_at') @action(detail=False, methods=['delete']) def delete(self, request, *args, **kwargs): data = self.get_queryset(ids=request.data).delete() return Response(data) @action(detail=False, methods=['put']) def put(self, request, *args, **kwargs): partial = kwargs.get('partial', False) ids = [x['id'] for x in request.data] # Sort the queryset and data by primary key # so we update the correct records. sorted_data = sorted(request.data, key=lambda x: x['id']) instances = self.get_queryset(ids=ids).order_by('id') serializer = self.get_serializer( instances, data=sorted_data, partial=partial, many=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) data = serializer.data return Response(data) @action(detail=False, methods=['patch']) def patch(self, request, *args, **kwargs): kwargs['partial'] = True return self.put(request, *args, **kwargs) def perform_update(self, serializer): old_data = copy.deepcopy(serializer.instance) old_todos = list(old_data) if isinstance( old_data, QuerySet) else [old_data] data = serializer.save() todos = data if isinstance(data, list) else [data] for old_todo, new_todo in zip(old_todos, todos): if isinstance(new_todo, Todo): notify_single_todo_update( self.request.user, old_todo, new_todo) def perform_create(self, serializer): data = serializer.save() todos = data if isinstance(data, list) else [data] for todo in todos: if isinstance(todo, Todo): notify_todo_created(todo, self.request.user) class TodoViewset(GenericTodoViewset): """ This viewset inherits from GenericTodoViewset is used by two endpoints (see urls.py). todo/ -- For creating and listing Todos. todo/1234/ -- For updating a Todo. """ http_method_names = ['get', 'post', 'put', 'delete'] def get_permissions(self): permission_classes = (permissions.IsAuthenticated, IsAssociatedWithProject) if self.action == 'update': permission_classes = (permissions.IsAuthenticated, IsAssociatedWithTodosProject) return [permission() for permission in permission_classes] def get_serializer_class(self): if self.action == 'list' or self.action == 'create': # Only include todo QA data for users in the # `project_admins` group. if self.request.user.groups.filter( name='project_admins').exists(): return BulkTodoSerializerWithQA else: return BulkTodoSerializerWithoutQA else: return super().get_serializer_class() @method_decorator(staff_member_required, name='dispatch') class ImportTodoListTemplateFromSpreadsheet(View): TEMPLATE = 'orchestra/import_todo_list_template_from_spreadsheet.html' def get(self, request, pk): # Display a form with a spreadsheet URL for import. return render( request, self.TEMPLATE, {'form': ImportTodoListTemplateFromSpreadsheetForm(initial={})}) def post(self, request, pk): # Try to import the spreadsheet and redirect back to the admin # entry for the imported TodoListTemplate. If we encounter an # error, display the error on the form. form = ImportTodoListTemplateFromSpreadsheetForm(request.POST) context = {'form': form} if form.is_valid(): try: todo_list_template = TodoListTemplate.objects.get( id=pk) import_from_spreadsheet( todo_list_template, form.cleaned_data['spreadsheet_url'], request) messages.info( request, 'Successfully imported from spreadsheet.') return redirect( 'admin:orchestra_todolisttemplate_change', pk) except TodoListTemplateValidationError as e: context['import_error'] = str(e) else: context['import_error'] = 'Please provide a spreadsheet URL' return render( request, self.TEMPLATE, context)
4,314
698
<gh_stars>100-1000 from .abc import ABCRequestRescheduler from .blocking import BlockingRequestRescheduler
30
335
<filename>V/Vibrator_noun.json { "word": "Vibrator", "definitions": [ "A device used for massage or sexual stimulation.", "A device for compacting concrete before it has set.", "A reed in a reed organ." ], "parts-of-speech": "Noun" }
114
1,968
<reponame>agramonte/corona #include "pch.h" #include "AngleBase.h" using namespace DirectX; using namespace Microsoft::WRL; using namespace Windows::Foundation; using namespace Windows::Graphics::Display; // Constructor. AngleBase::AngleBase() : m_bAngleInitialized(false) , m_eglDisplay(nullptr) , m_eglSurface(nullptr) , m_eglContext(nullptr) , m_eglWindow(nullptr) , m_eglPhoneWindow(nullptr) , m_d3dDeferredContext(nullptr) { } AngleBase::~AngleBase() { CloseAngle(); } // Initialize the Direct3D resources required to run. void AngleBase::Initialize() { } // These are the resources that depend on the device. void AngleBase::CreateDeviceResources() { } void AngleBase::UpdateDevice(ID3D11Device1* device, ID3D11DeviceContext1* context, ID3D11RenderTargetView* renderTargetView) { m_d3dContext = context; m_d3dRenderTargetView = renderTargetView; m_featureLevel = device->GetFeatureLevel(); if (m_d3dDevice.Get() != device) { CloseAngle(); m_d3dDevice = device; CreateDeviceResources(); // Force call to CreateWindowSizeDependentResources m_renderTargetSize.Width = -1; m_renderTargetSize.Height = -1; m_d3dDeferredContext = nullptr; } ComPtr<ID3D11Resource> renderTargetViewResource; m_d3dRenderTargetView->GetResource(&renderTargetViewResource); ComPtr<ID3D11Texture2D> backBuffer; DX::ThrowIfFailed( renderTargetViewResource.As(&backBuffer) ); // Cache the rendertarget dimensions in our helper class for convenient use. D3D11_TEXTURE2D_DESC backBufferDesc; backBuffer->GetDesc(&backBufferDesc); if (m_renderTargetSize.Width != static_cast<float>(backBufferDesc.Width) || m_renderTargetSize.Height != static_cast<float>(backBufferDesc.Height)) { m_renderTargetSize.Width = static_cast<float>(backBufferDesc.Width); m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height); CreateWindowSizeDependentResources(); } if(!m_bAngleInitialized) { InitializeAngle(); CreateGLResources(); } else { m_eglPhoneWindow->Update(m_d3dDevice.Get(), m_d3dContext.Get(), m_d3dRenderTargetView.Get()); } } void AngleBase::UpdateForWindowSizeChange(float width, float height) { if (width != m_windowBounds.Width || height != m_windowBounds.Height) { m_windowBounds.Width = width; m_windowBounds.Height = height; } } // Allocate all memory resources that depend on the window size. void AngleBase::CreateWindowSizeDependentResources() { } void AngleBase::OnOrientationChanged(DisplayOrientations orientation) { m_aspectRatio = m_renderTargetSize.Width / m_renderTargetSize.Height; switch(orientation) { case DisplayOrientations::Portrait: m_orientationMatrix = XMMatrixIdentity(); break; case DisplayOrientations::PortraitFlipped: m_orientationMatrix = XMMatrixRotationZ(XM_PI); break; case DisplayOrientations::Landscape: m_orientationMatrix = XMMatrixRotationZ(-XM_PIDIV2); break; case DisplayOrientations::LandscapeFlipped: m_orientationMatrix = XMMatrixRotationZ(XM_PIDIV2); break; } } void AngleBase::Render() { if (m_d3dDeferredContext.Get() == nullptr) { m_d3dDevice.Get()->CreateDeferredContext(0, &m_d3dDeferredContext); } ComPtr<ID3D11DeviceContext1> deferredContect; DX::ThrowIfFailed(m_d3dDeferredContext.As(&deferredContect)); m_eglPhoneWindow->Update(m_d3dDevice.Get(), deferredContect.Get(), m_d3dRenderTargetView.Get()); OnRender(); ComPtr<ID3D11CommandList> d3dCommandList; m_d3dDeferredContext->FinishCommandList(FALSE, &d3dCommandList); m_d3dContext->ExecuteCommandList(d3dCommandList.Get(), FALSE); m_eglPhoneWindow->Update(m_d3dDevice.Get(), m_d3dContext.Get(), m_d3dRenderTargetView.Get()); eglSwapBuffers(m_eglDisplay, m_eglSurface); } void AngleBase::CloseAngle() { if(m_eglDisplay && m_eglSurface) { eglDestroySurface(m_eglDisplay, m_eglSurface); m_eglSurface = nullptr; } if(m_eglDisplay && m_eglContext) { eglDestroyContext(m_eglDisplay, m_eglContext); m_eglContext = nullptr; } if(m_eglDisplay) { eglTerminate(m_eglDisplay); m_eglDisplay = nullptr; } if(m_eglPhoneWindow != nullptr) { m_eglPhoneWindow->Update(nullptr, nullptr, nullptr); } eglMakeCurrent(NULL, NULL, NULL, NULL); m_eglPhoneWindow = nullptr; m_eglWindow = nullptr; m_bAngleInitialized = false; } bool AngleBase::InitializeAngle() { // setup EGL EGLint configAttribList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, EGL_SAMPLE_BUFFERS, 0, EGL_NONE }; EGLint surfaceAttribList[] = { EGL_NONE, EGL_NONE }; EGLint numConfigs; EGLint majorVersion; EGLint minorVersion; EGLDisplay display; EGLContext context; EGLSurface surface; EGLConfig config; EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE }; // we need to select the correct DirectX feature level depending on the platform // default is D3D_FEATURE_LEVEL_9_3 Windows Phone 8.0 ANGLE_D3D_FEATURE_LEVEL featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_3; switch(m_featureLevel) { case ANGLE_D3D_FEATURE_LEVEL_9_3: featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_3; break; case ANGLE_D3D_FEATURE_LEVEL_9_2: featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_2; break; case ANGLE_D3D_FEATURE_LEVEL_9_1: featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_1; break; } if (m_eglPhoneWindow == nullptr) { DX::ThrowIfFailed( CreateWinPhone8XamlWindow(&m_eglPhoneWindow) ); } m_eglPhoneWindow->Update(m_d3dDevice.Get(), m_d3dContext.Get(), m_d3dRenderTargetView.Get()); if (m_eglWindow == nullptr) { DX::ThrowIfFailed( CreateWinrtEglWindow(WINRT_EGL_IUNKNOWN(m_eglPhoneWindow.Get()), featureLevel, m_eglWindow.GetAddressOf()) ); } display = eglGetDisplay(m_eglWindow); if(display == EGL_NO_DISPLAY){ //ofLogError("ofAppWinRTWindow") << "couldn't get EGL display"; return false; } if(!eglInitialize(display, &majorVersion, &minorVersion)){ //ofLogError("ofAppWinRTWindow") << "failed to initialize EGL"; return false; } // Get configs if ( !eglGetConfigs(display, NULL, 0, &numConfigs) ){ //ofLogError("ofAppWinRTWindow") << "failed to get configurations"; return false; } // Choose config if(!eglChooseConfig(display, configAttribList, &config, 1, &numConfigs)){ //ofLogError("ofAppWinRTWindow") << "failed to choose configuration"; return false; } // Create a surface surface = eglCreateWindowSurface(display, config, m_eglWindow, surfaceAttribList); if(surface == EGL_NO_SURFACE){ //ofLogError("ofAppWinRTWindow") << "failed to create EGL window surface"; return false; } // Create a GL context context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs); if(context == EGL_NO_CONTEXT){ //ofLogError("ofAppWinRTWindow") << "failed to create EGL context"; return false; } // Make the context current if (!eglMakeCurrent(display, surface, surface, context)){ //ofLogError("ofAppWinRTWindow") << "failed to make EGL context current"; return false; } m_eglDisplay = display; m_eglSurface = surface; m_eglContext = context; m_bAngleInitialized = true; return true; }
3,216
412
<filename>server/src/main/java/datart/server/controller/ThirdPartyAuthController.java package datart.server.controller; import datart.core.base.annotations.SkipLogin; import datart.core.base.consts.Const; import datart.core.entity.User; import datart.core.entity.ext.UserBaseInfo; import datart.security.base.PasswordToken; import datart.security.util.JwtUtils; import datart.server.base.dto.ResponseData; import datart.server.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; @Api @Slf4j @RestController @RequestMapping(value = "/tpa") public class ThirdPartyAuthController extends BaseController { private final UserService userService; public ThirdPartyAuthController(UserService userService) { this.userService = userService; } private ClientRegistrationRepository clientRegistrationRepository; @ApiOperation(value = "Get Oauth2 clents") @GetMapping(value = "getOauth2Clients", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @SkipLogin public ResponseData<List<HashMap<String, String>>> getOauth2Clients(HttpServletRequest request) { if (clientRegistrationRepository == null) { return ResponseData.success(Collections.emptyList()); } Iterable<ClientRegistration> clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository; List<HashMap<String, String>> clients = new ArrayList<>(); clientRegistrations.forEach(registration -> { HashMap<String, String> map = new HashMap<>(); map.put(registration.getClientName(), OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + registration.getRegistrationId() + "?redirect_url=/"); clients.add(map); }); return ResponseData.success(clients); } @ApiOperation(value = "External Login") @SkipLogin @PostMapping(value = "oauth2login", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseData<UserBaseInfo> externalLogin(Principal principal, HttpServletResponse response) { if (principal instanceof OAuth2AuthenticationToken) { User user = userService.externalRegist((OAuth2AuthenticationToken) principal); PasswordToken passwordToken = new PasswordToken(user.getUsername(), null, System.currentTimeMillis()); passwordToken.setPassword(<PASSWORD>()); String token = JwtUtils.toJwtString(passwordToken); response.setHeader(Const.TOKEN, token); response.setStatus(200); return ResponseData.success(new UserBaseInfo(user)); } response.setStatus(401); return ResponseData.failure("oauth2登录失败"); } @Autowired(required = false) public void setClientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) { this.clientRegistrationRepository = clientRegistrationRepository; } }
1,398
427
//===--- NSUndoManagerShims.h - Foundation decl. for NSUndoManager overlay ===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #import "FoundationShimSupport.h" NS_BEGIN_DECLS NS_INLINE void __NSUndoManagerRegisterWithTargetHandler(NSUndoManager * self_, id target, void (^handler)(id)) { [self_ registerUndoWithTarget:target handler:handler]; } NS_END_DECLS
213
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/CoreDAV.framework/CoreDAV */ #import <CoreDAV/CoreDAVTaskGroup.h> #import <CoreDAV/CoreDAVPropPatchTaskDelegate.h> @class NSURL; @interface CardDAVUpdateMeCardTaskGroup : CoreDAVTaskGroup <CoreDAVPropPatchTaskDelegate> { NSURL *_homeURL; // 44 = 0x2c NSURL *_cardURL; // 48 = 0x30 } @property(readonly, assign) NSURL *homeURL; // G=0x3a369; @synthesize=_homeURL @property(readonly, assign) NSURL *cardURL; // G=0x3a359; @synthesize=_cardURL // declared property getter: - (id)homeURL; // 0x3a369 // declared property getter: - (id)cardURL; // 0x3a359 - (void)propPatchTask:(id)task parsedResponses:(id)responses error:(id)error; // 0x3a2b9 - (void)startTaskGroup; // 0x3a1e5 - (id)_newPropPatchTask; // 0x3a099 - (void)taskGroupWillCancelWithError:(id)taskGroup; // 0x3a045 - (id)description; // 0x39fe5 - (void)dealloc; // 0x39f85 - (id)initWithAccountInfoProvider:(id)accountInfoProvider taskManager:(id)manager homeURL:(id)url cardURL:(id)url4; // 0x39f19 @end
434
1,056
<reponame>timfel/netbeans<filename>java/java.hints/src/org/netbeans/modules/java/hints/errors/EnablePreviewSingleSourceFile.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.java.hints.errors; import com.sun.source.util.TreePath; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.lang.model.SourceVersion; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.source.CompilationInfo; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.modules.java.hints.spi.ErrorRule; import org.netbeans.spi.editor.hints.ChangeInfo; import org.netbeans.spi.editor.hints.Fix; import org.openide.filesystems.FileObject; import org.openide.util.NbBundle; import org.openide.util.Parameters; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.openide.util.EditableProperties; import org.openide.util.Mutex; import org.openide.util.MutexException; /** * Handle error rule "compiler.err.preview.feature.disabled.plural" and provide * the fix for Single Source Java File. * * @author <NAME> */ public class EnablePreviewSingleSourceFile implements ErrorRule<Void> { private static final Set<String> ERROR_CODES = new HashSet<String>(Arrays.asList( "compiler.err.preview.feature.disabled", //NOI18N "compiler.err.preview.feature.disabled.plural")); // NOI18N private static final String ENABLE_PREVIEW_FLAG = "--enable-preview"; // NOI18N private static final String SOURCE_FLAG = "--source"; // NOI18N private static final String FILE_VM_OPTIONS = "single_file_vm_options"; //NOI18N @Override public Set<String> getCodes() { return Collections.unmodifiableSet(ERROR_CODES); } @Override @NonNull public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) { if (SourceVersion.latest() != compilationInfo.getSourceVersion()) { return Collections.<Fix>emptyList(); } final FileObject file = compilationInfo.getFileObject(); Fix fix = null; if (file != null) { final Project prj = FileOwnerQuery.getOwner(file); if (prj == null) { fix = new EnablePreviewSingleSourceFile.ResolveFix(file); } else { fix = null; } } return (fix != null) ? Collections.<Fix>singletonList(fix) : Collections.<Fix>emptyList(); } @Override public String getId() { return EnablePreviewSingleSourceFile.class.getName(); } @Override public String getDisplayName() { return NbBundle.getMessage(EnablePreviewSingleSourceFile.class, "FIX_EnablePreviewFeature"); // NOI18N } public String getDescription() { return NbBundle.getMessage(EnablePreviewSingleSourceFile.class, "FIX_EnablePreviewFeature"); // NOI18N } @Override public void cancel() { } private static final class ResolveFix implements Fix { private FileObject file; ResolveFix(@NonNull FileObject file) { Parameters.notNull("file", file); //NOI18N this.file = file; } @Override public String getText() { return NbBundle.getMessage(EnablePreviewSingleSourceFile.class, "FIX_EnablePreviewFeature"); // NOI18N } @Override public ChangeInfo implement() throws Exception { EditableProperties ep = getEditableProperties(file); String compilerArgs = (String) file.getAttribute(FILE_VM_OPTIONS); if (compilerArgs != null && !compilerArgs.isEmpty()) { compilerArgs = compilerArgs.contains(SOURCE_FLAG) ? compilerArgs + " " + ENABLE_PREVIEW_FLAG : compilerArgs + " " + ENABLE_PREVIEW_FLAG + " " + SOURCE_FLAG + " " + getJdkRunVersion(); } else { compilerArgs = ENABLE_PREVIEW_FLAG + " " + SOURCE_FLAG + " " + getJdkRunVersion(); } file.setAttribute(FILE_VM_OPTIONS, compilerArgs); storeEditableProperties(ep, file); return null; } } private static EditableProperties getEditableProperties(FileObject file) throws IOException { try { return ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<EditableProperties>() { @Override public EditableProperties run() throws IOException { FileObject propertiesFo = file; EditableProperties ep = null; if (propertiesFo != null) { InputStream is = null; ep = new EditableProperties(false); try { is = propertiesFo.getInputStream(); ep.load(is); } finally { if (is != null) { is.close(); } } } return ep; } }); } catch (MutexException ex) { return null; } } private static void storeEditableProperties(final EditableProperties ep, FileObject file) throws IOException { try { ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() { @Override public Void run() throws IOException { FileObject propertiesFo = null; if (file != null) { propertiesFo = file; } if (propertiesFo != null) { OutputStream os = null; try { os = propertiesFo.getOutputStream(); ep.store(os); } finally { if (os != null) { os.flush(); os.close(); } } } return null; } }); } catch (MutexException ex) { } } private static String getJdkRunVersion() { String javaVersion = System.getProperty("java.specification.version"); //NOI18N if (javaVersion.startsWith("1.")) { //NOI18N javaVersion = javaVersion.substring(2); } return javaVersion; } }
3,326
416
package org.springframework.roo.addon.web.mvc.thymeleaf.addon.link.factory; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.annotations.populator.*; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.RooJavaType; /** * = LinkFactoryAnnotationValues * * Annotation values for @RooLinkFactory * * @author <NAME> * @since 2.0 */ public class LinkFactoryAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private JavaType controller; /** * Constructor * * @param governorPhysicalTypeMetadata to parse (required) */ public LinkFactoryAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, RooJavaType.ROO_LINK_FACTORY); AutoPopulationUtils.populate(this, annotationMetadata); } public LinkFactoryAnnotationValues(final ClassOrInterfaceTypeDetails cid) { super(cid, RooJavaType.ROO_LINK_FACTORY); AutoPopulationUtils.populate(this, annotationMetadata); } public JavaType getController() { return controller; } }
377
4,262
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.util; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.apache.camel.ContextTestSupport; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.converter.jaxp.XmlConverter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * */ public class DumpModelAsXmlFromRouteTemplateTest extends ContextTestSupport { @Test public void testDumpModelAsXml() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("bar", "start"); map.put("greeting", "Hello"); map.put("whereto", "Moes"); context.addRouteFromTemplate("foo", "myTemplate", map); ExtendedCamelContext ecc = context.adapt(ExtendedCamelContext.class); String xml = ecc.getModelToXMLDumper().dumpModelAsXml(context, context.getRouteDefinition("foo")); assertNotNull(xml); log.info(xml); Document doc = new XmlConverter().toDOMDocument(xml, null); NodeList nodes = doc.getElementsByTagName("simple"); assertEquals(1, nodes.getLength()); Element node = (Element) nodes.item(0); assertNotNull(node, "Node <simple> expected to be instanceof Element"); assertEquals("{{greeting}}", node.getTextContent()); nodes = doc.getElementsByTagName("to"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertNotNull(node, "Node <to> expected to be instanceof Element"); assertEquals("mock:{{whereto}}", node.getAttribute("uri")); nodes = doc.getElementsByTagName("route"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertEquals("foo", node.getAttribute("id")); } @Test public void testDumpModelAsXmlResolvePlaceholder() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("bar", "start"); map.put("greeting", "Hello"); map.put("whereto", "Moes"); context.addRouteFromTemplate("bar", "myTemplate", map); map.clear(); map.put("bar", "start2"); map.put("greeting", "Bye"); map.put("whereto", "Jacks"); context.addRouteFromTemplate("bar2", "myTemplate", map); ExtendedCamelContext ecc = context.adapt(ExtendedCamelContext.class); String xml = ecc.getModelToXMLDumper().dumpModelAsXml(context, context.getRouteDefinition("bar"), true, false); assertNotNull(xml); log.info(xml); Document doc = new XmlConverter().toDOMDocument(xml, null); NodeList nodes = doc.getElementsByTagName("simple"); assertEquals(1, nodes.getLength()); Element node = (Element) nodes.item(0); assertNotNull(node, "Node <simple> expected to be instanceof Element"); assertEquals("Hello", node.getTextContent()); nodes = doc.getElementsByTagName("to"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertNotNull(node, "Node <to> expected to be instanceof Element"); assertEquals("mock:Moes", node.getAttribute("uri")); nodes = doc.getElementsByTagName("route"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertEquals("bar", node.getAttribute("id")); xml = ecc.getModelToXMLDumper().dumpModelAsXml(context, context.getRouteDefinition("bar2"), true, false); assertNotNull(xml); log.info(xml); doc = new XmlConverter().toDOMDocument(xml, null); nodes = doc.getElementsByTagName("simple"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertNotNull(node, "Node <simple> expected to be instanceof Element"); assertEquals("Bye", node.getTextContent()); nodes = doc.getElementsByTagName("to"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertNotNull(node, "Node <to> expected to be instanceof Element"); assertEquals("mock:Jacks", node.getAttribute("uri")); nodes = doc.getElementsByTagName("route"); assertEquals(1, nodes.getLength()); node = (Element) nodes.item(0); assertEquals("bar2", node.getAttribute("id")); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { routeTemplate("myTemplate").templateParameter("bar").templateParameter("greeting").templateParameter("whereto") .from("direct:{{bar}}").transform(simple("{{greeting}}")).to("mock:{{whereto}}"); } }; } }
2,195
6,192
import pandas as pd from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, MinMaxScaler from deepctr.feature_column import SparseFeat, DenseFeat, get_feature_names from deepctr.models import MMOE if __name__ == "__main__": column_names = ['age', 'class_worker', 'det_ind_code', 'det_occ_code', 'education', 'wage_per_hour', 'hs_college', 'marital_stat', 'major_ind_code', 'major_occ_code', 'race', 'hisp_origin', 'sex', 'union_member', 'unemp_reason', 'full_or_part_emp', 'capital_gains', 'capital_losses', 'stock_dividends', 'tax_filer_stat', 'region_prev_res', 'state_prev_res', 'det_hh_fam_stat', 'det_hh_summ', 'instance_weight', 'mig_chg_msa', 'mig_chg_reg', 'mig_move_reg', 'mig_same', 'mig_prev_sunbelt', 'num_emp', 'fam_under_18', 'country_father', 'country_mother', 'country_self', 'citizenship', 'own_or_self', 'vet_question', 'vet_benefits', 'weeks_worked', 'year', 'income_50k'] data = pd.read_csv('./census-income.sample', header=None, names=column_names) data['label_income'] = data['income_50k'].map({' - 50000.': 0, ' 50000+.': 1}) data['label_marital'] = data['marital_stat'].apply(lambda x: 1 if x == ' Never married' else 0) data.drop(labels=['income_50k', 'marital_stat'], axis=1, inplace=True) columns = data.columns.values.tolist() sparse_features = ['class_worker', 'det_ind_code', 'det_occ_code', 'education', 'hs_college', 'major_ind_code', 'major_occ_code', 'race', 'hisp_origin', 'sex', 'union_member', 'unemp_reason', 'full_or_part_emp', 'tax_filer_stat', 'region_prev_res', 'state_prev_res', 'det_hh_fam_stat', 'det_hh_summ', 'mig_chg_msa', 'mig_chg_reg', 'mig_move_reg', 'mig_same', 'mig_prev_sunbelt', 'fam_under_18', 'country_father', 'country_mother', 'country_self', 'citizenship', 'vet_question'] dense_features = [col for col in columns if col not in sparse_features and col not in ['label_income', 'label_marital']] data[sparse_features] = data[sparse_features].fillna('-1', ) data[dense_features] = data[dense_features].fillna(0, ) mms = MinMaxScaler(feature_range=(0, 1)) data[dense_features] = mms.fit_transform(data[dense_features]) for feat in sparse_features: lbe = LabelEncoder() data[feat] = lbe.fit_transform(data[feat]) fixlen_feature_columns = [SparseFeat(feat, data[feat].max() + 1, embedding_dim=4) for feat in sparse_features] \ + [DenseFeat(feat, 1, ) for feat in dense_features] dnn_feature_columns = fixlen_feature_columns linear_feature_columns = fixlen_feature_columns feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns) # 3.generate input data for model train, test = train_test_split(data, test_size=0.2, random_state=2020) train_model_input = {name: train[name] for name in feature_names} test_model_input = {name: test[name] for name in feature_names} # 4.Define Model,train,predict and evaluate model = MMOE(dnn_feature_columns, tower_dnn_hidden_units=[], task_types=['binary', 'binary'], task_names=['label_income', 'label_marital']) model.compile("adam", loss=["binary_crossentropy", "binary_crossentropy"], metrics=['binary_crossentropy'], ) history = model.fit(train_model_input, [train['label_income'].values, train['label_marital'].values], batch_size=256, epochs=10, verbose=2, validation_split=0.2) pred_ans = model.predict(test_model_input, batch_size=256) print("test income AUC", round(roc_auc_score(test['label_income'], pred_ans[0]), 4)) print("test marital AUC", round(roc_auc_score(test['label_marital'], pred_ans[1]), 4))
1,724
334
<gh_stars>100-1000 #!/usr/bin/python import os import shutil from calvin.utilities import certificate from calvin.utilities import certificate_authority from calvin.utilities import runtime_credentials from calvin.utilities.utils import get_home from calvin.utilities import calvinuuid homefolder = get_home() domain = "sec-dht-security-test" testdir = os.path.join(homefolder, ".calvin","sec_dht_security_test") configdir = os.path.join(testdir, domain) runtimesdir = os.path.join(testdir,"runtimes") runtimes_truststore = os.path.join(runtimesdir,"truststore_for_transport") try: shutil.rmtree(testdir) except: print "Failed to remove old tesdir" pass print "Creating new domain." testca = certificate_authority.CA(domain="test", commonName="sec-dht-test-security-CA", security_dir=testdir) print "Created new domain." print "Import CA cert into truststore." testca.export_ca_cert(runtimes_truststore) print "Generate runtime credentials and sign their certificates" for i in range(1, 5): for j in range(0, 6): name = "node{}:{}".format(i, j) enrollment_password = testca.cert_enrollment_add_new_runtime(name) nodeid = calvinuuid.uuid("NODE") rt_cred = runtime_credentials.RuntimeCredentials(name, domain="test", security_dir=testdir, nodeid=nodeid, enrollment_password=<PASSWORD>) csr_path = os.path.join(rt_cred.runtime_dir, name + ".csr") try: with open(csr_path +".challenge_password", 'w') as csr_fd: csr_fd.write(enrollment_password) except Exception as err: _log.exception("Failed to write challenge password to file, err={}".format(err)) raise certpath = testca.sign_csr(csr_path) rt_cred.store_own_cert(certpath=certpath) print "Generate evil node runtime credentials and sign certificate" enrollment_password = testca.cert_enrollment_add_new_runtime("evil") nodeid = calvinuuid.uuid("NODE") rt_cred = runtime_credentials.RuntimeCredentials("evil", domain="test", security_dir=testdir, nodeid=nodeid, enrollment_password=<PASSWORD>) csr_path = os.path.join(rt_cred.runtime_dir, "evil.csr") try: with open(csr_path +".challenge_password", 'w') as csr_fd: csr_fd.write(enrollment_password) except Exception as err: _log.exception("Failed to write challenge password to file, err={}".format(err)) raise certpath = testca.sign_csr(csr_path) rt_cred.store_own_cert(certpath=certpath)
1,155
348
{"nom":"Plan-de-Cuques","circ":"10ème circonscription","dpt":"Bouches-du-Rhône","inscrits":9398,"abs":5818,"votants":3580,"blancs":218,"nuls":67,"exp":3295,"res":[{"nuance":"REM","nom":"<NAME>","voix":1731},{"nuance":"FN","nom":"<NAME>","voix":1564}]}
104
745
<gh_stars>100-1000 # -*- coding: utf-8 -*- import sys from html.parser import HTMLParser import requests from httpretty import HTTPretty from openid import oidutil from ...backends.utils import load_backends from ...utils import parse_qs, module_member from ..models import TestStorage, User, TestUserSocialAuth, \ TestNonce, TestAssociation from ..strategy import TestStrategy from .base import BaseBackendTest sys.path.insert(0, '..') # Patch to remove the too-verbose output until a new version is released oidutil.log = lambda *args, **kwargs: None class FormHTMLParser(HTMLParser): form = {} inputs = {} def handle_starttag(self, tag, attrs): attrs = dict(attrs) if tag == 'form': self.form.update(attrs) elif tag == 'input' and 'name' in attrs: self.inputs[attrs['name']] = attrs['value'] class OpenIdTest(BaseBackendTest): backend_path = None backend = None access_token_body = None user_data_body = None user_data_url = '' expected_username = '' settings = None partial_login_settings = None raw_complete_url = '/complete/{0}/' def setUp(self): HTTPretty.enable(allow_net_connect=False) Backend = module_member(self.backend_path) self.strategy = TestStrategy(TestStorage) self.complete_url = self.raw_complete_url.format(Backend.name) self.backend = Backend(self.strategy, redirect_uri=self.complete_url) self.strategy.set_settings({ 'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': ( self.backend_path, 'social_core.tests.backends.test_broken.BrokenBackendAuth' ) }) # Force backends loading to trash PSA cache load_backends( self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'), force_load=True ) def tearDown(self): self.strategy = None User.reset_cache() TestUserSocialAuth.reset_cache() TestNonce.reset_cache() TestAssociation.reset_cache() HTTPretty.disable() HTTPretty.reset() def get_form_data(self, html): parser = FormHTMLParser() parser.feed(html) return parser.form, parser.inputs def openid_url(self): return self.backend.openid_url() def post_start(self): pass def do_start(self): HTTPretty.register_uri(HTTPretty.GET, self.openid_url(), status=200, body=self.discovery_body, content_type='application/xrds+xml') start = self.backend.start() self.post_start() form, inputs = self.get_form_data(start) HTTPretty.register_uri(HTTPretty.POST, form.get('action'), status=200, body=self.server_response) response = requests.post(form.get('action'), data=inputs) self.strategy.set_request_data(parse_qs(response.content), self.backend) HTTPretty.register_uri(HTTPretty.POST, form.get('action'), status=200, body='is_valid:true\n') return self.backend.complete()
1,616
315
<gh_stars>100-1000 /*************************************************************************** Copyright (c) 2019, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 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. ***************************************************************************/ #ifndef _XF_HOG_DESCRIPTOR_PM_HPP_ #define _XF_HOG_DESCRIPTOR_PM_HPP_ #ifndef __cplusplus #error C++ is needed to include this header #endif #include "core/xf_math.h" // to convert the radians value to degrees #define XF_NORM_FACTOR 58671 // (180/PI) in Q6.10 /*********************************************************************************************** * xFHOGPhaseMagnitudeKernel : The Gradient Phase and Gradient magnitude Computation Kernel. * This kernel takes two gradients in XF_9SP depth and computes the angles and magnitude * for each pixel and store this in a XF_9UP images. * * The Input arguments are _gradx_stream, _grady_stream * _gradx_stream --> Gradient X data from the gradient computation function of * depth XF_9SP. * _grady_stream --> Gradient Y data from the gradient computation function of * depth XF_9SP. * _phase_stream --> phase computed image of depth XF_16UP. * _mag_stream --> magnitude computed image of depth XF_16UP. * * Depending on NPC, 1 or 8 pixels are read and gradient values are calculated. **********************************************************************************************/ template <int ROWS, int COLS, int DEPTH_SRC,int DEPTH_DST, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST, int COLS_TRIP> void xFHOGPhaseMagnitudeKernel( hls::stream<XF_SNAME(WORDWIDTH_SRC)>& _gradx_stream, hls::stream<XF_SNAME(WORDWIDTH_SRC)>& _grady_stream, hls::stream<XF_SNAME(WORDWIDTH_DST)>& _phase_stream, hls::stream<XF_SNAME(WORDWIDTH_DST)>& _mag_stream, uint16_t height, uint16_t width) { // Data in the packed format XF_SNAME(WORDWIDTH_SRC) grad_x_packed_val, grad_y_packed_val; XF_SNAME(WORDWIDTH_DST) phase_packed_val, mag_packed_val; // declaring the loop variables uint16_t i, j; uint16_t k, l; // VARIABLES FOR PHASE KERNEL // Fixed point format of x and y, x = QM1.N1, y = QM2.N2 // Q9.0 format input int M1, N1, M2, N2; M1 = XF_PIXELDEPTH(DEPTH_SRC); N1 = 0; M2 = M1; N2 = N1; rowLoop: for(i = 0; i < height; i++) { #pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS #pragma HLS LOOP_FLATTEN OFF colLoop: for(j = 0; j < width; j++) { #pragma HLS LOOP_TRIPCOUNT min=COLS_TRIP max=COLS_TRIP #pragma HLS PIPELINE grad_x_packed_val = (XF_SNAME(WORDWIDTH_SRC)) (_gradx_stream.read()); grad_y_packed_val = (XF_SNAME(WORDWIDTH_SRC)) (_grady_stream.read()); uchar_t step_src = XF_PIXELDEPTH(DEPTH_SRC); uchar_t step_dst = XF_PIXELDEPTH(DEPTH_DST); uint16_t proc_loop_src = XF_PIXELDEPTH(DEPTH_SRC)<<XF_BITSHIFT(NPC); uint16_t proc_loop_dst = XF_PIXELDEPTH(DEPTH_DST)<<XF_BITSHIFT(NPC); procLoop: for(k = 0, l = 0; k < proc_loop_src, l < proc_loop_dst; k += step_src, l += step_dst) { #pragma HLS UNROLL XF_PTNAME(DEPTH_SRC) g_x = grad_x_packed_val.range(k + (step_src - 1), k); // Get bits from certain range of positions. XF_PTNAME(DEPTH_SRC) g_y = grad_y_packed_val.range(k + (step_src - 1), k); // Get bits from certain range of positions. int16_t g_x_16_p, g_x_16_m, g_y_16_p, g_y_16_m; g_x_16_p = g_x_16_m = g_x; g_y_16_p = g_y_16_m = g_y; ///////////// PHASE COMPUTATION ///////////// // output will be in the radians int16_t ret = 0; int result_temp = 0; ret = xf::Atan2LUT8(g_x_16_p, g_y_16_p,M1,N1,M2,N2); if((ret<0) || ((ret==0)&&(g_y_16_p<0))) result_temp = ret + XF_PI_FIXED + XF_PI_FIXED; else result_temp = ret ; // converting the radians value to degree // instead of removing complete 22 fractional bits, we shift only 15 times, for we have some precision for HoG gradient computation XF_PTNAME(DEPTH_DST) result_phase = ((XF_NORM_FACTOR * result_temp)>>15); // Q9.7 format //////////////////////////////////////////////////// ///////////// MAGNITUDE COMPUTATION ///////////// // absolute difference of the input data __HOG_ABS(g_x_16_m); __HOG_ABS(g_y_16_m); ap_uint17_t gx_sq = (uchar_t)g_x_16_m * (uchar_t)g_x_16_m; ap_uint17_t gy_sq = (uchar_t)g_y_16_m * (uchar_t)g_y_16_m; // perform square root for the result_tmp ap_uint<17> sum_sq_grad = gx_sq + gy_sq; ap_ufixed<31,31,AP_TRN,AP_SAT> tmp_mag = ((ap_uint<31>)sum_sq_grad)<<14; XF_PTNAME(DEPTH_DST) result_mag = xFSqrtHOG<16>(tmp_mag); // Q9.7 format //////////////////////////////////////////////////// // packing the output pixel data phase_packed_val.range(l + (step_dst - 1), l) = result_phase; mag_packed_val.range(l + (step_dst - 1), l) = result_mag; } // end of proc loop _phase_stream.write(phase_packed_val); _mag_stream.write(mag_packed_val); } // end of col loop } // end of row loop } // end of function /******************************************************************* * xFPhaseMagnitude: This function acts as a wrapper function and * calls the phaseMagnitude Kernel function. *******************************************************************/ template <int ROWS, int COLS, int DEPTH_SRC,int DEPTH_DST, int NPC, int WORDWIDTH_SRC, int WORDWIDTH_DST> void xFHOGPhaseMagnitude( hls::stream<XF_SNAME(WORDWIDTH_SRC)>& _grad_x, hls::stream<XF_SNAME(WORDWIDTH_SRC)>& _grad_y, hls::stream<XF_SNAME(WORDWIDTH_DST)>& _phase_stream, hls::stream<XF_SNAME(WORDWIDTH_DST)>& _mag_stream, uint16_t height,uint16_t width) { assert((DEPTH_SRC == XF_9SP) && "DEPTH_SRC must be XF_9SP"); assert((DEPTH_DST == XF_16UP) && "DEPTH_DST must be of type XF_16UP"); assert(((NPC == XF_NPPC1) || (NPC == XF_NPPC8) || (NPC == XF_NPPC16)) && "NPC must be XF_NPPC1, XF_NPPC8 or XF_NPPC16"); assert(((WORDWIDTH_SRC == XF_9UW) || (WORDWIDTH_SRC == XF_72UW) || (WORDWIDTH_SRC == XF_144UW)) && "WORDWIDTH_SRC must be XF_9UW, XF_72UW or XF_144UW"); assert(((WORDWIDTH_DST == XF_16UW) || (WORDWIDTH_DST == XF_128UW) || (WORDWIDTH_DST == XF_256UW)) && "WORDWIDTH_DST must be XF_16UW, XF_128UW or XF_256UW"); xFHOGPhaseMagnitudeKernel<ROWS,COLS,DEPTH_SRC,DEPTH_DST,NPC,WORDWIDTH_SRC, WORDWIDTH_DST,(COLS>>XF_BITSHIFT(NPC))>(_grad_x,_grad_y,_phase_stream,_mag_stream,height,width); } #endif // _XF_HOG_DESCRIPTOR_PM_HPP_
3,187
605
<reponame>LaudateCorpus1/llvm-project /*===--------------- x86gprintrin.h - X86 GPR intrinsics ------------------=== * * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. * See https://llvm.org/LICENSE.txt for license information. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception * *===-----------------------------------------------------------------------=== */ #ifndef __X86GPRINTRIN_H #define __X86GPRINTRIN_H #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ defined(__HRESET__) #include <hresetintrin.h> #endif #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ defined(__UINTR__) #include <uintrintrin.h> #endif #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ defined(__CRC32__) #include <crc32intrin.h> #endif #define __SSC_MARK(Tag) \ __asm__ __volatile__("mov {%%ebx, %%eax|eax, ebx}; " \ "mov {%0, %%ebx|ebx, %0}; " \ ".byte 0x64, 0x67, 0x90; " \ "mov {%%eax, %%ebx|ebx, eax};" ::"i"(Tag) \ : "%eax"); #endif /* __X86GPRINTRIN_H */
686
585
<reponame>richung99/digitizePlots # -*- coding: utf-8 -*- """Diffusion Toolkit performs data reconstruction and fiber tracking on diffusion MR images.""" from .base import Info from .postproc import SplineFilter, TrackMerge from .dti import DTIRecon, DTITracker from .odf import HARDIMat, ODFRecon, ODFTracker
99
493
<reponame>venkattgg/venkey #include <algorithm> #include <flexible_type/flexible_type.hpp> #include <boost/circular_buffer.hpp> #include <boost/algorithm/string.hpp> #include <sframe/rolling_aggregate.hpp> namespace graphlab { namespace rolling_aggregate { ssize_t clip(ssize_t val, ssize_t lower, ssize_t upper) { return std::min(upper, std::max(lower, val)); } // Calculate the size of an inclusive range size_t calculate_window_size(ssize_t start, ssize_t end) { if((start < 0) && (end >= 0)) { return size_t(std::abs(start) + end + 1); } auto the_size = size_t(std::abs(end - start) + 1); return the_size; } std::shared_ptr<sarray<flexible_type>> rolling_apply( const sarray<flexible_type> &input, std::shared_ptr<group_aggregate_value> agg_op, ssize_t window_start, ssize_t window_end, size_t min_observations) { /// Sanity checks if(window_start > window_end) { log_and_throw("Start of window cannot be > end of window."); } // Check type is supported by aggregate operator if(!agg_op->support_type(input.get_type())) { log_and_throw(agg_op->name() + std::string(" does not support input type.")); } agg_op->set_input_type(input.get_type()); // Get window size given inclusive range size_t total_window_size = calculate_window_size(window_start, window_end); if(total_window_size > uint32_t(-1)) { log_and_throw("Window size cannot be larger than " + std::to_string(uint32_t(-1))); } bool check_num_observations = (min_observations != 0); if(min_observations > total_window_size) { if(min_observations != size_t(-1)) logprogress_stream << "Warning: min_observations (" << min_observations << ") larger than window size (" << total_window_size << "). Continuing with min_observations=" << total_window_size << "." << std::endl; min_observations = total_window_size; } auto num_segments = thread::cpu_count(); // sarray_reader as shared_ptr so we can use sarray_reader_buffer. Segments // are not used to actually iterate, just to evenly split up the array. std::shared_ptr<sarray_reader<flexible_type>> reader( std::move(input.get_reader(num_segments))); auto ret_sarray = std::make_shared<sarray<flexible_type>>(); ret_sarray->open_for_write(num_segments); // Calculate the valid range of data that each segment will need to do its // full rolling aggregate calculation. size_t running_length = 0; std::vector<std::pair<size_t,size_t>> seg_ranges(num_segments); std::vector<size_t> seg_starts(num_segments); for(size_t i = 0; i < num_segments; ++i) { seg_starts[i] = running_length; ssize_t beg = clip((window_start+running_length), 0, reader->size()); running_length += reader->segment_length(i); ssize_t end = clip(window_end+(running_length-1), 0, reader->size()); seg_ranges[i] = std::make_pair(size_t(beg), size_t(end)); } // Store the type returned by the aggregation function of each segment std::vector<flex_type_enum> fn_returned_types(num_segments, flex_type_enum::UNDEFINED); parallel_for(0, num_segments, [&](size_t segment_id) { auto range = seg_ranges[segment_id]; // Create buffer for the window auto window_buf = boost::circular_buffer<flexible_type>(total_window_size, flex_undefined()); auto out_iter = ret_sarray->get_output_iterator(segment_id); sarray_reader_buffer<flexible_type> buf_reader(reader, range.first, range.second+1); // The esteemed "current" value that all the documentation talks about ssize_t logical_pos = ssize_t(seg_starts[segment_id]); // The last row for which this thread should calculate the aggregate ssize_t logical_end = ssize_t(seg_starts[segment_id] + reader->segment_length(segment_id)); // The "fake" row numbers that comprise the window of the current value. // This can have negative numbers and numbers past the end. std::pair<ssize_t,ssize_t> my_logical_window = std::make_pair(window_start+logical_pos, window_end+logical_pos); // Initially fill the window buffer for(ssize_t i = my_logical_window.first; i <= my_logical_window.second; ++i) { if(i >= 0 && buf_reader.has_next()) { window_buf.push_back(buf_reader.next()); } } // Go through array with window while(logical_pos < logical_end) { // First check if we have the minimum non-NULL observations. This is here // to remove the burden of checking from every aggregation function. if(check_num_observations && !has_min_observations(min_observations, window_buf.begin(), window_buf.end())) { *out_iter = flex_undefined(); } else { auto result = full_window_aggregate(agg_op, window_buf.begin(), window_buf.end()); // Record the emitted type from the function. We just take the first // one that is non-NULL. if(fn_returned_types[segment_id] == flex_type_enum::UNDEFINED && result.get_type() != flex_type_enum::UNDEFINED) { fn_returned_types[segment_id] = result.get_type(); } *out_iter = result; } // Update logical window ++logical_pos; ++my_logical_window.first; ++my_logical_window.second; // Get the next value in the SArray if(my_logical_window.second >= 0 && buf_reader.has_next()) { window_buf.push_back(buf_reader.next()); } else { // If this is a "fake" section of the logical window, just fill with // NULL values window_buf.push_back(flex_undefined()); } } } ); // Set output type of SArray based on what the aggregation function returned flex_type_enum array_type = flex_type_enum::UNDEFINED; for(const auto &i : fn_returned_types) { // Error out if the aggregation function outputs values with more than one // type (not counting NULL) if((i != array_type) && (array_type != flex_type_enum::UNDEFINED) && (i != flex_type_enum::UNDEFINED)) { log_and_throw("Aggregation function returned two different non-NULL " "types!"); } if(i != flex_type_enum::UNDEFINED) { array_type = i; } } ret_sarray->set_type(array_type); ret_sarray->close(); return ret_sarray; } } // namespace rolling_aggregate } // namespace graphlab
2,601
7,581
<reponame>dinhtuyen/PRML01<gh_stars>1000+ import numpy as np from prml.nn.array.broadcast import broadcast_to from prml.nn.function import Function from prml.nn.math.log import log from prml.nn.nonlinear.sigmoid import sigmoid from prml.nn.random.random import RandomVariable from prml.nn.tensor.tensor import Tensor class Bernoulli(RandomVariable): """ Bernoulli distribution p(x|mu) = mu^x (1 - mu)^(1 - x) Parameters ---------- mu : tensor_like probability of value 1 logit : tensor_like log-odd of value 1 data : tensor_like observed data p : RandomVariable original distribution of a model """ def __init__(self, mu=None, logit=None, data=None, p=None): super().__init__(data, p) if mu is not None and logit is None: mu = self._convert2tensor(mu) self.mu = mu elif mu is None and logit is not None: logit = self._convert2tensor(logit) self.logit = logit elif mu is None and logit is None: raise ValueError("Either mu or logit must not be None") else: raise ValueError("Cannot assign both mu and logit") @property def mu(self): try: return self.parameter["mu"] except KeyError: return sigmoid(self.logit) @mu.setter def mu(self, mu): try: inrange = (0 <= mu.value <= 1) except ValueError: inrange = ((mu.value >= 0).all() and (mu.value <= 1).all()) if not inrange: raise ValueError("value of mu must all be positive") self.parameter["mu"] = mu @property def logit(self): try: return self.parameter["logit"] except KeyError: raise AttributeError("no attribute named logit") @logit.setter def logit(self, logit): self.parameter["logit"] = logit def forward(self): return (np.random.uniform(size=self.mu.shape) < self.mu.value).astype(np.int) def _pdf(self, x): return self.mu ** x * (1 - self.mu) ** (1 - x) def _log_pdf(self, x): try: return -SigmoidCrossEntropy().forward(self.logit, x) except AttributeError: return x * log(self.mu) + (1 - x) * log(1 - self.mu) class SigmoidCrossEntropy(Function): """ sum of cross entropies for binary data logistic sigmoid y_i = 1 / (1 + exp(-x_i)) cross_entropy_i = -t_i * log(y_i) - (1 - t_i) * log(1 - y_i) Parameters ---------- x : ndarary input logit y : ndarray corresponding target binaries """ def _check_input(self, x, t): x = self._convert2tensor(x) t = self._convert2tensor(t) if x.shape != t.shape: shape = np.broadcast(x.value, t.value).shape if x.shape != shape: x = broadcast_to(x, shape) if t.shape != shape: t = broadcast_to(t, shape) return x, t def forward(self, x, t): x, t = self._check_input(x, t) self.x = x self.t = t # y = self.forward(x) # np.clip(y, 1e-10, 1 - 1e-10, out=y) # return np.sum(-t * np.log(y) - (1 - t) * np.log(1 - y)) loss = ( np.maximum(x.value, 0) - t.value * x.value + np.log1p(np.exp(-np.abs(x.value))) ) return Tensor(loss, function=self) def backward(self, delta): y = np.tanh(self.x.value * 0.5) * 0.5 + 0.5 dx = delta * (y - self.t.value) dt = - delta * self.x.value self.x.backward(dx) self.t.backward(dt)
1,792
310
{ "name": "POG", "description": "A polyphonic octave generator.", "url": "https://www.ehx.com/products/pog" }
47
428
<reponame>radoslawcybulski/CastXML<filename>test/input/Class-forward.cxx class start; class start { public: start(); start(start const&); start& operator=(start const&); ~start(); };
71
396
<reponame>daattali/dashR<gh_stars>100-1000 app_with_theme = """ library(dash) controls <- dbcCard(list( div( dbcLabel("Dataset"), dbcInput(id="dbc-input", type="text", value="<NAME>") ) ), body=T) dash_app() %>% add_stylesheet(dbcThemes$BOOTSTRAP) %>% set_layout( dbcContainer(list( dbcRow(list( h1("Dash Bootstrap Components"), dbcCol(controls, md=4) ), align="right") ), fluid=T) ) %>% run_app() """ def test_rdbc001_bootstrap_theme(dashr): dashr.start_server(app_with_theme) dashr.wait_for_element_by_id("dbc-input", timeout=4) dashr.percy_snapshot("rdbc001 - bootstrap components")
301
411
<reponame>sumau/tick # License: BSD 3 clause import unittest from tick.solver import GD from tick.solver.tests import TestSolver class GDTest(object): def test_solver_gd(self): """...Check GD solver for Logistic Regression with Ridge penalization """ solver = GD(max_iter=100, verbose=False, linesearch=True) self.check_solver(solver, fit_intercept=True, model="logreg", decimal=1) def test_gd_sparse_and_dense_consistency(self): """...Test GD can run all glm models and is consistent with sparsity """ def create_solver(): return GD(max_iter=1, verbose=False) self._test_solver_sparse_and_dense_consistency(create_solver) def test_gd_dtype_can_change(self): """...Test gd astype method """ def create_solver(): return GD(max_iter=100, verbose=False, step=0.1) self._test_solver_astype_consistency(create_solver) class GDTestFloat32(TestSolver, GDTest): def __init__(self, *args, **kwargs): TestSolver.__init__(self, *args, dtype="float32", **kwargs) class GDTestFloat64(TestSolver, GDTest): def __init__(self, *args, **kwargs): TestSolver.__init__(self, *args, dtype="float64", **kwargs) if __name__ == '__main__': unittest.main()
582
1,907
<filename>src/appleseed/foundation/curve/binarycurvefilewriter.cpp // // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2018 <NAME>, The appleseedhq Organization // // 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. // // Interface header. #include "binarycurvefilewriter.h" // appleseed.foundation headers. #include "foundation/core/exceptions/exceptionioerror.h" #include "foundation/curve/icurvewalker.h" #include "foundation/math/vector.h" // Standard headers. #include <cstring> namespace foundation { // // BinaryCurveFileWriter class implementation. // BinaryCurveFileWriter::BinaryCurveFileWriter(const std::string& filename) : m_filename(filename) , m_writer(m_file, 256 * 1024) { } void BinaryCurveFileWriter::write(const ICurveWalker& walker) { if (!m_file.is_open()) { m_file.open( m_filename.c_str(), BufferedFile::BinaryType, BufferedFile::WriteMode); if (!m_file.is_open()) throw ExceptionIOError(); write_signature(); write_version(); } write_curves(walker); } void BinaryCurveFileWriter::write_signature() { static const char Signature[11] = { 'B', 'I', 'N', 'A', 'R', 'Y', 'C', 'U', 'R', 'V', 'E' }; checked_write(m_file, Signature, sizeof(Signature)); } void BinaryCurveFileWriter::write_version() { const std::uint16_t Version = 2; checked_write(m_file, Version); } void BinaryCurveFileWriter::write_curves(const ICurveWalker& walker) { write_basis(walker); write_curve_count(walker); std::uint32_t vertex_count = 0; for (std::uint32_t i = 0; i < walker.get_curve_count(); ++i) write_curve(walker, i, vertex_count); } void BinaryCurveFileWriter::write_basis(const ICurveWalker& walker) { const unsigned char basis = static_cast<unsigned char>(walker.get_basis()); checked_write(m_writer, basis); } void BinaryCurveFileWriter::write_curve_count(const ICurveWalker& walker) { const std::uint32_t curve_count = static_cast<std::uint32_t>(walker.get_curve_count()); checked_write(m_writer, curve_count); } void BinaryCurveFileWriter::write_curve(const ICurveWalker& walker, const std::uint32_t curve_id, std::uint32_t& vertex_count) { const std::uint32_t count = static_cast<std::uint32_t>(walker.get_vertex_count(curve_id)); checked_write(m_writer, count); for (std::uint32_t i = 0; i < count; ++i) checked_write(m_writer, walker.get_vertex(i + vertex_count)); for (std::uint32_t i = 0; i < count; ++i) checked_write(m_writer, walker.get_vertex_width(i + vertex_count)); for (std::uint32_t i = 0; i < count; ++i) checked_write(m_writer, walker.get_vertex_opacity(i + vertex_count)); for (std::uint32_t i = 0; i < count; ++i) checked_write(m_writer, walker.get_vertex_color(i + vertex_count)); vertex_count += count; } } // namespace foundation
1,442
3,301
package com.alibaba.alink.operator.common.linear.unarylossfunc; /** * Squared loss function. * https://en.wikipedia.org/wiki/Loss_functions_for_classification#Square_loss */ public class SquareLossFunc implements UnaryLossFunc { private static final long serialVersionUID = 4979822510416701065L; public SquareLossFunc() { } @Override public double loss(double eta, double y) { return 0.5 * (eta - y) * (eta - y); } @Override public double derivative(double eta, double y) { return eta - y; } @Override public double secondDerivative(double eta, double y) { return 1; } }
208
2,389
<reponame>Ankit01Mishra/java /* Copyright 2020 The Kubernetes Authors. 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. */ package io.kubernetes.client.extended.network; import io.kubernetes.client.extended.network.exception.NoAvailableAddressException; import java.util.List; /** LoadBalancer provides IP address for L4 client-side load-balancing. */ public interface LoadBalancer { List<String> getAllAvailableIPs() throws NoAvailableAddressException; List<String> getAllAvailableIPs(int port) throws NoAvailableAddressException; String getTargetIP() throws NoAvailableAddressException; String getTargetIP(int port) throws NoAvailableAddressException; }
303
751
<filename>src/plugins/ioam/lib-trace/trace_test.c /* * Copyright (c) 2016 Cisco and/or its affiliates. * 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. */ /* *------------------------------------------------------------------ * trace_test.c - test harness for trace plugin *------------------------------------------------------------------ */ #include <vat/vat.h> #include <vlibapi/api.h> #include <vlibmemory/api.h> #include <vppinfra/error.h> #define __plugin_msg_base trace_test_main.msg_id_base #include <vlibapi/vat_helper_macros.h> /* Declare message IDs */ #include <ioam/lib-trace/trace.api_enum.h> #include <ioam/lib-trace/trace.api_types.h> typedef struct { /* API message ID base */ u16 msg_id_base; vat_main_t *vat_main; } trace_test_main_t; trace_test_main_t trace_test_main; static int api_trace_profile_add (vat_main_t * vam) { unformat_input_t *input = vam->input; vl_api_trace_profile_add_t *mp; u8 trace_type = 0; u8 num_elts = 0; u32 node_id = 0; u32 app_data = 0; u8 trace_tsp = 0; int ret; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "trace-type 0x%x", &trace_type)) ; else if (unformat (input, "trace-elts %d", &num_elts)) ; else if (unformat (input, "trace-tsp %d", &trace_tsp)) ; else if (unformat (input, "node-id 0x%x", &node_id)) ; else if (unformat (input, "app-data 0x%x", &app_data)) ; else break; } M (TRACE_PROFILE_ADD, mp); mp->trace_type = trace_type; mp->trace_tsp = trace_tsp; mp->node_id = htonl (node_id); mp->app_data = htonl (app_data); mp->num_elts = num_elts; S (mp); W (ret); return ret; } static int api_trace_profile_del (vat_main_t * vam) { vl_api_trace_profile_del_t *mp; int ret; M (TRACE_PROFILE_DEL, mp); S (mp); W (ret); return ret; } static int api_trace_profile_show_config (vat_main_t * vam) { vl_api_trace_profile_show_config_t *mp; int ret; M (TRACE_PROFILE_SHOW_CONFIG, mp); S (mp); W (ret); return ret; } static int vl_api_trace_profile_show_config_reply_t_handler (vat_main_t * vam) { return -1; } /* Override generated plugin register symbol */ #define vat_plugin_register trace_vat_plugin_register #include <ioam/lib-trace/trace.api_test.c> /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
1,132
324
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.googlecloud.domain; import java.util.List; import org.jclouds.javax.annotation.Nullable; /** An immutable list that includes a token, if there is another page available. */ public interface ListPage<T> extends List<T> { /** Indicates more data is available. */ @Nullable String nextPageToken(); }
291
422
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt #ifndef MESH_PROCESSING_LIBHH_COMBINATION_H_ #define MESH_PROCESSING_LIBHH_COMBINATION_H_ #include "libHh/Map.h" #include "libHh/RangeOp.h" #if 0 { Combination<Vertex> combination; for_combination(combination, [&](Vertex v, float val) { func(v, val); }); } #endif namespace hh { // Represents a weighted combination of elements where the weights are float. template <typename T> class Combination : public Map<T, float> { using base = Map<T, float>; public: float sum() const { return hh::sum<float>(values()); } void shrink_to_fit() const { // remove elements with zero weights Combination& var_self = const_cast<Combination&>(*this); Array<T> ar; for_map_key_value(*this, [&](const T& e, float v) { if (!v) ar.push(e); }); for (const T& e : ar) var_self.remove(e); } using base::values; }; template <typename T, typename Func = void(const T& e, float val)> void for_combination(const Combination<T>& combination, Func func) { for (auto& kv : combination) func(kv.first, kv.second); } } // namespace hh #endif // MESH_PROCESSING_LIBHH_COMBINATION_H_
449
1,388
<gh_stars>1000+ #!/usr/bin/env python # Copyright (C) 2007 <NAME>' <<EMAIL>>. # Use of this source code is governed by MIT license that can be # found in the LICENSE file. """ A FTP server which handles every connection in a separate thread. Useful if your handler class contains blocking calls or your filesystem is too slow. """ from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import ThreadedFTPServer def main(): authorizer = DummyAuthorizer() authorizer.add_user('user', '12345', '.') handler = FTPHandler handler.authorizer = authorizer server = ThreadedFTPServer(('', 2121), handler) server.serve_forever() if __name__ == "__main__": main()
242
1,529
/* * Copyright (c) 2016 咖枯 <<EMAIL>> * * 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. * */ package com.kaku.colorfulnews.event; /** * @author 咖枯 * @version 1.0 2016/7/2 */ public class ChannelItemMoveEvent { private int fromPosition; private int toPosition; public int getFromPosition() { return fromPosition; } public int getToPosition() { return toPosition; } public ChannelItemMoveEvent(int fromPosition, int toPosition) { this.fromPosition = fromPosition; this.toPosition = toPosition; } }
345
335
<filename>F/Fenestration_noun.json { "word": "Fenestration", "definitions": [ "The arrangement of windows in a building.", "The condition of being fenestrate.", "A surgical operation in which a new opening is formed, especially in the bony labyrinth of the inner ear to treat certain types of deafness." ], "parts-of-speech": "Noun" }
133
2,636
<gh_stars>1000+ package com.hitomi.tilibrary.style.index; import androidx.viewpager.widget.ViewPager; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.hitomi.tilibrary.style.IIndexIndicator; import com.hitomi.tilibrary.view.indicator.CircleIndicator; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; /** * 图片翻页时使用 {@link CircleIndicator} 去指示当前图片的位置 * <p> * Created by <NAME> on 2017/2/4. * <p> * email: <EMAIL> */ public class CircleIndexIndicator implements IIndexIndicator { private CircleIndicator circleIndicator; @Override public void attach(FrameLayout parent) { FrameLayout.LayoutParams indexLp = new FrameLayout.LayoutParams(WRAP_CONTENT, 48); indexLp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; indexLp.bottomMargin = 10; circleIndicator = new CircleIndicator(parent.getContext()); circleIndicator.setGravity(Gravity.CENTER_VERTICAL); circleIndicator.setLayoutParams(indexLp); parent.addView(circleIndicator); } @Override public void onShow(ViewPager viewPager) { if (circleIndicator == null) return; circleIndicator.setVisibility(View.VISIBLE); circleIndicator.setViewPager(viewPager); } @Override public void onHide() { if (circleIndicator == null) return; circleIndicator.setVisibility(View.GONE); } @Override public void onRemove() { if (circleIndicator == null) return; ViewGroup vg = (ViewGroup) circleIndicator.getParent(); if (vg != null) { vg.removeView(circleIndicator); } } }
696
519
<gh_stars>100-1000 from django.conf.urls import url from . import views from . import restapi app_name = 'x123' urlpatterns = [ # ex: / url(r'^$', views.index, name='index'), # ex: /d/1/ url(r'^d/(?P<domain_id>[0-9]+)/$', views.domain, name='domain'), # ex: /a/1/ url(r'^a/(?P<aspect_id>[0-9]+)/$', views.aspect, name='aspect'), # ex: /bookmark/5/ url(r'^b/(?P<bookmark_id>[0-9]+)/$', views.bookmark, name='bookmark'), url(r'^api/domains/$', restapi.DomainList.as_view()), url(r'^api/angles/$', restapi.AngleList.as_view()), url(r'^api/bookmarks/$', restapi.BookmarkList.as_view()), url(r'^api/bookmarks/(?P<pk>[0-9]+)/$', restapi.BookmarkDetail.as_view()), url(r'^api/auth_info/$', restapi.auth_info), url(r'^api/bookmark_existed/$', restapi.bookmark_existed), url(r'^api/bookmark_save/$', restapi.bookmark_save), url(r'^api/bookmark_remove/$', restapi.bookmark_remove), url(r'^api/bookmark_click/$', restapi.bookmark_click), url(r'^api/bookmarks_in_aspect/(?P<aspect_id>[0-9]+)/$', restapi.BookmarkListInAspect.as_view()), url(r'^api/feeds/$', restapi.FeedList.as_view()), ]
538
622
<gh_stars>100-1000 """string.format""" from runtime import * def main(): a = '{x}{y}'.format( x='A', y='B') assert(a == 'AB') main()
58
518
<filename>src/etc/generate-keyword-tests.py #!/usr/bin/env python """ This script takes a list of keywords and generates a testcase, that checks if using the keyword as identifier fails, for every keyword. The generate test files are set read-only. Test for https://github.com/rust-lang/rust/issues/2275 sample usage: src/etc/generate-keyword-tests.py as break """ import sys import os import datetime import stat template = """\ // This file was auto-generated using 'src/etc/generate-keyword-tests.py %s' fn main() { let %s = "foo"; //~ error: expected pattern, found keyword `%s` } """ test_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '../test/ui/parser') ) for kw in sys.argv[1:]: test_file = os.path.join(test_dir, 'keyword-%s-as-identifier.rs' % kw) # set write permission if file exists, so it can be changed if os.path.exists(test_file): os.chmod(test_file, stat.S_IWUSR) with open(test_file, 'wt') as f: f.write(template % (kw, kw, kw)) # mark file read-only os.chmod(test_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
430
1,383
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: <NAME> // ============================================================================= // // Marder support roller subsystem. // // ============================================================================= #ifndef MARDER_SUPPORT_ROLLER_H #define MARDER_SUPPORT_ROLLER_H #include <string> #include "chrono_vehicle/ChSubsysDefs.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/tracked_vehicle/roller/ChDoubleRoller.h" #include "chrono_models/ChApiModels.h" namespace chrono { namespace vehicle { namespace marder { /// @addtogroup vehicle_models_marder /// @{ /// Support roller model for the Marder vehicle (base class). class CH_MODELS_API Marder_SupportRoller : public ChDoubleRoller { public: virtual ~Marder_SupportRoller() {} /// Return the mass of the idler wheel body. virtual double GetMass() const override { return m_wheel_mass; } /// Return the moments of inertia of the idler wheel body. virtual const ChVector<>& GetInertia() override { return m_wheel_inertia; } /// Return the radius of the idler wheel. virtual double GetRadius() const override { return m_wheel_radius; } /// Return the total width of the idler wheel. virtual double GetWidth() const override { return m_wheel_width; } /// Return the gap width. virtual double GetGap() const override { return m_wheel_gap; } protected: Marder_SupportRoller(const std::string& name); virtual VehicleSide GetVehicleSide() const = 0; virtual std::string GetMeshFile() const = 0; /// Create the contact material consistent with the specified contact method. virtual void CreateContactMaterial(ChContactMethod contact_method) override; /// Add visualization of the road wheel. virtual void AddVisualizationAssets(VisualizationType vis) override; static const double m_wheel_mass; static const ChVector<> m_wheel_inertia; static const double m_wheel_radius; static const double m_wheel_width; static const double m_wheel_gap; }; /// Road-wheel model for the M113 vehicle (left side). class CH_MODELS_API Marder_SupportRollerLeft : public Marder_SupportRoller { public: Marder_SupportRollerLeft(int index) : Marder_SupportRoller("Marder_SupportRollerLeft_" + std::to_string(index)) {} ~Marder_SupportRollerLeft() {} virtual VehicleSide GetVehicleSide() const override { return LEFT; } virtual std::string GetMeshFile() const override { return GetDataFile(m_meshFile); } private: static const std::string m_meshFile; }; /// Road-wheel model for the M113 vehicle (right side). class CH_MODELS_API Marder_SupportRollerRight : public Marder_SupportRoller { public: Marder_SupportRollerRight(int index) : Marder_SupportRoller("Marder_SupportRollerRight_" + std::to_string(index)) {} ~Marder_SupportRollerRight() {} virtual VehicleSide GetVehicleSide() const override { return RIGHT; } virtual std::string GetMeshFile() const override { return GetDataFile(m_meshFile); } private: static const std::string m_meshFile; }; /// @} vehicle_models_marder } // namespace marder } // end namespace vehicle } // end namespace chrono #endif
1,104
1,968
<reponame>agramonte/corona<gh_stars>1000+ ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #pragma once #include "Input\Rtt_InputAxisType.h" #include "Input\Rtt_InputDeviceType.h" #include "Key.h" #include "WinString.h" #include <string> #include <vector> namespace Interop { namespace Input { class InputAxisSettings; /// <summary>Stores the configuration for one input device such as a keyboard, gamepad, etc.</summary> class InputDeviceSettings { public: #pragma region Public AxisCollectionAdapter Class /// <summary> /// <para>Provides access to an InputDeviceSettings object's axis collection.</para> /// <para>Instances of this class was designed to be passed by value efficiently.</para> /// </summary> class AxisCollectionAdapter { public: /// <summary> /// Creates a new object providing writeable access to the given input device's axis collection. /// </summary> /// <param name="settings">Reference to the input device to access the axis collection of.</param> AxisCollectionAdapter(InputDeviceSettings& settings); /// <summary>Creates a new object providing access to the given input device's axis collection.</summary> /// <param name="settings">Reference to the input device to access the axis collection of.</param> AxisCollectionAdapter(const InputDeviceSettings& settings); /// <summary>Destroys this object.</summary> virtual ~AxisCollectionAdapter(); /// <summary> /// Adds a new input axis configuration initialized to its defaults to the end of the /// axis collection and returns it. /// </summary> /// <returns>Returns a pointer to the newly added axis configuration.</returns> InputAxisSettings* Add(); /// <summary>Removes all axes from the collection.</summary> void Clear(); /// <summary>Gets the number of axis configurations in the collection.</summary> /// <returns> /// <para>Returns the number of axes in the collection.</para> /// <para>Returns zero if the device has no axes.</para> /// </returns> int GetCount() const; /// <summary>Fetches an axis configuration from the collection by its zero based index.</summary> /// <param name="index">Zero based index to the axis configuration.</param> /// <returns> /// <para>Returns a pointer to the index axis configuration.</para> /// <para>Returns null if given an invalid index.</para> /// </returns> InputAxisSettings* GetByIndex(int index) const; /// <summary>Determines if this collection contains at least one axis of the given type.</summary> /// <param name="value">The axis type to search for such as kLeftX, kLeftY, kLeftTrigger, etc.</param> /// <returns> /// <para>Returns true if this collection contains at least one axis of the given type.</para> /// <para>Returns false if the given axis type was not found in the collection.</para> /// </returns> bool Contains(const Rtt::InputAxisType& value) const; /// <summary> /// Determines if all of the axis configurations in this collection exactly match /// the axis configurations in the given collection. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if the axis configurations in this collection exactly match with the given collection. /// </para> /// <para> /// Returns false if at least one axis configuration does not match or if the number of axes differ /// between the two collections. /// </para> /// </returns> bool Equals(const AxisCollectionAdapter& collection) const; /// <summary> /// Determines if the axis configurations between this collection and the given collection /// do not exactly match. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if at least one axis configuration does not match or if the number of axes differ /// between the two collections. /// </para> /// <para> /// Returns false if the axis configurations in this collection exactly match with the given collection. /// </para> /// </returns> bool NotEquals(const AxisCollectionAdapter& collection) const; /// <summary> /// Determines if all of the axis configurations in this collection exactly match /// the axis configurations in the given collection. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if the axis configurations in this collection exactly match with the given collection. /// </para> /// <para> /// Returns false if at least one axis configuration does not match or if the number of axes differ /// between the two collections. /// </para> /// </returns> bool operator==(const AxisCollectionAdapter& collection) const; /// <summary> /// Determines if the axis configurations between this collection and the given collection /// do not exactly match. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if at least one axis configuration does not match or if the number of axes differ /// between the two collections. /// </para> /// <para> /// Returns false if the axis configurations in this collection exactly match with the given collection. /// </para> /// </returns> bool operator!=(const AxisCollectionAdapter& collection) const; private: /// <summary> /// <para>Reference to the input device object this class wraps.</para> /// <para>Used to access the actual InputAxisSettings collection object that this class manipulates.</para> /// </summary> InputDeviceSettings& fSettings; }; #pragma endregion #pragma region Public KeyCollectionAdapter Class /// <summary> /// <para>Provides access to an InputDeviceSettings object's key collection.</para> /// <para>Instances of this class was designed to be passed by value efficiently.</para> /// </summary> class KeyCollectionAdapter { public: /// <summary> /// Creates a new object providing writeable access to the given input device's key collection. /// </summary> /// <param name="settings">Reference to the input device to access the key collection of.</param> KeyCollectionAdapter(InputDeviceSettings& settings); /// <summary>Creates a new object providing access to the given input device's key collection.</summary> /// <param name="settings">Reference to the input device to access the key collection of.</param> KeyCollectionAdapter(const InputDeviceSettings& settings); /// <summary>Destroys this object.</summary> virtual ~KeyCollectionAdapter(); /// <summary> /// <para>Adds the given key to the collection, if it hasn't been added already.</para> /// <para>Note that the collection will only store a unique set of keys. Duplicates are not allowed.</para> /// </summary> /// <param name="value">The key to be added to the collection.</param> /// <returns> /// <para>Returns true if the key was added.</para> /// <para>Returns false if the given key already exists in the collection.</para> /// </returns> bool Add(const Key& value); /// <summary>Removes all keys from the collection.</summary> void Clear(); /// <summary>Gets the number of keys in the collection.</summary> /// <returns> /// <para>Returns the number of keys in the collection.</para> /// <para>Returns zero if the device has no keys.</para> /// </returns> int GetCount() const; /// <summary>Fetches a key from the collection by its zero based index.</summary> /// <param name="index">Zero based index to the key.</param> /// <returns> /// <para>Returns a pointer to the indexed key.</para> /// <para>Returns null if given an invalid index.</para> /// </returns> const Key* GetByIndex(int index) const; /// <summary>Determines if the given key exists in the collection.</summary> /// <param name="value">The key to search for.</param> /// <returns>Returns true if the given key exists in the collection. Returns false if not.</returns> bool Contains(const Key& value) const; /// <summary> /// Determines if all of the keys in this collection match the keys in the given collection. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para>Returns true if the keys in this collection exactly match with the given collection.</para> /// <para> /// Returns false if at least one key does not match or if the number of keys differ /// between the two collections. /// </para> /// </returns> bool Equals(const KeyCollectionAdapter& collection) const; /// <summary> /// Determines if the keys between this collection and the given collection do not exactly match. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if at least one key does not match or if the number of keys differ /// between the two collections. /// </para> /// <para>Returns false if the keys in this collection exactly match with the given collection.</para> /// </returns> bool NotEquals(const KeyCollectionAdapter& collection) const; /// <summary> /// Determines if all of the keys in this collection match the keys in the given collection. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para>Returns true if the keys in this collection exactly match with the given collection.</para> /// <para> /// Returns false if at least one key does not match or if the number of keys differ /// between the two collections. /// </para> /// </returns> bool operator==(const KeyCollectionAdapter& collection) const; /// <summary> /// Determines if the keys between this collection and the given collection do not exactly match. /// </summary> /// <param name="collection">The collection to be compared against.</param> /// <returns> /// <para> /// Returns true if at least one key does not match or if the number of keys differ /// between the two collections. /// </para> /// <para>Returns false if the keys in this collection exactly match with the given collection.</para> /// </returns> bool operator!=(const KeyCollectionAdapter& collection) const; private: /// <summary> /// <para>Reference to the input device object this class wraps.</para> /// <para>Used to access the actual Key collection member variable that this class manipulates.</para> /// </summary> InputDeviceSettings& fSettings; }; #pragma endregion #pragma region Constructors/Destructors /// <summary>Creates a new input device configuration initialized to its defaults.</summary> InputDeviceSettings(); /// <summary>Creates a new input device configuration providing a copy of the given configuration.</summary> /// <param name="settings">The input device configuration to be copied.</param> InputDeviceSettings(const InputDeviceSettings& settings); /// <summary>Destroys this object.</summary> virtual ~InputDeviceSettings(); #pragma endregion #pragma region Public Methods /// <summary>Gets the type of input device this is such as kKeyboard, kJoystick, etc.</summary> /// <returns>Returns the type of input device this is.</returns> Rtt::InputDeviceType GetType() const; /// <summary>Sets the type of input device this is such as kKeyboard, kJoystick, etc.</summary> /// <param name="value">The type of input device this is.</param> void SetType(const Rtt::InputDeviceType& value); /// <summary> /// <para>Gets a unique string ID assigned to the device that can be saved to file.</para> /// <para>This string ID will persist after restarting the app or after rebooting the system.</para> /// </summary> /// <returns> /// <para>Returns the device's unique string ID.</para> /// <para>Returns an empty string if the device does not have a permanent string ID assigned to it.</para> /// </returns> const char* GetPermanentStringId() const; /// <summary> /// <para>Sets a unique string ID that is assigned to the device that can be saved to file.</para> /// <para>This string ID will persist after restarting the app or after rebooting the system.</para> /// </summary> /// <param name="value">The unique string ID. Can be null or empty string.</param> void SetPermanentStringId(const char* value); /// <summary>Gets a UTF-8 encoded name of the input device as assigned by the manufacturer.</summary> /// <remarks> /// If the device is a gamepad or joystick, then this name is typically used to determined /// which axis inputs and key/button inputs are what on the device. Especially when determining /// which axis inputs make up the right thumbstick on a gamepad since there is no standard. /// </remarks> /// <returns> /// <para>Returns the device's UTF-8 encoded name as assigned to it by the manufacturer.</para> /// <para>Returns an empty string if the product name could not be obtained.</para> /// </returns> const char* GetProductNameAsUtf8() const; /// <summary>Gets a UTF-16 encoded name of the input device as assigned by the manufacturer.</summary> /// <remarks> /// If the device is a gamepad or joystick, then this name is typically used to determined /// which axis inputs and key/button inputs are what on the device. Especially when determining /// which axis inputs make up the right thumbstick on a gamepad since there is no standard. /// </remarks> /// <returns> /// <para>Returns the device's UTF-16 encoded name as assigned to it by the manufacturer.</para> /// <para>Returns an empty string if the product name could not be obtained.</para> /// </returns> const wchar_t* GetProductNameAsUtf16() const; /// <summary>Sets the UTF-8 encoded name of the input device as assigned by the manufacturer.</summary> /// <param name="value">The UTF-8 encoded name. Can be null or empty string.</param> void SetProductName(const char* value); /// <summary>Sets the UTF-16 encoded name of the input device as assigned by the manufacturer.</summary> /// <param name="value">The UTF-16 encoded name. Can be null or empty string.</param> void SetProductName(const wchar_t* value); /// <summary> /// <para>Gets a UTF-8 encoded descriptive name assigned to the device by the end-user or by the system.</para> /// <para>This is typically the product name if the display/alias name could not be obtained.</para> /// </summary> /// <returns> /// <para>Returns the device's display name as a UTF-8 encoded string.</para> /// <para>Returns an empty string if the display name could not be obtained.</para> /// </returns> const char* GetDisplayNameAsUtf8() const; /// <summary> /// <para>Gets a UTF-16 encoded descriptive name assigned to the device by the end-user or by the system.</para> /// <para>This is typically the product name if the display/alias name could not be obtained.</para> /// </summary> /// <returns> /// <para>Returns the device's display name as a UTF-16 encoded string.</para> /// <para>Returns an empty string if the display name could not be obtained.</para> /// </returns> const wchar_t* GetDisplayNameAsUtf16() const; /// <summary> /// <para>Sets the descriptive name assigned to the device by the end-user or by the system.</para> /// <para>This is typically the product name if the display/alias name could not be obtained.</para> /// </summary> /// <param name="value">The UTF-8 encoded name. Can be null or empty string.</param> void SetDisplayName(const char* value); /// <summary> /// <para>Sets the descriptive name assigned to the device by the end-user or by the system.</para> /// <para>This is typically the product name if the display/alias name could not be obtained.</para> /// </summary> /// <param name="value">The UTF-16 encoded name. Can be null or empty string.</param> void SetDisplayName(const wchar_t* value); /// <summary> /// <para>Gets a one based player number assigned to the device by the system.</para> /// <para>Player numbers are typically assigned to XInput devices that are currently connected.</para> /// <para>DirectInput and RawInput devices do not support player numbers.</para> /// </summary> /// <returns> /// <para>Returns a one based player number assigned to the device.</para> /// <para>Returns zero if a player number is not assigned to the device.</para> /// </returns> unsigned int GetPlayerNumber() const; /// <summary> /// <para>Sets a one based player number to the device, if it has one.</para> /// <para>This is typically XInput's user index (which is zero based) plus one.</para> /// <para>Should be set to zero if a player number is not assigned to the device by the system.</para> /// </summary> /// <param name="value"> /// <para>A one based player number assigned to the device.</para> /// <para>Set to zero to indicate that a player number is not assigned to the device. This is the default.</para> /// </param> void SetPlayerNumber(unsigned int value); /// <summary>Determines if the input device supports vibrate/rumble functionality.</summary> /// <returns>Returns true if the device support vibration feedback. Returns false if not.</returns> bool CanVibrate() const; /// <summary>Sets whether or not the input device supports vibrate/rumble functionality.</summary> /// <param name="value>Set true to indicate the device supports vibration feedback. Set false if not.</param> void SetCanVibrate(bool value); /// <summary>Gets modifiable access to this input device's axis configuration collection.</summary> /// <returns>Returns an object providing modifiable access to the input device's axis collection.</returns> InputDeviceSettings::AxisCollectionAdapter GetAxes(); /// <summary>Gets read-only access to this input device's axis configuration collection.</summary> /// <returns>Returns an object providing read-only access to the input device's axis collection.</returns> const InputDeviceSettings::AxisCollectionAdapter GetAxes() const; /// <summary>Gets modifiable access to this input device's key collection.</summary> /// <returns>Returns an object providing modifiable access to the input device's key collection.</returns> InputDeviceSettings::KeyCollectionAdapter GetKeys(); /// <summary>Gets modifiable access to this input device's key collection.</summary> /// <returns>Returns an object providing modifiable access to the input device's key collection.</returns> const InputDeviceSettings::KeyCollectionAdapter GetKeys() const; /// <summary>Copies the given input device settings to this object's settings.</summary> /// <param name="settings">The settings to be copied.</param> void CopyFrom(const InputDeviceSettings& settings); /// <summary>Copies the given input device settings to this object's settings.</summary> /// <param name="settings">The settings to be copied.</param> void operator=(const InputDeviceSettings& settings); /// <summary>Determines if this configuration matches the given configuration.</summary> /// <param name="value">Reference to the configuration to compare against.</param> /// <returns>Returns true if the configurations match. Returns false if not.</returns> bool Equals(const InputDeviceSettings& value) const; /// <summary>Determines if this configuration does not match the given configuration.</summary> /// <param name="value">Reference to the configuration to compare against.</param> /// <returns>Returns true if the configurations do not match. Returns false if they do match.</returns> bool NotEquals(const InputDeviceSettings& value) const; /// <summary>Determines if this configuration matches the given configuration.</summary> /// <param name="value">Reference to the configuration to compare against.</param> /// <returns>Returns true if the configurations match. Returns false if not.</returns> bool operator==(const InputDeviceSettings& value) const; /// <summary>Determines if this configuration does not match the given configuration.</summary> /// <param name="value">Reference to the configuration to compare against.</param> /// <returns>Returns true if the configurations do not match. Returns false if they do match.</returns> bool operator!=(const InputDeviceSettings& value) const; #pragma endregion private: #pragma region Private Member Variables /// <summary>The type of input device this is such as kJoystick, kGamepad, kKeyboard, etc.</summary> Rtt::InputDeviceType fType; /// <summary>The device's unique string ID that will persist after rebooting the system.</summary> std::string fPermanentStringId; /// <summary>The product name assigned to this device by the manufacturer.</summary> WinString fProductName; /// <summary>Human readable name assigned to this device by the system.</summary> WinString fDisplayName; /// <summary> /// <para>One based player number assigned to the device by the system, such as XInput.</para> /// <para>This is normally the XInput user index plus 1 since it is zero based.</para> /// <para>Set to zero if a number was not assigned to the device.</para> /// </summary> unsigned int fPlayerNumber; /// <summary>Set true if the device supports vibrate/rumble functionality.</summary> bool fCanVibrate; /// <summary>Collection of axis configurations owned by this input device. Order matters.</summary> std::vector<InputAxisSettings*> fAxisCollection; /// <summary>Stores a collection of unique keys owned by this input device. Order matters.</summary> std::vector<Key> fKeyCollection; #pragma endregion }; } } // namespace Interop::Input
6,848
302
<filename>Updater/ipostpreparestrategy.cpp #include "ipostpreparestrategy.h" IPostPrepareStrategy::IPostPrepareStrategy(QObject *parent) : QObject(parent) { }
77
575
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_OVERVIEW_OVERVIEW_CONSTANTS_H_ #define ASH_WM_OVERVIEW_OVERVIEW_CONSTANTS_H_ #include "ash/ash_export.h" #include "ash/style/ash_color_provider.h" #include "ash/wm/window_mini_view.h" #include "base/time/time.h" namespace ash { // The time duration for transformation animations. constexpr base::TimeDelta kTransition = base::TimeDelta::FromMilliseconds(300); // In the conceptual overview table, the window margin is the space reserved // around the window within the cell. This margin does not overlap so the // closest distance between adjacent windows will be twice this amount. constexpr int kWindowMargin = 5; // Height of an item header. constexpr int kHeaderHeightDp = WindowMiniView::kHeaderHeightDp; // Windows whose aspect ratio surpass this (width twice as large as height or // vice versa) will be classified as too wide or too tall and will be handled // slightly differently in overview mode. constexpr float kExtremeWindowRatioThreshold = 2.f; } // namespace ash #endif // ASH_WM_OVERVIEW_OVERVIEW_CONSTANTS_H_
358
348
<reponame>vmusch/OpenMS<gh_stars>100-1000 // -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: <NAME> $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CONCEPT/UniqueIdInterface.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(UniqueIdInterface, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// UniqueIdInterface* ptr = nullptr; UniqueIdInterface* nullPointer = nullptr; START_SECTION(UniqueIdInterface()) { ptr = new UniqueIdInterface(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~UniqueIdInterface()) { delete ptr; } END_SECTION START_SECTION((UniqueIdInterface(const UniqueIdInterface &rhs))) { UniqueIdInterface uii1; UniqueIdInterface uii2(uii1); // to be continued further below NOT_TESTABLE } END_SECTION START_SECTION((UniqueIdInterface(UniqueIdInterface &&rhs))) { // Ensure that UniqueIdInterface has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(UniqueIdInterface(std::declval<UniqueIdInterface&&>())), true) } END_SECTION START_SECTION((UniqueIdInterface& operator=(UniqueIdInterface const &rhs))) { UniqueIdInterface uii1; UniqueIdInterface uii2; uii2 = uii1; // to be continued further below NOT_TESTABLE } END_SECTION START_SECTION([EXTRA](~UniqueIdInterface())) { { UniqueIdInterface uii1; UniqueIdInterface uii2; uii2.setUniqueId(17); // destructor called when the scope is left } // to be continued further below ;-) NOT_TESTABLE } END_SECTION START_SECTION((bool operator==(UniqueIdInterface const &rhs) const )) { UniqueIdInterface uii1; UniqueIdInterface uii2; TEST_EQUAL(uii1 == uii2,true); UniqueIdInterface uii3(uii1); TEST_EQUAL(uii1 == uii3,true); uii2.setUniqueId(17); TEST_EQUAL(uii1 == uii2,false); uii1.setUniqueId(17); TEST_EQUAL(uii1 == uii2,true); } END_SECTION START_SECTION((UInt64 getUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.getUniqueId(),0); UniqueIdInterface uii2; uii2 = uii1; TEST_EQUAL(uii2.getUniqueId(),0); UniqueIdInterface uii3(uii1); TEST_EQUAL(uii3.getUniqueId(),0); uii1.setUniqueId(17); TEST_EQUAL(uii1.getUniqueId(),17); uii2 = uii1; TEST_EQUAL(uii2.getUniqueId(),17); UniqueIdInterface uii4(uii1); TEST_EQUAL(uii4.getUniqueId(),17); } END_SECTION START_SECTION((Size clearUniqueId())) { UniqueIdInterface uii1; uii1.clearUniqueId(); TEST_EQUAL(uii1.getUniqueId(),0) uii1.setUniqueId(17); TEST_EQUAL(uii1.getUniqueId(),17); uii1.clearUniqueId(); TEST_EQUAL(uii1.getUniqueId(),0) } END_SECTION START_SECTION((void swap(UniqueIdInterface &from))) { UniqueIdInterface u1; u1.setUniqueId(111); UniqueIdInterface u2; u2.setUniqueId(222); u1.swap(u2); TEST_EQUAL(u1.getUniqueId(),222); TEST_EQUAL(u2.getUniqueId(),111); std::swap(u1,u2); TEST_EQUAL(u1.getUniqueId(),111); TEST_EQUAL(u2.getUniqueId(),222); } END_SECTION START_SECTION((static bool isValid(UInt64 unique_id))) { TEST_EQUAL(UniqueIdInterface::isValid(UniqueIdInterface::INVALID),false); TEST_EQUAL(UniqueIdInterface::isValid(1234567890),true); } END_SECTION START_SECTION((Size hasValidUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(0); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),false); } END_SECTION START_SECTION((Size hasInvalidUniqueId() const )) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasInvalidUniqueId(),false); uii1.setUniqueId(0); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); uii1.setUniqueId(17); TEST_EQUAL(uii1.hasInvalidUniqueId(),false); uii1.clearUniqueId(); TEST_EQUAL(uii1.hasInvalidUniqueId(),true); } END_SECTION START_SECTION((Size setUniqueId())) { UniqueIdInterface uii1; TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); uii1.setUniqueId(); TEST_EQUAL(uii1.hasValidUniqueId(),true); } END_SECTION START_SECTION((Size ensureUniqueId())) { UInt64 the_unique_id; UniqueIdInterface uii1; the_unique_id = uii1.getUniqueId(); TEST_EQUAL(the_unique_id,0); uii1.ensureUniqueId(); the_unique_id = uii1.getUniqueId(); TEST_NOT_EQUAL(the_unique_id,0); uii1.ensureUniqueId(); TEST_EQUAL(uii1.getUniqueId(),the_unique_id); } END_SECTION START_SECTION((void setUniqueId(UInt64 rhs))) { // that one was used throughout the other tests NOT_TESTABLE; } END_SECTION START_SECTION((void setUniqueId(const String &rhs))) { UniqueIdInterface uii1; TEST_EQUAL(uii1.getUniqueId(),0); uii1.setUniqueId(""); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("17"); TEST_EQUAL(uii1.getUniqueId(),17); uii1.setUniqueId("18"); TEST_EQUAL(uii1.getUniqueId(),18); uii1.setUniqueId("asdf_19"); TEST_EQUAL(uii1.getUniqueId(),19); uii1.setUniqueId("_20"); TEST_EQUAL(uii1.getUniqueId(),20); uii1.setUniqueId("_021"); TEST_EQUAL(uii1.getUniqueId(),21); uii1.setUniqueId("asdf_19_22"); TEST_EQUAL(uii1.getUniqueId(),22); uii1.setUniqueId("_20_23"); TEST_EQUAL(uii1.getUniqueId(),23); uii1.setUniqueId("_021_024"); TEST_EQUAL(uii1.getUniqueId(),24); uii1.setUniqueId(" _021_025 "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId("bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123_ 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 _456"); TEST_EQUAL(uii1.getUniqueId(),456); uii1.setUniqueId(1000000); uii1.setUniqueId("123 _ 456"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456_ "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 _ "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 _"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("123 456 ff"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021bla_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021 bla "); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021 bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021_bla"); TEST_EQUAL(uii1.hasValidUniqueId(),false); uii1.setUniqueId(1000000); uii1.setUniqueId("_021_bla_"); TEST_EQUAL(uii1.hasValidUniqueId(),false); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
3,769
1,179
/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (c) 2019-2021, Linaro Limited */ #ifndef __MM_FOBJ_H #define __MM_FOBJ_H #include <kernel/panic.h> #include <kernel/refcount.h> #include <mm/tee_pager.h> #include <sys/queue.h> #include <tee_api_types.h> #include <types_ext.h> /* * struct fobj - file object storage abstraction * @ops: Operations pointer * @num_pages: Number of pages covered * @refc: Reference counter */ struct fobj { const struct fobj_ops *ops; unsigned int num_pages; struct refcount refc; #ifdef CFG_WITH_PAGER struct vm_paged_region_head regions; #endif }; /* * struct fobj_ops - operations struct for struct fobj * @free: Frees the @fobj * @load_page: Loads page with index @page_idx at address @va * @save_page: Saves page with index @page_idx from address @va * @get_iv_vaddr: Returns virtual address of tag and IV for the page at * @page_idx if tag and IV are paged for this fobj * @get_pa: Returns physical address of page at @page_idx if not paged */ struct fobj_ops { void (*free)(struct fobj *fobj); #ifdef CFG_WITH_PAGER TEE_Result (*load_page)(struct fobj *fobj, unsigned int page_idx, void *va); TEE_Result (*save_page)(struct fobj *fobj, unsigned int page_idx, const void *va); vaddr_t (*get_iv_vaddr)(struct fobj *fobj, unsigned int page_idx); #endif paddr_t (*get_pa)(struct fobj *fobj, unsigned int page_idx); }; #ifdef CFG_WITH_PAGER /* * fobj_locked_paged_alloc() - Allocate storage which is locked in memory * @num_pages: Number of pages covered * * This object only supports loading pages zero initialized. Saving a page * will result in an error. * * Returns a valid pointer on success or NULL on failure. */ struct fobj *fobj_locked_paged_alloc(unsigned int num_pages); /* * fobj_rw_paged_alloc() - Allocate read/write storage * @num_pages: Number of pages covered * * This object supports both load and saving of pages. Pages are zero * initialized the first time they are loaded. * * Returns a valid pointer on success or NULL on failure. */ struct fobj *fobj_rw_paged_alloc(unsigned int num_pages); /* * fobj_ro_paged_alloc() - Allocate initialized read-only storage * @num_pages: Number of pages covered * @hashes: Hashes to verify the pages * @store: Clear text data for all pages * * This object only support loading pages with an already provided content * in @store. When a page is loaded it will be verified against an hash in * @hash. Saving a page will result in an error. * * Returns a valid pointer on success or NULL on failure. */ struct fobj *fobj_ro_paged_alloc(unsigned int num_pages, void *hashes, void *store); /* * fobj_ro_reloc_paged_alloc() - Allocate initialized read-only storage with * relocation * @num_pages: Number of pages covered * @hashes: Hashes to verify the pages * @reloc_offs: Offset from the base address in the relocations in @reloc * @reloc: Relocation data * @reloc_len: Length of relocation data * @store: Clear text data for all pages * * This object is like fobj_ro_paged_alloc() above, but in addition the * relocation information is applied to a populated page. This makes sure * the offset to which all pages are relocated doesn't leak out to storage. * * Returns a valid pointer on success or NULL on failure. */ struct fobj *fobj_ro_reloc_paged_alloc(unsigned int num_pages, void *hashes, unsigned int reloc_offs, const void *reloc, unsigned int reloc_len, void *store); /* * fobj_load_page() - Load a page into memory * @fobj: Fobj pointer * @page_index: Index of page in @fobj * @va: Address where content should be stored and verified * * Returns TEE_SUCCESS on success or TEE_ERROR_* on failure. */ static inline TEE_Result fobj_load_page(struct fobj *fobj, unsigned int page_idx, void *va) { if (fobj) return fobj->ops->load_page(fobj, page_idx, va); return TEE_ERROR_GENERIC; } /* * fobj_save_page() - Save a page into storage * @fobj: Fobj pointer * @page_index: Index of page in @fobj * @va: Address of the page to store. * * Returns TEE_SUCCESS on success or TEE_ERROR_* on failure. */ static inline TEE_Result fobj_save_page(struct fobj *fobj, unsigned int page_idx, const void *va) { if (fobj) return fobj->ops->save_page(fobj, page_idx, va); return TEE_ERROR_GENERIC; } static inline vaddr_t fobj_get_iv_vaddr(struct fobj *fobj, unsigned int page_idx) { if (fobj && fobj->ops->get_iv_vaddr) return fobj->ops->get_iv_vaddr(fobj, page_idx); return 0; } #endif /* * fobj_ta_mem_alloc() - Allocates TA memory * @num_pages: Number of pages * * If paging of user TAs read/write paged fobj is allocated otherwise a * fobj which uses unpaged secure memory directly. * * Returns a valid pointer on success or NULL on failure. */ #ifdef CFG_PAGED_USER_TA #define fobj_ta_mem_alloc(num_pages) fobj_rw_paged_alloc(num_pages) #else /* * fobj_sec_mem_alloc() - Allocates storage directly in secure memory * @num_pages: Number of pages * * Returns a valid pointer on success or NULL on failure. */ struct fobj *fobj_sec_mem_alloc(unsigned int num_pages); #define fobj_ta_mem_alloc(num_pages) fobj_sec_mem_alloc(num_pages) #endif /* * fobj_get() - Increase fobj reference count * @fobj: Fobj pointer * * Returns @fobj, if @fobj isn't NULL its reference counter is first * increased. */ static inline struct fobj *fobj_get(struct fobj *fobj) { if (fobj && !refcount_inc(&fobj->refc)) panic(); return fobj; } /* * fobj_put() - Decrease reference counter of fobj * @fobj: Fobj pointer * * If reference counter reaches 0, matching the numbers of fobj_alloc_*() + * fobj_get(), the fobj is freed. */ static inline void fobj_put(struct fobj *fobj) { if (fobj && refcount_dec(&fobj->refc)) fobj->ops->free(fobj); } #endif /*__MM_FOBJ_H*/
2,080
1,338
<gh_stars>1000+ /* * Copyright 2008-2010, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "BootManagerWindow.h" #include <Application.h> #include <Catalog.h> #include <LayoutBuilder.h> #include <Roster.h> #include <Screen.h> #include <tracker_private.h> #include "DefaultPartitionPage.h" #include "PartitionsPage.h" #include "WizardView.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "BootManagerWindow" BootManagerWindow::BootManagerWindow() : BWindow(BRect(100, 100, 500, 400), B_TRANSLATE_SYSTEM_NAME("BootManager"), B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { float minWidth, maxWidth, minHeight, maxHeight; GetSizeLimits(&minWidth, &maxWidth, &minHeight, &maxHeight); // Use font to determine necessary size of window: const BFont* font = be_plain_font; minWidth = 400 * (double)font->Size() / 12.0f; minHeight = 250 * (double)font->Size() / 12.0f; SetSizeLimits(minWidth, maxWidth, minHeight, maxHeight); fWizardView = new WizardView("wizard"); BLayoutBuilder::Group<>(this) .Add(fWizardView); fController.Initialize(fWizardView); CenterOnScreen(); // Prevent minimizing this window if the user would have no way to // get back to it. (For example when only the Installer runs.) if (!be_roster->IsRunning(kDeskbarSignature)) SetFlags(Flags() | B_NOT_MINIMIZABLE); } BootManagerWindow::~BootManagerWindow() { } void BootManagerWindow::MessageReceived(BMessage* msg) { switch (msg->what) { case kMessageNext: fController.Next(fWizardView); break; case kMessagePrevious: fController.Previous(fWizardView); break; default: BWindow::MessageReceived(msg); } } bool BootManagerWindow::QuitRequested() { be_app->PostMessage(B_QUIT_REQUESTED); return true; }
692
506
// https://codeforces.com/contest/1406/problem/D #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<ll>; int main() { cin.tie(0), ios::sync_with_stdio(0); int n, q; cin >> n; vi a(n); ll p = 0; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = n - 1; i >= 1; i--) { a[i] -= a[i - 1]; if (a[i] > 0) p += a[i]; } ll ans = a[0] + p; if (ans >= 0) ans++; cout << ans / 2 << '\n'; cin >> q; while (q--) { int l, r; ll x; cin >> l >> r >> x; l--; if (l) if (a[l] > 0 && x > 0) p += x; else if (a[l] > 0 && x <= 0) { if (a[l] > -x) p += x; else p -= a[l]; } else if (a[l] <= 0 && x > 0) if (-a[l] <= x) p += x + a[l]; a[l] += x; if (r < n) { x = -x; if (a[r] > 0 && x > 0) p += x; else if (a[r] > 0 && x <= 0) { if (a[r] > -x) p += x; else p -= a[r]; } else if (a[r] <= 0 && x > 0) if (-a[r] < x) p += x + a[r]; a[r] += x; } ans = a[0] + p; if (ans >= 0) ans++; cout << ans / 2 << '\n'; } }
649
32,544
<gh_stars>1000+ package com.baeldung.systemstubs; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import uk.org.webcompere.systemstubs.jupiter.SystemStub; import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; import uk.org.webcompere.systemstubs.stream.SystemOut; import uk.org.webcompere.systemstubs.stream.output.NoopStream; import static uk.org.webcompere.systemstubs.SystemStubs.muteSystemOut; class OutputMutingUnitTest { @Nested class MutingWithFacade { @Test void givenMuteSystemOut() throws Exception { muteSystemOut(() -> { System.out.println("nothing is output"); }); } } @ExtendWith(SystemStubsExtension.class) @Nested class MutingWithJUnit5 { @SystemStub private SystemOut systemOut = new SystemOut(new NoopStream()); @Test void givenMuteSystemOut() throws Exception { System.out.println("nothing is output"); } } }
454
371
<filename>jar-enginex-runner/src/main/java/com/baoying/enginex/executor/util/DataHelp.java package com.baoying.enginex.executor.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DataHelp { public static int day=0; public static String getNowDate(){ Date date = new Date(); SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s = simple.format(date); return s; } public static String getEndDate(){ SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, + DataHelp.day); Date monday = c.getTime(); String s = simple.format(monday); return s; } public static String getNowDateString(){ Date date = new Date(); SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddHHmmss"); String s = simple.format(date); return s; } public static String getDay(){ Date date = new Date(); SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd"); String s = simple.format(date); return s; } public static void main(String[] args) { System.out.println(getNowDate()); System.out.println(getNowDateString()); } }
443
1,162
package io.digdag.client.api; import com.google.common.base.Preconditions; import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.UTF_8; public class SecretValidation { private static final String SECRET_KEY_SEGMENT = "[a-zA-Z]|[a-zA-Z][a-zA-Z0-9_\\-]*[a-zA-Z0-9]"; private static final Pattern SECRET_KEY_PATTERN = Pattern.compile( "^(" + SECRET_KEY_SEGMENT + ")(\\.(" + SECRET_KEY_SEGMENT + "))*$"); private static final int MAX_SECRET_KEY_LENGTH = 255; private static final int MAX_SECRET_VALUE_LENGTH = 16 * 1024; private SecretValidation() { throw new UnsupportedOperationException(); } public static boolean isValidSecretKey(String key) { Preconditions.checkNotNull(key); return key.length() <= MAX_SECRET_KEY_LENGTH && SECRET_KEY_PATTERN.matcher(key).matches(); } public static boolean isValidSecretValue(String value) { Preconditions.checkNotNull(value); return value.getBytes(UTF_8).length <= MAX_SECRET_VALUE_LENGTH; } public static boolean isValidSecret(String key, String value) { return isValidSecretKey(key) && isValidSecretValue(value); } }
483
1,144
package de.metas.materialtracking; /* * #%L * de.metas.materialtracking * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Date; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.lang.IContextAware; import org.compiere.model.I_C_UOM; import org.compiere.model.I_M_Product; import org.eevolution.api.BOMComponentType; import org.eevolution.api.CostCollectorType; import org.eevolution.model.I_PP_Cost_Collector; import org.hamcrest.Matchers; import org.junit.Assert; import de.metas.material.planning.pporder.PPOrderUtil; import de.metas.materialtracking.impl.MaterialTrackingPPOrderBL; import de.metas.materialtracking.model.IPPOrderQualityFields; import de.metas.materialtracking.model.I_M_Material_Tracking; import de.metas.materialtracking.model.I_M_Material_Tracking_Ref; import de.metas.materialtracking.model.I_PP_Order; import de.metas.materialtracking.model.I_PP_Order_BOMLine; import de.metas.materialtracking.qualityBasedInvoicing.IQualityInspectionOrder; import de.metas.materialtracking.qualityBasedInvoicing.impl.QualityInspectionOrderFactory; import de.metas.util.Services; /** * TODO: one instance per PP_Order. * <p> * Helper class to create Manufacturing orders for Carrot Waschproble use-case. * <p> * We use this class because we also want to keep the structure all together. * * @author tsa */ public class WaschprobeOrderData { // Data public final Date productionDate; private WaschprobeStandardMasterData data; public I_M_Material_Tracking materialTracking; public I_PP_Order ppOrder; /** * Unwashed carrots, raw material */ public I_PP_Order_BOMLine ppOrderBOMLine_Carrot_Unwashed; public I_PP_Cost_Collector ppOrderCostOllector_Issue_Carrot_Unwashed; /** * Unwashed carrots, raw material variant */ public I_PP_Order_BOMLine ppOrderBOMLine_Carrot_Unwashed_Alternative01; /** * Big Carrots, Co-Product */ public I_PP_Order_BOMLine ppOrderBOMLine_Carrot_Big; /** * Animal food, By-Product */ public I_PP_Order_BOMLine ppOrderBOMLine_Carrot_AnimalFood; /** * UOM used for Order and Order BOM Lines */ public final I_C_UOM uom; public WaschprobeOrderData( final WaschprobeStandardMasterData masterData, final Date productionDate) { this.data = masterData; this.uom = data.uom; this.productionDate = productionDate; create(); } private void create() { this.ppOrder = data.createPP_Order(data.pCarrot_Washed, BigDecimal.ZERO, uom, productionDate); // Flag it as Quality Inspection (QI) this.ppOrder.setOrderType(MaterialTrackingPPOrderBL.C_DocType_DOCSUBTYPE_QualityInspection); InterfaceWrapperHelper.save(this.ppOrder); // // Main component: raw material this.ppOrderBOMLine_Carrot_Unwashed = data.createPP_Order_BOMLine(ppOrder, BOMComponentType.Component, data.pCarrot_Unwashed, BigDecimal.ZERO, // delivered uom); this.ppOrderBOMLine_Carrot_Unwashed.setVariantGroup("Alternative01"); InterfaceWrapperHelper.save(this.ppOrderBOMLine_Carrot_Unwashed); // // Raw material variant this.ppOrderBOMLine_Carrot_Unwashed_Alternative01 = data.createPP_Order_BOMLine(ppOrder, BOMComponentType.Variant, data.pCarrot_Unwashed_Alternative01, BigDecimal.ZERO, // delivered uom); this.ppOrderBOMLine_Carrot_Unwashed_Alternative01.setVariantGroup("Alternative01"); InterfaceWrapperHelper.save(this.ppOrderBOMLine_Carrot_Unwashed_Alternative01); // // Co-Products this.ppOrderBOMLine_Carrot_Big = data.createPP_Order_BOMLine(ppOrder, BOMComponentType.CoProduct, data.pCarrot_Big, BigDecimal.ZERO, // delivered uom); // // By-Products this.ppOrderBOMLine_Carrot_AnimalFood = data.createPP_Order_BOMLine(ppOrder, BOMComponentType.ByProduct, data.pCarrot_AnimalFood, BigDecimal.ZERO, // delivered uom); // required because currently we get the inOutLines and this the receipt date and country of origin via cc. this.ppOrderCostOllector_Issue_Carrot_Unwashed = createPP_CostCollector_Issue( data.getContext(), ppOrder, data.pCarrot_Unwashed, BigDecimal.ZERO); } private I_PP_Cost_Collector createPP_CostCollector_Issue( final IContextAware context, final I_PP_Order ppOrder, final I_M_Product issuedProduct, final BigDecimal issuedQty) { final I_PP_Cost_Collector cc = InterfaceWrapperHelper.newInstance(I_PP_Cost_Collector.class, context); cc.setPP_Order(ppOrder); cc.setCostCollectorType(CostCollectorType.ComponentIssue.getCode()); cc.setMovementQty(issuedQty); InterfaceWrapperHelper.save(cc); return cc; } public WaschprobeOrderData assignToMaterialTracking(final I_M_Material_Tracking materialTracking) { final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final I_M_Material_Tracking_Ref ref = materialTrackingDAO.createMaterialTrackingRefNoSave(materialTracking, ppOrder); // NOTE: because we are running without model interceptors, listeners, we need to set IsQualityInspectionDoc flag manually ref.setIsQualityInspectionDoc(true); InterfaceWrapperHelper.save(ref); ppOrder.setM_Material_Tracking(materialTracking); InterfaceWrapperHelper.save(ppOrder); this.materialTracking = materialTracking; return this; } public WaschprobeOrderData setCarrot_Washed_QtyDelivered(final BigDecimal qtyDelivered) { ppOrder.setQtyDelivered(qtyDelivered); InterfaceWrapperHelper.save(ppOrder); return this; } public WaschprobeOrderData setCarrot_Unwashed_QtyDelivered(final BigDecimal qtyDelivered) { return setQtyDelivered(ppOrderBOMLine_Carrot_Unwashed, qtyDelivered); } public WaschprobeOrderData setCarrot_Big_QtyDelivered(final BigDecimal qtyDelivered) { return setQtyDelivered(ppOrderBOMLine_Carrot_Big, qtyDelivered); } public WaschprobeOrderData setCarrot_AnimalFood_QtyDelivered(final BigDecimal qtyDelivered) { return setQtyDelivered(ppOrderBOMLine_Carrot_AnimalFood, qtyDelivered); } private WaschprobeOrderData setQtyDelivered(final I_PP_Order_BOMLine ppOrderBOMLine, final BigDecimal qtyDelivered) { // // Validate for common mistakes when defining tests: if we are dealing with a co/by-product line the qty shall be negative if (qtyDelivered != null && qtyDelivered.signum() > 0 && PPOrderUtil.isCoOrByProduct(ppOrderBOMLine)) { throw new IllegalArgumentException("Possible testing issue found: when setting Qty Delivered on a co/by product line, the qty shall be negative" + "\n QtyDelivered to set: " + qtyDelivered + "\n Line: " + ppOrderBOMLine); } // // Set QtyDeliveredActual ppOrderBOMLine.setQtyDeliveredActual(qtyDelivered); InterfaceWrapperHelper.save(ppOrderBOMLine); return this; } public IQualityInspectionOrder createQualityInspectionOrder() { return QualityInspectionOrderFactory.createQualityInspectionOrder(ppOrder, materialTracking); } public WaschprobeOrderData refresh() { InterfaceWrapperHelper.refresh(ppOrder); InterfaceWrapperHelper.refresh(ppOrderBOMLine_Carrot_Unwashed); InterfaceWrapperHelper.refresh(ppOrderBOMLine_Carrot_Big); InterfaceWrapperHelper.refresh(ppOrderBOMLine_Carrot_AnimalFood); return this; } // ------------------------------------------------------------------------------------------------------------------------- public WaschprobeOrderData assert_Carrot_Washed_QM_QtyDeliveredPercOfRaw(final BigDecimal expectedQM_QtyDeliveredPercOfRaw) { assertQM_QtyDeliveredPercOfRaw("Carrot washed", ppOrder, expectedQM_QtyDeliveredPercOfRaw); return this; } public WaschprobeOrderData assert_Carrot_Unwashed_QM_QtyDeliveredPercOfRaw(final BigDecimal expectedQM_QtyDeliveredPercOfRaw) { assertQM_QtyDeliveredPercOfRaw("Carrot unwashed", ppOrderBOMLine_Carrot_Unwashed, expectedQM_QtyDeliveredPercOfRaw); return this; } public WaschprobeOrderData assert_Carrot_Big_QM_QtyDeliveredPercOfRaw(final BigDecimal expectedQM_QtyDeliveredPercOfRaw) { assertQM_QtyDeliveredPercOfRaw("Carrot big", ppOrderBOMLine_Carrot_Big, expectedQM_QtyDeliveredPercOfRaw); return this; } private void assertQM_QtyDeliveredPercOfRaw(final String qiItemName, final IPPOrderQualityFields qiItem, final BigDecimal expectedQM_QtyDeliveredPercOfRaw) { Assert.assertThat("Invalid QM_QtyDeliveredPercOfRaw for " + qiItemName, qiItem.getQM_QtyDeliveredPercOfRaw(), Matchers.comparesEqualTo(expectedQM_QtyDeliveredPercOfRaw)); } // ------------------------------------------------------------------------------------------------------------------------- public WaschprobeOrderData assert_Carrot_Washed_QM_QtyDeliveredAvg(final BigDecimal expectedQM_QtyDeliveredAvg) { assertQM_QtyDeliveredAvg("Carrot washed", ppOrder, expectedQM_QtyDeliveredAvg); return this; } public WaschprobeOrderData assert_Carrot_Unwashed_QM_QtyDeliveredAvg(final BigDecimal expectedQM_QtyDeliveredAvg) { assertQM_QtyDeliveredAvg("Carrot unwashed", ppOrderBOMLine_Carrot_Unwashed, expectedQM_QtyDeliveredAvg); return this; } public WaschprobeOrderData assert_Carrot_Big_QM_QtyDeliveredAvg(final BigDecimal expectedQM_QtyDeliveredAvg) { assertQM_QtyDeliveredAvg("Carrot big", ppOrderBOMLine_Carrot_Big, expectedQM_QtyDeliveredAvg); return this; } private void assertQM_QtyDeliveredAvg(final String qiItemName, final IPPOrderQualityFields qiItem, final BigDecimal expectedQM_QtyDeliveredAvg) { Assert.assertThat("Invalid QM_QtyDeliveredAvg for " + qiItemName, qiItem.getQM_QtyDeliveredAvg(), Matchers.comparesEqualTo(expectedQM_QtyDeliveredAvg)); } // ------------------------------------------------------------------------------------------------------------------------- public WaschprobeOrderData setDateOfProduction(final Timestamp date) { // see de.metas.materialtracking.qualityBasedInvoicing.impl.QualityInspectionOrder.getDateOfProduction() ppOrder.setDateDelivered(date); return this; } public WaschprobeOrderData setDocStatus(final String docStatus) { ppOrder.setDocStatus(docStatus); return this; } }
3,732
829
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by <NAME>. */ #import <Cocoa/Cocoa.h> /*#import <IDEKit/IDEViewController.h> #import "DVTEditor-Protocol.h" #import "DVTReplacementViewDelegate-Protocol.h" #import "DVTStatefulObject-Protocol.h" #import "DVTTabbedWindowTabContentControlling-Protocol.h" #import "IDEEditorAreaContainer-Protocol.h" #import "IDEStructureEditingWorkspaceTabContext-Protocol.h" #import "IDEWorkspaceDocumentProvider-Protocol.h" #import "NSTextViewDelegate-Protocol.h" */ @class DVTFilePath, DVTMapTable, DVTMutableOrderedSet, DVTNotificationToken, DVTObservingToken, DVTReplacementView, DVTSplitView, DVTSplitViewItem, DVTStackBacktrace, IDEARCConversionAssistantContext, IDEAppChooserWindowController, IDEBuildAlertMonitor, IDEEditorArea, IDELaunchSession, IDENavigatorArea, IDEObjCModernizationAssistantContext, IDERunAlertMonitor, IDEUnitTestsModernizationAssistantContext, IDEWorkspace, IDEWorkspaceDocument, IDEWorkspaceWindowController, NSAlert, NSDocument/*<DVTTabbedWindowCreation>*/, NSMutableArray, NSString; @interface IDEWorkspaceTabController : NSObject /*IDEViewController <NSTextViewDelegate, DVTTabbedWindowTabContentControlling, DVTStatefulObject, DVTReplacementViewDelegate, IDEEditorAreaContainer, IDEStructureEditingWorkspaceTabContext, IDEWorkspaceDocumentProvider, DVTEditor>*/ { DVTSplitView *_designAreaSplitView; DVTReplacementView *_navReplacementView; DVTReplacementView *_editorReplacementView; DVTSplitView *_utilityAreaSplitView; DVTSplitViewItem *_navigatorAreaSplitViewItem; DVTSplitViewItem *_utilitiesAreaSplitViewItem; DVTReplacementView *_inspectorReplacementView; DVTReplacementView *_libraryReplacementView; DVTMutableOrderedSet *_cursorRectInterceptors; int _assistantEditorsLayout; NSString *_name; IDELaunchSession *_currentLaunchSession; IDEWorkspaceDocument *_workspaceDocument; DVTMapTable *_additionControllersForLaunchSessionTable; NSMutableArray *_debuggingUIControllerLifeCycleObservers; NSString *_userDefinedTabLabel; NSString *_lastValidUserDefinedName; NSString *_savedTabLabel; DVTFilePath *_savedTabFilePath; DVTMapTable *_observerTokenForLaunchSessionTable; DVTMapTable *_observerTokenForLaunchSessionsDebuggingAdditionsTable; NSMutableArray *_uiControllerObserverEntries; DVTObservingToken *_mainCurrentLaunchSessionObserverToken; DVTObservingToken *_currentLaunchSessionStateObserverToken; DVTObservingToken *_launchSessionAlertErrorObservingToken; DVTObservingToken *_debugSessionObserverToken; DVTObservingToken *_debugSessionCoalescedStateObservingToken; DVTObservingToken *_documentLoadingObservationToken; DVTObservingToken *_firstIssueObservationToken; DVTObservingToken *_buildCompleteObservationToken; DVTObservingToken *_inMiniDebuggingModeObservingToken; DVTObservingToken *_userWantsMiniDebuggingConsoleObservingToken; DVTObservingToken *_firstTimeSnapshotObserverToken; DVTNotificationToken *_codesignFailureObserver; NSAlert *_stoppingExecutionAlert; id _pendingExecutionNotificationToken; IDEBuildAlertMonitor *_buildAlertMonitor; IDERunAlertMonitor *_runAlertMonitor; IDEARCConversionAssistantContext *_conversionAssistantContext; IDEObjCModernizationAssistantContext *_objcModernizationAssistantContext; IDEUnitTestsModernizationAssistantContext *_unitTestsModernizationAssistantContext; BOOL _isAnimatingUtilities; BOOL _userWantsUtilitiesVisible; BOOL _userWantsNavigatorVisible; BOOL _stateRestoreCompleted; BOOL _tabLoadingCompleted; IDEAppChooserWindowController *_appChooserWindowController; } + (id)keyPathsForValuesAffectingTabLabel; + (void)initialize; + (id)keyPathsForValuesAffectingEditorArea; + (id)keyPathsForValuesAffectingNavigatorArea; + (id)keyPathsForValuesAffectingWindowController; + (id)keyPathsForValuesAffectingShowNavigator; + (id)keyPathsForValuesAffectingShowUtilities; + (id)keyPathsForValuesAffectingWorkspace; + (BOOL)automaticallyNotifiesObserversOfCurrentLaunchSession; + (long long)version; + (void)configureStateSavingObjectPersistenceByName:(id)arg1; + (int)defaultAssistantEditorsLayout; + (void)setDefaultAssistantEditorsLayout:(int)arg1; + (BOOL)automaticallyNotifiesObserversOfSavedTabFilePath; + (BOOL)automaticallyNotifiesObserversOfSavedTabLabel; @property(retain) IDEAppChooserWindowController *appChooserWindowController; // @synthesize appChooserWindowController=_appChooserWindowController; @property(retain) DVTObservingToken *buildCompleteObservationToken; // @synthesize buildCompleteObservationToken=_buildCompleteObservationToken; @property(retain) DVTObservingToken *firstIssueObservationToken; // @synthesize firstIssueObservationToken=_firstIssueObservationToken; @property(retain) DVTObservingToken *documentLoadingObservationToken; // @synthesize documentLoadingObservationToken=_documentLoadingObservationToken; @property(nonatomic) BOOL tabLoadingCompleted; // @synthesize tabLoadingCompleted=_tabLoadingCompleted; @property BOOL stateRestoreCompleted; // @synthesize stateRestoreCompleted=_stateRestoreCompleted; @property(copy) NSString *userDefinedTabLabel; // @synthesize userDefinedTabLabel=_userDefinedTabLabel; @property(retain, nonatomic) DVTFilePath *savedTabFilePath; // @synthesize savedTabFilePath=_savedTabFilePath; @property(copy, nonatomic) NSString *savedTabLabel; // @synthesize savedTabLabel=_savedTabLabel; @property(copy) NSString *name; // @synthesize name=_name; @property(retain) IDEWorkspaceDocument *workspaceDocument; // @synthesize workspaceDocument=_workspaceDocument; @property(retain, nonatomic) IDELaunchSession *currentLaunchSession; // @synthesize currentLaunchSession=_currentLaunchSession; @property(retain) DVTReplacementView *editorReplacementView; // @synthesize editorReplacementView=_editorReplacementView; @property(retain) DVTReplacementView *navigatorReplacementView; // @synthesize navigatorReplacementView=_navReplacementView; @property(nonatomic) BOOL userWantsNavigatorVisible; // @synthesize userWantsNavigatorVisible=_userWantsNavigatorVisible; @property(nonatomic) BOOL userWantsUtilitiesVisible; // @synthesize userWantsUtilitiesVisible=_userWantsUtilitiesVisible; @property BOOL isAnimatingUtilities; // @synthesize isAnimatingUtilities=_isAnimatingUtilities; @property(nonatomic) int assistantEditorsLayout; // @synthesize assistantEditorsLayout=_assistantEditorsLayout; //- (void).cxx_destruct; - (void)discardEditing; - (BOOL)commitEditingForAction:(int)arg1 errors:(id)arg2; @property(readonly) DVTFilePath *tabFilePath; @property(readonly) NSString *tabLabel; //@property(retain) NSDocument<DVTTabbedWindowCreation> *document; - (void)codesignFailureNotification:(id)arg1 continuationBlock:(id)arg2; - (id)_codesignResolutionActionContextProviderExtension; - (void)moveKeyboardFocusToPreviousArea:(id)arg1; - (void)moveKeyboardFocusToNextArea:(id)arg1; - (void)_moveKeyboardFocusToNextAreaForward:(BOOL)arg1; - (id)_keyboardFocusAreas; - (id)_currentFirstResponderArea; - (void)performCloseWorkspace:(id)arg1; - (void)_workspaceDocument:(id)arg1 shouldClose:(BOOL)arg2 contextInfo:(void *)arg3; - (void)setShowPendingBlocksWhenDebugging:(id)arg1; - (void)setShowDisassemblyWhenDebugging:(id)arg1; - (void)setDebuggingWindowBehaviorXcodeInFront:(id)arg1; - (void)setDebuggingWindowBehaviorXcodeBehind:(id)arg1; - (void)setDebuggingWindowBehaviorNormal:(id)arg1; - (void)_setDebuggingWindowBehavior:(int)arg1; - (void)clearConsole:(id)arg1; - (void)viewMemory:(id)arg1; - (void)_unitTestsModernizationFoundErrorsAlertDidEnd:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3; - (void)showModernUnitTestsConversionAssistant:(id)arg1; - (void)_objCModernizationFoundErrorsAlertDidEnd:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3; - (void)showModernObjectiveCConversionAssistant:(id)arg1; - (void)_arcConversionFoundErrorsAlertDidEnd:(id)arg1 returnCode:(long long)arg2 contextInfo:(void *)arg3; - (void)showARCConversionAssistant:(id)arg1; - (void)showSharedLibrariesPopUp:(id)arg1; - (void)askUserForProcessIdentifierToAttachTo:(id)arg1; - (void)attachToProcess:(id)arg1; - (void)backgroundFetchEvent:(id)arg1; - (void)stepOut:(id)arg1; - (void)stepOverInstruction:(id)arg1; - (void)stepOverThread:(id)arg1; - (void)stepOver:(id)arg1; - (void)stepIntoInstruction:(id)arg1; - (void)stepIntoThread:(id)arg1; - (void)stepInto:(id)arg1; - (void)detach:(id)arg1; - (void)pauseOrContinue:(id)arg1; - (void)toggleBreakpoints:(id)arg1; - (void)createTestFailureBreakpoint:(id)arg1; - (void)createSymbolicBreakpoint:(id)arg1; - (void)createExceptionBreakpoint:(id)arg1; - (void)restoreSnapshot:(id)arg1; - (void)createSnapshot:(id)arg1; - (void)editWorkspaceUserSettings:(id)arg1; - (void)newRunContext:(id)arg1; - (void)takeScreenshot:(id)arg1; - (void)createBot:(id)arg1; - (void)manageRunContexts:(id)arg1; - (void)selectPreviousDestination:(id)arg1; - (void)selectNextDestination:(id)arg1; - (void)selectPreviousRunContext:(id)arg1; - (void)selectNextRunContext:(id)arg1; - (id)_prevIndex; - (id)_nextIndex; - (void)_selectDestination:(id)arg1; - (void)_selectRunContext:(id)arg1; - (void)editActiveRunContext:(id)arg1; - (void)editAndAnalyzeActiveRunContext:(id)arg1; - (void)editBuildAndIntegrateActiveRunContext:(id)arg1; - (void)editBuildAndArchiveActiveRunContext:(id)arg1; - (void)editAndBuildForTestingActiveRunContext:(id)arg1; - (void)editAndTestActiveRunContext:(id)arg1; - (void)editAndBuildForProfilingActiveScheme:(id)arg1; - (void)editAndProfileActiveScheme:(id)arg1; - (void)editAndBuildForRunningActiveRunContext:(id)arg1; - (void)editAndRunActiveRunContext:(id)arg1; - (void)_doCommandForEditAndSchemeCommand:(id)arg1; - (void)_doCommandForEditAndSchemeCommand:(id)arg1 schemeTask:(int)arg2; - (void)showAppChooserIfNecessaryForScheme:(id)arg1 runDestination:(id)arg2 command:(id)arg3 onCompletion:(id)arg4; - (BOOL)_shouldShowAppChooserForScheme:(id)arg1 command:(id)arg2; - (void)_showAppChooserForCurrentSchemeIfNecessaryForCommand:(id)arg1 launch:(id)arg2; - (void)showModalAlertForScheme:(id)arg1; - (void)runWithoutBuildingForSchemeIdentifier:(id)arg1 runDestination:(id)arg2 invocationRecord:(id)arg3; - (void)compileFileAtPath:(id)arg1 forSchemeCommand:(id)arg2; - (void)analyzeFileAtPath:(id)arg1; - (void)generateAssemblyCodeForFilePath:(id)arg1 forSchemeCommand:(id)arg2; - (void)generatePreprocessedFileForFilePath:(id)arg1 forSchemeCommand:(id)arg2; - (void)cleanBuildFolder:(id)arg1; - (void)reallyCleanBuildFolder; - (void)cleanActiveRunContext:(id)arg1; - (void)installActiveRunContext:(id)arg1; - (void)analyzeActiveRunContext:(id)arg1; - (void)buildAndRunToGenerateOptimizationProfileActiveRunContext:(id)arg1; - (void)buildForInstallActiveRunContext:(id)arg1; - (void)buildAndIntegrateActiveRunContext:(id)arg1; - (void)buildAndArchiveActiveRunContext:(id)arg1; - (void)buildActiveRunContext:(id)arg1; - (void)testActiveRunContextWithoutBuilding:(id)arg1; - (void)buildForTestActiveRunContext:(id)arg1; - (void)profileUsingActiveRunContextWithOverridingTestingSpecifiers:(id)arg1; - (void)testUsingActiveRunContextWithOverridingTestingSpecifiers:(id)arg1; - (void)testActiveRunContext:(id)arg1; - (void)profileActiveSchemeWithoutBuilding:(id)arg1; - (void)buildForProfileActiveRunContext:(id)arg1; - (void)profileActiveScheme:(id)arg1; - (void)runActiveRunContextWithoutBuilding:(id)arg1; - (void)_runWithoutBuildingForScheme:(id)arg1 runDestination:(id)arg2 invocationRecord:(id)arg3; - (void)buildForRunActiveRunContext:(id)arg1; - (void)_alertNonExistentWorkingDirectoryBeforeRunOrProfileForContext:(id)arg1 workingDirectory:(id)arg2 title:(id)arg3 defaultButton:(id)arg4 usingBlock:(id)arg5; - (void)_alertNonExistentWorkingDirectoryBeforeProfileForContext:(id)arg1 usingBlock:(id)arg2; - (void)_alertNonExistentWorkingDirectoryBeforeRunForContext:(id)arg1 usingBlock:(id)arg2; - (void)_askShouldBuildBeforeRunOrProfileForContext:(id)arg1 title:(id)arg2 defaultButton:(id)arg3 usingBlock:(id)arg4; - (void)runActiveRunContext:(id)arg1; - (void)_runScheme:(id)arg1 runDestination:(id)arg2 invocationRecord:(id)arg3; - (BOOL)_needToSwitchSchemeActionToSwitchToLLDB:(id)arg1; - (BOOL)textView:(id)arg1 clickedOnLink:(id)arg2 atIndex:(unsigned long long)arg3; - (void)_performDebuggableSchemeTask:(int)arg1 onScheme:(id)arg2 runDestination:(id)arg3 command:(id)arg4 commandName:(id)arg5 buildCommand:(int)arg6 filePath:(id)arg7 overridingTestingSpecifiers:(id)arg8 invocationRecord:(id)arg9 completionBlock:(id)arg10; - (void)_debugSessionCoalescedStateChanged:(id)arg1; - (BOOL)isActiveWorkspaceTabController; - (id)debuggingAdditionUIControllersForLaunchSession:(id)arg1; - (id)currentDebuggingAdditionUIControllers; - (id)debugSessionController; - (void)_updateForDebuggingKVOChange; - (BOOL)_contentSizeCanBeZeroSize; - (void)_performContextTask:(int)arg1 command:(id)arg2 commandName:(id)arg3 buildCommand:(int)arg4 filePath:(id)arg5 invocationRecord:(id)arg6 completionBlock:(id)arg7; - (void)_performSchemeTask:(int)arg1 onScheme:(id)arg2 runDestination:(id)arg3 command:(id)arg4 commandName:(id)arg5 buildCommand:(int)arg6 filePath:(id)arg7 overridingTestingSpecifiers:(id)arg8 invocationRecord:(id)arg9 completionBlock:(id)arg10; - (BOOL)_launchingOrProfiling:(int)arg1 withNonExistentWorkingDirectory:(id)arg2; - (void)_showWarningForBuild:(BOOL)arg1 forTest:(BOOL)arg2 forOtherExecution:(BOOL)arg3 trackersToStop:(id)arg4 taskActionBlock:(id)arg5; - (void)_runAnotherInstance:(id)arg1; - (void)_acceptStoppingExecutionAlert:(id)arg1; - (void)_rejectStoppingExecutionAlert:(id)arg1; - (void)_cleanupAfterStoppingExecutionAlert; - (void)_actuallyPerformSchemeTask:(int)arg1 onScheme:(id)arg2 runDestination:(id)arg3 command:(id)arg4 commandName:(id)arg5 buildCommand:(int)arg6 filePath:(id)arg7 overridingTestingSpecifiers:(id)arg8 invocationRecord:(id)arg9 completionBlock:(id)arg10; - (void)invalidateAllBuildAlertMonitors; - (BOOL)_cleanBuildFolderWithExecutionContext:(id)arg1 commandName:(id)arg2 error:(id *)arg3; - (void)observeBuildOperationForRestoringState:(id)arg1; - (void)switchNavigatorOnBuild; - (void)newWindow:(id)arg1; - (void)hideUtilitiesArea:(id)arg1; - (void)showUtilitiesArea:(id)arg1; - (BOOL)isUtilitiesAreaVisible; - (void)toggleUtilitiesVisibilityAlternate:(id)arg1; - (void)toggleUtilitiesVisibility:(id)arg1; - (void)hideNavigator:(id)arg1; - (BOOL)isNavigatorVisible; - (void)toggleNavigatorsVisibility:(id)arg1; - (void)changeToBreakpointsNavigator:(id)arg1; - (void)changeToDebuggerNavigator:(id)arg1; - (void)changeToFindNavigator:(id)arg1; - (void)changeToTestNavigator:(id)arg1; - (void)changeToIssuesNavigator:(id)arg1; - (void)changeToLogsNavigator:(id)arg1; - (void)changeToSymbolsNavigator:(id)arg1; - (void)changeToStructureNavigator:(id)arg1; - (void)showNavigatorWithIdentifier:(id)arg1; - (void)changeToNavigatorWithIdentifier:(id)arg1 sender:(id)arg2; - (void)_splitViewDidToggleClosed; - (BOOL)performKeyEquivalent:(id)arg1; - (id)_choiceWithKeyEquivalent:(id)arg1 modifierFlags:(unsigned long long)arg2 inUtilityArea:(id)arg3; - (void)showLibraryWithChoiceFromSender:(id)arg1; - (void)showInspectorWithChoiceFromSender:(id)arg1; - (void)showInspectorCategoryWithExtensionIdentifier:(id)arg1; - (void)showLibraryWithChoice:(id)arg1; - (void)showInspectorWithChoice:(id)arg1; - (id)libraryArea; - (id)inspectorArea; - (void)filterInNavigator:(id)arg1; - (void)filterInLibrary:(id)arg1; - (void)focusOnLibraryFilter; - (void)changeToAssistantLayout_BH:(id)arg1; - (void)changeToAssistantLayout_BV:(id)arg1; - (void)changeToAssistantLayout_TH:(id)arg1; - (void)changeToAssistantLayout_TV:(id)arg1; - (void)changeToAssistantLayout_LH:(id)arg1; - (void)changeToAssistantLayout_LV:(id)arg1; - (void)changeToAssistantLayout_RH:(id)arg1; - (void)changeToAssistantLayout_RV:(id)arg1; - (void)_changeToAssistantLayoutForActionSelector:(SEL)arg1; - (void)changeToVersionEditorLogView:(id)arg1; - (void)changeToVersionEditorBlameView:(id)arg1; - (void)changeToVersionEditorComparisonView:(id)arg1; - (void)_changeToVersionEditorSubmode:(int)arg1; - (void)changeToVersionEditor:(id)arg1; - (void)changeToGeniusEditor:(id)arg1; - (void)changeToStandardEditor:(id)arg1; - (void)_changeToEditorMode:(int)arg1; - (void)cancelCurrentExecution:(id)arg1; - (void)resetEditor:(id)arg1; - (void)removeAssistantEditor:(id)arg1; - (void)addAssistantEditor:(id)arg1; @property(readonly) IDEWorkspaceTabController *structureEditWorkspaceTabController; @property(readonly) IDEWorkspace *structureEditWorkspace; - (BOOL)validateUserInterfaceItem:(id)arg1; - (BOOL)_validateEditorLayoutUserInterfaceItem:(id)arg1 forActionSelector:(SEL)arg2; - (id)supplementalTargetForAction:(SEL)arg1 sender:(id)arg2; @property(readonly) IDEEditorArea *editorArea; @property(readonly) IDENavigatorArea *navigatorArea; @property(readonly) IDEWorkspaceWindowController *windowController; - (id)splitView:(id)arg1 needsRectanglesForViewsWithState:(id)arg2 forSize:(struct CGSize)arg3; - (void)splitView:(id)arg1 resizeSubviewsWithOldSize:(struct CGSize)arg2; - (void)_adjustUtilityAreaSplitViewWithOldSize:(struct CGSize)arg1; - (void)_adjustDesignAreaSplitViewWithOldSize:(struct CGSize)arg1; - (id)_framesForDesignAreaWithNavigatorState:(int)arg1 editorAreaState:(int)arg2 utilityAreaState:(int)arg3 forSize:(struct CGSize)arg4; - (id)splitView:(id)arg1 additionalEffectiveRectsOfDividerAtIndex:(long long)arg2; - (double)splitView:(id)arg1 constrainSplitPosition:(double)arg2 ofSubviewAt:(long long)arg3; - (BOOL)splitView:(id)arg1 canCollapseSubview:(id)arg2; - (double)splitView:(id)arg1 constrainMaxCoordinate:(double)arg2 ofSubviewAt:(long long)arg3; - (double)splitView:(id)arg1 constrainMinCoordinate:(double)arg2 ofSubviewAt:(long long)arg3; - (struct CGSize)minimumSizeForView:(id)arg1; - (void)updateMinimumWindowSize:(BOOL)arg1; - (struct CGSize)minimumSizeForDesignArea; - (struct CGSize)minimumSizeForDesignAreaIfNavigatorVisible:(BOOL)arg1 editorVisisble:(BOOL)arg2 andUtilityAreaVisible:(BOOL)arg3; - (void)_removeCursorRectInterceptor:(id)arg1; - (void)_addCursorRectInterceptor:(id)arg1; - (void)_interceptWillInvalidateCursorRectsForViewsWithNoTrackingAreas; - (void)_interceptWillInvalidateCursorRectsForView:(id)arg1; - (BOOL)_interceptAddCursorRect:(struct CGRect)arg1 cursor:(id)arg2 forView:(id)arg3 inWindow:(id)arg4; - (BOOL)_interceptSetCursorForMouseLocation:(struct CGPoint)arg1 inWindow:(id)arg2; - (void)_pushDefaultPrimaryEditorFrameSize; @property BOOL showNavigator; @property BOOL showUtilities; - (id)workspace; - (void)_removePendingDebuggingAdditionUIControllerObserversForLaunchSession:(id)arg1; - (void)_notifyAndRemoveObserversForCreatedUIController:(id)arg1 inLaunchSession:(id)arg2; - (id)debuggingAdditionUIControllerMatchingID:(id)arg1 forLaunchSession:(id)arg2 handler:(id)arg3; - (id)_createDebuggingAdditionUIControllersForDebuggingAddition:(id)arg1; - (void)_createDebuggingAdditionUIControllersForLaunchSession:(id)arg1; - (void)showAlertModallyInWorkspaceForError:(id)arg1; - (void)replacementView:(id)arg1 willInstallViewController:(id)arg2; - (void)primitiveInvalidate; - (void)viewWillUninstall; - (void)workspaceWindowIsClosing; - (void)viewDidInstall; - (void)_performExtraViewDidInstallWork; - (void)commitStateToDictionary:(id)arg1; - (void)revertStateWithDictionary:(id)arg1; - (void)_revertStateForNewWindowWithDictionary:(id)arg1 simpleEditorWindowLayout:(BOOL)arg2; - (void)_primitiveSetAssistantEditorsLayout:(int)arg1; - (void)loadView; - (id)initWithNibName:(id)arg1 bundle:(id)arg2; // Remaining properties @property(readonly) DVTStackBacktrace *creationBacktrace; @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
6,949
803
package com.lfk.demo.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.ActionBarActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import com.lfk.justwetools.View.FileExplorer.FileExplorer; import com.lfk.justwetools.View.FileExplorer.OnFileChosenListener; import com.lfk.justwetools.View.FileExplorer.OnPathChangedListener; import com.lfk.justwetools.View.Proportionview.ProportionView; import com.lfk.demo.R; public class ExplorerActivity extends ActionBarActivity { private FileExplorer fileExplorer; private long exitTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_explorer); final ProportionView view = (ProportionView) findViewById(R.id.pv); fileExplorer = (FileExplorer)findViewById(R.id.ex); //覆盖屏蔽原有长按事件 fileExplorer.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return false; } }); //新路径下分析文件比例 fileExplorer.setOnPathChangedListener(new OnPathChangedListener() { @Override public void onPathChanged(String path) { try { view.setData(fileExplorer.getPropotionText(path)); } catch (Exception e) { Toast.makeText(getApplicationContext(), "此路径下不可访问或文件夹下无文件", Toast.LENGTH_LONG).show(); } } }); fileExplorer.setOnFileChosenListener(new OnFileChosenListener() { @Override public void onFileChosen(Uri fileUri) { Intent intent = new Intent(ExplorerActivity.this, CodeActivity.class); intent.setData(fileUri); startActivity(intent); } }); fileExplorer.setCurrentDir(Environment.getExternalStorageDirectory().getPath()+"/DCIM"); fileExplorer.setRootDir(Environment.getExternalStorageDirectory().getPath()+"/DCIM"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_explorer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if(!fileExplorer.toParentDir()){ if(System.currentTimeMillis() - exitTime < 1000) finish(); exitTime = System.currentTimeMillis(); Toast.makeText(this, "再次点击退出", Toast.LENGTH_SHORT).show(); } return true; } return super.onKeyDown(keyCode, event); } }
1,618
2,329
package issue34; public abstract class Implementation2<T1,T2> extends Implementation1<T2> implements Interface2<T1,T2> { }
38
344
/* * Copyright (c) 2019 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/ns/signal_model_estimator.h" #include "modules/audio_processing/ns/fast_math.h" namespace webrtc { namespace { constexpr float kOneByFftSizeBy2Plus1 = 1.f / kFftSizeBy2Plus1; // Computes the difference measure between input spectrum and a template/learned // noise spectrum. float ComputeSpectralDiff( rtc::ArrayView<const float, kFftSizeBy2Plus1> conservative_noise_spectrum, rtc::ArrayView<const float, kFftSizeBy2Plus1> signal_spectrum, float signal_spectral_sum, float diff_normalization) { // spectral_diff = var(signal_spectrum) - cov(signal_spectrum, magnAvgPause)^2 // / var(magnAvgPause) // Compute average quantities. float noise_average = 0.f; for (size_t i = 0; i < kFftSizeBy2Plus1; ++i) { // Conservative smooth noise spectrum from pause frames. noise_average += conservative_noise_spectrum[i]; } noise_average = noise_average * kOneByFftSizeBy2Plus1; float signal_average = signal_spectral_sum * kOneByFftSizeBy2Plus1; // Compute variance and covariance quantities. float covariance = 0.f; float noise_variance = 0.f; float signal_variance = 0.f; for (size_t i = 0; i < kFftSizeBy2Plus1; ++i) { float signal_diff = signal_spectrum[i] - signal_average; float noise_diff = conservative_noise_spectrum[i] - noise_average; covariance += signal_diff * noise_diff; noise_variance += noise_diff * noise_diff; signal_variance += signal_diff * signal_diff; } covariance *= kOneByFftSizeBy2Plus1; noise_variance *= kOneByFftSizeBy2Plus1; signal_variance *= kOneByFftSizeBy2Plus1; // Update of average magnitude spectrum. float spectral_diff = signal_variance - (covariance * covariance) / (noise_variance + 0.0001f); // Normalize. return spectral_diff / (diff_normalization + 0.0001f); } // Updates the spectral flatness based on the input spectrum. void UpdateSpectralFlatness( rtc::ArrayView<const float, kFftSizeBy2Plus1> signal_spectrum, float signal_spectral_sum, float* spectral_flatness) { RTC_DCHECK(spectral_flatness); // Compute log of ratio of the geometric to arithmetic mean (handle the log(0) // separately). constexpr float kAveraging = 0.3f; float avg_spect_flatness_num = 0.f; for (size_t i = 1; i < kFftSizeBy2Plus1; ++i) { if (signal_spectrum[i] == 0.f) { *spectral_flatness -= kAveraging * (*spectral_flatness); return; } } for (size_t i = 1; i < kFftSizeBy2Plus1; ++i) { avg_spect_flatness_num += LogApproximation(signal_spectrum[i]); } float avg_spect_flatness_denom = signal_spectral_sum - signal_spectrum[0]; avg_spect_flatness_denom = avg_spect_flatness_denom * kOneByFftSizeBy2Plus1; avg_spect_flatness_num = avg_spect_flatness_num * kOneByFftSizeBy2Plus1; float spectral_tmp = ExpApproximation(avg_spect_flatness_num) / avg_spect_flatness_denom; // Time-avg update of spectral flatness feature. *spectral_flatness += kAveraging * (spectral_tmp - *spectral_flatness); } // Updates the log LRT measures. void UpdateSpectralLrt(rtc::ArrayView<const float, kFftSizeBy2Plus1> prior_snr, rtc::ArrayView<const float, kFftSizeBy2Plus1> post_snr, rtc::ArrayView<float, kFftSizeBy2Plus1> avg_log_lrt, float* lrt) { RTC_DCHECK(lrt); for (size_t i = 0; i < kFftSizeBy2Plus1; ++i) { float tmp1 = 1.f + 2.f * prior_snr[i]; float tmp2 = 2.f * prior_snr[i] / (tmp1 + 0.0001f); float bessel_tmp = (post_snr[i] + 1.f) * tmp2; avg_log_lrt[i] += .5f * (bessel_tmp - LogApproximation(tmp1) - avg_log_lrt[i]); } float log_lrt_time_avg_k_sum = 0.f; for (size_t i = 0; i < kFftSizeBy2Plus1; ++i) { log_lrt_time_avg_k_sum += avg_log_lrt[i]; } *lrt = log_lrt_time_avg_k_sum * kOneByFftSizeBy2Plus1; } } // namespace SignalModelEstimator::SignalModelEstimator() : prior_model_estimator_(kLtrFeatureThr) {} void SignalModelEstimator::AdjustNormalization(int32_t num_analyzed_frames, float signal_energy) { diff_normalization_ *= num_analyzed_frames; diff_normalization_ += signal_energy; diff_normalization_ /= (num_analyzed_frames + 1); } // Update the noise features. void SignalModelEstimator::Update( rtc::ArrayView<const float, kFftSizeBy2Plus1> prior_snr, rtc::ArrayView<const float, kFftSizeBy2Plus1> post_snr, rtc::ArrayView<const float, kFftSizeBy2Plus1> conservative_noise_spectrum, rtc::ArrayView<const float, kFftSizeBy2Plus1> signal_spectrum, float signal_spectral_sum, float signal_energy) { // Compute spectral flatness on input spectrum. UpdateSpectralFlatness(signal_spectrum, signal_spectral_sum, &features_.spectral_flatness); // Compute difference of input spectrum with learned/estimated noise spectrum. float spectral_diff = ComputeSpectralDiff(conservative_noise_spectrum, signal_spectrum, signal_spectral_sum, diff_normalization_); // Compute time-avg update of difference feature. features_.spectral_diff += 0.3f * (spectral_diff - features_.spectral_diff); signal_energy_sum_ += signal_energy; // Compute histograms for parameter decisions (thresholds and weights for // features). Parameters are extracted periodically. if (--histogram_analysis_counter_ > 0) { histograms_.Update(features_); } else { // Compute model parameters. prior_model_estimator_.Update(histograms_); // Clear histograms for next update. histograms_.Clear(); histogram_analysis_counter_ = kFeatureUpdateWindowSize; // Update every window: // Compute normalization for the spectral difference for next estimation. signal_energy_sum_ = signal_energy_sum_ / kFeatureUpdateWindowSize; diff_normalization_ = 0.5f * (signal_energy_sum_ + diff_normalization_); signal_energy_sum_ = 0.f; } // Compute the LRT. UpdateSpectralLrt(prior_snr, post_snr, features_.avg_log_lrt, &features_.lrt); } } // namespace webrtc
2,478
561
import os import torch import torch.distributed as dist from torch import nn from torch.utils.data import DistributedSampler from tasks.vocoder.dataset_utils import VocoderDataset, EndlessDistributedSampler from utils.audio.io import save_wav from utils.commons.base_task import BaseTask from utils.commons.dataset_utils import data_loader from utils.commons.hparams import hparams from utils.commons.tensor_utils import tensors_to_scalars class VocoderBaseTask(BaseTask): def __init__(self): super(VocoderBaseTask, self).__init__() self.max_sentences = hparams['max_sentences'] self.max_valid_sentences = hparams['max_valid_sentences'] if self.max_valid_sentences == -1: hparams['max_valid_sentences'] = self.max_valid_sentences = self.max_sentences self.dataset_cls = VocoderDataset @data_loader def train_dataloader(self): train_dataset = self.dataset_cls('train', shuffle=True) return self.build_dataloader(train_dataset, True, self.max_sentences, hparams['endless_ds']) @data_loader def val_dataloader(self): valid_dataset = self.dataset_cls('test', shuffle=False) return self.build_dataloader(valid_dataset, False, self.max_valid_sentences) @data_loader def test_dataloader(self): test_dataset = self.dataset_cls('test', shuffle=False) return self.build_dataloader(test_dataset, False, self.max_valid_sentences) def build_dataloader(self, dataset, shuffle, max_sentences, endless=False): world_size = 1 rank = 0 if dist.is_initialized(): world_size = dist.get_world_size() rank = dist.get_rank() sampler_cls = DistributedSampler if not endless else EndlessDistributedSampler train_sampler = sampler_cls( dataset=dataset, num_replicas=world_size, rank=rank, shuffle=shuffle, ) return torch.utils.data.DataLoader( dataset=dataset, shuffle=False, collate_fn=dataset.collater, batch_size=max_sentences, num_workers=dataset.num_workers, sampler=train_sampler, pin_memory=True, ) def build_optimizer(self, model): optimizer_gen = torch.optim.AdamW(self.model_gen.parameters(), lr=hparams['lr'], betas=[hparams['adam_b1'], hparams['adam_b2']]) optimizer_disc = torch.optim.AdamW(self.model_disc.parameters(), lr=hparams['lr'], betas=[hparams['adam_b1'], hparams['adam_b2']]) return [optimizer_gen, optimizer_disc] def build_scheduler(self, optimizer): return { "gen": torch.optim.lr_scheduler.StepLR( optimizer=optimizer[0], **hparams["generator_scheduler_params"]), "disc": torch.optim.lr_scheduler.StepLR( optimizer=optimizer[1], **hparams["discriminator_scheduler_params"]), } def validation_step(self, sample, batch_idx): outputs = {} total_loss, loss_output = self._training_step(sample, batch_idx, 0) outputs['losses'] = tensors_to_scalars(loss_output) outputs['total_loss'] = tensors_to_scalars(total_loss) if self.global_step % hparams['valid_infer_interval'] == 0 and \ batch_idx < 10: mels = sample['mels'] y = sample['wavs'] f0 = sample['f0'] y_ = self.model_gen(mels, f0) for idx, (wav_pred, wav_gt, item_name) in enumerate(zip(y_, y, sample["item_name"])): wav_pred = wav_pred / wav_pred.abs().max() if self.global_step == 0: wav_gt = wav_gt / wav_gt.abs().max() self.logger.add_audio(f'wav_{batch_idx}_{idx}_gt', wav_gt, self.global_step, hparams['audio_sample_rate']) self.logger.add_audio(f'wav_{batch_idx}_{idx}_pred', wav_pred, self.global_step, hparams['audio_sample_rate']) return outputs def test_start(self): self.gen_dir = os.path.join(hparams['work_dir'], f'generated_{self.trainer.global_step}_{hparams["gen_dir_name"]}') os.makedirs(self.gen_dir, exist_ok=True) def test_step(self, sample, batch_idx): mels = sample['mels'] y = sample['wavs'] f0 = sample['f0'] loss_output = {} y_ = self.model_gen(mels, f0) gen_dir = os.path.join(hparams['work_dir'], f'generated_{self.trainer.global_step}_{hparams["gen_dir_name"]}') os.makedirs(gen_dir, exist_ok=True) for idx, (wav_pred, wav_gt, item_name) in enumerate(zip(y_, y, sample["item_name"])): wav_gt = wav_gt.clamp(-1, 1) wav_pred = wav_pred.clamp(-1, 1) save_wav( wav_gt.view(-1).cpu().float().numpy(), f'{gen_dir}/{item_name}_gt.wav', hparams['audio_sample_rate']) save_wav( wav_pred.view(-1).cpu().float().numpy(), f'{gen_dir}/{item_name}_pred.wav', hparams['audio_sample_rate']) return loss_output def test_end(self, outputs): return {} def on_before_optimization(self, opt_idx): if opt_idx == 0: nn.utils.clip_grad_norm_(self.model_gen.parameters(), hparams['generator_grad_norm']) else: nn.utils.clip_grad_norm_(self.model_disc.parameters(), hparams["discriminator_grad_norm"]) def on_after_optimization(self, epoch, batch_idx, optimizer, optimizer_idx): if optimizer_idx == 0: self.scheduler['gen'].step(self.global_step // hparams['accumulate_grad_batches']) else: self.scheduler['disc'].step(self.global_step // hparams['accumulate_grad_batches'])
2,938
145,614
""" Given an array of integer elements and an integer 'k', we are required to find the maximum sum of 'k' consecutive elements in the array. Instead of using a nested for loop, in a Brute force approach we will use a technique called 'Window sliding technique' where the nested loops can be converted to a single loop to reduce time complexity. """ from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: """ Returns the maximum sum of k consecutive elements >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] >>> k = 4 >>> max_sum_in_array(arr, k) 24 >>> k = 10 >>> max_sum_in_array(arr,k) Traceback (most recent call last): ... ValueError: Invalid Input >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2] >>> k = 4 >>> max_sum_in_array(arr, k) 27 """ if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) for i in range(len(array) - k): current_sum = current_sum - array[i] + array[i + k] max_sum = max(max_sum, current_sum) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() array = [randint(-1000, 1000) for i in range(100)] k = randint(0, 110) print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
528
363
package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.repository.impl; import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo; import java.util.Optional; import javax.annotation.Resource; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.Alert; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.mapper.dynamic.AlertDynamicMapper; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.mapper.dynamic.AlertDynamicSqlSupport; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.repository.IAlertRepository; import org.springframework.stereotype.Repository; @Repository public class AlertRepository implements IAlertRepository { @Resource private AlertDynamicMapper alertDynamicMapper; @Override public int deleteByPrimaryKey(Long id) { return alertDynamicMapper.deleteByPrimaryKey(id); } @Override public int insert(Alert record) { return alertDynamicMapper.insert(record); } @Override public int insertSelective(Alert record) { return alertDynamicMapper.insertSelective(record); } @Override public Optional<Alert> selectByPrimaryKey(Long id) { return alertDynamicMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(Alert record) { return alertDynamicMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(Alert record) { return alertDynamicMapper.updateByPrimaryKey(record); } @Override public int deleteByAlarm(Long alarmId) { return alertDynamicMapper.delete(query -> query.where().and(AlertDynamicSqlSupport.alarmId, isEqualTo(alarmId))); } @Override public Optional<Alert> findOneByAlarm(Long alarmId) { return alertDynamicMapper.selectOne(query -> query.where().and(AlertDynamicSqlSupport.alarmId, isEqualTo(alarmId)).limit(1)); } }
716
548
#include <fastdds/rtps/writer/LivelinessManager.h> #include <fastdds/dds/log/Log.hpp> #include <algorithm> using namespace std::chrono; namespace eprosima { namespace fastrtps { namespace rtps { using LivelinessDataIterator = ResourceLimitedVector<LivelinessData>::iterator; LivelinessManager::LivelinessManager( const LivelinessCallback& callback, ResourceEvent& service, bool manage_automatic) : callback_(callback) , manage_automatic_(manage_automatic) , writers_() , mutex_() , timer_owner_(nullptr) , timer_( service, [this]() -> bool { return timer_expired(); }, 0) { } LivelinessManager::~LivelinessManager() { std::unique_lock<std::mutex> lock(mutex_); timer_owner_ = nullptr; timer_.cancel_timer(); } bool LivelinessManager::add_writer( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration) { std::unique_lock<std::mutex> lock(mutex_); if (!manage_automatic_ && kind == LivelinessQosPolicyKind::AUTOMATIC_LIVELINESS_QOS) { logWarning(RTPS_WRITER, "Liveliness manager not managing automatic writers, writer not added"); return false; } for (LivelinessData& writer : writers_) { if (writer.guid == guid && writer.kind == kind && writer.lease_duration == lease_duration) { writer.count++; return true; } } writers_.emplace_back(guid, kind, lease_duration); if (!calculate_next()) { timer_.cancel_timer(); return true; } // Some times the interval could be negative if a writer expired during the call to this function // Once in this situation there is not much we can do but let asio timers expire immediately auto interval = timer_owner_->time - steady_clock::now(); timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count()); timer_.restart_timer(); return true; } bool LivelinessManager::remove_writer( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration) { std::unique_lock<std::mutex> lock(mutex_); for (LivelinessData& writer: writers_) { if (writer.guid == guid && writer.kind == kind && writer.lease_duration == lease_duration) { if (--writer.count == 0) { LivelinessData::WriterStatus status = writer.status; writers_.remove(writer); if (callback_ != nullptr) { if (status == LivelinessData::WriterStatus::ALIVE) { callback_(guid, kind, lease_duration, -1, 0); } else if (status == LivelinessData::WriterStatus::NOT_ALIVE) { callback_(guid, kind, lease_duration, 0, -1); } } if (timer_owner_ != nullptr) { if (!calculate_next()) { timer_.cancel_timer(); return true; } // Some times the interval could be negative if a writer expired during the call to this function // Once in this situation there is not much we can do but let asio timers expire inmediately auto interval = timer_owner_->time - steady_clock::now(); timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count()); timer_.restart_timer(); } return true; } } } return false; } bool LivelinessManager::assert_liveliness( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration) { std::unique_lock<std::mutex> lock(mutex_); ResourceLimitedVector<LivelinessData>::iterator wit; if (!find_writer( guid, kind, lease_duration, &wit)) { return false; } timer_.cancel_timer(); if (wit->kind == LivelinessQosPolicyKind::MANUAL_BY_PARTICIPANT_LIVELINESS_QOS || wit->kind == LivelinessQosPolicyKind::AUTOMATIC_LIVELINESS_QOS) { for (LivelinessData& w: writers_) { if (w.kind == wit->kind) { assert_writer_liveliness(w); } } } else if (wit->kind == LivelinessQosPolicyKind::MANUAL_BY_TOPIC_LIVELINESS_QOS) { assert_writer_liveliness(*wit); } // Updates the timer owner if (!calculate_next()) { logError(RTPS_WRITER, "Error when restarting liveliness timer"); return false; } // Some times the interval could be negative if a writer expired during the call to this function // Once in this situation there is not much we can do but let asio timers expire inmediately auto interval = timer_owner_->time - steady_clock::now(); timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count()); timer_.restart_timer(); return true; } bool LivelinessManager::assert_liveliness( LivelinessQosPolicyKind kind) { std::unique_lock<std::mutex> lock(mutex_); if (!manage_automatic_ && kind == LivelinessQosPolicyKind::AUTOMATIC_LIVELINESS_QOS) { logWarning(RTPS_WRITER, "Liveliness manager not managing automatic writers, writer not added"); return false; } if (writers_.empty()) { return true; } timer_.cancel_timer(); for (LivelinessData& writer: writers_) { if (writer.kind == kind) { assert_writer_liveliness(writer); } } // Updates the timer owner if (!calculate_next()) { logInfo(RTPS_WRITER, "Error when restarting liveliness timer: " << writers_.size() << " writers, liveliness " << kind); return false; } // Some times the interval could be negative if a writer expired during the call to this function // Once in this situation there is not much we can do but let asio timers expire inmediately auto interval = timer_owner_->time - steady_clock::now(); timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count()); timer_.restart_timer(); return true; } bool LivelinessManager::calculate_next() { timer_owner_ = nullptr; steady_clock::time_point min_time = steady_clock::now() + nanoseconds(c_TimeInfinite.to_ns()); bool any_alive = false; for (LivelinessDataIterator it = writers_.begin(); it != writers_.end(); ++it) { if (it->status == LivelinessData::WriterStatus::ALIVE) { if (it->time < min_time) { min_time = it->time; timer_owner_ = &*it; } any_alive = true; } } return any_alive; } bool LivelinessManager::timer_expired() { std::unique_lock<std::mutex> lock(mutex_); if (timer_owner_ == nullptr) { logError(RTPS_WRITER, "Liveliness timer expired but there is no writer"); return false; } if (callback_ != nullptr) { callback_(timer_owner_->guid, timer_owner_->kind, timer_owner_->lease_duration, -1, 1); } timer_owner_->status = LivelinessData::WriterStatus::NOT_ALIVE; if (calculate_next()) { // Some times the interval could be negative if a writer expired during the call to this function // Once in this situation there is not much we can do but let asio timers expire inmediately auto interval = timer_owner_->time - steady_clock::now(); timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count()); return true; } return false; } bool LivelinessManager::find_writer( const GUID_t& guid, const LivelinessQosPolicyKind& kind, const Duration_t& lease_duration, ResourceLimitedVector<LivelinessData>::iterator* wit_out) { for (LivelinessDataIterator it = writers_.begin(); it != writers_.end(); ++it) { if (it->guid == guid && it->kind == kind && it->lease_duration == lease_duration) { *wit_out = it; return true; } } return false; } bool LivelinessManager::is_any_alive( LivelinessQosPolicyKind kind) { std::unique_lock<std::mutex> lock(mutex_); for (const auto& writer : writers_) { if (writer.kind == kind && writer.status == LivelinessData::WriterStatus::ALIVE) { return true; } } return false; } void LivelinessManager::assert_writer_liveliness( LivelinessData& writer) { if (callback_ != nullptr) { if (writer.status == LivelinessData::WriterStatus::NOT_ASSERTED) { callback_(writer.guid, writer.kind, writer.lease_duration, 1, 0); } else if (writer.status == LivelinessData::WriterStatus::NOT_ALIVE) { callback_(writer.guid, writer.kind, writer.lease_duration, 1, -1); } } writer.status = LivelinessData::WriterStatus::ALIVE; writer.time = steady_clock::now() + nanoseconds(writer.lease_duration.to_ns()); } const ResourceLimitedVector<LivelinessData>& LivelinessManager::get_liveliness_data() const { return writers_; } } // namespace rtps } // namespace fastrtps } // namespace eprosima
4,497
347
package org.ovirt.engine.core.utils.serialization.json; import java.util.ArrayList; import org.ovirt.engine.core.common.action.ActionParametersBase; import org.ovirt.engine.core.common.action.ActionType; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @SuppressWarnings("serial") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) public abstract class JsonActionParametersBaseMixIn extends ActionParametersBase { /** * Ignore this method since Jackson will try to recursively dereference it and fail to serialize. */ @JsonIgnore @Override public abstract ActionParametersBase getParentParameters(); @JsonIgnore @Override public abstract ArrayList<ActionParametersBase> getImagesParameters(); @JsonDeserialize(using=ActionTypeDeserializer.class) @Override public abstract void setParentCommand(ActionType value); @JsonDeserialize (using=ActionTypeDeserializer.class) @Override public abstract void setCommandType(ActionType commandType); }
358
465
<reponame>nannullna/deep-active-learning<gh_stars>100-1000 from torchvision import transforms from handlers import MNIST_Handler, SVHN_Handler, CIFAR10_Handler from data import get_MNIST, get_FashionMNIST, get_SVHN, get_CIFAR10 from nets import Net, MNIST_Net, SVHN_Net, CIFAR10_Net from query_strategies import RandomSampling, LeastConfidence, MarginSampling, EntropySampling, \ LeastConfidenceDropout, MarginSamplingDropout, EntropySamplingDropout, \ KMeansSampling, KCenterGreedy, BALDDropout, \ AdversarialBIM, AdversarialDeepFool params = {'MNIST': {'n_epoch': 10, 'train_args':{'batch_size': 64, 'num_workers': 1}, 'test_args':{'batch_size': 1000, 'num_workers': 1}, 'optimizer_args':{'lr': 0.01, 'momentum': 0.5}}, 'FashionMNIST': {'n_epoch': 10, 'train_args':{'batch_size': 64, 'num_workers': 1}, 'test_args':{'batch_size': 1000, 'num_workers': 1}, 'optimizer_args':{'lr': 0.01, 'momentum': 0.5}}, 'SVHN': {'n_epoch': 20, 'train_args':{'batch_size': 64, 'num_workers': 1}, 'test_args':{'batch_size': 1000, 'num_workers': 1}, 'optimizer_args':{'lr': 0.01, 'momentum': 0.5}}, 'CIFAR10': {'n_epoch': 20, 'train_args':{'batch_size': 64, 'num_workers': 1}, 'test_args':{'batch_size': 1000, 'num_workers': 1}, 'optimizer_args':{'lr': 0.05, 'momentum': 0.3}} } def get_handler(name): if name == 'MNIST': return MNIST_Handler elif name == 'FashionMNIST': return MNIST_Handler elif name == 'SVHN': return SVHN_Handler elif name == 'CIFAR10': return CIFAR10_Handler def get_dataset(name): if name == 'MNIST': return get_MNIST(get_handler(name)) elif name == 'FashionMNIST': return get_FashionMNIST(get_handler(name)) elif name == 'SVHN': return get_SVHN(get_handler(name)) elif name == 'CIFAR10': return get_CIFAR10(get_handler(name)) else: raise NotImplementedError def get_net(name, device): if name == 'MNIST': return Net(MNIST_Net, params[name], device) elif name == 'FashionMNIST': return Net(MNIST_Net, params[name], device) elif name == 'SVHN': return Net(SVHN_Net, params[name], device) elif name == 'CIFAR10': return Net(CIFAR10_Net, params[name], device) else: raise NotImplementedError def get_params(name): return params[name] def get_strategy(name): if name == "RandomSampling": return RandomSampling elif name == "LeastConfidence": return LeastConfidence elif name == "MarginSampling": return MarginSampling elif name == "EntropySampling": return EntropySampling elif name == "LeastConfidenceDropout": return LeastConfidenceDropout elif name == "MarginSamplingDropout": return MarginSamplingDropout elif name == "EntropySamplingDropout": return EntropySamplingDropout elif name == "KMeansSampling": return KMeansSampling elif name == "KCenterGreedy": return KCenterGreedy elif name == "BALDDropout": return BALDDropout elif name == "AdversarialBIM": return AdversarialBIM elif name == "AdversarialDeepFool": return AdversarialDeepFool else: raise NotImplementedError # albl_list = [MarginSampling(X_tr, Y_tr, idxs_lb, net, handler, args), # KMeansSampling(X_tr, Y_tr, idxs_lb, net, handler, args)] # strategy = ActiveLearningByLearning(X_tr, Y_tr, idxs_lb, net, handler, args, strategy_list=albl_list, delta=0.1)
1,853
531
/* * Copyright (c) 2015-2020, www.dibo.ltd (<EMAIL>). * <p> * 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 * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package com.diboot.file.util; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy; import com.diboot.core.exception.BusinessException; import com.diboot.core.util.BeanUtils; import com.diboot.core.util.S; import com.diboot.core.util.V; import com.diboot.core.vo.Status; import com.diboot.file.excel.BaseExcelModel; import com.diboot.file.excel.listener.DynamicHeadExcelListener; import com.diboot.file.excel.listener.FixedHeadExcelListener; import com.diboot.file.excel.write.CommentWriteHandler; import com.diboot.file.excel.write.OptionWriteHandler; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.function.Supplier; /*** * excel数据导入导出工具类 * @auther <EMAIL> * @date 2019-10-9 */ @Slf4j public class ExcelHelper { /** * 读取ecxel * * @param inputStream * @param excelType excel类型,为空自动推断 * @param listener */ public static void read(InputStream inputStream, ExcelTypeEnum excelType, ReadListener<?> listener) { read(inputStream, excelType, listener, null); } /** * 读取ecxel * * @param inputStream * @param excelType excel类型,为空自动推断 * @param listener * @param headClazz ExcelModel.class */ public static <T> void read(InputStream inputStream, ExcelTypeEnum excelType, ReadListener<T> listener, Class<T> headClazz) { EasyExcel.read(inputStream).excelType(excelType).registerReadListener(listener).head(headClazz).sheet().doRead(); } /** * 预览读取excel文件数据 * * @param filePath * @param listener * @return */ @Deprecated public static <T extends BaseExcelModel> boolean previewReadExcel(String filePath, FixedHeadExcelListener listener) throws Exception { listener.setPreview(true); return readAndSaveExcel(filePath, listener); } /** * 预览读取excel文件数据 * * @param inputStream * @param listener * @return */ @Deprecated public static <T extends BaseExcelModel> boolean previewReadExcel(InputStream inputStream, FixedHeadExcelListener listener) throws Exception { listener.setPreview(true); return readAndSaveExcel(inputStream, listener); } /** * 读取excel文件数据并保存到数据库 * * @param filePath * @param listener * @return */ @Deprecated public static <T extends BaseExcelModel> boolean readAndSaveExcel(String filePath, FixedHeadExcelListener listener) throws Exception { File excel = getExcelFile(filePath); Class<T> headClazz = BeanUtils.getGenericityClass(listener, 0); EasyExcel.read(excel).registerReadListener(listener).head(headClazz).sheet().doRead(); return true; } /** * 读取excel流文件数据并保存到数据库 * * @param listener * @return */ @Deprecated public static <T extends BaseExcelModel> boolean readAndSaveExcel(InputStream inputStream, FixedHeadExcelListener listener) throws Exception { Class<T> headClazz = BeanUtils.getGenericityClass(listener, 0); EasyExcel.read(inputStream).registerReadListener(listener).head(headClazz).sheet().doRead(); return true; } /** * 读取非确定/动态表头的excel文件数据 * * @param filePath * @return */ @Deprecated public static boolean readDynamicHeadExcel(String filePath, DynamicHeadExcelListener listener) { File excel = getExcelFile(filePath); EasyExcel.read(excel).registerReadListener(listener).sheet().doRead(); return true; } /** * 读取非确定/动态表头的excel文件数据 * * @param inputStream * @param listener * @return */ @Deprecated public static boolean readDynamicHeadExcel(InputStream inputStream, DynamicHeadExcelListener listener) { EasyExcel.read(inputStream).registerReadListener(listener).sheet().doRead(); return true; } /** * 简单将数据写入excel文件 * <p>默认列宽自适应数据长度, 可自定义</p> * * @param filePath * @param sheetName * @param dataList * @param writeHandlers * @return */ @Deprecated public static boolean writeDynamicData(String filePath, String sheetName, List<List<String>> dataList, WriteHandler... writeHandlers) throws Exception { try { ExcelWriterBuilder write = EasyExcel.write(filePath); write = write.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); for (WriteHandler handler : writeHandlers) { write = write.registerWriteHandler(handler); } ExcelWriterSheetBuilder sheet = write.sheet(sheetName); sheet.doWrite(dataList); return true; } catch (Exception e) { log.error("数据写入excel文件失败", e); return false; } } /** * 简单将数据写入excel文件 * <p>默认列宽自适应数据长度、写入单元格下拉选项, 可自定义</p> * * @param filePath * @param sheetName * @param dataList * @param <T> * @return */ @Deprecated public static <T extends BaseExcelModel> boolean writeData(String filePath, String sheetName, List<T> dataList, WriteHandler... writeHandlers) throws Exception { try { if (V.isEmpty(dataList)) { return writeDynamicData(filePath, sheetName, Collections.emptyList()); } Class<T> tClass = (Class<T>) dataList.get(0).getClass(); ExcelWriterBuilder write = EasyExcel.write(filePath, tClass); write = write.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); for (WriteHandler handler : writeHandlers) { write = write.registerWriteHandler(handler); } write.sheet(sheetName).doWrite(dataList); return true; } catch (Exception e) { log.error("数据写入excel文件失败", e); return false; } } /** * Excel写入 * <p> * 默认支持:批注写入、单元格下拉选项写入 * * @param outputStream * @param clazz 导出的ExcelModel * @param dataList * @param writeHandlers 写入处理程序 * @return */ public static <T> boolean write(OutputStream outputStream, Class<T> clazz, List<T> dataList, WriteHandler... writeHandlers) { return write(outputStream, clazz, null, dataList, writeHandlers); } /** * Excel写入 * * @param outputStream * @param clazz 导出的ExcelModel * @param columnNameList 需要导出的列属性名,为空时导出所有列 * @param dataList * @param writeHandlers 写入处理程序 * @return */ public static <T> boolean write(OutputStream outputStream, Class<T> clazz, Collection<String> columnNameList, List<T> dataList, WriteHandler... writeHandlers) { AtomicBoolean first = new AtomicBoolean(true); return write(outputStream, clazz, columnNameList, () -> first.getAndSet(false) ? dataList : null, writeHandlers); } /** * 分批多次写入 * * @param outputStream * @param clazz * @param columnNameList * @param dataList * @param writeHandlers * @return */ public static <T> boolean write(OutputStream outputStream, Class<T> clazz, Collection<String> columnNameList, Supplier<List<T>> dataList, WriteHandler... writeHandlers) { try { write(outputStream, clazz, columnNameList, null, dataList, writeHandlers); return true; } catch (Exception e) { log.error("数据写入excel文件失败", e); return false; } } /** * 多次写入 * * @param outputStream * @param clazz * @param columnNameList * @param autoClose 是否自动关闭流 * @param dataList * @param writeHandlers */ public static <T> void write(OutputStream outputStream, Class<T> clazz, Collection<String> columnNameList, Boolean autoClose, Supplier<List<T>> dataList, WriteHandler... writeHandlers) { ExcelWriter writer = EasyExcel.write(outputStream, clazz).autoCloseStream(autoClose).build(); buildWriteSheet(columnNameList, (commentWriteHandler, writeSheet) -> { List<T> list = dataList.get(); boolean assignableFrom = BaseExcelModel.class.isAssignableFrom(clazz); do { if (assignableFrom) { commentWriteHandler.setDataList((List<? extends BaseExcelModel>) list); } writer.write(list, writeSheet); } while (V.notEmpty(list = dataList.get())); }, writeHandlers); writer.finish(); } /** * 构建WriteSheet * <p> * 默认:自列适应宽、单元格下拉选项(验证)写入,批注写入 * * @param columnNameList 需要导出的ExcelModel列字段名称列表,为空时导出所有列 * @param consumer * @param writeHandlers */ public static <T> void buildWriteSheet(Collection<String> columnNameList, BiConsumer<CommentWriteHandler, WriteSheet> consumer, WriteHandler... writeHandlers) { buildWriteSheet("Sheet1", columnNameList, consumer, writeHandlers); } /** * 构建WriteSheet * <p> * 默认:自列适应宽、单元格下拉选项(验证)写入,批注写入 * * @param sheetName 可指定sheetName * @param columnNameList 需要导出的ExcelModel列字段名称列表,为空时导出所有列 * @param consumer * @param writeHandlers */ public static <T> void buildWriteSheet(String sheetName, Collection<String> columnNameList, BiConsumer<CommentWriteHandler, WriteSheet> consumer, WriteHandler... writeHandlers) { ExcelWriterSheetBuilder writerSheet = EasyExcel.writerSheet().sheetName(sheetName); CommentWriteHandler commentWriteHandler = new CommentWriteHandler(); writerSheet.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()); writerSheet.registerWriteHandler(new OptionWriteHandler()); writerSheet.registerWriteHandler(commentWriteHandler); for (WriteHandler handler : writeHandlers) { writerSheet.registerWriteHandler(handler); } if (V.notEmpty(columnNameList)) { writerSheet.includeColumnFiledNames(columnNameList); } consumer.accept(commentWriteHandler, writerSheet.build()); } /** * web 导出excel * <p> * 默认:自列适应宽、单元格下拉选项(验证)写入,批注写入 * * @param response * @param fileName * @param clazz 导出的ExcelModel * @param dataList * @param writeHandlers 写入处理程序 */ public static <T> void exportExcel(HttpServletResponse response, String fileName, Class<T> clazz, List<T> dataList, WriteHandler... writeHandlers) { exportExcel(response, fileName, clazz, null, dataList, writeHandlers); } /** * web 导出excel * <p> * 默认 自列适应宽、单元格下拉选项(验证)写入,批注写入 * * @param response * @param clazz 导出的ExcelModel * @param dataList 导出的数据 * @param columnNameList 需要导出的ExcelModel列字段名称列表,为空时导出所有列 * @param writeHandlers 写入处理程序 */ public static <T> void exportExcel(HttpServletResponse response, String fileName, Class<T> clazz, Collection<String> columnNameList, List<T> dataList, WriteHandler... writeHandlers) { AtomicBoolean first = new AtomicBoolean(true); exportExcel(response, fileName, clazz, columnNameList, () -> first.getAndSet(false) ? dataList : null, writeHandlers); } /** * web 导出excel * <p> * 分批多次写入 * * @param response * @param fileName * @param clazz * @param columnNameList * @param dataList * @param writeHandlers * @param <T> */ public static <T> void exportExcel(HttpServletResponse response, String fileName, Class<T> clazz, Collection<String> columnNameList, Supplier<List<T>> dataList, WriteHandler... writeHandlers) { setExportExcelResponseHeader(response, fileName); try { write(response.getOutputStream(), clazz, columnNameList, Boolean.FALSE, dataList, writeHandlers); } catch (Exception e) { log.error("下载文件失败:", e); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.setHeader("code", String.valueOf(Status.FAIL_OPERATION.code())); try { response.setHeader("msg", URLEncoder.encode("下载文件失败", StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException ex) { log.error("不支持字符编码", ex); } } } /** * 设置导出的excel 响应头 * * @param response * @param fileName */ public static void setExportExcelResponseHeader(HttpServletResponse response, String fileName) { response.setContentType("application/x-msdownload"); response.setCharacterEncoding("utf-8"); response.setHeader("code", String.valueOf(Status.OK.code())); try { fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); response.setHeader("Content-disposition", "attachment; filename=" + fileName); response.setHeader("filename", fileName); response.setHeader("msg", URLEncoder.encode("操作成功", StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { log.error("不支持字符编码", e); } } /** * 获取本地文件内容 * * @param filePath * @return */ @Deprecated private static File getExcelFile(String filePath) { File file = new File(filePath); if (!file.exists()) { log.error("找不到指定文件,路径:" + filePath); throw new BusinessException(Status.FAIL_EXCEPTION, "找不到指定文件,导入excel失败"); } return file; } /** * 获取 Excel 模板中的表头 * * @param clazz ExcelModel * @return excel表头映射 */ public static List<TableHead> getTableHead(Class<?> clazz) { TreeMap<Integer, Field> sortedAllFiledMap = new TreeMap<>(); ClassUtils.declaredFields(clazz, sortedAllFiledMap, false, null); TreeMap<Integer, List<String>> headNameMap = new TreeMap<>(); HashMap<Integer, String> fieldNameMap = new HashMap<>(); sortedAllFiledMap.forEach((index, field) -> { fieldNameMap.put(index, field.getName()); headNameMap.put(index, getHeadColumnName(field)); }); return buildTableHead(headNameMap, fieldNameMap); } /** * 获取表头列名称 * * @param field 列字段 * @return 列名称列表 */ public static List<String> getHeadColumnName(Field field) { ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class); return excelProperty == null ? Collections.singletonList(FieldUtils.resolveCglibFieldName(field)) : Arrays.asList(excelProperty.value()); } /** * 构建 Excel 表头映射 * * @param headNameMap * @param fieldNameMap * @return 表头映射 */ public static List<TableHead> buildTableHead(Map<Integer, List<String>> headNameMap, Map<Integer, String> fieldNameMap) { List<TableHead> tableHead = new ArrayList<>(); Map<String, TableHead> hashMap = new HashMap<>(); int col = Integer.MIN_VALUE; for (Map.Entry<Integer, List<String>> entry : headNameMap.entrySet()) { if (entry.getKey() - 1 != col) { // 表头断列 hashMap = new HashMap<>(); } col = entry.getKey(); List<String> list = entry.getValue(); // 移除尾部重复列名 boolean bool = true; while (list.size() > 1 && bool) { int lastIndex = list.size() - 1; if (list.get(lastIndex).equals(list.get(lastIndex - 1))) { list.remove(lastIndex); } else { bool = false; } } List<String> path = new ArrayList<>(); // 当前节点 TableHead node = null; int lastIndex = list.size() - 1; for (int i = 0; i <= lastIndex; i++) { String name = list.get(i); path.add(name); String key = S.join(path, "→"); TableHead item; if (hashMap.containsKey(key)) { item = hashMap.get(key); } else { if (i == 0) { // 避免跨列合并 hashMap = new HashMap<>(); } item = new TableHead() {{ setTitle(name); }}; hashMap.put(key, item); if (node == null) { tableHead.add(item); } else { List<TableHead> children = node.getChildren(); if (children == null) { // 创建children children = new ArrayList<>(); node.setChildren(children); } if (node.getKey() != null) { // 原节点延伸 TableHead originalNode = new TableHead(); originalNode.setKey(node.getKey()); originalNode.setTitle(node.getTitle()); node.setKey(null); children.add(originalNode); } children.add(item); } } node = item; if (i == lastIndex) { // 添加key List<TableHead> children = item.getChildren(); if (children == null) { item.setKey(fieldNameMap.get(col)); } else { // 当前节点延伸 TableHead thisNode = new TableHead(); thisNode.setKey(fieldNameMap.get(col)); thisNode.setTitle(item.getTitle()); children.add(thisNode); } } } } return tableHead; } @Getter @Setter public static class TableHead { private String key; private String title; private List<TableHead> children; } }
10,237
310
<filename>Publications/DPC++/Ch01_intro/fig_1_6_functor.cpp // Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: MIT #include <iostream> // START BOOK SNIP class Functor { public: Functor(int i, int &j) : my_i{i}, my_jRef{j} { } int operator()(int k0, int &l0) { my_jRef = 2 * my_jRef; k0 = 2 * k0; l0 = 2 * l0; return my_i + my_jRef + k0 + l0; } private: int my_i; int &my_jRef; }; // END BOOK SNIP int main() { int i = 1, j = 10, k = 100, l = 1000; Functor F{i, j}; std::cout << "First call returned " << F( k, l ) << "\n"; std::cout << "Second call returned " << F( k, l ) << "\n"; return 0; }
315
1,338
<gh_stars>1000+ /* * Copyright 2002, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> // 2002, <NAME> // technical reference: // http://bedriven.be-in.org/document/280-serial_port_driver.html // 2004: bedriven is down now, mirror at: // http://web.archive.org/web/20040220055400/http://bedriven.be-in.org/document/280-serial_port_driver.html int main(int argc, char **argv) { char *default_scan[] = { "scsi_dsk", "scsi_cd", "ata", "atapi" }; // not really sure here... char *default_scan_names[] = { "scsi disks", "scsi cdroms", "ide ata", "ide atapi" }; char **scan = default_scan; char **scan_names = default_scan_names; int scan_count = 4; int scan_index = 0; int fd_dev; if (argc == 2 && !strcmp(argv[1], "--help")) { printf("usage: rescan [driver]\n"); return 0; } if (argc > 1) { scan = scan_names = argv; scan_count = argc; scan_index++; // not argv[0] } for (; scan_index < scan_count; scan_index++) { printf("scanning %s...\n", scan_names[scan_index]); fd_dev = open("/dev", O_WRONLY); write(fd_dev, scan[scan_index], strlen(scan[scan_index])); close(fd_dev); } return 0; }
502
2,151
/* * * Copyright 2015 gRPC authors. * * 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. * */ /* This benchmark exists to show that byte-buffer copy is size-independent */ #include <memory> #include <benchmark/benchmark.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/support/byte_buffer.h> #include "test/cpp/microbenchmarks/helpers.h" #include "test/cpp/util/test_config.h" namespace grpc { namespace testing { auto& force_library_initialization = Library::get(); static void BM_ByteBuffer_Copy(benchmark::State& state) { int num_slices = state.range(0); size_t slice_size = state.range(1); std::vector<grpc::Slice> slices; while (num_slices > 0) { num_slices--; std::unique_ptr<char[]> buf(new char[slice_size]); memset(buf.get(), 0, slice_size); slices.emplace_back(buf.get(), slice_size); } grpc::ByteBuffer bb(slices.data(), num_slices); while (state.KeepRunning()) { grpc::ByteBuffer cc(bb); } } BENCHMARK(BM_ByteBuffer_Copy)->Ranges({{1, 64}, {1, 1024 * 1024}}); } // namespace testing } // namespace grpc // Some distros have RunSpecifiedBenchmarks under the benchmark namespace, // and others do not. This allows us to support both modes. namespace benchmark { void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); } } // namespace benchmark int main(int argc, char** argv) { ::benchmark::Initialize(&argc, argv); ::grpc::testing::InitTest(&argc, &argv, false); benchmark::RunTheBenchmarksNamespaced(); return 0; }
661
6,989
#pragma once #include "typetraits.h" #include <util/system/types.h> #include <cstring> template <class T> using TIfPOD = std::enable_if_t<TTypeTraits<T>::IsPod, T*>; template <class T> using TIfNotPOD = std::enable_if_t<!TTypeTraits<T>::IsPod, T*>; template <class T> static inline TIfPOD<T> MemCopy(T* to, const T* from, size_t n) noexcept { if (n) { memcpy(to, from, n * sizeof(T)); } return to; } template <class T> static inline TIfNotPOD<T> MemCopy(T* to, const T* from, size_t n) { for (size_t i = 0; i < n; ++i) { to[i] = from[i]; } return to; } template <class T> static inline TIfPOD<T> MemMove(T* to, const T* from, size_t n) noexcept { if (n) { memmove(to, from, n * sizeof(T)); } return to; } template <class T> static inline TIfNotPOD<T> MemMove(T* to, const T* from, size_t n) { if (to <= from || to >= from + n) { return MemCopy(to, from, n); } //copy backwards while (n) { to[n - 1] = from[n - 1]; --n; } return to; }
503
364
package org.cyclopsgroup.jmxterm.cmd; import java.io.IOException; import java.util.HashSet; import java.util.List; import org.apache.commons.lang3.Validate; import org.cyclopsgroup.jcli.annotation.Argument; import org.cyclopsgroup.jcli.annotation.Cli; import org.cyclopsgroup.jmxterm.Command; import org.cyclopsgroup.jmxterm.Session; import org.cyclopsgroup.jmxterm.SyntaxUtils; /** * Get or set current selected domain * * @author <a href="mailto:<EMAIL>"><NAME></a> */ @Cli( name = "domain", description = "Display or set current selected domain. ", note = "With a parameter, parameter defined domain is selected, otherwise it displays current selected domain." + " eg. domain java.lang") public class DomainCommand extends Command { /** * Get domain name from given domain expression * * @param domain Domain expression, which can be a name or NULL * @param session Current JMX session * @return String name of domain coming from given parameter or current session * @throws IOException */ static String getDomainName(String domain, Session session) throws IOException { Validate.notNull(session, "Session can't be NULL"); Validate.isTrue(session.getConnection() != null, "Session isn't opened"); if (domain == null) { return session.getDomain(); } if (SyntaxUtils.isNull(domain)) { return null; } HashSet<String> domains = new HashSet<String>(DomainsCommand.getCandidateDomains(session)); if (!domains.contains(domain)) { throw new IllegalArgumentException( "Domain " + domain + " doesn't exist, check your spelling"); } return domain; } private String domain; @Override public List<String> doSuggestArgument() throws IOException { return DomainsCommand.getCandidateDomains(getSession()); } @Override public void execute() throws IOException { Session session = getSession(); if (domain == null) { if (session.getDomain() == null) { session.output.printMessage("domain is not set"); session.output.println(SyntaxUtils.NULL); } else { session.output.printMessage("domain = " + session.getDomain()); session.output.println(session.getDomain()); } return; } String domainName = getDomainName(domain, session); if (domainName == null) { session.unsetDomain(); session.output.printMessage("domain is unset"); } else { session.setDomain(domainName); session.output.printMessage("domain is set to " + session.getDomain()); } } /** @param domain Domain to select */ @Argument(displayName = "domain", description = "Name of domain to set") public final void setDomain(String domain) { this.domain = domain; } }
934
335
<filename>L/Luck_verb.json { "word": "Luck", "definitions": [ "Chance to find or acquire.", "Achieve success or advantage by good luck." ], "parts-of-speech": "Verb" }
86
412
from __future__ import print_function, absolute_import def display(args): # Display information of current training print('Learn Rate \t%.1e' % args.lr) print('Epochs \t%05d' % args.epochs) print('Log Path \t%s' % args.save_dir) print('Network \t %s' % args.net) print('Data Set \t %s' % args.data) print('Batch Size \t %d' % args.batch_size) print('Num-Instance \t %d' % args.num_instances) print('Embedded Dimension \t %d' % args.dim) print('Loss Function \t%s' % args.loss) # print('Number of Neighbour \t%d' % args.k) print('Alpha \t %d' % args.alpha) print('Begin to fine tune %s Network' % args.net) print(40*'#')
280
337
import pywasm # pywasm.on_debug() runtime = pywasm.load('./examples/add.wasm') r = runtime.exec('add', [4, 5]) print(r) # 4 + 5 = 9
60
1,125
<filename>third_party/libigl/include/igl/cut_mesh.h<gh_stars>1000+ // This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2019 <NAME> <<EMAIL>> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_CUT_MESH_H #define IGL_CUT_MESH_H #include "igl_inline.h" #include <Eigen/Core> namespace igl { // Given a mesh and a list of edges that are to be cut, the function // generates a new disk-topology mesh that has the cuts at its boundary. // // // Known issues: Assumes mesh is edge-manifold. // // Inputs: // V #V by 3 list of the vertex positions // F #F by 3 list of the faces // cuts #F by 3 list of boolean flags, indicating the edges that need to // be cut (has 1 at the face edges that are to be cut, 0 otherwise) // Outputs: // Vn #V by 3 list of the vertex positions of the cut mesh. This matrix // will be similar to the original vertices except some rows will be // duplicated. // Fn #F by 3 list of the faces of the cut mesh(must be triangles). This // matrix will be similar to the original face matrix except some indices // will be redirected to point to the newly duplicated vertices. // I #V by 1 list of the map between Vn to original V index. // In place mesh cut template <typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedI> IGL_INLINE void cut_mesh( Eigen::PlainObjectBase<DerivedV>& V, Eigen::PlainObjectBase<DerivedF>& F, const Eigen::MatrixBase<DerivedC>& cuts, Eigen::PlainObjectBase<DerivedI>& I ); template <typename DerivedV, typename DerivedF, typename DerivedFF, typename DerivedFFi, typename DerivedC, typename DerivedI> IGL_INLINE void cut_mesh( Eigen::PlainObjectBase<DerivedV>& V, Eigen::PlainObjectBase<DerivedF>& F, Eigen::MatrixBase<DerivedFF>& FF, Eigen::MatrixBase<DerivedFFi>& FFi, const Eigen::MatrixBase<DerivedC>& C, Eigen::PlainObjectBase<DerivedI>& I ); template <typename DerivedV, typename DerivedF, typename DerivedC> IGL_INLINE void cut_mesh( const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, const Eigen::MatrixBase<DerivedC>& cuts, Eigen::PlainObjectBase<DerivedV>& Vn, Eigen::PlainObjectBase<DerivedF>& Fn ); template <typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedI> IGL_INLINE void cut_mesh( const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, const Eigen::MatrixBase<DerivedC>& cuts, Eigen::PlainObjectBase<DerivedV>& Vn, Eigen::PlainObjectBase<DerivedF>& Fn, Eigen::PlainObjectBase<DerivedI>& I ); } #ifndef IGL_STATIC_LIBRARY #include "cut_mesh.cpp" #endif #endif
1,097