max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
787
<filename>leetcode/270. Closest Binary Search Tree Value/s2.cpp // OJ: https://leetcode.com/problems/closest-binary-search-tree-value/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(logN) // Ref: https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70331/Clean-and-concise-java-solution class Solution { public: int closestValue(TreeNode* root, double target) { int ans = root->val; while (root) { if (abs(target - root->val) < abs(target - ans)) ans = root->val; root = root->val > target ? root->left : root->right; } return ans; } };
266
1,866
import functools import threading class PromiseError(Exception): """A failed Promise is to be resolved with this PromiseError. Normal errors and exceptions can't be catched by the applicaiton due to multithreading. Therefore a function should return PromiseError to indicate a failure to be handled by `.then()` """ pass class Promise(object): """A simple implementation of the Promise specification. See: https://promisesaplus.com Promise is in essence a syntactic sugar for callbacks. Simplifies passing values from functions that might do work in asynchronous manner. Example usage: * Passing return value of one function to another: def do_work_async(resolve): # "resolve" is a function that, when called with a value, resolves # the promise with provided value and passes the value to the next # chained promise. resolve(111) # Can be invoked asynchronously. def process_value(value): assert value === 111 Promise(do_work_async).then(process_value) * Returning Promise from chained promise: def do_work_async_1(resolve): # Compute value asynchronously. resolve(111) def do_work_async_2(resolve): # Compute value asynchronously. resolve(222) def do_more_work_async(value): # Do more work with the value asynchronously. For the sake of this # example, we don't use 'value' for anything. assert value === 111 return Promise(do_work_async_2) def process_value(value): assert value === 222 Promise(do_work_async_1).then(do_more_work_async).then(process_value) """ def __init__(self, executor): """Initialize Promise object. Arguments: executor: A function that is executed immediately by this Promise. It gets passed a "resolve" function. The "resolve" function, when called, resolves the Promise with the value passed to it. """ self.value = None self.resolved = False self.mutex = threading.Lock() self.callbacks = [] self._invoke_executor(executor) @classmethod def resolve(cls, resolve_value=None): """Immediatelly resolve a Promise. Convenience function for creating a Promise that gets immediately resolved with the specified value. Arguments: resolve_value: The value to resolve the promise with. """ def executor(resolve_fn): return resolve_fn(resolve_value) return cls(executor) def then(self, callback): """Create a new promise and chain it with this promise. When this promise gets resolved, the callback will be called with the value that this promise resolved with. Returns a new promise that can be used to do further chaining. Arguments: callback: The callback to call when this promise gets resolved. """ def callback_wrapper(resolve_fn, resolve_value): """A wrapper called when this promise resolves. Arguments: resolve_fn: A resolve function of newly created promise. resolve_value: The value with which this promise resolved. """ result = callback(resolve_value) # If returned value is a promise then this promise needs to be # resolved with the value of returned promise. if isinstance(result, Promise): result.then(resolve_fn) else: resolve_fn(result) def sync_executor(resolve_fn): """Call resolve_fn immediately with the resolved value. An executor that will immediately resolve resolve_fn with the resolved value of this promise. """ callback_wrapper(resolve_fn, self._get_value()) def async_executor(resolve_fn): """Queue resolve_fn to be called after this promise resolves later. An executor that will resolve received resolve_fn when this promise resolves later. """ self._add_callback(functools.partial(callback_wrapper, resolve_fn)) if self._is_resolved(): return Promise(sync_executor) return Promise(async_executor) def _invoke_executor(self, executor): def resolve_fn(new_value): self._do_resolve(new_value) executor(resolve_fn) def _do_resolve(self, new_value): # No need to block as we can't change from resolved to unresolved. if self.resolved: raise RuntimeError( "cannot set the value of an already resolved promise") with self.mutex: self.value = new_value for callback in self.callbacks: callback(new_value) self.resolved = True def _add_callback(self, callback): with self.mutex: self.callbacks.append(callback) def _is_resolved(self): with self.mutex: return self.resolved def _get_value(self): with self.mutex: return self.value
2,155
318
{ "name": "presentator-client", "version": "2.7.1", "description": "Presentator v2 API JavaScript Client", "main": "dist/client.min.js", "keywords": [ "presentator", "api", "api-client", "presentatorapi", "presentator-api", "presentatorclient", "presentator-client" ], "author": "<NAME> <<EMAIL>>", "license": "BSD-3-Clause", "repository": { "type": "git", "url": "git://github.com/presentator/presentator-js-client.git" }, "scripts": { "build": "webpack --mode=production", "test": "mocha-webpack --webpack-config webpack-test.config.js \"tests/**/*.spec.js\" || true", "prepublishOnly": "npm run build" }, "dependencies": { "axios": "^0.21.1" }, "devDependencies": { "@babel/core": "^7.14.8", "@babel/preset-env": "^7.14.8", "axios-mock-adapter": "^1.19.0", "babel-loader": "^8.2.2", "babel-plugin-add-module-exports": "^1.0.4", "chai": "^4.3.4", "mocha": "^6.2.3", "mocha-webpack": "^2.0.0-beta.0", "webpack": "^4.46.0", "webpack-cli": "^3.3.12" } }
512
575
<filename>src/base/trace_event/category_registry.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/trace_event/category_registry.h" #include <string.h> #include <ostream> #include <type_traits> #include "base/check.h" #include "base/debug/leak_annotations.h" #include "base/notreached.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" namespace base { namespace trace_event { namespace { // |categories_| might end up causing creating dynamic initializers if not POD. static_assert(std::is_pod<TraceCategory>::value, "TraceCategory must be POD"); } // namespace // static TraceCategory CategoryRegistry::categories_[kMaxCategories] = { INTERNAL_TRACE_LIST_BUILTIN_CATEGORIES(INTERNAL_TRACE_INIT_CATEGORY)}; // static base::subtle::AtomicWord CategoryRegistry::category_index_ = BuiltinCategories::Size(); // static TraceCategory* const CategoryRegistry::kCategoryExhausted = &categories_[0]; TraceCategory* const CategoryRegistry::kCategoryAlreadyShutdown = &categories_[1]; TraceCategory* const CategoryRegistry::kCategoryMetadata = &categories_[2]; // static void CategoryRegistry::Initialize() { // Trace is enabled or disabled on one thread while other threads are // accessing the enabled flag. We don't care whether edge-case events are // traced or not, so we allow races on the enabled flag to keep the trace // macros fast. for (size_t i = 0; i < kMaxCategories; ++i) { ANNOTATE_BENIGN_RACE(categories_[i].state_ptr(), "trace_event category enabled"); // If this DCHECK is hit in a test it means that ResetForTesting() is not // called and the categories state leaks between test fixtures. DCHECK(!categories_[i].is_enabled()); } } // static void CategoryRegistry::ResetForTesting() { // reset_for_testing clears up only the enabled state and filters. The // categories themselves cannot be cleared up because the static pointers // injected by the macros still point to them and cannot be reset. for (size_t i = 0; i < kMaxCategories; ++i) categories_[i].reset_for_testing(); } // static TraceCategory* CategoryRegistry::GetCategoryByName(const char* category_name) { DCHECK(!strchr(category_name, '"')) << "Category names may not contain double quote"; // The categories_ is append only, avoid using a lock for the fast path. size_t category_index = base::subtle::Acquire_Load(&category_index_); // Search for pre-existing category group. for (size_t i = 0; i < category_index; ++i) { if (strcmp(categories_[i].name(), category_name) == 0) { return &categories_[i]; } } return nullptr; } bool CategoryRegistry::GetOrCreateCategoryLocked( const char* category_name, CategoryInitializerFn category_initializer_fn, TraceCategory** category) { // This is the slow path: the lock is not held in the fastpath // (GetCategoryByName), so more than one thread could have reached here trying // to add the same category. *category = GetCategoryByName(category_name); if (*category) return false; // Create a new category. size_t category_index = base::subtle::Acquire_Load(&category_index_); if (category_index >= kMaxCategories) { NOTREACHED() << "must increase kMaxCategories"; *category = kCategoryExhausted; return false; } // TODO(primiano): this strdup should be removed. The only documented reason // for it was TraceWatchEvent, which is gone. However, something might have // ended up relying on this. Needs some auditing before removal. const char* category_name_copy = strdup(category_name); ANNOTATE_LEAKING_OBJECT_PTR(category_name_copy); *category = &categories_[category_index]; DCHECK(!(*category)->is_valid()); DCHECK(!(*category)->is_enabled()); (*category)->set_name(category_name_copy); category_initializer_fn(*category); // Update the max index now. base::subtle::Release_Store(&category_index_, category_index + 1); return true; } // static const TraceCategory* CategoryRegistry::GetCategoryByStatePtr( const uint8_t* category_state) { const TraceCategory* category = TraceCategory::FromStatePtr(category_state); DCHECK(IsValidCategoryPtr(category)); return category; } // static bool CategoryRegistry::IsMetaCategory(const TraceCategory* category) { DCHECK(IsValidCategoryPtr(category)); return category <= kCategoryMetadata; } // static CategoryRegistry::Range CategoryRegistry::GetAllCategories() { // The |categories_| array is append only. We have to only guarantee to // not return an index to a category which is being initialized by // GetOrCreateCategoryByName(). size_t category_index = base::subtle::Acquire_Load(&category_index_); return CategoryRegistry::Range(&categories_[0], &categories_[category_index]); } // static bool CategoryRegistry::IsValidCategoryPtr(const TraceCategory* category) { // If any of these are hit, something has cached a corrupt category pointer. uintptr_t ptr = reinterpret_cast<uintptr_t>(category); return ptr % sizeof(void*) == 0 && ptr >= reinterpret_cast<uintptr_t>(&categories_[0]) && ptr <= reinterpret_cast<uintptr_t>(&categories_[kMaxCategories - 1]); } } // namespace trace_event } // namespace base
1,709
774
<reponame>moonantonio/lunar-unity-console<filename>Native/Android/LunarConsole/lunarConsole/src/main/java/spacemadness/com/lunarconsole/settings/PluginSettings.java<gh_stars>100-1000 // // PluginSettings.java // // Lunar Unity Mobile Console // https://github.com/SpaceMadness/lunar-unity-console // // Copyright 2015-2021 <NAME>, SpaceMadness. // // 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 spacemadness.com.lunarconsole.settings; import java.util.Arrays; import spacemadness.com.lunarconsole.json.Required; /** * Global settings from Unity editor. */ public final class PluginSettings { /** * Exception warning settings. */ public @Required ExceptionWarningSettings exceptionWarning; /** * Log overlay settings */ public @Required @ProOnly LogOverlaySettings logOverlay; /** * Log output would not grow bigger than this capacity. */ public @Required @Readonly int capacity; /** * Log output will be trimmed this many lines when overflown. */ public @Required @Readonly int trim; /** * Gesture type to open the console. */ public @Required @Readonly Gesture gesture; /** * Indicates if reach text tags should be ignored. */ public boolean richTextTags; /** * Indicates if actions should be sorted. */ public boolean sortActions; /** * Indicates if variables should be sorted. */ public boolean sortVariables; /** * Optional list of the email recipients for sending a report. */ public @Readonly String[] emails; //region Equality @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PluginSettings settings = (PluginSettings) o; if (capacity != settings.capacity) return false; if (trim != settings.trim) return false; if (richTextTags != settings.richTextTags) return false; if (sortActions != settings.sortActions) return false; if (sortVariables != settings.sortVariables) return false; if (exceptionWarning != null ? !exceptionWarning.equals(settings.exceptionWarning) : settings.exceptionWarning != null) return false; if (logOverlay != null ? !logOverlay.equals(settings.logOverlay) : settings.logOverlay != null) return false; if (gesture != settings.gesture) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(emails, settings.emails); } @Override public int hashCode() { int result = exceptionWarning != null ? exceptionWarning.hashCode() : 0; result = 31 * result + (logOverlay != null ? logOverlay.hashCode() : 0); result = 31 * result + capacity; result = 31 * result + trim; result = 31 * result + (gesture != null ? gesture.hashCode() : 0); result = 31 * result + (richTextTags ? 1 : 0); result = 31 * result + (sortActions ? 1 : 0); result = 31 * result + (sortVariables ? 1 : 0); result = 31 * result + Arrays.hashCode(emails); return result; } //endregion }
1,344
1,176
<filename>src/include/execution/plans/index_scan_plan.h<gh_stars>1000+ //===----------------------------------------------------------------------===// // // BusTub // // index_scan_plan.h // // Identification: src/include/execution/plans/index_scan_plan.h // // Copyright (c) 2015-19, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include "catalog/catalog.h" #include "execution/expressions/abstract_expression.h" #include "execution/plans/abstract_plan.h" namespace bustub { /** * IndexScanPlanNode identifies a table that should be scanned with an optional predicate. */ class IndexScanPlanNode : public AbstractPlanNode { public: /** * Creates a new index scan plan node. * @param output the output format of this scan plan node * @param predicate the predicate to scan with, tuples are returned if predicate(tuple) == true or predicate == * nullptr * @param table_oid the identifier of table to be scanned */ IndexScanPlanNode(const Schema *output, const AbstractExpression *predicate, index_oid_t index_oid) : AbstractPlanNode(output, {}), predicate_{predicate}, index_oid_(index_oid) {} PlanType GetType() const override { return PlanType::IndexScan; } /** @return the predicate to test tuples against; tuples should only be returned if they evaluate to true */ const AbstractExpression *GetPredicate() const { return predicate_; } /** @return the identifier of the table that should be scanned */ index_oid_t GetIndexOid() const { return index_oid_; } private: /** The predicate that all returned tuples must satisfy. */ const AbstractExpression *predicate_; /** The table whose tuples should be scanned. */ index_oid_t index_oid_; }; } // namespace bustub
528
1,792
package org.hongxi.summer.codec; import org.apache.commons.lang3.StringUtils; import org.hongxi.summer.common.extension.ExtensionLoader; import org.hongxi.summer.exception.SummerErrorMsgConstants; import org.hongxi.summer.exception.SummerFrameworkException; import org.hongxi.summer.exception.SummerServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Created by shenhongxi on 2020/7/25. */ public abstract class AbstractCodec implements Codec { private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); protected static ConcurrentMap<Integer, String> serializations; protected void serialize(ObjectOutput output, Object message, Serialization serialization) throws IOException { if (message == null) { output.writeObject(null); return; } output.writeObject(serialization.serialize(message)); } protected Object deserialize(byte[] value, Class<?> type, Serialization serialization) throws IOException { if (value == null) { return null; } return serialization.deserialize(value, type); } public ObjectOutput createOutput(OutputStream out) { try { return new ObjectOutputStream(out); } catch (Exception e) { throw new SummerFrameworkException(this.getClass().getSimpleName() + " createOutput error", e, SummerErrorMsgConstants.FRAMEWORK_ENCODE_ERROR); } } public ObjectInput createInput(InputStream in) { try { return new ObjectInputStream(in); } catch (Exception e) { throw new SummerFrameworkException(this.getClass().getSimpleName() + " createInput error", e, SummerErrorMsgConstants.FRAMEWORK_DECODE_ERROR); } } protected static synchronized void initAllSerialization() { if (serializations == null) { serializations = new ConcurrentHashMap<>(); try { ExtensionLoader<Serialization> loader = ExtensionLoader.getExtensionLoader(Serialization.class); List<Serialization> exts = loader.getExtensions(); for (Serialization s : exts) { String old = serializations.put(s.getSerializationNumber(), loader.getSpiName(s.getClass())); if (old != null) { logger.warn("conflict serialization spi! serialization num :{}, old spi :{}, new spi :{}", s.getSerializationNumber(), old, serializations.get(s.getSerializationNumber())); } } } catch (Exception e) { logger.warn("init all serializations failed", e); } } } protected Serialization getSerializationByNum(int serializationNum) { if (serializations == null) { initAllSerialization(); } String name = serializations.get(serializationNum); Serialization s = null; if (StringUtils.isNotBlank(name)) { s = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); } if (s == null) { throw new SummerServiceException("can not find serialization by number " + serializationNum); } return s; } }
1,428
709
<gh_stars>100-1000 #include "msdf-edge-artifact-patcher.h" #include <cstring> #include <vector> #include <utility> #include "arithmetics.hpp" #include "equation-solver.h" #include "bitmap-interpolation.hpp" #include "edge-selectors.h" #include "contour-combiners.h" #include "ShapeDistanceFinder.h" namespace msdfgen { static bool isHotspot(float am, float bm, float xm) { return (am > .5f && bm > .5f && xm < .5f) || (am < .5f && bm < .5f && xm > .5f); // A much more aggressive version for the entire distance field (not just edges): return median(am, bm, xm) != xm; } static int findLinearChannelHotspots(double t[1], const float *a, const float *b, float dA, float dB) { int found = 0; double x = (double) dA/(dA-dB); if (x > 0 && x < 1) { float am = median(a[0], a[1], a[2]); float bm = median(b[0], b[1], b[2]); float xm = median( mix(a[0], b[0], x), mix(a[1], b[1], x), mix(a[2], b[2], x) ); if (isHotspot(am, bm, xm)) t[found++] = x; } return found; } static int findDiagonalChannelHotspots(double t[2], const float *a, const float *b, const float *c, const float *d, float dA, float dB, float dC, float dD) { int found = 0; double x[2]; int solutions = solveQuadratic(x, (dD-dC)-(dB-dA), dC+dB-2*dA, dA); for (int i = 0; i < solutions; ++i) if (x[i] > 0 && x[i] < 1) { float am = median(a[0], a[1], a[2]); float bm = median(b[0], b[1], b[2]); float xm = median( mix(mix(a[0], b[0], x[i]), mix(c[0], d[0], x[i]), x[i]), mix(mix(a[1], b[1], x[i]), mix(c[1], d[1], x[i]), x[i]), mix(mix(a[2], b[2], x[i]), mix(c[2], d[2], x[i]), x[i]) ); if (isHotspot(am, bm, xm)) t[found++] = x[i]; } return found; } static int findLinearHotspots(double t[3], const float *a, const float *b) { int found = 0; found += findLinearChannelHotspots(t+found, a, b, a[1]-a[0], b[1]-b[0]); found += findLinearChannelHotspots(t+found, a, b, a[2]-a[1], b[2]-b[1]); found += findLinearChannelHotspots(t+found, a, b, a[0]-a[2], b[0]-b[2]); return found; } static int findDiagonalHotspots(double t[6], const float *a, const float *b, const float *c, const float *d) { int found = 0; found += findDiagonalChannelHotspots(t+found, a, b, c, d, a[1]-a[0], b[1]-b[0], c[1]-c[0], d[1]-d[0]); found += findDiagonalChannelHotspots(t+found, a, b, c, d, a[2]-a[1], b[2]-b[1], c[2]-c[1], d[2]-d[1]); found += findDiagonalChannelHotspots(t+found, a, b, c, d, a[0]-a[2], b[0]-b[2], c[0]-c[2], d[0]-d[2]); return found; } template <int N> void findHotspots(std::vector<Point2> &hotspots, const BitmapConstRef<float, N> &sdf) { // All hotspots intersect either the horizontal, vertical, or diagonal line that connects neighboring texels // Horizontal: for (int y = 0; y < sdf.height; ++y) { const float *left = sdf(0, y); const float *right = sdf(1, y); for (int x = 0; x < sdf.width-1; ++x) { double t[3]; int found = findLinearHotspots(t, left, right); for (int i = 0; i < found; ++i) hotspots.push_back(Point2(x+.5+t[i], y+.5)); left += N, right += N; } } // Vertical: for (int y = 0; y < sdf.height-1; ++y) { const float *bottom = sdf(0, y); const float *top = sdf(0, y+1); for (int x = 0; x < sdf.width; ++x) { double t[3]; int found = findLinearHotspots(t, bottom, top); for (int i = 0; i < found; ++i) hotspots.push_back(Point2(x+.5, y+.5+t[i])); bottom += N, top += N; } } // Diagonal: for (int y = 0; y < sdf.height-1; ++y) { const float *lb = sdf(0, y); const float *rb = sdf(1, y); const float *lt = sdf(0, y+1); const float *rt = sdf(1, y+1); for (int x = 0; x < sdf.width-1; ++x) { double t[6]; int found = 0; found = findDiagonalHotspots(t, lb, rb, lt, rt); for (int i = 0; i < found; ++i) hotspots.push_back(Point2(x+.5+t[i], y+.5+t[i])); found = findDiagonalHotspots(t, lt, rt, lb, rb); for (int i = 0; i < found; ++i) hotspots.push_back(Point2(x+.5+t[i], y+1.5-t[i])); lb += N, rb += N, lt += N, rt += N; } } } template <template <typename> class ContourCombiner, int N> static void msdfPatchEdgeArtifactsInner(const BitmapRef<float, N> &sdf, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) { ShapeDistanceFinder<ContourCombiner<PseudoDistanceSelector> > distanceFinder(shape); std::vector<Point2> hotspots; findHotspots(hotspots, BitmapConstRef<float, N>(sdf)); std::vector<std::pair<int, int> > artifacts; artifacts.reserve(hotspots.size()); for (std::vector<Point2>::const_iterator hotspot = hotspots.begin(); hotspot != hotspots.end(); ++hotspot) { Point2 pos = *hotspot/scale-translate; double actualDistance = distanceFinder.distance(pos); float sd = float(actualDistance/range+.5); // Store hotspot's closest texel's current color float *subject = sdf((int) hotspot->x, (int) hotspot->y); float texel[N]; memcpy(texel, subject, N*sizeof(float)); // Sample signed distance at hotspot float msd[N]; interpolate(msd, BitmapConstRef<float, N>(sdf), *hotspot); float oldSsd = median(msd[0], msd[1], msd[2]); // Flatten hotspot's closest texel float med = median(subject[0], subject[1], subject[2]); subject[0] = med, subject[1] = med, subject[2] = med; // Sample signed distance at hotspot after flattening interpolate(msd, BitmapConstRef<float, N>(sdf), *hotspot); float newSsd = median(msd[0], msd[1], msd[2]); // Revert modified texel memcpy(subject, texel, N*sizeof(float)); // Consider hotspot an artifact if flattening improved the sample if (fabsf(newSsd-sd) < fabsf(oldSsd-sd)) artifacts.push_back(std::make_pair((int) hotspot->x, (int) hotspot->y)); } for (std::vector<std::pair<int, int> >::const_iterator artifact = artifacts.begin(); artifact != artifacts.end(); ++artifact) { float *pixel = sdf(artifact->first, artifact->second); float med = median(pixel[0], pixel[1], pixel[2]); pixel[0] = med, pixel[1] = med, pixel[2] = med; } } void msdfPatchEdgeArtifacts(const BitmapRef<float, 3> &sdf, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) { if (overlapSupport) msdfPatchEdgeArtifactsInner<OverlappingContourCombiner>(sdf, shape, range, scale, translate); else msdfPatchEdgeArtifactsInner<SimpleContourCombiner>(sdf, shape, range, scale, translate); } void msdfPatchEdgeArtifacts(const BitmapRef<float, 4> &sdf, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) { if (overlapSupport) msdfPatchEdgeArtifactsInner<OverlappingContourCombiner>(sdf, shape, range, scale, translate); else msdfPatchEdgeArtifactsInner<SimpleContourCombiner>(sdf, shape, range, scale, translate); } }
3,468
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "feature_name_extractor.h" namespace vespalib::eval { namespace { struct LegalChar { bool legal[256]; LegalChar(std::initializer_list<uint8_t> extra_chars) { for (int c = 0; c < 256; ++c) { legal[c] = isalnum(c); } for (uint8_t c: extra_chars) { legal[c] = true; } } bool is_legal(uint8_t c) { return legal[c]; } }; static LegalChar prefix({'_', '$', '@'}); static LegalChar suffix({'_', '.', '$', '@'}); struct CountParen { size_t depth = 0; bool quoted = false; bool escaped = false; bool done(char c) { if (quoted) { if (escaped) { escaped = false; } else { if (c == '\\') { escaped = true; } else if (c == '"') { quoted = false; } } } else { if (c == '"') { quoted = true; } else if (c == '(') { ++depth; } else if (c == ')') { if (--depth == 0) { return true; } } } return false; } }; } // namespace <unnamed> void FeatureNameExtractor::extract_symbol(const char *pos_in, const char *end_in, const char *&pos_out, vespalib::string &symbol_out) const { while ((pos_in < end_in) && prefix.is_legal(*pos_in)) { symbol_out.push_back(*pos_in++); } if ((pos_in < end_in) && (*pos_in == '(')) { CountParen paren; while (pos_in < end_in) { symbol_out.push_back(*pos_in); if (paren.done(*pos_in++)) { break; } } } if ((pos_in < end_in) && (*pos_in == '.')) { symbol_out.push_back(*pos_in++); while ((pos_in < end_in) && suffix.is_legal(*pos_in)) { symbol_out.push_back(*pos_in++); } } pos_out = pos_in; } }
1,156
611
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2017, Carnegie Mellon University and University of Cambridge, // all rights reserved. // // ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY // // BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS LICENSE AGREEMENT. // IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR DOWNLOAD THE SOFTWARE. // // License can be found in OpenFace-license.txt // // * Any publications arising from the use of this software, including but // not limited to academic journal and conference publications, technical // reports and manuals, must cite at least one of the following works: // // OpenFace 2.0: Facial Behavior Analysis Toolkit // <NAME>, <NAME>, <NAME>, and <NAME> // in IEEE International Conference on Automatic Face and Gesture Recognition, 2018 // // Convolutional experts constrained local model for facial landmark detection. // <NAME>, <NAME>, and <NAME>, // in Computer Vision and Pattern Recognition Workshops, 2017. // // Rendering of Eyes for Eye-Shape Registration and Gaze Estimation // <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> // in IEEE International. Conference on Computer Vision (ICCV), 2015 // // Cross-dataset learning and person-specific normalisation for automatic Action Unit detection // <NAME>, <NAME>, and <NAME> // in Facial Expression Recognition and Analysis Challenge, // IEEE International Conference on Automatic Face and Gesture Recognition, 2015 // /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SVR_patch_expert.h" // OpenCV include #include <opencv2/core/core.hpp> #include <opencv2/imgproc.hpp> #include "LandmarkDetectorUtils.h" using namespace LandmarkDetector; //=========================================================================== // Computing the image gradient void Grad(const cv::Mat& im, cv::Mat& grad) { /*float filter[3] = {1, 0, -1}; float dfilter[1] = {1}; cv::Mat filterX = cv::Mat(1,3,CV_32F, filter).clone(); cv::Mat filterY = cv::Mat(1,1,CV_32F, dfilter).clone(); cv::Mat gradX; cv::Mat gradY; cv::sepFilter2D(im, gradX, CV_32F, filterY, filterX, cv::Point(-1,-1), 0); cv::sepFilter2D(im, gradY, CV_32F, filterX.t(), filterY, cv::Point(-1,-1), 0); cv::pow(gradX,2, gradX); cv::pow(gradY,2, gradY); grad = gradX + gradY; grad.row(0).setTo(0); grad.col(0).setTo(0); grad.col(grad.cols-1).setTo(0); grad.row(grad.rows-1).setTo(0); */ // A quicker alternative int x,y,h = im.rows,w = im.cols; float vx,vy; // Initialise the gradient grad.create(im.size(), CV_32F); grad.setTo(0.0f); cv::MatIterator_<float> gp = grad.begin<float>() + w+1; cv::MatConstIterator_<float> px1 = im.begin<float>() + w+2; cv::MatConstIterator_<float> px2 = im.begin<float>() + w; cv::MatConstIterator_<float> py1 = im.begin<float>() + 2*w+1; cv::MatConstIterator_<float> py2 = im.begin<float>() + 1; for(y = 1; y < h-1; y++) { for(x = 1; x < w-1; x++) { vx = *px1++ - *px2++; vy = *py1++ - *py2++; *gp++ = vx*vx + vy*vy; } px1 += 2; px2 += 2; py1 += 2; py2 += 2; gp += 2; } } // A copy constructor SVR_patch_expert::SVR_patch_expert(const SVR_patch_expert& other) : weights(other.weights.clone()) { this->type = other.type; this->scaling = other.scaling; this->bias = other.bias; this->confidence = other.confidence; for (std::map<int, cv::Mat_<double> >::const_iterator it = other.weights_dfts.begin(); it != other.weights_dfts.end(); it++) { // Make sure the matrix is copied. this->weights_dfts.insert(std::pair<int, cv::Mat>(it->first, it->second.clone())); } } //=========================================================================== void SVR_patch_expert::Read(std::ifstream &stream) { // A sanity check when reading patch experts int read_type; stream >> read_type; assert(read_type == 2); stream >> type >> confidence >> scaling >> bias; LandmarkDetector::ReadMat(stream, weights); // OpenCV and Matlab matrix cardinality is different, hence the transpose weights = weights.t(); } //=========================================================================== void SVR_patch_expert::Response(const cv::Mat_<float>& area_of_interest, cv::Mat_<float>& response) { int response_height = area_of_interest.rows - weights.rows + 1; int response_width = area_of_interest.cols - weights.cols + 1; // the patch area on which we will calculate reponses cv::Mat_<float> normalised_area_of_interest; if(response.rows != response_height || response.cols != response_width) { response.create(response_height, response_width); } // If type is raw just normalise mean and standard deviation if(type == 0) { // Perform normalisation across whole patch cv::Scalar mean; cv::Scalar std; cv::meanStdDev(area_of_interest, mean, std); // Avoid division by zero if(std[0] == 0) { std[0] = 1; } normalised_area_of_interest = (area_of_interest - mean[0]) / std[0]; } // If type is gradient, perform the image gradient computation else if(type == 1) { Grad(area_of_interest, normalised_area_of_interest); } else { printf("ERROR(%s,%d): Unsupported patch type %d!\n", __FILE__,__LINE__, type); abort(); } cv::Mat_<float> svr_response; // The empty matrix as we don't pass precomputed dft's of image cv::Mat_<double> empty_matrix_0(0,0,0.0); cv::Mat_<float> empty_matrix_1(0,0,0.0); cv::Mat_<float> empty_matrix_2(0,0,0.0); // Efficient calc of patch expert SVR response across the area of interest matchTemplate_m(normalised_area_of_interest, empty_matrix_0, empty_matrix_1, empty_matrix_2, weights, weights_dfts, svr_response, cv::TM_CCOEFF_NORMED); response.create(svr_response.size()); cv::MatIterator_<float> p = response.begin(); cv::MatIterator_<float> q1 = svr_response.begin(); // respone for each pixel cv::MatIterator_<float> q2 = svr_response.end(); while(q1 != q2) { // the SVR response passed into logistic regressor *p++ = 1.0/(1.0 + exp( -(*q1++ * scaling + bias ))); } } void SVR_patch_expert::ResponseDepth(const cv::Mat_<float>& area_of_interest, cv::Mat_<float> &response) { // How big the response map will be int response_height = area_of_interest.rows - weights.rows + 1; int response_width = area_of_interest.cols - weights.cols + 1; // the patch area on which we will calculate reponses cv::Mat_<float> normalised_area_of_interest; if(response.rows != response_height || response.cols != response_width) { response.create(response_height, response_width); } if(type == 0) { // Perform normalisation across whole patch cv::Scalar mean; cv::Scalar std; // ignore missing values cv::Mat_<uchar> mask = area_of_interest > 0; cv::meanStdDev(area_of_interest, mean, std, mask); // if all values the same don't divide by 0 if(std[0] == 0) { std[0] = 1; } normalised_area_of_interest = (area_of_interest - mean[0]) / std[0]; // Set the invalid pixels to 0 normalised_area_of_interest.setTo(0, mask == 0); } else { printf("ERROR(%s,%d): Unsupported patch type %d!\n", __FILE__,__LINE__,type); abort(); } cv::Mat_<float> svr_response; // The empty matrix as we don't pass precomputed dft's of image cv::Mat_<double> empty_matrix_0(0,0,0.0); cv::Mat_<float> empty_matrix_1(0,0,0.0); cv::Mat_<float> empty_matrix_2(0,0,0.0); // Efficient calc of patch expert response across the area of interest matchTemplate_m(normalised_area_of_interest, empty_matrix_0, empty_matrix_1, empty_matrix_2, weights, weights_dfts, svr_response, cv::TM_CCOEFF); response.create(svr_response.size()); cv::MatIterator_<float> p = response.begin(); cv::MatIterator_<float> q1 = svr_response.begin(); // respone for each pixel cv::MatIterator_<float> q2 = svr_response.end(); while(q1 != q2) { // the SVR response passed through a logistic regressor *p++ = 1.0/(1.0 + exp( -(*q1++ * scaling + bias ))); } } // Copy constructor Multi_SVR_patch_expert::Multi_SVR_patch_expert(const Multi_SVR_patch_expert& other) : svr_patch_experts(other.svr_patch_experts) { this->width = other.width; this->height = other.height; } //=========================================================================== void Multi_SVR_patch_expert::Read(std::ifstream &stream) { // A sanity check when reading patch experts int type; stream >> type; assert(type == 3); // The number of patch experts for this view (with different modalities) int number_modalities; stream >> width >> height >> number_modalities; svr_patch_experts.resize(number_modalities); for(int i = 0; i < number_modalities; i++) svr_patch_experts[i].Read(stream); } //=========================================================================== void Multi_SVR_patch_expert::Response(const cv::Mat_<float> &area_of_interest, cv::Mat_<float> &response) { int response_height = area_of_interest.rows - height + 1; int response_width = area_of_interest.cols - width + 1; if(response.rows != response_height || response.cols != response_width) { response.create(response_height, response_width); } // For the purposes of the experiment only use the response of normal intensity, for fair comparison if(svr_patch_experts.size() == 1) { svr_patch_experts[0].Response(area_of_interest, response); } else { // responses from multiple patch experts these can be gradients, LBPs etc. response.setTo(1.0); cv::Mat_<float> modality_resp(response_height, response_width); for(size_t i = 0; i < svr_patch_experts.size(); i++) { svr_patch_experts[i].Response(area_of_interest, modality_resp); response = response.mul(modality_resp); } } } void Multi_SVR_patch_expert::ResponseDepth(const cv::Mat_<float>& area_of_interest, cv::Mat_<float>& response) { int response_height = area_of_interest.rows - height + 1; int response_width = area_of_interest.cols - width + 1; if(response.rows != response_height || response.cols != response_width) { response.create(response_height, response_width); } // With depth patch experts only do raw data modality svr_patch_experts[0].ResponseDepth(area_of_interest, response); } //===========================================================================
3,803
6,009
<reponame>zhouhp007/AndroidPicker<gh_stars>1000+ /* * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<<EMAIL>> * * The software is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. */ package com.github.gzuliyujiang.wheelpicker; import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.StyleRes; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Locale; /** * 性别选择器 * * @author 贵州山野羡民(<EMAIL>) * @since 2019/6/23 11:48 */ @SuppressWarnings("WeakerAccess") public class SexPicker extends OptionPicker { public static final List<String> DATA_CN = Arrays.asList( "男", "女" ); public static final List<String> DATA_EN = Arrays.asList( "Male", "Female" ); private final boolean includeSecrecy; public SexPicker(Activity activity) { this(activity, false); } public SexPicker(@NonNull Activity activity, @StyleRes int themeResId) { super(activity, themeResId); this.includeSecrecy = false; } public SexPicker(Activity activity, boolean includeSecrecy) { super(activity); this.includeSecrecy = includeSecrecy; } public SexPicker(@NonNull Activity activity, @StyleRes int themeResId, boolean includeSecrecy) { super(activity, themeResId); this.includeSecrecy = includeSecrecy; } @Override protected void initView() { super.initView(); titleView.setText("性别选择"); } @Override protected List<?> provideData() { boolean isChinese = Locale.getDefault().getDisplayLanguage().contains("中文"); LinkedList<String> data = new LinkedList<>(); if (isChinese) { data.addAll(DATA_CN); if (includeSecrecy) { data.addFirst("保密"); } } else { data.addAll(DATA_EN); if (includeSecrecy) { data.addFirst("Unlimited"); } } return data; } }
1,043
26,901
<reponame>lff0305/apollo<filename>apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SystemInfoController.java /* * Copyright 2021 Apollo 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.Apollo; import com.ctrip.framework.apollo.portal.environment.PortalMetaDomainService; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.component.PortalSettings; import com.ctrip.framework.apollo.portal.component.RestTemplateFactory; import com.ctrip.framework.apollo.portal.entity.vo.EnvironmentInfo; import com.ctrip.framework.apollo.portal.entity.vo.SystemInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.health.Health; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.util.List; @RestController @RequestMapping("/system-info") public class SystemInfoController { private static final Logger logger = LoggerFactory.getLogger(SystemInfoController.class); private static final String CONFIG_SERVICE_URL_PATH = "/services/config"; private static final String ADMIN_SERVICE_URL_PATH = "/services/admin"; private RestTemplate restTemplate; private final PortalSettings portalSettings; private final RestTemplateFactory restTemplateFactory; private final PortalMetaDomainService portalMetaDomainService; public SystemInfoController( final PortalSettings portalSettings, final RestTemplateFactory restTemplateFactory, final PortalMetaDomainService portalMetaDomainService ) { this.portalSettings = portalSettings; this.restTemplateFactory = restTemplateFactory; this.portalMetaDomainService = portalMetaDomainService; } @PostConstruct private void init() { restTemplate = restTemplateFactory.getObject(); } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @GetMapping public SystemInfo getSystemInfo() { SystemInfo systemInfo = new SystemInfo(); String version = Apollo.VERSION; if (isValidVersion(version)) { systemInfo.setVersion(version); } List<Env> allEnvList = portalSettings.getAllEnvs(); for (Env env : allEnvList) { EnvironmentInfo environmentInfo = adaptEnv2EnvironmentInfo(env); systemInfo.addEnvironment(environmentInfo); } return systemInfo; } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @GetMapping(value = "/health") public Health checkHealth(@RequestParam String instanceId) { List<Env> allEnvs = portalSettings.getAllEnvs(); ServiceDTO service = null; for (final Env env : allEnvs) { EnvironmentInfo envInfo = adaptEnv2EnvironmentInfo(env); if (envInfo.getAdminServices() != null) { for (final ServiceDTO s : envInfo.getAdminServices()) { if (instanceId.equals(s.getInstanceId())) { service = s; break; } } } if (envInfo.getConfigServices() != null) { for (final ServiceDTO s : envInfo.getConfigServices()) { if (instanceId.equals(s.getInstanceId())) { service = s; break; } } } } if (service == null) { throw new IllegalArgumentException("No such instance of instanceId: " + instanceId); } return restTemplate.getForObject(service.getHomepageUrl() + "/health", Health.class); } private EnvironmentInfo adaptEnv2EnvironmentInfo(final Env env) { EnvironmentInfo environmentInfo = new EnvironmentInfo(); String metaServerAddresses = portalMetaDomainService.getMetaServerAddress(env); environmentInfo.setEnv(env); environmentInfo.setActive(portalSettings.isEnvActive(env)); environmentInfo.setMetaServerAddress(metaServerAddresses); String selectedMetaServerAddress = portalMetaDomainService.getDomain(env); try { environmentInfo.setConfigServices(getServerAddress(selectedMetaServerAddress, CONFIG_SERVICE_URL_PATH)); environmentInfo.setAdminServices(getServerAddress(selectedMetaServerAddress, ADMIN_SERVICE_URL_PATH)); } catch (Throwable ex) { String errorMessage = "Loading config/admin services from meta server: " + selectedMetaServerAddress + " failed!"; logger.error(errorMessage, ex); environmentInfo.setErrorMessage(errorMessage + " Exception: " + ex.getMessage()); } return environmentInfo; } private ServiceDTO[] getServerAddress(String metaServerAddress, String path) { String url = metaServerAddress + path; return restTemplate.getForObject(url, ServiceDTO[].class); } private boolean isValidVersion(String version) { return !version.equals("java-null"); } }
1,807
1,350
<filename>sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.computervision.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * An object describing supported model by name and categories. */ public class ModelDescription { /** * The name of the model. */ @JsonProperty(value = "name") private String name; /** * Categories of the model. */ @JsonProperty(value = "categories") private List<String> categories; /** * Get the name value. * * @return the name value */ public String name() { return this.name; } /** * Set the name value. * * @param name the name value to set * @return the ModelDescription object itself. */ public ModelDescription withName(String name) { this.name = name; return this; } /** * Get the categories value. * * @return the categories value */ public List<String> categories() { return this.categories; } /** * Set the categories value. * * @param categories the categories value to set * @return the ModelDescription object itself. */ public ModelDescription withCategories(List<String> categories) { this.categories = categories; return this; } }
624
1,144
<filename>core/libmemunreachable/include/memunreachable/memunreachable.h<gh_stars>1000+ /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIBMEMUNREACHABLE_MEMUNREACHABLE_H_ #define LIBMEMUNREACHABLE_MEMUNREACHABLE_H_ #include <sys/cdefs.h> #ifdef __cplusplus #include <vector> #include <string> struct Leak { uintptr_t begin; size_t size; size_t referenced_count; size_t referenced_size; size_t similar_count; size_t similar_size; size_t similar_referenced_count; size_t similar_referenced_size; size_t total_size; static const size_t contents_length = 32; char contents[contents_length]; struct Backtrace { size_t num_frames; static const size_t max_frames = 16; uintptr_t frames[max_frames]; } backtrace; std::string ToString(bool log_contents) const; }; struct UnreachableMemoryInfo { std::vector<Leak> leaks; size_t num_leaks; size_t leak_bytes; size_t num_allocations; size_t allocation_bytes; UnreachableMemoryInfo() {} ~UnreachableMemoryInfo() { // Clear the memory that holds the leaks, otherwise the next attempt to // detect leaks may find the old data (for example in the jemalloc tcache) // and consider all the leaks to be referenced. memset(leaks.data(), 0, leaks.capacity() * sizeof(Leak)); } std::string ToString(bool log_contents) const; }; bool GetUnreachableMemory(UnreachableMemoryInfo& info, size_t limit = 100); std::string GetUnreachableMemoryString(bool log_contents = false, size_t limit = 100); #endif __BEGIN_DECLS bool LogUnreachableMemory(bool log_contents, size_t limit); bool NoLeaks(); __END_DECLS #endif // LIBMEMUNREACHABLE_MEMUNREACHABLE_H_
749
3,102
<gh_stars>1000+ int *x0; float **x1; #include "var1.h" int xarray0[17]; int xarray1[]; int xarray2[18]; int xarray3[18];
60
323
<reponame>markyong97/retinafacetest from typing import Any, Dict, List import cv2 import numpy as np import torch def vis_annotations(image: np.ndarray, annotations: List[Dict[str, Any]]) -> np.ndarray: vis_image = image.copy() for annotation in annotations: landmarks = annotation["landmarks"] colors = [(255, 0, 0), (128, 255, 0), (255, 178, 102), (102, 128, 255), (0, 255, 255)] for landmark_id, (x, y) in enumerate(landmarks): vis_image = cv2.circle(vis_image, (int(x), int(y)), radius=3, color=colors[landmark_id], thickness=3) x_min, y_min, x_max, y_max = (int(tx) for tx in annotation["bbox"]) x_min = np.clip(x_min, 0, x_max - 1) y_min = np.clip(y_min, 0, y_max - 1) vis_image = cv2.rectangle(vis_image, (x_min, y_min), (x_max, y_max), color=(0, 255, 0), thickness=2) return vis_image def tensor_from_rgb_image(image: np.ndarray) -> torch.Tensor: image = np.ascontiguousarray(np.transpose(image, (2, 0, 1))) return torch.from_numpy(image)
455
8,027
<gh_stars>1000+ /* * Copyright (c) Facebook, Inc. and 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. */ package com.facebook.buck.features.go; import static org.junit.Assert.assertThat; import com.facebook.buck.core.config.FakeBuckConfig; import com.facebook.buck.cxx.toolchain.CxxPlatformUtils; import com.facebook.buck.io.AlwaysFoundExecutableFinder; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem; import com.facebook.buck.util.FakeProcessExecutor; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Test; public class GoPlatformFactoryTest { @Test public void getPlatform() throws IOException { ProjectFilesystem filesystem = new FakeProjectFilesystem(); Path root = filesystem.resolve("root"); filesystem.mkdirs(root); GoPlatformFactory factory = ImmutableGoPlatformFactory.of( FakeBuckConfig.builder() .setFilesystem(filesystem) .setSections( ImmutableMap.of( "section", ImmutableMap.of( "os", "linux", "arch", "amd64", "root", root.toString(), "tool_dir", root.toString()))) .build(), new FakeProcessExecutor(), new AlwaysFoundExecutableFinder(), CxxPlatformUtils.DEFAULT_PLATFORMS, CxxPlatformUtils.DEFAULT_UNRESOLVED_PLATFORM); GoPlatform platform = factory.getPlatform("section", CxxPlatformUtils.DEFAULT_PLATFORM_FLAVOR); assertThat(platform.getGoOs(), Matchers.equalTo(GoOs.LINUX)); assertThat(platform.getGoArch(), Matchers.equalTo(GoArch.AMD64)); } }
1,052
3,252
<filename>mmf/utils/download.py #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # Original taken from ParlAI https://git.io/JvjfS, this file has been # adapted for MMF use cases. """ Utilities for downloading and building data. These can be replaced if your particular file system does not support them. """ import collections import datetime import hashlib import io import json import os import shutil import time from pathlib import Path import numpy as np import requests import tqdm from mmf.utils.file_io import PathManager from mmf.utils.general import get_absolute_path from PIL import Image class DownloadableFile: """ A class used to abstract any file that has to be downloaded online. Originally taken from ParlAI, this file has been modified for MMF specific use cases. Any dataset/model that needs to download a file needs to have a list RESOURCES that have objects of this class as elements. The class automatically figures out if the file is from Google Drive. This class provides the following functionality: - Download a file from a URL / Google Drive - Decompress the file if compressed - Checksum for the downloaded file - Send HEAD request to validate URL or Google Drive link - If the file is present and checksum is same, it won't be redownloaded Raises: AssertionError: If while downloading checksum of the files fails. """ GOOGLE_DRIVE_SUBSTR = "drive.google" MMF_PREFIX = "mmf://" MMF_PREFIX_REPLACEMENT = "https://dl.fbaipublicfiles.com/mmf/data/" def __init__( self, url, file_name, hashcode=None, compressed=True, delete_original=False, dest_folder=None, ): """ An object of this class needs to be created with: Args: url (string): URL or Google Drive id to download from file_name (string): File name that the file should be named hashcode (string, optional): SHA256 hashcode of the downloaded file. Defaults to None. Won't be checked if not passed. compressed (bool, optional): False if the file is not compressed. Defaults to True. delete_original (bool, optional): If compressed whether to delete original. Defaults to False. dest_folder (str, optional): Folder which will be appended to destination path provided when downloading. Defaults to None. """ self._url = self._parse_url(url) self._file_name = file_name self._hashcode = hashcode self._compressed = compressed self._from_google = self._url.find(self.GOOGLE_DRIVE_SUBSTR) != -1 if self._from_google: assert "id=" in self._url, "Google Drive URL should have Google Drive ID" self._url = self._url.split("=")[-1] self._delete_original = delete_original self._dest_folder = dest_folder def _parse_url(self, url): if url.find(self.MMF_PREFIX) == -1: return url else: return self.MMF_PREFIX_REPLACEMENT + url[len(self.MMF_PREFIX) :] def checksum(self, download_path): """ Checksum on a given file. Args: download_path (string): path to the downloaded file. """ if self._hashcode is None: print(f"[ Checksum not provided, skipping for {self._file_name}]") return sha256_hash = hashlib.sha256() destination = os.path.join(download_path, self._file_name) if not PathManager.isfile(destination): # File is not present, nothing to checksum return with PathManager.open(destination, "rb") as f: print(f"[ Starting checksum for {self._file_name}]") for byte_block in iter(lambda: f.read(65536), b""): sha256_hash.update(byte_block) if sha256_hash.hexdigest() != self._hashcode: # remove_dir(download_path) raise AssertionError( f"[ Checksum for {self._file_name} from \n{self._url}\n" "does not match the expected checksum. Please try again. ]" ) else: print(f"[ Checksum successful for {self._file_name}]") def download_file(self, download_path): downloaded = False redownload = False if self._dest_folder is not None: download_path = str(Path(f"{download_path}/{self._dest_folder}")) make_dir(download_path) try: self.checksum(download_path) except AssertionError: # File exists but checksum has changed. Will be redownloaded print(f"[ Checksum changed for {download_path}. Redownloading]") redownload = True if self._from_google: downloaded = download_from_google_drive( self._url, os.path.join(download_path, self._file_name), redownload=redownload, ) else: downloaded = download( self._url, download_path, self._file_name, redownload=redownload ) # If download actually happened, then only checksum again and decompress if downloaded: self.checksum(download_path) if self._compressed: decompress(download_path, self._file_name, self._delete_original) def built(path, version_string=None): """ Check if '.built' flag has been set for that task. If a version_string is provided, this has to match, or the version is regarded as not built. Version_string are generally the dataset version + the date the file was last updated. If this doesn't match, dataset will be mark not built. This makes sure that if we update our features or anything else features are updated for the end user. """ if version_string: fname = os.path.join(path, ".built.json") if not PathManager.isfile(fname): return False else: with PathManager.open(fname, "r") as read: text = json.load(read) return text.get("version", None) == version_string else: return PathManager.isfile(os.path.join(path, ".built.json")) def mark_done(path, version_string=None): """ Mark this path as prebuilt. Marks the path as done by adding a '.built' file with the current timestamp plus a version description string if specified. Args: path (str): The file path to mark as built version_string (str): The version of this dataset """ data = {} data["created_at"] = str(datetime.datetime.today()) data["version"] = version_string with PathManager.open(os.path.join(path, ".built.json"), "w") as f: json.dump(data, f) def download(url, path, fname, redownload=True, disable_tqdm=False): """ Download file using `requests`. If ``redownload`` is set to false, then will not download tar file again if it is present (default ``True``). Returns whether download actually happened or not """ outfile = os.path.join(path, fname) download = not PathManager.isfile(outfile) or redownload retry = 5 exp_backoff = [2**r for r in reversed(range(retry))] pbar = None if download: # First test if the link is actually downloadable check_header(url) if not disable_tqdm: print("[ Downloading: " + url + " to " + outfile + " ]") pbar = tqdm.tqdm( unit="B", unit_scale=True, desc=f"Downloading {fname}", disable=disable_tqdm ) while download and retry >= 0: resume_file = outfile + ".part" resume = PathManager.isfile(resume_file) if resume: resume_pos = os.path.getsize(resume_file) mode = "ab" else: resume_pos = 0 mode = "wb" response = None with requests.Session() as session: try: header = ( {"Range": "bytes=%d-" % resume_pos, "Accept-Encoding": "identity"} if resume else {} ) response = session.get(url, stream=True, timeout=5, headers=header) # negative reply could be 'none' or just missing if resume and response.headers.get("Accept-Ranges", "none") == "none": resume_pos = 0 mode = "wb" CHUNK_SIZE = 32768 total_size = int(response.headers.get("Content-Length", -1)) # server returns remaining size if resuming, so adjust total total_size += resume_pos pbar.total = total_size done = resume_pos with PathManager.open(resume_file, mode) as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) if total_size > 0: done += len(chunk) if total_size < done: # don't freak out if content-length was too small total_size = done pbar.total = total_size pbar.update(len(chunk)) break except ( requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout, ): retry -= 1 pbar.clear() if retry >= 0: print("Connection error, retrying. (%d retries left)" % retry) time.sleep(exp_backoff[retry]) else: print("Retried too many times, stopped retrying.") finally: if response: response.close() if retry < 0: raise RuntimeWarning("Connection broken too many times. Stopped retrying.") if download and retry > 0: pbar.update(done - pbar.n) if done < total_size: raise RuntimeWarning( "Received less data than specified in " + "Content-Length header for " + url + ". There may be a download problem." ) move(resume_file, outfile) if pbar: pbar.close() return download def check_header(url, from_google=False): """ Performs a HEAD request to check if the URL / Google Drive ID is live. """ session = requests.Session() if from_google: URL = "https://docs.google.com/uc?export=download" response = session.head(URL, params={"id": url}, stream=True) else: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/77.0.3865.90 Safari/537.36" } response = session.head(url, allow_redirects=True, headers=headers) status = response.status_code session.close() assert status == 200, ( "The url {} is broken. If this is not your own url," + " please open up an issue on GitHub" ).format(url) def download_pretrained_model(model_name, *args, **kwargs): import omegaconf from mmf.utils.configuration import get_mmf_env, load_yaml from omegaconf import OmegaConf model_zoo = load_yaml(get_mmf_env(key="model_zoo")) OmegaConf.set_struct(model_zoo, True) OmegaConf.set_readonly(model_zoo, True) data_dir = get_absolute_path(get_mmf_env("data_dir")) model_data_dir = os.path.join(data_dir, "models") download_path = os.path.join(model_data_dir, model_name) try: model_config = OmegaConf.select(model_zoo, model_name) except omegaconf.errors.OmegaConfBaseException as e: print(f"No such model name {model_name} defined in mmf zoo") raise e if "version" not in model_config or "resources" not in model_config: # Version and Resources are not present time to try the defaults try: model_config = model_config.defaults download_path = os.path.join(model_data_dir, model_name + ".defaults") except omegaconf.errors.OmegaConfBaseException as e: print( f"Model name {model_name} doesn't specify 'resources' and 'version' " "while no defaults have been provided" ) raise e # Download requirements if any specified by "zoo_requirements" field # This can either be a list or a string if "zoo_requirements" in model_config: requirements = model_config.zoo_requirements if isinstance(requirements, str): requirements = [requirements] for item in requirements: download_pretrained_model(item, *args, **kwargs) version = model_config.version resources = model_config.resources download_resources(resources, download_path, version) return download_path def download_resources(resources, download_path, version): is_built = built(download_path, version_string=version) if not is_built: make_dir(download_path) # Make it list if it isn't if not isinstance(resources, collections.abc.Sequence): resources = [resources] if len(resources) == 0: return for resource in resources: download_resource(resource, download_path) mark_done(download_path, version_string=version) def download_resource(resource, download_path): if isinstance(resource, collections.abc.Mapping): # Try building DownloadableFile class object from resource dict resource = DownloadableFile(**resource) assert isinstance(resource, DownloadableFile) resource.download_file(download_path) def make_dir(path): """ Make the directory and any nonexistent parent directories (`mkdir -p`). """ # the current working directory is a fine path if path != "": PathManager.mkdirs(path) def move(path1, path2): """ Rename the given file. """ shutil.move(path1, path2) def copy(path1, path2): """ Copy the given file from path1 to path2. """ shutil.copy(path1, path2) def remove_dir(path): """ Remove the given directory, if it exists. """ shutil.rmtree(path, ignore_errors=True) def decompress(path, fname, delete_original=True): """ Unpack the given archive file to the same directory. Args: path(str): The folder containing the archive. Will contain the contents. fname (str): The filename of the archive file. delete_original (bool, optional): If true, the archive will be deleted after extraction. Default to True. """ print("Unpacking " + fname) fullpath = os.path.join(path, fname) shutil.unpack_archive(fullpath, path) if delete_original: os.remove(fullpath) def _get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith("download_warning"): return value return None def download_from_google_drive(gd_id, destination, redownload=True): """ Use the requests package to download a file from Google Drive. """ download = not PathManager.isfile(destination) or redownload URL = "https://docs.google.com/uc?export=download" if not download: return download else: # Check first if link is live check_header(gd_id, from_google=True) with requests.Session() as session: response = session.get(URL, params={"id": gd_id}, stream=True) token = _get_confirm_token(response) if token: response.close() params = {"id": gd_id, "confirm": token} response = session.get(URL, params=params, stream=True) CHUNK_SIZE = 32768 with PathManager.open(destination, "wb") as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) response.close() return download def get_image_from_url(url): response = requests.get(url) img = np.array(Image.open(io.BytesIO(response.content))) return img
7,270
468
<filename>algorithms/greedy/minimumProductSubset.cpp //Find minimum product subset in an array using Greedy method #include <bits/stdc++.h> using namespace std; int calculate(int a[], int n) { if (n == 1) return a[0]; int max_neg = INT_MIN; int min_pos = INT_MAX; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { if (a[i] == 0) { count_zero++; continue; } if (a[i] < 0) { count_neg++; max_neg = max(max_neg, a[i]); } if (a[i] > 0) min_pos = min(min_pos, a[i]); prod = prod * a[i]; } if (count_zero == n || (count_neg == 0 && count_zero > 0)) return 0; if (count_neg == 0) return min_pos; if (!(count_neg & 1) && count_neg != 0) { prod = prod / max_neg; } return prod; } int main() { int n; cout<<"Enter size of array: "; cin>>n; int a[n]; cout<<"\nEnter array elements: "; for(int i=0;i<n;i++) cin>>a[i]; cout << "\nAnswer: "<<calculate(a, n); return 0; }
453
649
<filename>demos/imagetagger/imagetagger/views.py<gh_stars>100-1000 import asyncio from typing import Dict from concurrent.futures import ProcessPoolExecutor import aiohttp_jinja2 from aiohttp import web from .worker import predict from .utils import Config class SiteHandler: def __init__(self, conf: Config, executor: ProcessPoolExecutor) -> None: self._conf = conf self._executor = executor self._loop = asyncio.get_event_loop() @aiohttp_jinja2.template('index.html') async def index(self, request: web.Request) -> Dict[str, str]: return {} async def predict(self, request: web.Request) -> web.Response: form = await request.post() raw_data = form['file'].file.read() executor = request.app['executor'] r = self._loop.run_in_executor raw_data = await r(executor, predict, raw_data) # raw_data = predict(raw_data) headers = {'Content-Type': 'application/json'} return web.Response(body=raw_data, headers=headers)
395
1,085
<filename>dac/backend/src/main/java/com/dremio/dac/explore/ExtractListRecommender.java<gh_stars>1000+ /* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.dac.explore; import static com.dremio.dac.proto.model.dataset.ExtractListRuleType.multiple; import static com.dremio.dac.proto.model.dataset.ExtractListRuleType.single; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dremio.common.exceptions.UserException; import com.dremio.dac.explore.JSONElementLocator.ArrayJsonPathElement; import com.dremio.dac.explore.JSONElementLocator.JsonPath; import com.dremio.dac.explore.JSONElementLocator.JsonSelection; import com.dremio.dac.explore.model.extract.Selection; import com.dremio.dac.explore.udfs.ExtractList; import com.dremio.dac.proto.model.dataset.DataType; import com.dremio.dac.proto.model.dataset.Direction; import com.dremio.dac.proto.model.dataset.ExtractListRule; import com.dremio.dac.proto.model.dataset.ExtractRuleMultiple; import com.dremio.dac.proto.model.dataset.ExtractRuleSingle; import com.dremio.dac.proto.model.dataset.ListSelection; import com.dremio.dac.proto.model.dataset.Offset; import com.dremio.dac.service.errors.ClientErrorException; /** * Extract list transformation recommendation suggestions and generating examples and number of matches in sample data * for each recommendation. */ public class ExtractListRecommender extends Recommender<ExtractListRule, Selection> { private static final Logger logger = LoggerFactory.getLogger(ReplaceRecommender.class); @Override public List<ExtractListRule> getRules(Selection selection, DataType selColType) { checkArgument(selColType == DataType.LIST, "Extract list items is supported only on LIST type columns"); JsonSelection jsonSelection; try { jsonSelection = new JSONElementLocator(selection.getCellText()).locate(selection.getOffset(), selection.getOffset() + selection.getLength()); } catch (IOException e) { throw new ClientErrorException(String.format("invalid JSON: %s", selection.getCellText()), e); } ArrayJsonPathElement start = extractArrayIndex(jsonSelection.getStart()); ArrayJsonPathElement end = extractArrayIndex(jsonSelection.getEnd()); List<ExtractListRule> rules = new ArrayList<>(); if (start == end) { rules.add(new ExtractListRule(single).setSingle(new ExtractRuleSingle(start.getPosition()))); } else { ListSelection[] selections = { new ListSelection(fromTheStart(start), fromTheStart(end)), new ListSelection(fromTheStart(start), fromTheEnd(end)), new ListSelection(fromTheEnd(start), fromTheStart(end)), new ListSelection(fromTheEnd(start), fromTheEnd(end)) }; for (ListSelection listSelection : selections) { rules.add((new ExtractListRule(multiple) .setMultiple( new ExtractRuleMultiple(listSelection) ))); } } return rules; } @Override public TransformRuleWrapper<ExtractListRule> wrapRule(ExtractListRule rule) { switch (rule.getType()) { case single: return new ExtractListSingleTransformRuleWrapper(rule); case multiple: return new ExtractListMultipleTransformRuleWrapper(rule); default: throw UserException.unsupportedError() .message("Unsupported list extract type: " + rule.getType()) .build(logger); } } private static class ExtractListSingleTransformRuleWrapper extends TransformRuleWrapper<ExtractListRule> { private final ExtractListRule rule; ExtractListSingleTransformRuleWrapper(ExtractListRule rule) { this.rule = rule; } @Override public String getMatchFunctionExpr(String input) { final String subList = getFunctionExpr(input); return String.format("%s IS NOT NULL", subList); } @Override public boolean canGenerateExamples() { return false; } @Override public String getExampleFunctionExpr(String input) { throw new UnsupportedOperationException("Example generation is not supported for extract list transform."); } @Override public String getFunctionExpr(String expr, Object... args) { return String.format("%s[%d]", expr, rule.getSingle().getIndex()); } @Override public ExtractListRule getRule() { return rule; } @Override public String describe() { return "Element: " + String.valueOf(getRule().getSingle().getIndex()); } } private static class ExtractListMultipleTransformRuleWrapper extends TransformRuleWrapper<ExtractListRule> { private final ExtractListRule rule; ExtractListMultipleTransformRuleWrapper(ExtractListRule rule) { this.rule = rule; } @Override public String getMatchFunctionExpr(String input) { final String subList = getFunctionExpr(input); // If the sublist contains at least one element, then a match is found. return String.format("%s(%s) > 0", ExtractList.LIST_LENGTH, subList); } @Override public boolean canGenerateExamples() { return false; } @Override public String getExampleFunctionExpr(String input) { throw new UnsupportedOperationException("Example generation is not supported for extract list transform."); } @Override public String getFunctionExpr(String expr, Object... args) { final ListSelection sel = rule.getMultiple().getSelection(); return String.format("%s(%s, %d, %s)", ExtractList.SUB_LIST, expr, getOffset(sel.getStart()), getLength(expr, sel.getStart(), sel.getEnd()) ); } @Override public ExtractListRule getRule() { return rule; } @Override public String describe() { ListSelection s = rule.getMultiple().getSelection(); return ExtractRecommender.describePlacement(s.getStart(), s.getEnd()) ; } } private static ArrayJsonPathElement extractArrayIndex(JsonPath path) { if (path.size() == 1 && path.last().isArray()) { return path.last().asArray(); } throw new ClientErrorException(String.format("not an array selection: %s", path)); } private static Offset fromTheEnd(ArrayJsonPathElement a) { return new Offset(a.getCount() - a.getPosition() - 1, Direction.FROM_THE_END); } private static Offset fromTheStart(ArrayJsonPathElement a) { return new Offset(a.getPosition(), Direction.FROM_THE_START); } private static int getOffset(Offset start) { // sublist takes offset in range [1, length] return start.getDirection() == Direction.FROM_THE_END ? -1 * (start.getValue() + 1) : (start.getValue() + 1); } private static String getLength(String expr, Offset start, Offset end) { // Both ends are inclusive if (start.getDirection() == Direction.FROM_THE_END) { if (end.getDirection() == Direction.FROM_THE_END) { // (length(str) - end - 1) - (length(str) - start - 1) + 1 = start - end return String.valueOf(start.getValue() - end.getValue() + 1); } // end - (length(str) - start - 1) + 1 = -length(str) + start + end + 2 return format("-array_length(%s) + %d", expr, start.getValue() + end.getValue() + 2); } if (end.getDirection() == Direction.FROM_THE_END) { // (length(str) - end - 1) - start + 1 = length(str) - (start + end) return format("array_length(%s) - %d", expr, start.getValue() + end.getValue()); } // end - start return String.valueOf(end.getValue() - start.getValue() + 1); } }
2,930
828
/* * Copyright 2008-2009 the original author or 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 net.hasor.core.container; import net.hasor.core.*; import net.hasor.core.aop.DynamicClass; import net.hasor.core.info.AopBindInfoAdapter; import net.hasor.core.info.DefaultBindInfoProviderAdapter; import net.hasor.test.core.aop.custom.MyAopInterceptor; import net.hasor.test.core.aop.ignore.level.LevelFooFunction; import net.hasor.test.core.aop.ignore.level.l2.L2FooFunction; import net.hasor.test.core.aop.ignore.thread.ThreadFooFunction; import net.hasor.test.core.aop.ignore.types.*; import net.hasor.test.core.basic.pojo.PojoBean; import net.hasor.utils.supplier.InstanceProvider; import org.junit.Before; import org.junit.Test; import org.powermock.api.mockito.PowerMockito; import java.lang.reflect.Method; import java.util.function.Predicate; public class AopBeanContainerTest { private AppContext appContext = null; @Before public void beforeTest() { this.appContext = PowerMockito.mock(AppContext.class); PowerMockito.when(appContext.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); } @Test public void aopTest1() { Environment mockEnv = Hasor.create().buildEnvironment(); AppContext appContext = PowerMockito.mock(AppContext.class); PowerMockito.when(appContext.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); BeanContainer container = new BeanContainer(mockEnv); container.preInitialize(); // DefaultBindInfoProviderAdapter<AopBindInfoAdapter> adapter = container.getBindInfoContainer().createInfoAdapter(AopBindInfoAdapter.class, null); Predicate<Class<?>> ma = aClass -> true; Predicate<Method> mb = aMethod -> true; MyAopInterceptor.resetInit(); MethodInterceptor interceptor = new MyAopInterceptor(); adapter.setCustomerProvider(Provider.of(new AopBindInfoAdapter(ma, mb, interceptor))); // PojoBean bean = container.providerOnlyType(PojoBean.class, appContext, null).get(); // assert !MyAopInterceptor.isCalled(); bean.setUuid("abc"); assert MyAopInterceptor.isCalled(); MyAopInterceptor.resetInit(); } @Test public void aopTest2() { Environment mockEnv = Hasor.create().buildEnvironment(); AppContext appContext = PowerMockito.mock(AppContext.class); PowerMockito.when(appContext.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); BeanContainer container = new BeanContainer(mockEnv); container.preInitialize(); // DefaultBindInfoProviderAdapter<AopBindInfoAdapter> adapter = container.getBindInfoContainer().createInfoAdapter(AopBindInfoAdapter.class, null); Predicate<Class<?>> ma = aClass -> false; Predicate<Method> mb = aMethod -> true; MyAopInterceptor.resetInit(); MethodInterceptor interceptor = new MyAopInterceptor(); adapter.setCustomerProvider(InstanceProvider.of(new AopBindInfoAdapter(ma, mb, interceptor))); // PojoBean bean = container.providerOnlyType(PojoBean.class, appContext, null).get(); // assert !MyAopInterceptor.isCalled(); bean.setUuid("abc"); assert !MyAopInterceptor.isCalled(); MyAopInterceptor.resetInit(); } @Test public void aopTest3() { Environment mockEnv = Hasor.create().buildEnvironment(); AppContext appContext = PowerMockito.mock(AppContext.class); PowerMockito.when(appContext.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader()); BeanContainer container = new BeanContainer(mockEnv); container.preInitialize(); // DefaultBindInfoProviderAdapter<AopBindInfoAdapter> adapter = container.getBindInfoContainer().createInfoAdapter(AopBindInfoAdapter.class, null); Predicate<Class<?>> ma = aClass -> true; Predicate<Method> mb = aMethod -> true; MethodInterceptor interceptor = new MyAopInterceptor(); adapter.setCustomerProvider(InstanceProvider.of(new AopBindInfoAdapter(ma, mb, interceptor))); // { GrandFatherBean bean1 = container.providerOnlyType(GrandFatherBean.class, appContext, null).get(); JamesBean bean2 = container.providerOnlyType(JamesBean.class, appContext, null).get(); JamesSonBean bean3 = container.providerOnlyType(JamesSonBean.class, appContext, null).get(); WilliamBean bean4 = container.providerOnlyType(WilliamBean.class, appContext, null).get(); WilliamSonBean bean5 = container.providerOnlyType(WilliamSonBean.class, appContext, null).get(); assert bean1 instanceof DynamicClass; assert !(bean2 instanceof DynamicClass); assert bean3 instanceof DynamicClass; assert !(bean4 instanceof DynamicClass); assert !(bean5 instanceof DynamicClass); } // { L2FooFunction bean1 = container.providerOnlyType(L2FooFunction.class, appContext, null).get(); LevelFooFunction bean2 = container.providerOnlyType(LevelFooFunction.class, appContext, null).get(); ThreadFooFunction bean3 = container.providerOnlyType(ThreadFooFunction.class, appContext, null).get(); assert !(bean1 instanceof DynamicClass); assert bean2 instanceof DynamicClass; assert !(bean3 instanceof DynamicClass); } // // } }
2,262
5,169
{ "name": "ForismaticKit", "version": "1.0.0", "summary": "📚 Access numerous of quotations available in Forismatic service with this small client. 🔆", "description": "📚 Love quotes? Write quotations app? Than this framework is for you! Access numerous of quotations available in Forismatic service with this small API client. 🔆", "homepage": "https://github.com/anverbogatov/ForismaticKit", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/anverbogatov/ForismaticKit.git", "tag": "1.0.0" }, "source_files": "ForismaticKit/**/*.swift", "pushed_with_swift_version": "4.0" }
282
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. #include "third_party/blink/renderer/core/layout/ng/inline/ng_text_offset.h" #include <ostream> namespace blink { std::ostream& operator<<(std::ostream& ostream, const NGTextOffset& offset) { return ostream << "{" << offset.start << ", " << offset.end << "}"; } } // namespace blink
144
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.app.Activity; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.chromium.base.Callback; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.firstrun.FirstRunStatus; import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.content.R; import org.chromium.content_public.browser.ActionModeCallbackHelper; import org.chromium.content_public.browser.WebContents; import org.chromium.testing.local.LocalRobolectricTestRunner; /** * Unit tests for the {@link ChromeActionModeCallback}. */ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class ChromeActionModeCallbackTest { @Mock private Tab mTab; @Mock private ActionModeCallbackHelper mActionModeCallbackHelper; @Mock private ActionMode mActionMode; @Mock private Menu mMenu; private class TestChromeActionModeCallback extends ChromeActionModeCallback { public TestChromeActionModeCallback(Tab tab, ActionModeCallbackHelper helper) { super(tab, null); } @Override public ActionModeCallbackHelper getActionModeCallbackHelper(WebContents webContents) { return mActionModeCallbackHelper; } } private TestChromeActionModeCallback mActionModeCallback; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); ContextUtils.initApplicationContextForTests(RuntimeEnvironment.application); CommandLine.init(null); RecordUserAction.setDisabledForTests(true); mActionModeCallback = Mockito.spy(new TestChromeActionModeCallback(mTab, mActionModeCallbackHelper)); } @After public void tearDown() { FirstRunStatus.setFirstRunFlowComplete(false); RecordUserAction.setDisabledForTests(false); } @Test public void testOptionsBeforeFre() { FirstRunStatus.setFirstRunFlowComplete(false); mActionModeCallback.onCreateActionMode(mActionMode, mMenu); Mockito.verify(mActionModeCallbackHelper) .setAllowedMenuItems(ActionModeCallbackHelper.MENU_ITEM_PROCESS_TEXT | ActionModeCallbackHelper.MENU_ITEM_SHARE); } @Test public void testOptionsAfterFre() { FirstRunStatus.setFirstRunFlowComplete(true); mActionModeCallback.onCreateActionMode(mActionMode, mMenu); Mockito.verify(mActionModeCallbackHelper) .setAllowedMenuItems(ActionModeCallbackHelper.MENU_ITEM_PROCESS_TEXT | ActionModeCallbackHelper.MENU_ITEM_SHARE | ActionModeCallbackHelper.MENU_ITEM_WEB_SEARCH); } @Test public void testShareTriggersSearchPromo() { FirstRunStatus.setFirstRunFlowComplete(true); Mockito.when(mActionModeCallbackHelper.isActionModeValid()).thenReturn(true); Mockito.when(mActionModeCallbackHelper.getSelectedText()).thenReturn("OhHai"); LocaleManager localeManager = Mockito.spy(new LocaleManager() { @Override public void showSearchEnginePromoIfNeeded( Activity activity, Callback<Boolean> onSearchEngineFinalized) { onSearchEngineFinalized.onResult(true); } }); LocaleManager.setInstanceForTest(localeManager); MenuItem shareItem = Mockito.mock(MenuItem.class); Mockito.when(shareItem.getItemId()).thenReturn(R.id.select_action_menu_web_search); mActionModeCallback.onActionItemClicked(mActionMode, shareItem); Mockito.verify(localeManager).showSearchEnginePromoIfNeeded(Mockito.any(), Mockito.any()); } }
1,634
623
<gh_stars>100-1000 // Copyright (C) 2021 The Android Open Source Project // // 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.google.gerrit.server.cancellation; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.gerrit.testing.GerritJUnit.assertThrows; import com.google.common.collect.ImmutableSet; import com.google.gerrit.server.cancellation.RequestStateContext.NonCancellableOperationContext; import org.junit.Test; public class RequestStateContextTest { @Test public void openContext() { assertNoRequestStateProviders(); RequestStateProvider requestStateProvider1 = new TestRequestStateProvider(); try (RequestStateContext requestStateContext = RequestStateContext.open().addRequestStateProvider(requestStateProvider1)) { RequestStateProvider requestStateProvider2 = new TestRequestStateProvider(); requestStateContext.addRequestStateProvider(requestStateProvider2); assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); } assertNoRequestStateProviders(); } @Test public void openNestedContexts() { assertNoRequestStateProviders(); RequestStateProvider requestStateProvider1 = new TestRequestStateProvider(); try (RequestStateContext requestStateContext = RequestStateContext.open().addRequestStateProvider(requestStateProvider1)) { RequestStateProvider requestStateProvider2 = new TestRequestStateProvider(); requestStateContext.addRequestStateProvider(requestStateProvider2); assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); RequestStateProvider requestStateProvider3 = new TestRequestStateProvider(); try (RequestStateContext requestStateContext2 = RequestStateContext.open().addRequestStateProvider(requestStateProvider3)) { RequestStateProvider requestStateProvider4 = new TestRequestStateProvider(); requestStateContext2.addRequestStateProvider(requestStateProvider4); assertRequestStateProviders( ImmutableSet.of( requestStateProvider1, requestStateProvider2, requestStateProvider3, requestStateProvider4)); } assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); } assertNoRequestStateProviders(); } @Test public void openNestedContextsWithSameRequestStateProviders() { assertNoRequestStateProviders(); RequestStateProvider requestStateProvider1 = new TestRequestStateProvider(); try (RequestStateContext requestStateContext = RequestStateContext.open().addRequestStateProvider(requestStateProvider1)) { RequestStateProvider requestStateProvider2 = new TestRequestStateProvider(); requestStateContext.addRequestStateProvider(requestStateProvider2); assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); try (RequestStateContext requestStateContext2 = RequestStateContext.open().addRequestStateProvider(requestStateProvider1)) { requestStateContext2.addRequestStateProvider(requestStateProvider2); assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); } assertRequestStateProviders(ImmutableSet.of(requestStateProvider1, requestStateProvider2)); } assertNoRequestStateProviders(); } @Test public void abortIfCancelled_noRequestStateProvider() { assertNoRequestStateProviders(); // Calling abortIfCancelled() shouldn't throw an exception. RequestStateContext.abortIfCancelled(); } @Test public void abortIfCancelled_requestNotCancelled() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) {} })) { // Calling abortIfCancelled() shouldn't throw an exception. RequestStateContext.abortIfCancelled(); } } @Test public void abortIfCancelled_requestCancelled() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) { onCancelled.onCancel( RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* message= */ null); } })) { RequestCancelledException requestCancelledException = assertThrows( RequestCancelledException.class, () -> RequestStateContext.abortIfCancelled()); assertThat(requestCancelledException) .hasMessageThat() .isEqualTo("Request cancelled: CLIENT_CLOSED_REQUEST"); assertThat(requestCancelledException.getCancellationReason()) .isEqualTo(RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST); assertThat(requestCancelledException.getCancellationMessage()).isEmpty(); } } @Test public void abortIfCancelled_requestCancelled_withMessage() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) { onCancelled.onCancel( RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED, "deadline = 10m"); } })) { RequestCancelledException requestCancelledException = assertThrows( RequestCancelledException.class, () -> RequestStateContext.abortIfCancelled()); assertThat(requestCancelledException) .hasMessageThat() .isEqualTo("Request cancelled: SERVER_DEADLINE_EXCEEDED (deadline = 10m)"); assertThat(requestCancelledException.getCancellationReason()) .isEqualTo(RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED); assertThat(requestCancelledException.getCancellationMessage()).hasValue("deadline = 10m"); } } @Test public void nonCancellableOperation_requestNotCanclled() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) {} })) { // Calling abortIfCancelled() shouldn't throw an exception. RequestStateContext.abortIfCancelled(); try (NonCancellableOperationContext nonCancellableOperationContext = RequestStateContext.startNonCancellableOperation()) { // Calling abortIfCancelled() shouldn't throw an exception. RequestStateContext.abortIfCancelled(); } // Calling abortIfCancelled() shouldn't throw an exception. RequestStateContext.abortIfCancelled(); } } @Test public void nonCancellableOperationNotAborted() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) { onCancelled.onCancel( RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* message= */ null); } })) { assertThrows(RequestCancelledException.class, () -> RequestStateContext.abortIfCancelled()); boolean cancelledOnClose = false; try (NonCancellableOperationContext nonCancellableOperationContext = RequestStateContext.startNonCancellableOperation()) { // Calling abortIfCancelled() shouldn't throw an exception since we are within a // non-cancellable operation. RequestStateContext.abortIfCancelled(); } catch (RequestCancelledException e) { // The request is expected to get aborted on close of the non-cancellable operation. cancelledOnClose = true; } assertThat(cancelledOnClose).isTrue(); } } @Test public void nestedNonCancellableOperationNotAborted() { try (RequestStateContext requestStateContext = RequestStateContext.open() .addRequestStateProvider( new RequestStateProvider() { @Override public void checkIfCancelled(OnCancelled onCancelled) { onCancelled.onCancel( RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* message= */ null); } })) { assertThrows(RequestCancelledException.class, () -> RequestStateContext.abortIfCancelled()); boolean cancelledOnClose = false; try (NonCancellableOperationContext nonCancellableOperationContext = RequestStateContext.startNonCancellableOperation()) { // Calling abortIfCancelled() shouldn't throw an exception since we are within a // non-cancellable operation. RequestStateContext.abortIfCancelled(); try (NonCancellableOperationContext nestedNonCancellableOperationContext = RequestStateContext.startNonCancellableOperation()) { // Calling abortIfCancelled() shouldn't throw an exception since we are within a // non-cacellable operation. RequestStateContext.abortIfCancelled(); // Close of the nestedNonCancellableOperationContext shouldn't throw an exception since // the outer nonCancellableOperationContext is still open. } // Calling abortIfCancelled() shouldn't throw an exception since we are within a // non-cancellable operation. RequestStateContext.abortIfCancelled(); } catch (RequestCancelledException e) { // The request is expected to get aborted on close of the non-cancellable operation. cancelledOnClose = true; } assertThat(cancelledOnClose).isTrue(); } } private void assertNoRequestStateProviders() { assertRequestStateProviders(ImmutableSet.of()); } private void assertRequestStateProviders( ImmutableSet<RequestStateProvider> expectedRequestStateProviders) { assertThat(RequestStateContext.getRequestStateProviders()) .containsExactlyElementsIn(expectedRequestStateProviders); } private static class TestRequestStateProvider implements RequestStateProvider { @Override public void checkIfCancelled(OnCancelled onCancelled) {} } }
4,154
348
{"nom":"Villécloye","circ":"2ème circonscription","dpt":"Meuse","inscrits":133,"abs":70,"votants":63,"blancs":10,"nuls":1,"exp":52,"res":[{"nuance":"REM","nom":"<NAME>","voix":34},{"nuance":"FN","nom":"<NAME>","voix":18}]}
90
3,986
<reponame>liuxiaoqiang1018/XUI /* * Copyright (C) 2020 xuexiangjys(<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.xuexiang.xuidemo.fragment.components.refresh.sample.selection; import android.view.View; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xui.utils.WidgetUtils; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseFragment; import com.xuexiang.xuidemo.utils.XToastUtils; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * @author xuexiang * @since 2020/9/2 8:55 PM */ @Page(name = "列表选择案例") public class ListSelectionFragment extends BaseFragment { @BindView(R.id.recyclerView) RecyclerView recyclerView; @BindView(R.id.tv_selection_total1) TextView tvSelectionTotal1; @BindView(R.id.tv_selection_total2) TextView tvSelectionTotal2; private SelectionListAdapter mAdapter; @Override protected int getLayoutId() { return R.layout.fragment_list_selection; } @Override protected TitleBar initTitle() { TitleBar titleBar = super.initTitle(); titleBar.addAction(new TitleBar.TextAction("保存") { @Override public void performAction(View view) { List<SelectionItem> result = mAdapter.getSelectionResult(); StringBuilder sb = new StringBuilder("选择结果:"); for (SelectionItem item : result) { sb.append("\n") .append(item.subjectName) .append(":") .append(getSelectionName(item.selection)); } XToastUtils.toast(sb.toString()); } }); return titleBar; } public String getSelectionName(int selection) { if (selection == 0) { return "符合"; } else if (selection == 1) { return "不符合"; } else { return "未选择"; } } @Override protected void initViews() { WidgetUtils.initRecyclerView(recyclerView); recyclerView.setAdapter(mAdapter = new SelectionListAdapter()); mAdapter.refresh(getSelectionItems()); updateSelectResult(); } @Override protected void initListeners() { mAdapter.setOnSelectionChangedListener(item -> { updateSelectResult(); }); } private void updateSelectResult() { int[] count = mAdapter.getSelectionCount(); tvSelectionTotal1.setText(String.valueOf(count[0])); tvSelectionTotal2.setText(String.valueOf(count[1])); } private List<SelectionItem> getSelectionItems() { List<SelectionItem> items = new ArrayList<>(); items.add(new SelectionItem("项目名称", "符合", "不符合")); // TODO: 2020/9/2 模拟接口返回的数据 for (int i = 1; i <= 5; i++) { items.add(new SelectionItem("项目" + i)); } return items; } }
1,602
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/frame/immersive_mode_tester.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_command_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/frame/browser_view.h" ImmersiveModeTester::ImmersiveModeTester(Browser* browser) : browser_(browser) { scoped_observation_.Observe(GetBrowserView()->immersive_mode_controller()); } ImmersiveModeTester::~ImmersiveModeTester() = default; BrowserView* ImmersiveModeTester::GetBrowserView() { return BrowserView::GetBrowserViewForBrowser(browser_); } void ImmersiveModeTester::RunCommand(int command, int expected_index) { reveal_started_ = reveal_ended_ = false; browser_->command_controller()->ExecuteCommand(command); VerifyTabIndexAfterReveal(expected_index); } void ImmersiveModeTester::VerifyTabIndexAfterReveal(int expected_index) { if (!reveal_ended_) { reveal_loop_ = std::make_unique<base::RunLoop>(); reveal_loop_->Run(); } EXPECT_TRUE(reveal_ended_); EXPECT_EQ(expected_index, browser_->tab_strip_model()->active_index()); } void ImmersiveModeTester::WaitForFullscreenToExit() { if (GetBrowserView()->immersive_mode_controller()->IsEnabled()) { fullscreen_loop_ = std::make_unique<base::RunLoop>(); fullscreen_loop_->Run(); } ASSERT_FALSE(GetBrowserView()->immersive_mode_controller()->IsEnabled()); } void ImmersiveModeTester::OnImmersiveRevealStarted() { EXPECT_FALSE(reveal_started_); EXPECT_FALSE(reveal_ended_); reveal_started_ = true; EXPECT_TRUE(GetBrowserView()->immersive_mode_controller()->IsRevealed()); } void ImmersiveModeTester::OnImmersiveRevealEnded() { EXPECT_TRUE(reveal_started_); EXPECT_FALSE(reveal_ended_); reveal_started_ = false; reveal_ended_ = true; EXPECT_FALSE(GetBrowserView()->immersive_mode_controller()->IsRevealed()); if (reveal_loop_ && reveal_loop_->running()) reveal_loop_->Quit(); } void ImmersiveModeTester::OnImmersiveModeControllerDestroyed() { DCHECK(scoped_observation_.IsObserving()); scoped_observation_.Reset(); } void ImmersiveModeTester::OnImmersiveFullscreenExited() { if (fullscreen_loop_ && fullscreen_loop_->running()) fullscreen_loop_->Quit(); }
839
882
package water.api; /** * Basic page introducing tutorial for Random Forest on Iris * * @author michal */ public class TutorialRFIris extends TutorialWorkflow { private final transient TutorWorkflow _wf; private final static String[][] TUTORIAL_STEPS = new String[][]{ /* Title Short Summary File containing step description */ new String[] { "Step 1", "Introduction", "/tutorials/rf.iris/step1.html" }, new String[] { "Step 2", "Dataset inhale", "/tutorials/rf.iris/step2.html" }, new String[] { "Step 3", "Parsing the dataset", "/tutorials/rf.iris/step3.html" }, new String[] { "Step 4", "Inspecting the dataset", "/tutorials/rf.iris/step4.html" }, new String[] { "Step 5", "Building the model", "/tutorials/rf.iris/step5.html" }, new String[] { "Step 6", "Inspecting the model", "/tutorials/rf.iris/step6.html" }, new String[] { "Step 7", "Predict on a test set", "/tutorials/rf.iris/step7.html" }, new String[] { "Step 8", "Scoring the prediction", "/tutorials/rf.iris/step8.html" }, }; public TutorialRFIris() { _wf = new TutorWorkflow("Random Forest Tutorial"); int i = 1; for (String[] info : TUTORIAL_STEPS) { _wf.addStep(i++, new FileTutorStep(info)); } } @Override protected TutorWorkflow getWorkflow() { return _wf; } }
500
3,138
# Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the Local stochastic volatility model.""" from absl.testing import parameterized import numpy as np import tensorflow.compat.v2 as tf import tf_quant_finance as tff from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import bs = tff.black_scholes lsv = tff.experimental.local_stochastic_volatility volatility_surface = tff.experimental.pricing_platform.framework.market_data.volatility_surface # This function can't be moved to SetUp since that would break graph mode # execution def build_tensors(dim, spot, risk_free_rate): year = [[2021, 2022]] * dim month = [[1, 1]] * dim day = [[1, 1]] * dim expiries = tff.datetime.dates_from_year_month_day(year, month, day) valuation_date = [(2020, 1, 1)] expiry_times = tff.datetime.daycount_actual_365_fixed( start_date=valuation_date, end_date=expiries, dtype=tf.float64) moneyness = [[[0.1, 0.9, 1.0, 1.1, 3], [0.1, 0.9, 1.0, 1.1, 3]]] * dim strikes = spot * np.array(moneyness) * np.exp( risk_free_rate * np.array([[1.0], [2.0]])) iv = [[[0.135, 0.12, 0.1, 0.11, 0.13], [0.135, 0.12, 0.1, 0.11, 0.13]]] * dim return valuation_date, expiries, expiry_times, strikes, iv def build_volatility_surface(val_date, expiry_times, expiries, strikes, iv, dtype): interpolator = tff.math.interpolation.interpolation_2d.Interpolation2D( expiry_times, strikes, iv, dtype=dtype) def _interpolator(t, x): x_transposed = tf.transpose(x) t = tf.broadcast_to(t, x_transposed.shape) return tf.transpose(interpolator.interpolate(t, x_transposed)) return volatility_surface.VolatilitySurface( val_date, expiries, strikes, iv, interpolator=_interpolator, dtype=dtype) # @test_util.run_all_in_graph_and_eager_modes class LocalStochasticVolatilityTest(tf.test.TestCase, parameterized.TestCase): def get_implied_vol(self, time, strike, paths, spot, r, dtype): r = tf.convert_to_tensor(r, dtype=dtype) discount_factor = tf.math.exp(-r * time) paths = tf.boolean_mask(paths, tf.math.logical_not(tf.math.is_nan(paths))) option_value = tf.math.reduce_mean(tf.nn.relu(paths - strike)) iv = bs.implied_vol( prices=discount_factor * option_value, strikes=strike, expiries=time, spots=spot, discount_factors=discount_factor, dtype=dtype, validate_args=True) return iv @parameterized.named_parameters( ('1d', 1, 0.0, [0.0], [1.0], [1.0], 0.1, 0.1, 0.0, 0.2, True), ('1d_corr', 1, -0.5, [0.0], [1.0], [1.0], 0.1, 0.1, 0.0, 0.2, True), ('1d_nonzero_rate', 1, 0.0, [0.05], [1.0], [1.0 ], 0.1, 0.1, 0.0, 0.2, True), ('1d_low_var', 1, 0.0, [0.0], [1.0], [0.04], 0.1, 0.1, 0.0, 0.2, True), ('1d_high_volvol', 1, 0.0, [0.0], [1.0], [0.04 ], 0.1, 0.1, 1.0, 0.5, True), ('1d_using_vol_surface', 1, 0.0, [0.0], [1.0], [1.0], 0.1, 0.1, 0.0, 0.2, False), ) def test_lv_correctness(self, dim, rho, risk_free_rate, spot, variance, pde_time_step, sim_time_step, mr, volvol, using_market_data): """Tests that the model reproduces implied volatility smile.""" dtype = tf.float64 num_samples = 50000 var_model = lsv.LSVVarianceModel( mr, variance, volvol * np.sqrt(variance), dtype=dtype) val_date, expiries, expiry_times, strikes, iv = build_tensors( dim, spot, risk_free_rate) if using_market_data: model = lsv.LocalStochasticVolatilityModel.from_market_data( val_date, expiries, strikes, iv, var_model, spot, variance, rho, risk_free_rate, [0.0], pde_time_step, 200, dtype=dtype) else: vs = build_volatility_surface( val_date, expiry_times, expiries, strikes, iv, dtype=dtype) model = lsv.LocalStochasticVolatilityModel.from_volatility_surface( vs, var_model, spot, variance, rho, risk_free_rate, [0.0], pde_time_step, 200, dtype=dtype) paths = model.sample_paths( [1.0, 2.0], num_samples=num_samples, initial_state=[spot[0], variance[0]], time_step=sim_time_step, random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC, seed=[1, 2]) for d in range(dim): for i in range(2): for j in [1, 2, 3]: sim_iv = self.evaluate( self.get_implied_vol(expiry_times[d][i], strikes[d][i][j], paths[:, i, d], spot[d], risk_free_rate, dtype)) self.assertAllClose(sim_iv[0], iv[d][i][j], atol=0.007, rtol=0.007) if __name__ == '__main__': tf.test.main()
2,623
369
<filename>FreeRTOSv10.4.1/FreeRTOS/Demo/CORTEX_AT91SAM3U256_IAR/AT91Lib/peripherals/systick/systick.c /* ---------------------------------------------------------------------------- * ATMEL Microcontroller Software Support * ---------------------------------------------------------------------------- * Copyright (c) 2008, Atmel Corporation * * 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 disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * ---------------------------------------------------------------------------- */ //------------------------------------------------------------------------------ // Headers //------------------------------------------------------------------------------ #include "systick.h" //------------------------------------------------------------------------------ /// Configures the SysTick in . /// \param countEnable Enable SysTick counting. /// \param reloadValue Value used for tick counter to reload. /// \param handler Interrupt handler function, 0 to disable interrupt. //------------------------------------------------------------------------------ void SysTick_Configure(unsigned char countEnable, unsigned int reloadValue, void( *handler )( void )) { unsigned int intEnable = handler ? AT91C_NVIC_STICKINT : 0; // Disable the SysTick & using core source AT91C_BASE_NVIC->NVIC_STICKCSR = AT91C_NVIC_STICKCLKSOURCE; // Reset the current value AT91C_BASE_NVIC->NVIC_STICKCVR &= ~AT91C_NVIC_STICKCURRENT; // Setup the reload value AT91C_BASE_NVIC->NVIC_STICKRVR = reloadValue; // Enable the SysTick AT91C_BASE_NVIC->NVIC_STICKCSR = AT91C_NVIC_STICKCLKSOURCE | AT91C_NVIC_STICKENABLE | intEnable; }
908
777
/* * Artificial Intelligence for Humans * Volume 3: Deep Learning and Neural Networks * Java Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * * Copyright 2014-2015 by <NAME> * * 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.dbnn; import com.heatonresearch.aifh.error.ErrorCalculation; import com.heatonresearch.aifh.error.ErrorCalculationMSE; import com.heatonresearch.aifh.learning.LearningMethod; /** * Supervised training for the DBN. Used to train the output layer with labels. */ public class SupervisedTrainDBN implements LearningMethod { /** * The network to train. */ private final DeepBeliefNetwork network; /** * The input (x) for the training. */ private final double[][] trainingInput; /** * The expected output (y, or labels). */ private final double[][] trainingIdeal; /** * The learning rate. */ private final double learningRate; /** * The error calculation to use. */ private ErrorCalculation errorCalc = new ErrorCalculationMSE(); /** * Construct the supervised trainer for DBN. * @param theNetwork The network to train. * @param theTrainingInput The input (x) to train. * @param theTrainingIdeal The expected output (y, or labels) to train. * @param theLearningRate The learning rate. */ public SupervisedTrainDBN(DeepBeliefNetwork theNetwork, double[][] theTrainingInput, double[][] theTrainingIdeal, double theLearningRate) { this.network = theNetwork; this.trainingInput = theTrainingInput; this.learningRate = theLearningRate; this.trainingIdeal = theTrainingIdeal; } /** * {@inheritDoc} */ @Override public void iteration() { double[] layerInput = new double[0]; double[] prevLayerInput; this.errorCalc.clear(); for (int n = 0; n < this.trainingInput.length; n++) { for (int i = 0; i < this.network.getLayers().length; i++) { if (i == 0) { prevLayerInput = new double[this.network.getInputCount()]; System.arraycopy(this.trainingInput[n], 0, prevLayerInput, 0, this.network.getInputCount()); } else { prevLayerInput = new double[this.network.getLayers()[i].getInputCount()]; System.arraycopy(layerInput, 0, prevLayerInput, 0, this.network.getLayers()[i].getInputCount()); } layerInput = new double[this.network.getLayers()[i].getOutputCount()]; this.network.getLayers()[i].sampleHgivenV(prevLayerInput, layerInput); } trainLogisticLayer(layerInput, this.trainingIdeal[n]); } } /** * {@inheritDoc} */ @Override public double getLastError() { return this.errorCalc.calculate(); } /** * {@inheritDoc} */ @Override public boolean done() { return false; } /** * {@inheritDoc} */ @Override public String getStatus() { return ""; } /** * {@inheritDoc} */ @Override public void finishTraining() { } /** * Train the logistic layer, the output layer. * @param input The input (x). * @param ideal The expected output (y, or labels). */ private void trainLogisticLayer(double[] input, double[] ideal) { double[] pYgivenX = new double[this.network.getLogLayer().getOutputCount()]; double[] dy = new double[this.network.getLogLayer().getOutputCount()]; for(int i=0; i<this.network.getLogLayer().getOutputCount(); i++) { pYgivenX[i] = 0; for(int j=0; j<this.network.getLogLayer().getInputCount(); j++) { pYgivenX[i] += this.network.getLogLayer().getWeights()[i][j] * input[j]; } pYgivenX[i] += this.network.getLogLayer().getBias()[i]; } this.network.getLogLayer().softmax(pYgivenX); for(int i=0; i<this.network.getLogLayer().getOutputCount(); i++) { dy[i] = ideal[i] - pYgivenX[i]; this.errorCalc.updateError(ideal[i], pYgivenX[i]); for(int j=0; j<this.network.getLogLayer().getInputCount(); j++) { this.network.getLogLayer().getWeights()[i][j] += this.learningRate * dy[i] * input[j] / this.trainingInput.length; } this.network.getLogLayer().getBias()[i] += this.learningRate * dy[i] / this.trainingInput.length; } } /** * @return The error calculation method. */ public ErrorCalculation getErrorCalc() { return this.errorCalc; } /** * Set the error calculation method. * @param errorCalc The error calculation method. */ public void setErrorCalc(final ErrorCalculation errorCalc) { this.errorCalc = errorCalc; } }
2,352
925
<gh_stars>100-1000 # Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.internal.browser import web_contents from telemetry.internal.image_processing import video DEFAULT_TAB_TIMEOUT = 60 class Tab(web_contents.WebContents): """Represents a tab in the browser The important parts of the Tab object are in the runtime and page objects. E.g.: # Navigates the tab to a given url. tab.Navigate('http://www.google.com/') # Evaluates 1+1 in the tab's JavaScript context. tab.Evaluate('1+1') """ def __init__(self, inspector_backend, tab_list_backend, browser): super(Tab, self).__init__(inspector_backend) self._tab_list_backend = tab_list_backend self._browser = browser @property def browser(self): """The browser in which this tab resides.""" return self._browser @property def url(self): """Returns the URL of the tab, as reported by devtools. Raises: devtools_http.DevToolsClientConnectionError """ return self._inspector_backend.url @property def dom_stats(self): """A dictionary populated with measured DOM statistics. Currently this dictionary contains: { 'document_count': integer, 'node_count': integer, 'event_listener_count': integer } Raises: inspector_memory.InspectorMemoryException exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ dom_counters = self._inspector_backend.GetDOMStats( timeout=DEFAULT_TAB_TIMEOUT) assert (len(dom_counters) == 3 and all([x in dom_counters for x in ['document_count', 'node_count', 'event_listener_count']])) return dom_counters def Activate(self): """Brings this tab to the foreground asynchronously. Not all browsers or browser versions support this method. Be sure to check browser.supports_tab_control. Please note: this is asynchronous. There is a delay between this call and the page's documentVisibilityState becoming 'visible', and yet more delay until the actual tab is visible to the user. None of these delays are included in this call. Raises: devtools_http.DevToolsClientConnectionError devtools_client_backend.TabNotFoundError tab_list_backend.TabUnexpectedResponseException """ self._tab_list_backend.ActivateTab(self.id) def Close(self): """Closes this tab. Not all browsers or browser versions support this method. Be sure to check browser.supports_tab_control. Raises: devtools_http.DevToolsClientConnectionError devtools_client_backend.TabNotFoundError tab_list_backend.TabUnexpectedResponseException exceptions.TimeoutException """ self._tab_list_backend.CloseTab(self.id) @property def screenshot_supported(self): """True if the browser instance is capable of capturing screenshots.""" return self._inspector_backend.screenshot_supported def Screenshot(self, timeout=DEFAULT_TAB_TIMEOUT): """Capture a screenshot of the tab's contents. Returns: A telemetry.core.Bitmap. Raises: exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ return self._inspector_backend.Screenshot(timeout) @property def video_capture_supported(self): """True if the browser instance is capable of capturing video.""" return self.browser.platform.CanCaptureVideo() def Highlight(self, color): """Synchronously highlights entire tab contents with the given RgbaColor. TODO(tonyg): It is possible that the z-index hack here might not work for all pages. If this happens, DevTools also provides a method for this. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ self.ExecuteJavaScript(""" (function() { var screen = document.createElement('div'); screen.style.background = 'rgba(%d, %d, %d, %d)'; screen.style.position = 'fixed'; screen.style.top = '0'; screen.style.left = '0'; screen.style.width = '100%%'; screen.style.height = '100%%'; screen.style.zIndex = '2147483638'; document.body.appendChild(screen); requestAnimationFrame(function() { requestAnimationFrame(function() { window.__telemetry_screen_%d = screen; }); }); })(); """ % (color.r, color.g, color.b, color.a, int(color))) self.WaitForJavaScriptExpression( '!!window.__telemetry_screen_%d' % int(color), 5) def ClearHighlight(self, color): """Clears a highlight of the given bitmap.RgbaColor. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ self.ExecuteJavaScript(""" (function() { document.body.removeChild(window.__telemetry_screen_%d); requestAnimationFrame(function() { requestAnimationFrame(function() { window.__telemetry_screen_%d = null; console.time('__ClearHighlight.video_capture_start'); console.timeEnd('__ClearHighlight.video_capture_start'); }); }); })(); """ % (int(color), int(color))) self.WaitForJavaScriptExpression( '!window.__telemetry_screen_%d' % int(color), 5) def StartVideoCapture(self, min_bitrate_mbps, highlight_bitmap=video.HIGHLIGHT_ORANGE_FRAME): """Starts capturing video of the tab's contents. This works by flashing the entire tab contents to a arbitrary color and then starting video recording. When the frames are processed, we can look for that flash as the content bounds. Args: min_bitrate_mbps: The minimum caputre bitrate in MegaBits Per Second. The platform is free to deliver a higher bitrate if it can do so without increasing overhead. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException ValueError: If the required |min_bitrate_mbps| can't be achieved. """ self.Highlight(highlight_bitmap) self.browser.platform.StartVideoCapture(min_bitrate_mbps) self.ClearHighlight(highlight_bitmap) @property def is_video_capture_running(self): return self.browser.platform.is_video_capture_running def StopVideoCapture(self): """Stops recording video of the tab's contents. This looks for the initial color flash in the first frame to establish the tab content boundaries and then omits all frames displaying the flash. Returns: video: A video object which is a telemetry.core.Video """ return self.browser.platform.StopVideoCapture() def GetCookieByName(self, name, timeout=DEFAULT_TAB_TIMEOUT): """Returns the value of the cookie by the given |name|. Raises: exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ return self._inspector_backend.GetCookieByName(name, timeout) def CollectGarbage(self): """Forces a garbage collection. Raises: exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException """ self._inspector_backend.CollectGarbage() def ClearCache(self, force): """Clears the browser's networking related disk, memory and other caches. Args: force: Iff true, navigates to about:blank which destroys the previous renderer, ensuring that even "live" resources in the memory cache are cleared. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected exceptions.TimeoutException exceptions.DevtoolsTargetCrashException errors.DeviceUnresponsiveError """ self.browser.platform.FlushDnsCache() self.ExecuteJavaScript(""" if (window.chrome && chrome.benchmarking && chrome.benchmarking.clearCache) { chrome.benchmarking.clearCache(); chrome.benchmarking.clearPredictorCache(); chrome.benchmarking.clearHostResolverCache(); } """) if force: self.Navigate('about:blank')
3,067
1,159
#ifndef STYLESHEET_H #define STYLESHEET_H #include "base/style/sheet.h" #include "chart/options/options.h" #include "style.h" namespace Vizzu { namespace Styles { class Sheet : public Style::Sheet<Chart> { public: typedef Style::Sheet<Chart> Base; using Base::Sheet; Chart getFullParams( const Diag::DiagramOptionsPtr &options, const Geom::Size &size); static double baseFontSize(const Geom::Size &size, bool rounded); private: using Base::getFullParams; const Diag::Options *options; void calcDefaults(const Geom::Size &size); void setBaseFontSize(const Geom::Size &size); void setPlot(); void setAxis(); void setAxisLabels(); void setAxisTitle(); void setMarkers(); void setMarkerLabels(); void setData(); static double nominalSize(const Geom::Size &size); }; } } #endif
293
684
<filename>console/extract_targets.py """Extract FQDNs, IPv4, and IPv6 networks/addresses from a string or file.""" # Standard Python libraries. import argparse import ipaddress import json import os import sys # Third party Python libraries. import fqdn import requests import tld # Custom Python libraries. __version__ = "1.0.0" def is_ip_address(ip): """Returns True/False if a string is a valid IPv4 or IPv6 address.""" ip = str(ip) try: ipaddress.ip_address(ip) return True except ValueError: return False def is_ipv4_address(ip): """Returns True/False if a string is a valid IPv4 address.""" ip = str(ip) try: if ipaddress.ip_address(ip).version == 4: return True else: return False except ValueError as e: print(f"{e}") def is_ipv6_address(ip): """Returns True/False if a string is a valid IPv6 address.""" ip = str(ip) try: if ipaddress.ip_address(ip).version == 6: return True else: return False except ValueError as e: print(f"{e}") def is_ip_network(network, strict=False): """Returns True/False if a string is a valid network.""" network = str(network) try: ipaddress.ip_network(network, strict) return True except ValueError: return False def is_valid_fqdn(domain): """Return True/False if a provided domain is a valid FQDN, not necessarily if it contains a valid top level domain.""" domain_is_valid_fqdn = fqdn.FQDN(domain).is_valid return domain_is_valid_fqdn def domain_has_valid_fqdn(domain): """Return True/False if a FQDN has a valid top level domain (TLD).""" try: tld.get_tld(domain, fix_protocol=True) return True except tld.exceptions.TldDomainNotFound: return False def retrieve_cloudflare_ip_networks( retrieve_new_data=False, cloudflare_filename="cloudflare_ip_networks.txt", write_to_disk=True ): """Retrieve the IPv4 and IPv6 ranges for Cloudflare servers. https://www.cloudflare.com/ips/ """ cloudflare_dict = { "list_of_strings": set(), "list_of_ipaddress_objects": set(), } # If cloudflare_filename already exists and fresh data isn't requested. if os.path.exists(cloudflare_filename) and not retrieve_new_data: print(f"File already exists: {cloudflare_filename}") with open(cloudflare_filename, "r") as fh: for ip_network in fh.readlines(): cloudflare_dict["list_of_ipaddress_objects"].add(ipaddress.ip_network(ip_network.strip())) else: for ip_version in ["4", "6"]: print(f"Retrieving Cloudflare IPv{ip_version} networks") url = f"https://www.cloudflare.com/ips-v{ip_version}" response = requests.get(url, timeout=2, verify=True) if response.status_code == 200: text = response.text for ip_network in text.strip().split("\n"): cloudflare_dict["list_of_ipaddress_objects"].add(ipaddress.ip_network(ip_network)) else: print("Cloudflare IP networks could not be retrieved.") # Return a list of sorted IPv4 and IPv6 networks. # See https://docs.python.org/3/library/ipaddress.html#ipaddress.get_mixed_type_key cloudflare_dict["list_of_ipaddress_objects"] = sorted( cloudflare_dict["list_of_ipaddress_objects"], key=lambda obj: ipaddress.get_mixed_type_key(obj) ) # Convert ipaddress objects to strings. cloudflare_dict["list_of_strings"] = [str(obj) for obj in cloudflare_dict["list_of_ipaddress_objects"]] # Only write to disk if fresh data is requested. if write_to_disk and retrieve_new_data: print(f"Writing CloudFront IP networks to disk: {cloudflare_filename}") with open(cloudflare_filename, "w") as fh: for ip_network in cloudflare_dict["list_of_strings"]: fh.write(f"{ip_network}\n") # print(f"cloudflare_dict: {cloudflare_dict}") return cloudflare_dict def retrieve_amazon_cloudfront_ip_ranges( retrieve_new_data=False, aws_cloudfront_filename="aws_cloudfront_ip_networks.txt", write_to_disk=True ): """Retrieve the IPv4 and IPv6 ranges for AWS' CloudFront servers. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html """ cloudfront_dict = { "list_of_strings": set(), "list_of_ipaddress_objects": set(), } # If aws_cloudfront_filename already exists and fresh data isn't requested. if os.path.exists(aws_cloudfront_filename) and not retrieve_new_data: print(f"File already exists: {aws_cloudfront_filename}") with open(aws_cloudfront_filename, "r") as fh: for ip_network in fh.readlines(): cloudfront_dict["list_of_ipaddress_objects"].add(ipaddress.ip_network(ip_network.strip())) else: print("Retrieving IPv4 and IPv6 network ranges for AWS' CloudFront servers.") url = "https://ip-ranges.amazonaws.com/ip-ranges.json" response = requests.get(url, verify=True) if response.status_code == 200: json_data = response.json() for service in json_data["prefixes"]: if service["service"] == "CLOUDFRONT": cloudfront_dict["list_of_ipaddress_objects"].add(ipaddress.ip_network(service["ip_prefix"])) for service in json_data["ipv6_prefixes"]: if service["service"] == "CLOUDFRONT": cloudfront_dict["list_of_ipaddress_objects"].add(ipaddress.ip_network(service["ipv6_prefix"])) else: print("CloudFront IP networks could not be retrieved.") # Return a list of sorted IPv4 and IPv6 networks. # See https://docs.python.org/3/library/ipaddress.html#ipaddress.get_mixed_type_key cloudfront_dict["list_of_ipaddress_objects"] = sorted( cloudfront_dict["list_of_ipaddress_objects"], key=lambda obj: ipaddress.get_mixed_type_key(obj) ) # Convert ipaddress objects to strings. cloudfront_dict["list_of_strings"] = [str(obj) for obj in cloudfront_dict["list_of_ipaddress_objects"]] # Only write to disk if fresh data is requested. if write_to_disk and retrieve_new_data: print(f"Writing CloudFront IP networks to disk: {aws_cloudfront_filename}") with open(aws_cloudfront_filename, "w") as fh: for ip_network in cloudfront_dict["list_of_strings"]: fh.write(f"{ip_network}\n") # print(f"cloudfront_dict: {cloudfront_dict}") return cloudfront_dict def retrieve_cdn_ip_networks(retrieve_new_data=False): """Create a list of CDN IPv4 and IPv6 networks.""" # Collect all CDN networks. cdn_ip_networks = [] # Retrieve AWS' CloudFront CDN IP networks. cloudfront_dict = retrieve_amazon_cloudfront_ip_ranges(retrieve_new_data) cdn_ip_networks += cloudfront_dict["list_of_ipaddress_objects"] # Retrieve Cloudflare's CDN IP networks. cloudflare_dict = retrieve_cloudflare_ip_networks(retrieve_new_data) cdn_ip_networks += cloudflare_dict["list_of_ipaddress_objects"] # Return a list of sorted IPv4 and IPv6 networks. # See https://docs.python.org/3/library/ipaddress.html#ipaddress.get_mixed_type_key cdn_ip_networks = sorted(cdn_ip_networks, key=lambda obj: ipaddress.get_mixed_type_key(obj)) return cdn_ip_networks class TargetExtractor: def __init__( self, delimiter="", targets_string=None, targets_file=None, exclude_private_ips=False, sort_targets=False, exclude_cdn_ip_networks=False, retrieve_new_cdn_ip_data=False, write_to_disk=False, ): self.delimiter = delimiter self.targets_string = str(targets_string).strip() self.targets_file = targets_file self.exclude_private_ips = exclude_private_ips self.sort_targets = sort_targets self.exclude_cdn_ip_networks = exclude_cdn_ip_networks self.retrieve_new_cdn_ip_data = retrieve_new_cdn_ip_data self.write_to_disk = write_to_disk if self.exclude_cdn_ip_networks: self.cdn_ip_networks = retrieve_cdn_ip_networks(self.retrieve_new_cdn_ip_data) # Read targets from file as string. if self.targets_file: with open(self.targets_file, "r") as fh: self.targets_string = fh.read().strip() self.targets_dict = self.extract_targets(self.targets_string) # def expand_range_of_ips(self, start_ip, end_ip): # """Takes an IP range and returns all the IPs in that range. # # http://cmikavac.net/2011/09/11/how-to-generate-an-ip-range-list-in-python/ # """ # ip_range = [] # if (ipaddress.ip_address(start_ip).version == 6) or (ipaddress.ip_address(end_ip).version == 6): # print(f"IPv6 IP range not supported in this function: {start_ip} - {end_ip}") # return ip_range # start = list(map(int, start_ip.split("."))) # end = list(map(int, end_ip.split("."))) # temp = start # ip_range.append(start_ip) # while temp != end: # start[3] += 1 # for i in (3, 2, 1): # if temp[i] == 256: # temp[i] = 0 # temp[i - 1] += 1 # ip_range.append(".".join(map(str, temp))) # return ip_range def update_disallowed_target(self, targets_dict, target): """Update disallowed target list.""" targets_dict["disallowed_targets"].add(target) def extract_targets(self, targets_string): """Extracts valid domains and IPv4/IPv6 addresses/networks from a string.""" # Dictionary to track valid, invalid, and disallowed targets. All sets are eventually converted to lists. targets_dict = { "ipv4_addresses": { "as_list": set(), "as_csv": "", "as_nmap": "", "total": 0, }, "ipv4_networks": { "as_list": set(), "as_csv": "", "as_nmap": "", "total": 0, }, "ipv6_addresses": { "as_list": set(), "as_csv": "", "as_nmap": "", "total": 0, }, "ipv6_networks": { "as_list": set(), "as_csv": "", "as_nmap": "", "total": 0, }, "domains": { "as_list": set(), "as_csv": "", "as_nmap": "", "total": 0, }, "invalid_targets": set(), "invalid_targets_total": 0, "disallowed_targets": set(), "disallowed_targets_total": 0, "as_list": [], "as_csv": "", "as_nmap": "", "total": 0, } # Split on delimiter if provided. if self.delimiter: print(f'Using delimiter: "{self.delimiter}"') target_list = targets_string.split(self.delimiter) else: target_list = targets_string.split() for target in target_list: # Check if target is an IP address. if is_ip_address(target): # If so, convert it to an ipaddress.ip_address object. ip_address = ipaddress.ip_address(target) if ip_address.is_multicast: print(f"IP address is a multicast IP: {ip_address}") self.update_disallowed_target(targets_dict, ip_address) continue elif ip_address.is_loopback: print(f"IP address is a loopback IP: {ip_address}") self.update_disallowed_target(targets_dict, ip_address) continue # Cloud metadata IPs are covered under this as well: 169.254.169.254 elif ip_address.is_link_local: print(f"IP address is a link local IP: {ip_address}") self.update_disallowed_target(targets_dict, ip_address) continue # Lastly, check if it is a RFC1918 IP address. 169.254.169.254 will be flagged as # private (which it technically is) instead of link local if this check is first. This check is saved # for last. if ip_address.is_private and self.exclude_private_ips: print(f"IP address is private IP: {ip_address}") self.update_disallowed_target(targets_dict, ip_address) continue # Double-check and make sure IP is not a public IP (and thus it's private) if private IPs are not # allowed...probably redundant. if not ip_address.is_global and self.exclude_private_ips: print(f"IP address is not a public IP: {ip_address}") self.update_disallowed_target(targets_dict, ip_address) continue # Check if IP is in a CDN network. if self.exclude_cdn_ip_networks: cdn_ip_found = False # Not efficient to loop through each CDN network, but necessary to test if an ip_address # (ipaddress.ip_address object) is in a network (ipaddress.IPv4Network or ipaddress.IPv6Network). # Note that self.cdn_ip_networks is a mix of IPv4 and IPv6 networks. for cdn_ip_network in self.cdn_ip_networks: if ip_address in cdn_ip_network: print(f"IP address {ip_address} is in CDN network: {cdn_ip_network}") self.update_disallowed_target(targets_dict, ip_address) # Using "continue" only returns to the local self.cdn_ip_networks for loop, not the parent # target_list for loop. Set cdn_ip_found to True so we can check and bail properly. cdn_ip_found = True break if cdn_ip_found: continue # At this point, the IP address is legit. if is_ipv4_address(ip_address): targets_dict["ipv4_addresses"]["as_list"].add(ip_address) elif is_ipv6_address(ip_address): targets_dict["ipv6_addresses"]["as_list"].add(ip_address) else: print(f"Unknown IP address type: {ip_address}") # Check if it is an IP network. elif is_ip_network(target): # Convert to a ipaddress.ip_network object. ip_network = ipaddress.ip_network(target, strict=False) # Ignore private networks if they are not allowed. if ip_network.is_private and self.exclude_private_ips: print(f"IP network is private: {target}") self.update_disallowed_target(targets_dict, ip_network) continue # IPv4 network. if type(ip_network) == ipaddress.IPv4Network: targets_dict["ipv4_networks"]["as_list"].add(target) # IPv6 network. else: targets_dict["ipv6_networks"]["as_list"].add(target) # Check if it is a FQDN with a valid top level domain (TLD). # Without the TLD check, it will categorize fat-fingered IP addresses (192.168.1.999) as valid FQDNs just # based off allowable characters in a FQDN. elif is_valid_fqdn(target) and domain_has_valid_fqdn(target): targets_dict["domains"]["as_list"].add(target.strip(".")) # Not a valid target. else: # print(f"Invalid target type: {target}") targets_dict["invalid_targets"].add(target) print("=" * 10) # Loop through each category and perform some cleanup maintenance. for target_type in ["ipv4_addresses", "ipv4_networks", "ipv6_addresses", "ipv6_networks", "domains"]: temp_list_of_objects = targets_dict[target_type]["as_list"] # Sort within each individual target type: "ipv4_addresses", "ipv4_networks", "ipv6_addresses", # "ipv6_networks", "domains" if self.sort_targets: try: # Calling sorted() returns temp_list as a list. temp_list_of_objects = sorted(temp_list_of_objects) except Exception as e: print(f"Exception sorting targets in '{target_type}': {e}") # Convert objects to strings. temp_list_of_strings = [str(obj) for obj in temp_list_of_objects] # Re-assign to the coresponding keys. targets_dict[target_type]["as_list"] = temp_list_of_strings targets_dict[target_type]["as_csv"] = ",".join(temp_list_of_strings) targets_dict[target_type]["as_nmap"] = " ".join(temp_list_of_strings) # For IP networks, calculate the number of targets in the network. At this point in the logic, # ip_network has been vetted to be either an IPv4 or IPv6 network (see is_ip_network() function). if target_type in ["ipv4_networks", "ipv6_networks"]: for ip_network in temp_list_of_objects: ip_network = ipaddress.ip_network(ip_network, strict=False) # IPv4 network. Only need to check the network type here. if type(ip_network) == ipaddress.IPv4Network: targets_in_ip_subnet = ip_network.num_addresses # IPv6 network. No need to check the network type here, if it is not IPv4, it has to be IPv6. else: targets_in_ip_subnet = ipaddress.IPv6Network(ip_network).num_addresses targets_dict[target_type]["total"] += targets_in_ip_subnet targets_dict["total"] += targets_in_ip_subnet else: targets_dict[target_type]["total"] = len(temp_list_of_strings) targets_dict["total"] += len(temp_list_of_strings) # Extend array with target_type's list. This is a kind of soft sort by putting them in order of the # target_type for loop ("ipv4_addresses", "ipv4_networks", "ipv6_addresses", "ipv6_networks", "domains"). # The traditional sorted() will not work with the various object types. targets_dict["as_list"].extend(temp_list_of_strings) # Convert to a csv delimited string. targets_dict["as_csv"] = ",".join(targets_dict["as_list"]) # Convert to a space-delimited string. targets_dict["as_nmap"] = " ".join(targets_dict["as_list"]) # Housekeeping for invalid_targets. # Convert from set to list. targets_dict["invalid_targets"] = list(targets_dict["invalid_targets"]) targets_dict["invalid_targets_total"] = len(targets_dict["invalid_targets"]) # Convert invalid_targets objects to strings. targets_dict["invalid_targets"] = [str(obj) for obj in targets_dict["invalid_targets"]] # Housekeeping for disallowed_targets. # Convert from set to list. targets_dict["disallowed_targets"] = list(targets_dict["disallowed_targets"]) targets_dict["disallowed_targets_total"] = len(targets_dict["disallowed_targets"]) # Convert disallowed_targets objects to strings. targets_dict["disallowed_targets"] = [str(obj) for obj in targets_dict["disallowed_targets"]] # At this stage, all the values in invalid_targets and disallowed_targets are strings. Thus, sorting may not be # perfect looking, but we can do it anyway. if self.sort_targets: for target_type in ["invalid_targets", "disallowed_targets"]: try: targets_dict[target_type].sort() except Exception as e: print(f"Exception sorting targets in '{target_type}': {e}") # Write output to disk. if self.write_to_disk: print("Writing targets_dict to disk") with open("targets_dict.json", "w") as fh: fh.write(json.dumps(targets_dict, indent=4)) return targets_dict if __name__ == "__main__": parser = argparse.ArgumentParser(description="Extract IPs and domains from a string or file.") parser.add_argument( "-d", "--delimiter", dest="delimiter", action="store", default="", type=str, help="Delimiter to find targets using Python's split().", ) parser.add_argument( "-i", "--exclude-cdn-ip-networks", dest="exclude_cdn_ip_networks", action="store_true", required=False, default=False, help="Exclude IPs belonging to CDNs like AWS' CloudFront, Cloudflare, etc.", ) parser.add_argument( "-n", "--retrieve-latest-cdn-data", dest="retrieve_new_cdn_ip_data", action="store_true", required=False, default=False, help=( "Retrieve new CDN IP data from AWS' CloudFront, Cloudflare, etc. instead of utilizing previous data stored " "on local files." ), ) parser.add_argument( "-p", "--exclude-private-ips", dest="exclude_private_ips", action="store_true", default=False, help="Exclude private RFC1918 IPs (192.168.1.1) and networks (192.168.1.0/24).", ) parser.add_argument("-s", "--sort", dest="sort_targets", action="store_true", default=False, help="Sort targets") parser.add_argument( "-w", "--write-to-disk", dest="write_to_disk", action="store_true", required=False, default=False, help="Write the targets_dict to disk.", ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument( "-f", "--targets-file", dest="targets_file", action="store", help="File containing potential targets." ) group.add_argument( "-t", "--target-string", dest="targets_string", action="store", help="String of targets '8.8.8.8 4.4.4.4 scanme.nmap.org ::ffff:c0a8:101'", ) args = parser.parse_args() if args.targets_file and not os.path.exists(args.targets_file): print("[!] Specify a valid file containing targets.") sys.exit(1) # args.targets_string = "rackspace.com rackspace.comm 192.168.127.12 1.2.3.4 1.5.4.8 22.22.224.24 2.2.2.2 127.0.0.1 2001:97fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b 7.7.7.0/24 4.4.4.4 . : % ^ 2.2.3.) 1.84.5.2555 192.168.3.11 169.254.169.254 2.2.2.3 2.2.2.4 192.168.3.11 2fdf8:f53e:61e4::18 192.168.3.11" te = TargetExtractor(**vars(args)) targets_dict = te.targets_dict print(json.dumps(targets_dict, indent=4))
10,917
443
#SPDX-License-Identifier: MIT import pytest def test_annual_commit_count_ranked_by_repo_in_repo_group(metrics): assert metrics.annual_commit_count_ranked_by_repo_in_repo_group(10).iloc[0].net > 0 assert metrics.annual_commit_count_ranked_by_repo_in_repo_group(10, 25430).iloc[0].net > 0 def test_annual_commit_count_ranked_by_new_repo_in_repo_group(metrics): assert metrics.annual_commit_count_ranked_by_new_repo_in_repo_group(10).iloc[0].net > 0 assert metrics.annual_commit_count_ranked_by_new_repo_in_repo_group(10, 25430).iloc[0].net > 0 def test_top_committers(metrics): assert metrics.top_committers(10, year=2017).iloc[0]['commits'] > 0 assert metrics.top_committers(10, year=2017, threshold=0.7).iloc[0]['commits'] > 0 assert metrics.top_committers(10, 25430, year=2017).iloc[0]['commits'] > 0 assert metrics.top_committers(10, 25430, year=2017, threshold=0.7).iloc[0]['commits'] > 0 assert metrics.top_committers(10).iloc[0]['commits'] > 0 assert metrics.top_committers(10, 25430).iloc[0]['commits'] > 0 def test_committer(metrics): assert metrics.committers(10, period='year').iloc[0]['count'] > 0 assert metrics.committers(10, 25430,period='year').iloc[0]['count'] > 0
504
3,102
<gh_stars>1000+ // RUN: %clang_cc1 %s -fsyntax-only -verify const char* test1 = 1 ? "i" : 1 == 1 ? "v" : "r"; void _efree(void *ptr); void free(void *ptr); int _php_stream_free1() { return (1 ? free(0) : _efree(0)); // expected-error {{returning 'void' from a function with incompatible result type 'int'}} } int _php_stream_free2() { return (1 ? _efree(0) : free(0)); // expected-error {{returning 'void' from a function with incompatible result type 'int'}} } void pr39809() { _Generic(0 ? (int const *)0 : (void *)0, int const *: (void)0); _Generic(0 ? (int const *)0 : (void *)1, void const *: (void)0); _Generic(0 ? (int volatile*)0 : (void const*)1, void volatile const*: (void)0); _Generic(0 ? (int volatile*)0 : (void const*)0, void volatile const*: (void)0); }
298
445
<reponame>minxuanjun/basalt-mirror /** BSD 3-Clause License This file is part of the Basalt project. https://gitlab.com/VladyslavUsenko/basalt.git Copyright (c) 2019, <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 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. */ #pragma once #include <basalt/calibration/aprilgrid.h> #include <basalt/calibration/calibration_helper.h> #include <basalt/spline/rd_spline.h> namespace basalt { class VignetteEstimator { public: static const int SPLINE_N = 4; static const int64_t knot_spacing = 1e10; static const int border_size = 2; VignetteEstimator( const VioDatasetPtr &vio_dataset, const Eigen::aligned_vector<Eigen::Vector2d> &optical_centers, const Eigen::aligned_vector<Eigen::Vector2i> &resolutions, const std::map<TimeCamId, Eigen::aligned_vector<Eigen::Vector3d>> &reprojected_vignette, const AprilGrid &april_grid); void compute_error(std::map<TimeCamId, std::vector<double>> *reprojected_vignette_error = nullptr); void opt_irradience(); void opt_vign(); void optimize(); void compute_data_log(std::vector<std::vector<float>> &vign_data_log); void save_vign_png(const std::string &path); inline const std::vector<basalt::RdSpline<1, SPLINE_N>> &get_vign_param() { return vign_param; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: const VioDatasetPtr vio_dataset; Eigen::aligned_vector<Eigen::Vector2d> optical_centers; Eigen::aligned_vector<Eigen::Vector2i> resolutions; std::map<TimeCamId, Eigen::aligned_vector<Eigen::Vector3d>> reprojected_vignette; const AprilGrid &april_grid; size_t vign_size; std::vector<double> irradiance; std::vector<basalt::RdSpline<1, SPLINE_N>> vign_param; }; } // namespace basalt
1,077
1,088
<filename>Objective-C/Tests/Util/CBLMockConnection.h // // CBLMockConnection.h // CouchbaseLite // // Copyright (c) 2018 Couchbase, Inc. All rights reserved. // // Licensed under the Couchbase License Agreement (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf // // 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. // #import "CBLMessageEndpointConnection.h" #import "CBLProtocolType.h" @protocol CBLMockConnectionErrorLogic; @class CBLMessageEndpointListener; @class CBLMockServerConnection; NS_ASSUME_NONNULL_BEGIN @interface CBLMockConnection : NSObject <CBLMessageEndpointConnection> @property (atomic, readonly, nullable) CBLMessageEndpointListener* listener; @property (atomic, readonly, nullable) id<CBLReplicatorConnection> replicatorConnection; @property (atomic, readonly) CBLProtocolType protocolType; @property (atomic, readonly) BOOL isClient; @property (atomic, nullable) id<CBLMockConnectionErrorLogic> errorLogic; - (instancetype) initWithListener: (nullable CBLMessageEndpointListener*)listener protocol: (CBLProtocolType)protocolType; - (void) acceptBytes: (NSData*)message; - (void) connectionBroken: (nullable CBLMessagingError*)error; - (void) performWrite: (NSData*)data; @end @interface CBLMockClientConnection : CBLMockConnection - (instancetype) initWithEndpoint: (CBLMessageEndpoint*)endpoint; - (void) serverConnected; - (void) serverDisconnected; @end @interface CBLMockServerConnection : CBLMockConnection - (void) clientConnected: (CBLMockClientConnection*)client; - (void) clientDisconnected: (nullable CBLMessagingError*)error; @end NS_ASSUME_NONNULL_END
647
738
/* * 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.hudi.sink; import org.apache.hudi.client.WriteStatus; import org.apache.hudi.common.model.HoodieAvroRecord; import org.apache.hudi.common.model.HoodieKey; import org.apache.hudi.common.model.HoodieOperation; import org.apache.hudi.common.model.HoodieRecord; import org.apache.hudi.common.model.HoodieRecordLocation; import org.apache.hudi.common.model.HoodieRecordPayload; import org.apache.hudi.common.model.WriteOperationType; import org.apache.hudi.common.util.ObjectSizeCalculator; import org.apache.hudi.common.util.ValidationUtils; import org.apache.hudi.configuration.FlinkOptions; import org.apache.hudi.exception.HoodieException; import org.apache.hudi.index.HoodieIndex; import org.apache.hudi.sink.common.AbstractStreamWriteFunction; import org.apache.hudi.sink.event.WriteMetadataEvent; import org.apache.hudi.table.action.commit.FlinkWriteHelper; import org.apache.hudi.util.StreamerUtil; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.ProcessFunction; import org.apache.flink.util.Collector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Sink function to write the data to the underneath filesystem. * * <p><h2>Work Flow</h2> * * <p>The function firstly buffers the data as a batch of {@link HoodieRecord}s, * It flushes(write) the records batch when the batch size exceeds the configured size {@link FlinkOptions#WRITE_BATCH_SIZE} * or the total buffer size exceeds the configured size {@link FlinkOptions#WRITE_TASK_MAX_SIZE} * or a Flink checkpoint starts. After a batch has been written successfully, * the function notifies its operator coordinator {@link StreamWriteOperatorCoordinator} to mark a successful write. * * <p><h2>The Semantics</h2> * * <p>The task implements exactly-once semantics by buffering the data between checkpoints. The operator coordinator * starts a new instant on the timeline when a checkpoint triggers, the coordinator checkpoints always * start before its operator, so when this function starts a checkpoint, a REQUESTED instant already exists. * * <p>The function process thread blocks data buffering after the checkpoint thread finishes flushing the existing data buffer until * the current checkpoint succeed and the coordinator starts a new instant. Any error triggers the job failure during the metadata committing, * when the job recovers from a failure, the write function re-send the write metadata to the coordinator to see if these metadata * can re-commit, thus if unexpected error happens during the instant committing, the coordinator would retry to commit when the job * recovers. * * <p><h2>Fault Tolerance</h2> * * <p>The operator coordinator checks and commits the last instant then starts a new one after a checkpoint finished successfully. * It rolls back any inflight instant before it starts a new instant, this means one hoodie instant only span one checkpoint, * the write function blocks data buffer flushing for the configured checkpoint timeout * before it throws exception, any checkpoint failure would finally trigger the job failure. * * <p>Note: The function task requires the input stream be shuffled by the file IDs. * * @param <I> Type of the input record * @see StreamWriteOperatorCoordinator */ public class StreamWriteFunction<I> extends AbstractStreamWriteFunction<I> { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(StreamWriteFunction.class); /** * Write buffer as buckets for a checkpoint. The key is bucket ID. */ private transient Map<String, DataBucket> buckets; private transient BiFunction<List<HoodieRecord>, String, List<WriteStatus>> writeFunction; /** * Total size tracer. */ private transient TotalSizeTracer tracer; /** * Constructs a StreamingSinkFunction. * * @param config The config options */ public StreamWriteFunction(Configuration config) { super(config); } @Override public void open(Configuration parameters) throws IOException { this.tracer = new TotalSizeTracer(this.config); initBuffer(); initWriteFunction(); } @Override public void snapshotState() { // Based on the fact that the coordinator starts the checkpoint first, // it would check the validity. // wait for the buffer data flush out and request a new instant flushRemaining(false); } @Override public void processElement(I value, ProcessFunction<I, Object>.Context ctx, Collector<Object> out) throws Exception { bufferRecord((HoodieRecord<?>) value); } @Override public void close() { if (this.writeClient != null) { this.writeClient.cleanHandlesGracefully(); this.writeClient.close(); } } /** * End input action for batch source. */ public void endInput() { flushRemaining(true); this.writeClient.cleanHandles(); this.writeStatuses.clear(); } // ------------------------------------------------------------------------- // Getter/Setter // ------------------------------------------------------------------------- @VisibleForTesting @SuppressWarnings("rawtypes") public Map<String, List<HoodieRecord>> getDataBuffer() { Map<String, List<HoodieRecord>> ret = new HashMap<>(); for (Map.Entry<String, DataBucket> entry : buckets.entrySet()) { ret.put(entry.getKey(), entry.getValue().writeBuffer()); } return ret; } // ------------------------------------------------------------------------- // Utilities // ------------------------------------------------------------------------- private void initBuffer() { this.buckets = new LinkedHashMap<>(); } private void initWriteFunction() { final String writeOperation = this.config.get(FlinkOptions.OPERATION); switch (WriteOperationType.fromValue(writeOperation)) { case INSERT: this.writeFunction = (records, instantTime) -> this.writeClient.insert(records, instantTime); break; case UPSERT: this.writeFunction = (records, instantTime) -> this.writeClient.upsert(records, instantTime); break; case INSERT_OVERWRITE: this.writeFunction = (records, instantTime) -> this.writeClient.insertOverwrite(records, instantTime); break; case INSERT_OVERWRITE_TABLE: this.writeFunction = (records, instantTime) -> this.writeClient.insertOverwriteTable(records, instantTime); break; default: throw new RuntimeException("Unsupported write operation : " + writeOperation); } } /** * Represents a data item in the buffer, this is needed to reduce the * memory footprint. * * <p>A {@link HoodieRecord} was firstly transformed into a {@link DataItem} * for buffering, it then transforms back to the {@link HoodieRecord} before flushing. */ private static class DataItem { private final String key; // record key private final String instant; // 'U' or 'I' private final HoodieRecordPayload<?> data; // record payload private final HoodieOperation operation; // operation private DataItem(String key, String instant, HoodieRecordPayload<?> data, HoodieOperation operation) { this.key = key; this.instant = instant; this.data = data; this.operation = operation; } public static DataItem fromHoodieRecord(HoodieRecord<?> record) { return new DataItem( record.getRecordKey(), record.getCurrentLocation().getInstantTime(), ((HoodieAvroRecord) record).getData(), record.getOperation()); } public HoodieRecord<?> toHoodieRecord(String partitionPath) { HoodieKey hoodieKey = new HoodieKey(this.key, partitionPath); HoodieRecord<?> record = new HoodieAvroRecord<>(hoodieKey, data, operation); HoodieRecordLocation loc = new HoodieRecordLocation(instant, null); record.setCurrentLocation(loc); return record; } } /** * Data bucket. */ private static class DataBucket { private final List<DataItem> records; private final BufferSizeDetector detector; private final String partitionPath; private final String fileID; private DataBucket(Double batchSize, HoodieRecord<?> hoodieRecord) { this.records = new ArrayList<>(); this.detector = new BufferSizeDetector(batchSize); this.partitionPath = hoodieRecord.getPartitionPath(); this.fileID = hoodieRecord.getCurrentLocation().getFileId(); } /** * Prepare the write data buffer: patch up all the records with correct partition path. */ public List<HoodieRecord> writeBuffer() { // rewrite all the records with new record key return records.stream() .map(record -> record.toHoodieRecord(partitionPath)) .collect(Collectors.toList()); } /** * Sets up before flush: patch up the first record with correct partition path and fileID. * * <p>Note: the method may modify the given records {@code records}. */ public void preWrite(List<HoodieRecord> records) { // rewrite the first record with expected fileID HoodieRecord<?> first = records.get(0); HoodieRecord<?> record = new HoodieAvroRecord<>(first.getKey(), (HoodieRecordPayload) first.getData(), first.getOperation()); HoodieRecordLocation newLoc = new HoodieRecordLocation(first.getCurrentLocation().getInstantTime(), fileID); record.setCurrentLocation(newLoc); records.set(0, record); } public void reset() { this.records.clear(); this.detector.reset(); } } /** * Tool to detect if to flush out the existing buffer. * Sampling the record to compute the size with 0.01 percentage. */ private static class BufferSizeDetector { private final Random random = new Random(47); private static final int DENOMINATOR = 100; private final double batchSizeBytes; private long lastRecordSize = -1L; private long totalSize = 0L; BufferSizeDetector(double batchSizeMb) { this.batchSizeBytes = batchSizeMb * 1024 * 1024; } boolean detect(Object record) { if (lastRecordSize == -1 || sampling()) { lastRecordSize = ObjectSizeCalculator.getObjectSize(record); } totalSize += lastRecordSize; return totalSize > this.batchSizeBytes; } boolean sampling() { // 0.01 sampling percentage return random.nextInt(DENOMINATOR) == 1; } void reset() { this.lastRecordSize = -1L; this.totalSize = 0L; } } /** * Tool to trace the total buffer size. It computes the maximum buffer size, * if current buffer size is greater than the maximum buffer size, the data bucket * flush triggers. */ private static class TotalSizeTracer { private long bufferSize = 0L; private final double maxBufferSize; TotalSizeTracer(Configuration conf) { long mergeReaderMem = 100; // constant 100MB long mergeMapMaxMem = conf.getInteger(FlinkOptions.WRITE_MERGE_MAX_MEMORY); this.maxBufferSize = (conf.getDouble(FlinkOptions.WRITE_TASK_MAX_SIZE) - mergeReaderMem - mergeMapMaxMem) * 1024 * 1024; final String errMsg = String.format("'%s' should be at least greater than '%s' plus merge reader memory(constant 100MB now)", FlinkOptions.WRITE_TASK_MAX_SIZE.key(), FlinkOptions.WRITE_MERGE_MAX_MEMORY.key()); ValidationUtils.checkState(this.maxBufferSize > 0, errMsg); } /** * Trace the given record size {@code recordSize}. * * @param recordSize The record size * @return true if the buffer size exceeds the maximum buffer size */ boolean trace(long recordSize) { this.bufferSize += recordSize; return this.bufferSize > this.maxBufferSize; } void countDown(long size) { this.bufferSize -= size; } public void reset() { this.bufferSize = 0; } } /** * Returns the bucket ID with the given value {@code value}. */ private String getBucketID(HoodieRecord<?> record) { final String fileId = record.getCurrentLocation().getFileId(); return StreamerUtil.generateBucketKey(record.getPartitionPath(), fileId); } /** * Buffers the given record. * * <p>Flush the data bucket first if the bucket records size is greater than * the configured value {@link FlinkOptions#WRITE_BATCH_SIZE}. * * <p>Flush the max size data bucket if the total buffer size exceeds the configured * threshold {@link FlinkOptions#WRITE_TASK_MAX_SIZE}. * * @param value HoodieRecord */ protected void bufferRecord(HoodieRecord<?> value) { final String bucketID = getBucketID(value); DataBucket bucket = this.buckets.computeIfAbsent(bucketID, k -> new DataBucket(this.config.getDouble(FlinkOptions.WRITE_BATCH_SIZE), value)); final DataItem item = DataItem.fromHoodieRecord(value); bucket.records.add(item); boolean flushBucket = bucket.detector.detect(item); boolean flushBuffer = this.tracer.trace(bucket.detector.lastRecordSize); if (flushBucket) { if (flushBucket(bucket)) { this.tracer.countDown(bucket.detector.totalSize); bucket.reset(); } } else if (flushBuffer) { // find the max size bucket and flush it out List<DataBucket> sortedBuckets = this.buckets.values().stream() .sorted((b1, b2) -> Long.compare(b2.detector.totalSize, b1.detector.totalSize)) .collect(Collectors.toList()); final DataBucket bucketToFlush = sortedBuckets.get(0); if (flushBucket(bucketToFlush)) { this.tracer.countDown(bucketToFlush.detector.totalSize); bucketToFlush.reset(); } else { LOG.warn("The buffer size hits the threshold {}, but still flush the max size data bucket failed!", this.tracer.maxBufferSize); } } } private boolean hasData() { return this.buckets.size() > 0 && this.buckets.values().stream().anyMatch(bucket -> bucket.records.size() > 0); } @SuppressWarnings("unchecked, rawtypes") private boolean flushBucket(DataBucket bucket) { String instant = instantToWrite(true); if (instant == null) { // in case there are empty checkpoints that has no input data LOG.info("No inflight instant when flushing data, skip."); return false; } List<HoodieRecord> records = bucket.writeBuffer(); ValidationUtils.checkState(records.size() > 0, "Data bucket to flush has no buffering records"); if (config.getBoolean(FlinkOptions.PRE_COMBINE)) { records = FlinkWriteHelper.newInstance().deduplicateRecords(records, (HoodieIndex) null, -1); } bucket.preWrite(records); final List<WriteStatus> writeStatus = new ArrayList<>(writeFunction.apply(records, instant)); records.clear(); final WriteMetadataEvent event = WriteMetadataEvent.builder() .taskID(taskID) .instantTime(instant) // the write instant may shift but the event still use the currentInstant. .writeStatus(writeStatus) .lastBatch(false) .endInput(false) .build(); this.eventGateway.sendEventToCoordinator(event); writeStatuses.addAll(writeStatus); return true; } @SuppressWarnings("unchecked, rawtypes") private void flushRemaining(boolean endInput) { this.currentInstant = instantToWrite(hasData()); if (this.currentInstant == null) { // in case there are empty checkpoints that has no input data throw new HoodieException("No inflight instant when flushing data!"); } final List<WriteStatus> writeStatus; if (buckets.size() > 0) { writeStatus = new ArrayList<>(); this.buckets.values() // The records are partitioned by the bucket ID and each batch sent to // the writer belongs to one bucket. .forEach(bucket -> { List<HoodieRecord> records = bucket.writeBuffer(); if (records.size() > 0) { if (config.getBoolean(FlinkOptions.PRE_COMBINE)) { records = FlinkWriteHelper.newInstance().deduplicateRecords(records, (HoodieIndex) null, -1); } bucket.preWrite(records); writeStatus.addAll(writeFunction.apply(records, currentInstant)); records.clear(); bucket.reset(); } }); } else { LOG.info("No data to write in subtask [{}] for instant [{}]", taskID, currentInstant); writeStatus = Collections.emptyList(); } final WriteMetadataEvent event = WriteMetadataEvent.builder() .taskID(taskID) .instantTime(currentInstant) .writeStatus(writeStatus) .lastBatch(true) .endInput(endInput) .build(); this.eventGateway.sendEventToCoordinator(event); this.buckets.clear(); this.tracer.reset(); this.writeClient.cleanHandles(); this.writeStatuses.addAll(writeStatus); // blocks flushing until the coordinator starts a new instant this.confirming = true; } }
6,056
4,933
<reponame>rbrtmrtn/PostgresApp /* * PostgresApplication.h */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> /* * Standard Suite */ @interface SBApplication(PostgresApplication) - (BOOL) openPreferences; // Opens the Preferences. - (BOOL) checkForUpdates; // Checks for updates. @end
115
367
# coding: utf-8 from __future__ import unicode_literals, absolute_import def is_json_response(network_response): """Return whether or not the network response content is json. :param network_response: The response from the Box API. :type network_response: :class:`NetworkResponse` """ try: network_response.json() return True except ValueError: return False
156
310
<filename>AI-and-Analytics/Features-and-Functionality/IntelTensorFlow_InferenceOptimization/scripts/tf_pb_utils.py #! /usr/bin/env python import os, sys import argparse class TF_PB_Utils: def __init__(self): self.graph_def = None self.graph = None self.fnames = ['op_type', 'op_name', 'op1', 'op2', 'op3', 'op4', 'op5', 'op6'] return def parse_pb_in_savemodel(self, folderpath): print('load SaveModel from : {}'.format(folderpath)) import tensorflow as tf graph = None graph = tf.compat.v1.Graph() with tf.compat.v1.Session(graph=graph) as sess: tf.compat.v1.saved_model.loader.load(sess, [tf.compat.v1.saved_model.tag_constants.SERVING], folderpath) return graph def parse_pb_in_graphdef(self, filepath): print('Loading graph definition from :{}'.format(filepath)) import tensorflow as tf graph_def = None graph = None try: with tf.compat.v1.gfile.GFile(filepath, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) if graph_def == None: print(" failures at init a graph_def") print('Importing graph') with tf.Graph().as_default() as graph: print(' before import_graph_def ') tf.import_graph_def( graph_def, input_map=None, return_elements=None, name='', op_dict=None, producer_op_list=None ) print(' after import_graph_def ') print("finish Importing ") except BaseException as e: print(' Error loading the graph definition: {}'.format(str(e))) print(" Errors for GraphDef Parsing") pass return graph def parse_pb(self, filepath): print('Parsing PB file : {}'.format(filepath)) graph = None graph = self.parse_pb_in_graphdef(filepath) if graph == None: print("Need to parse it as save model") filename = filepath.split(os.sep)[-1] folderpath = filepath[:(len(filepath) - len(filename))] print(folderpath) if filename != 'saved_model.pb': print('need to make symbolic link') dst = folderpath + os.sep + 'saved_model.pb' if os.path.islink(dst): print("link exists. unlink it : ", dst) os.unlink(dst) os.symlink(filename, dst) graph = self.parse_pb_in_savemodel(folderpath) return graph def dump_ops_in_graph_into_csv(self, graph, filename='out.csv'): import tensorflow as tf import csv ops = graph.get_operations() # type: Iterable[tf.Operation] f = open(filename, 'w') with f: writer = csv.DictWriter(f, fieldnames=self.fnames) writer.writeheader() for op in ops: #print('- {0} {1} ({2} outputs)'.format(op.type, op.name, len(op.outputs))) op_name = op.name.split('/')[-1] count = op.name.count('/') if count > 6: count = 6 op_list = [0 for i in range(6)] for i in range(count): op_list[i] = op.name.split('/')[i] writer.writerow({'op_type': op.type, 'op_name': op_name, 'op1': op_list[0], 'op2': op_list[1], 'op3': op_list[2], 'op4': op_list[3], 'op5': op_list[4], 'op6': op_list[5]}) def parse_ops_from_csv(self, filename='out.csv'): import pandas as pd data = pd.read_csv(filename, names=self.fnames) return data def draw_pie_chart(self, topo_data, group, topk=10): import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(18, 15)) ax = fig.add_subplot(111) figsize = (13, 15) title = group + "Count Breakdown" print(" draw pie chart : ", title) if topk > len(topo_data): topk = len(topo_data) topo_data[:topk].plot.pie( ax=ax, title=title, figsize=figsize, logx=True, textprops=dict(fontsize=18), autopct='%1.1f%%', labeldistance=1.1) box = ax.legend( topo_data[:topk].index, title="TF Ops", loc="best", bbox_to_anchor=(1, 0, 0.5, 1), fontsize=20) box.get_title().set_fontsize(20) plt.tight_layout() ax.figure.savefig(title) return def breakdown(self, data, columnindex, group, topk=5, keyword='', rowindex=-1): print("\n === Breakdown on Column: {0} , {1} === : ".format(columnindex, group)) topo_data_list = [] group_list = [] groupdata = data.groupby(group).size().sort_values(ascending=False) #print(groupdata) group_size = groupdata.index.size print("group_size : ",group_size) if group_size > topk: group_size = topk if rowindex != -1: print('\n Group ops on row: {0} , {1} '.format(rowindex, groupdata.index[rowindex])) topo_data = data.loc[data[group] == groupdata.index[rowindex]] sorted_topo_data = topo_data.groupby('op_type').size().sort_values(ascending=False) print(sorted_topo_data) topo_data_list.append(sorted_topo_data) group_list.append(groupdata.index[rowindex]) else: for i in range(group_size): #print('\n Group ops on: ',groupdata.index[i]) print('\n Group ops on row: {0} , {1} '.format(i, groupdata.index[i])) topo_data = data.loc[data[group] == groupdata.index[i]] sorted_topo_data = topo_data.groupby('op_type').size().sort_values(ascending=False) print(sorted_topo_data) topo_data_list.append(sorted_topo_data) group_list.append(groupdata.index[i]) return topo_data_list, group_list def get_data(self, filepath): data = None self.graph = self.parse_pb(filepath) if self.graph != None: self.dump_ops_in_graph_into_csv(self.graph) data = self.parse_ops_from_csv() return data def dump_columns(self, data, topk=10): for i in range(5): print("\n == Dump column : {0} == ".format(i)) group = self.fnames[i] groupdata = data.groupby(group).size().sort_values(ascending=False).head(topk) print(groupdata) return if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('file', type=str, help='The file name of the frozen graph/ The folder name contained the saved model') # will dump all columns if no column index is assigned, and group by second column (index=1) parser.add_argument("-c", "--column", type=int, choices=[0, 1, 2, 3, 4, 5], default=-1, help="Input column index") # will dump all rows if no row index is assigned parser.add_argument("-r", "--row", type=int, choices=[0, 1, 2, 3, 4, 5], default=-1, help="Input sored row index") args = parser.parse_args() tfpb = TF_PB_Utils() data = tfpb.get_data(args.file) if args.column == -1: tfpb.dump_columns(data) sys.exit() topo_data_list, group_list = tfpb.breakdown(data, args.column, tfpb.fnames[args.column], rowindex=args.row) if args.row == -1: sys.exit() for i in range(len(topo_data_list)): tfpb.draw_pie_chart(topo_data_list[i], group_list[i])
3,818
335
{ "word": "Wearisome", "definitions": [ "Causing one to feel tired or bored." ], "parts-of-speech": "Adjective" }
64
8,805
<filename>shared/ios/Pods/Headers/Private/libwebp/mips_macro.h ../../../libwebp/src/dsp/mips_macro.h
46
809
<filename>src/compat/libc/include/netinet/ip.h /* * Stub for netinet/ip.h * * @author <NAME> * @date 3 Oct 2014 */ #ifndef _NETINET_IP_H_ #define _NETINET_IP_H_ #define IPTOS_LOWDELAY 0x10 #define IPTOS_THROUGHPUT 0x20 #define IPTOS_RELIABILITY 0x40 #define IP_TOS 0x01 /* Socket option. * The obvious way to tell the IP layer not to prepend its own header * is by calling the setsockopt() syscall and setting the IP_HDRINCL. * See http://sock-raw.org/papers/sock_raw */ #define IP_HDRINCL 0x03 #endif
235
668
<gh_stars>100-1000 /** * 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.fineract.portfolio.tax.api; import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDate; import java.util.List; import java.util.Set; /** * Created by <NAME> on 12/14/17. */ final class TaxGroupApiResourceSwagger { private TaxGroupApiResourceSwagger() {} @Schema(description = "GetTaxesGroupResponse") public static final class GetTaxesGroupResponse { private GetTaxesGroupResponse() {} static final class GetTaxesGroupTaxAssociations { private GetTaxesGroupTaxAssociations() {} static final class GetTaxesGroupTaxComponent { private GetTaxesGroupTaxComponent() {} @Schema(example = "7") public Integer id; @Schema(example = "tax component 2") public String name; } @Schema(example = "7") public Integer id; public GetTaxesGroupTaxComponent taxComponent; @Schema(example = "[2016, 4, 11]") public LocalDate startDate; } @Schema(example = "7") public Integer id; @Schema(example = "tax group 1") public String name; public Set<GetTaxesGroupTaxAssociations> taxAssociations; } @Schema(description = "PostTaxesGroupRequest") public static final class PostTaxesGroupRequest { private PostTaxesGroupRequest() {} static final class PostTaxesGroupTaxComponents { private PostTaxesGroupTaxComponents() {} @Schema(example = "7") public Integer taxComponentId; @Schema(example = "11 April 2016") public String startDate; } @Schema(example = "tax group 1") public String name; @Schema(example = "en") public String locale; public Set<PostTaxesGroupTaxComponents> taxComponents; @Schema(example = "dd MMMM yyyy") public String dateFormat; } @Schema(description = "PostTaxesGroupResponse") public static final class PostTaxesGroupResponse { private PostTaxesGroupResponse() {} @Schema(example = "1") public Integer resourceId; } @Schema(description = "PutTaxesGroupTaxGroupIdRequest") public static final class PutTaxesGroupTaxGroupIdRequest { private PutTaxesGroupTaxGroupIdRequest() {} static final class PutTaxesGroupTaxComponents { private PutTaxesGroupTaxComponents() {} @Schema(example = "7") public Integer id; @Schema(example = "7") public Integer taxComponentId; @Schema(example = "22 April 2016") public String endDate; } @Schema(example = "tax group 2") public String name; @Schema(example = "en") public String locale; public Set<PutTaxesGroupTaxComponents> taxComponents; @Schema(example = "dd MMMM yyyy") public String dateFormat; } @Schema(description = "PutTaxesGroupTaxGroupIdResponse") public static final class PutTaxesGroupTaxGroupIdResponse { private PutTaxesGroupTaxGroupIdResponse() {} static final class PutTaxesGroupChanges { private PutTaxesGroupChanges() {} static final class PutTaxesGroupModifiedComponents { private PutTaxesGroupModifiedComponents() {} @Schema(example = "Apr 22, 2016 12:00:00 AM") public String endDate; @Schema(example = "7") public Integer taxComponentId; } @Schema(example = "[6]") public List<Integer> addComponents; public Set<PutTaxesGroupModifiedComponents> modifiedComponents; @Schema(example = "tax group 2") public String name; } @Schema(example = "7") public Integer resourceId; public PutTaxesGroupChanges changes; } }
1,910
8,323
"""Implementation of :class:`Domain` class. """ from typing import Any, Optional, Type from sympy.core import Basic, sympify from sympy.core.compatibility import is_sequence, ordered from sympy.core.decorators import deprecated from sympy.external.gmpy import HAS_GMPY from sympy.polys.domains.domainelement import DomainElement from sympy.polys.orderings import lex from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError from sympy.polys.polyutils import _unify_gens, _not_a_coeff from sympy.utilities import default_sort_key, public @public class Domain: """Superclass for all domains in the polys domains system. See :ref:`polys-domainsintro` for an introductory explanation of the domains system. The :py:class:`~.Domain` class is an abstract base class for all of the concrete domain types. There are many different :py:class:`~.Domain` subclasses each of which has an associated ``dtype`` which is a class representing the elements of the domain. The coefficients of a :py:class:`~.Poly` are elements of a domain which must be a subclass of :py:class:`~.Domain`. Examples ======== The most common example domains are the integers :ref:`ZZ` and the rationals :ref:`QQ`. >>> from sympy import Poly, symbols, Domain >>> x, y = symbols('x, y') >>> p = Poly(x**2 + y) >>> p Poly(x**2 + y, x, y, domain='ZZ') >>> p.domain ZZ >>> isinstance(p.domain, Domain) True >>> Poly(x**2 + y/2) Poly(x**2 + 1/2*y, x, y, domain='QQ') The domains can be used directly in which case the domain object e.g. (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of ``dtype``. >>> from sympy import ZZ, QQ >>> ZZ(2) 2 >>> ZZ.dtype # doctest: +SKIP <class 'int'> >>> type(ZZ(2)) # doctest: +SKIP <class 'int'> >>> QQ(1, 2) 1/2 >>> type(QQ(1, 2)) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> The corresponding domain elements can be used with the arithmetic operations ``+,-,*,**`` and depending on the domain some combination of ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor division) and ``%`` (modulo division) can be used but ``/`` (true division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements can be used with ``/`` but ``//`` and ``%`` should not be used. Some domains have a :py:meth:`~.Domain.gcd` method. >>> ZZ(2) + ZZ(3) 5 >>> ZZ(5) // ZZ(2) 2 >>> ZZ(5) % ZZ(2) 1 >>> QQ(1, 2) / QQ(2, 3) 3/4 >>> ZZ.gcd(ZZ(4), ZZ(2)) 2 >>> QQ.gcd(QQ(2,7), QQ(5,3)) 1/21 >>> ZZ.is_Field False >>> QQ.is_Field True There are also many other domains including: 1. :ref:`GF(p)` for finite fields of prime order. 2. :ref:`RR` for real (floating point) numbers. 3. :ref:`CC` for complex (floating point) numbers. 4. :ref:`QQ(a)` for algebraic number fields. 5. :ref:`K[x]` for polynomial rings. 6. :ref:`K(x)` for rational function fields. 7. :ref:`EX` for arbitrary expressions. Each domain is represented by a domain object and also an implementation class (``dtype``) for the elements of the domain. For example the :ref:`K[x]` domains are represented by a domain object which is an instance of :py:class:`~.PolynomialRing` and the elements are always instances of :py:class:`~.PolyElement`. The implementation class represents particular types of mathematical expressions in a way that is more efficient than a normal SymPy expression which is of type :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr` to a domain element and vice versa. >>> from sympy import Symbol, ZZ, Expr >>> x = Symbol('x') >>> K = ZZ[x] # polynomial ring domain >>> K ZZ[x] >>> type(K) # class of the domain <class 'sympy.polys.domains.polynomialring.PolynomialRing'> >>> K.dtype # class of the elements <class 'sympy.polys.rings.PolyElement'> >>> p_expr = x**2 + 1 # Expr >>> p_expr x**2 + 1 >>> type(p_expr) <class 'sympy.core.add.Add'> >>> isinstance(p_expr, Expr) True >>> p_domain = K.from_sympy(p_expr) >>> p_domain # domain element x**2 + 1 >>> type(p_domain) <class 'sympy.polys.rings.PolyElement'> >>> K.to_sympy(p_domain) == p_expr True The :py:meth:`~.Domain.convert_from` method is used to convert domain elements from one domain to another. >>> from sympy import ZZ, QQ >>> ez = ZZ(2) >>> eq = QQ.convert_from(ez, ZZ) >>> type(ez) # doctest: +SKIP <class 'int'> >>> type(eq) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> Elements from different domains should not be mixed in arithmetic or other operations: they should be converted to a common domain first. The domain method :py:meth:`~.Domain.unify` is used to find a domain that can represent all the elements of two given domains. >>> from sympy import ZZ, QQ, symbols >>> x, y = symbols('x, y') >>> ZZ.unify(QQ) QQ >>> ZZ[x].unify(QQ) QQ[x] >>> ZZ[x].unify(QQ[y]) QQ[x,y] If a domain is a :py:class:`~.Ring` then is might have an associated :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and :py:meth:`~.Domain.get_ring` methods will find or create the associated domain. >>> from sympy import ZZ, QQ, Symbol >>> x = Symbol('x') >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ >>> K = QQ[x] >>> K QQ[x] >>> K.get_field() QQ(x) See also ======== DomainElement: abstract base class for domain elements construct_domain: construct a minimal domain for some expressions """ dtype = None # type: Optional[Type] """The type (class) of the elements of this :py:class:`~.Domain`: >>> from sympy import ZZ, QQ, Symbol >>> ZZ.dtype <class 'int'> >>> z = ZZ(2) >>> z 2 >>> type(z) <class 'int'> >>> type(z) == ZZ.dtype True Every domain has an associated **dtype** ("datatype") which is the class of the associated domain elements. See also ======== of_type """ zero = None # type: Optional[Any] """The zero element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.zero 0 >>> QQ.of_type(QQ.zero) True See also ======== of_type one """ one = None # type: Optional[Any] """The one element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.one 1 >>> QQ.of_type(QQ.one) True See also ======== of_type zero """ is_Ring = False """Boolean flag indicating if the domain is a :py:class:`~.Ring`. >>> from sympy import ZZ >>> ZZ.is_Ring True Basically every :py:class:`~.Domain` represents a ring so this flag is not that useful. See also ======== is_PID is_Field get_ring has_assoc_Ring """ is_Field = False """Boolean flag indicating if the domain is a :py:class:`~.Field`. >>> from sympy import ZZ, QQ >>> ZZ.is_Field False >>> QQ.is_Field True See also ======== is_PID is_Ring get_field has_assoc_Field """ has_assoc_Ring = False """Boolean flag indicating if the domain has an associated :py:class:`~.Ring`. >>> from sympy import QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ See also ======== is_Field get_ring """ has_assoc_Field = False """Boolean flag indicating if the domain has an associated :py:class:`~.Field`. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ See also ======== is_Field get_field """ is_FiniteField = is_FF = False is_IntegerRing = is_ZZ = False is_RationalField = is_QQ = False is_GaussianRing = is_ZZ_I = False is_GaussianField = is_QQ_I = False is_RealField = is_RR = False is_ComplexField = is_CC = False is_AlgebraicField = is_Algebraic = False is_PolynomialRing = is_Poly = False is_FractionField = is_Frac = False is_SymbolicDomain = is_EX = False is_SymbolicRawDomain = is_EXRAW = False is_FiniteExtension = False is_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False """Boolean flag indicating if the domain is a `principal ideal domain`_. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain See also ======== is_Field get_field """ has_CharacteristicZero = False rep = None # type: Optional[str] alias = None # type: Optional[str] @property # type: ignore @deprecated(useinstead="is_Field", issue=12723, deprecated_since_version="1.1") def has_Field(self): return self.is_Field @property # type: ignore @deprecated(useinstead="is_Ring", issue=12723, deprecated_since_version="1.1") def has_Ring(self): return self.is_Ring def __init__(self): raise NotImplementedError def __str__(self): return self.rep def __repr__(self): return str(self) def __hash__(self): return hash((self.__class__.__name__, self.dtype)) def new(self, *args): return self.dtype(*args) @property def tp(self): """Alias for :py:attr:`~.Domain.dtype`""" return self.dtype def __call__(self, *args): """Construct an element of ``self`` domain from ``args``. """ return self.new(*args) def normal(self, *args): return self.dtype(*args) def convert_from(self, element, base): """Convert ``element`` to ``self.dtype`` given the base domain. """ if base.alias is not None: method = "from_" + base.alias else: method = "from_" + base.__class__.__name__ _convert = getattr(self, method) if _convert is not None: result = _convert(element, base) if result is not None: return result raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self)) def convert(self, element, base=None): """Convert ``element`` to ``self.dtype``. """ if base is not None: if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) return self.convert_from(element, base) if self.of_type(element): return element if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) from sympy.polys.domains import ZZ, QQ, RealField, ComplexField if ZZ.of_type(element): return self.convert_from(element, ZZ) if isinstance(element, int): return self.convert_from(ZZ(element), ZZ) if HAS_GMPY: integers = ZZ if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = QQ if isinstance(element, rationals.tp): return self.convert_from(element, rationals) if isinstance(element, float): parent = RealField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, complex): parent = ComplexField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, DomainElement): return self.convert_from(element, element.parent()) # TODO: implement this in from_ methods if self.is_Numerical and getattr(element, 'is_ground', False): return self.convert(element.LC()) if isinstance(element, Basic): try: return self.from_sympy(element) except (TypeError, ValueError): pass else: # TODO: remove this branch if not is_sequence(element): try: element = sympify(element, strict=True) if isinstance(element, Basic): return self.from_sympy(element) except (TypeError, ValueError): pass raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self)) def of_type(self, element): """Check if ``a`` is of type ``dtype``. """ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement def __contains__(self, a): """Check if ``a`` belongs to this domain. """ try: if _not_a_coeff(a): raise CoercionFailed self.convert(a) # this might raise, too except CoercionFailed: return False return True def to_sympy(self, a): """Convert domain element *a* to a SymPy expression (Expr). Explanation =========== Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most public SymPy functions work with objects of type :py:class:`~.Expr`. The elements of a :py:class:`~.Domain` have a different internal representation. It is not possible to mix domain elements with :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and :py:meth:`~.Domain.from_sympy` methods to convert its domain elements to and from :py:class:`~.Expr`. Parameters ========== a: domain element An element of this :py:class:`~.Domain`. Returns ======= expr: Expr A normal sympy expression of type :py:class:`~.Expr`. Examples ======== Construct an element of the :ref:`QQ` domain and then convert it to :py:class:`~.Expr`. >>> from sympy import QQ, Expr >>> q_domain = QQ(2) >>> q_domain 2 >>> q_expr = QQ.to_sympy(q_domain) >>> q_expr 2 Although the printed forms look similar these objects are not of the same type. >>> isinstance(q_domain, Expr) False >>> isinstance(q_expr, Expr) True Construct an element of :ref:`K[x]` and convert to :py:class:`~.Expr`. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> x_domain = K.gens[0] # generator x as a domain element >>> p_domain = x_domain**2/3 + 1 >>> p_domain 1/3*x**2 + 1 >>> p_expr = K.to_sympy(p_domain) >>> p_expr x**2/3 + 1 The :py:meth:`~.Domain.from_sympy` method is used for the opposite conversion from a normal SymPy expression to a domain element. >>> p_domain == p_expr False >>> K.from_sympy(p_expr) == p_domain True >>> K.to_sympy(p_domain) == p_expr True >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain True >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr True The :py:meth:`~.Domain.from_sympy` method makes it easier to construct domain elements interactively. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> K.from_sympy(x**2/3 + 1) 1/3*x**2 + 1 See also ======== from_sympy convert_from """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy expression to an element of this domain. Explanation =========== See :py:meth:`~.Domain.to_sympy` for explanation and examples. Parameters ========== expr: Expr A normal sympy expression of type :py:class:`~.Expr`. Returns ======= a: domain element An element of this :py:class:`~.Domain`. See also ======== to_sympy convert_from """ raise NotImplementedError def sum(self, args): return sum(args) def from_FF(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return None def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return None def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return None def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return None def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return None def from_RealField(K1, a, K0): """Convert a real element object to ``dtype``. """ return None def from_ComplexField(K1, a, K0): """Convert a complex element to ``dtype``. """ return None def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ return None def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.is_ground: return K1.convert(a.LC, K0.dom) def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ return None def from_MonogenicFiniteExtension(K1, a, K0): """Convert an ``ExtensionElement`` to ``dtype``. """ return K1.convert_from(a.rep, K0.ring) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a.ex) def from_ExpressionRawDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a) def from_GlobalPolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.degree() <= 0: return K1.convert(a.LC(), K0.dom) def from_GeneralizedPolynomialRing(K1, a, K0): return K1.from_FractionField(a, K0) def unify_with_symbols(K0, K1, symbols): if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))): raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols))) return K0.unify(K1) def unify(K0, K1, symbols=None): """ Construct a minimal domain that contains elements of ``K0`` and ``K1``. Known domains (from smallest to largest): - ``GF(p)`` - ``ZZ`` - ``QQ`` - ``RR(prec, tol)`` - ``CC(prec, tol)`` - ``ALG(a, b, c)`` - ``K[x, y, z]`` - ``K(x, y, z)`` - ``EX`` """ if symbols is not None: return K0.unify_with_symbols(K1, symbols) if K0 == K1: return K0 if K0.is_EXRAW: return K0 if K1.is_EXRAW: return K1 if K0.is_EX: return K0 if K1.is_EX: return K1 if K0.is_FiniteExtension or K1.is_FiniteExtension: if K1.is_FiniteExtension: K0, K1 = K1, K0 if K1.is_FiniteExtension: # Unifying two extensions. # Try to ensure that K0.unify(K1) == K1.unify(K0) if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus: K0, K1 = K1, K0 return K1.set_domain(K0) else: # Drop the generator from other and unify with the base domain K1 = K1.drop(K0.symbol) K1 = K0.domain.unify(K1) return K0.set_domain(K1) if K0.is_Composite or K1.is_Composite: K0_ground = K0.dom if K0.is_Composite else K0 K1_ground = K1.dom if K1.is_Composite else K1 K0_symbols = K0.symbols if K0.is_Composite else () K1_symbols = K1.symbols if K1.is_Composite else () domain = K0_ground.unify(K1_ground) symbols = _unify_gens(K0_symbols, K1_symbols) order = K0.order if K0.is_Composite else K1.order if ((K0.is_FractionField and K1.is_PolynomialRing or K1.is_FractionField and K0.is_PolynomialRing) and (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field and domain.has_assoc_Ring): domain = domain.get_ring() if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing): cls = K0.__class__ else: cls = K1.__class__ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing if cls == GlobalPolynomialRing: return cls(domain, symbols) return cls(domain, symbols, order) def mkinexact(cls, K0, K1): prec = max(K0.precision, K1.precision) tol = max(K0.tolerance, K1.tolerance) return cls(prec=prec, tol=tol) if K1.is_ComplexField: K0, K1 = K1, K0 if K0.is_ComplexField: if K1.is_ComplexField or K1.is_RealField: return mkinexact(K0.__class__, K0, K1) else: return K0 if K1.is_RealField: K0, K1 = K1, K0 if K0.is_RealField: if K1.is_RealField: return mkinexact(K0.__class__, K0, K1) elif K1.is_GaussianRing or K1.is_GaussianField: from sympy.polys.domains.complexfield import ComplexField return ComplexField(prec=K0.precision, tol=K0.tolerance) else: return K0 if K1.is_AlgebraicField: K0, K1 = K1, K0 if K0.is_AlgebraicField: if K1.is_GaussianRing: K1 = K1.get_field() if K1.is_GaussianField: K1 = K1.as_AlgebraicField() if K1.is_AlgebraicField: return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext)) else: return K0 if K0.is_GaussianField: return K0 if K1.is_GaussianField: return K1 if K0.is_GaussianRing: if K1.is_RationalField: K0 = K0.get_field() return K0 if K1.is_GaussianRing: if K0.is_RationalField: K1 = K1.get_field() return K1 if K0.is_RationalField: return K0 if K1.is_RationalField: return K1 if K0.is_IntegerRing: return K0 if K1.is_IntegerRing: return K1 if K0.is_FiniteField and K1.is_FiniteField: return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key)) from sympy.polys.domains import EX return EX def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, Domain) and self.dtype == other.dtype def __ne__(self, other): """Returns ``False`` if two domains are equivalent. """ return not self == other def map(self, seq): """Rersively apply ``self`` to all elements of ``seq``. """ result = [] for elt in seq: if isinstance(elt, list): result.append(self.map(elt)) else: result.append(self(elt)) return result def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def get_field(self): """Returns a field associated with ``self``. """ raise DomainError('there is no field associated with %s' % self) def get_exact(self): """Returns an exact domain associated with ``self``. """ return self def __getitem__(self, symbols): """The mathematical way to make a polynomial ring. """ if hasattr(symbols, '__iter__'): return self.poly_ring(*symbols) else: return self.poly_ring(symbols) def poly_ring(self, *symbols, order=lex): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.polynomialring import PolynomialRing return PolynomialRing(self, symbols, order) def frac_field(self, *symbols, order=lex): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.fractionfield import FractionField return FractionField(self, symbols, order) def old_poly_ring(self, *symbols, **kwargs): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.old_polynomialring import PolynomialRing return PolynomialRing(self, *symbols, **kwargs) def old_frac_field(self, *symbols, **kwargs): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.old_fractionfield import FractionField return FractionField(self, *symbols, **kwargs) def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """ raise DomainError("Cannot create algebraic field over %s" % self) def inject(self, *symbols): """Inject generators into this domain. """ raise NotImplementedError def drop(self, *symbols): """Drop generators from this domain. """ if self.is_Simple: return self raise NotImplementedError # pragma: no cover def is_zero(self, a): """Returns True if ``a`` is zero. """ return not a def is_one(self, a): """Returns True if ``a`` is one. """ return a == self.one def is_positive(self, a): """Returns True if ``a`` is positive. """ return a > 0 def is_negative(self, a): """Returns True if ``a`` is negative. """ return a < 0 def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a <= 0 def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a >= 0 def canonical_unit(self, a): if self.is_negative(a): return -self.one else: return self.one def abs(self, a): """Absolute value of ``a``, implies ``__abs__``. """ return abs(a) def neg(self, a): """Returns ``a`` negated, implies ``__neg__``. """ return -a def pos(self, a): """Returns ``a`` positive, implies ``__pos__``. """ return +a def add(self, a, b): """Sum of ``a`` and ``b``, implies ``__add__``. """ return a + b def sub(self, a, b): """Difference of ``a`` and ``b``, implies ``__sub__``. """ return a - b def mul(self, a, b): """Product of ``a`` and ``b``, implies ``__mul__``. """ return a * b def pow(self, a, b): """Raise ``a`` to power ``b``, implies ``__pow__``. """ return a ** b def exquo(self, a, b): """Exact quotient of *a* and *b*. Analogue of ``a / b``. Explanation =========== This is essentially the same as ``a / b`` except that an error will be raised if the division is inexact (if there is any remainder) and the result will always be a domain element. When working in a :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ` or :ref:`K[x]`) ``exquo`` should be used instead of ``/``. The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does not raise an exception) then ``a == b*q``. Examples ======== We can use ``K.exquo`` instead of ``/`` for exact division. >>> from sympy import ZZ >>> ZZ.exquo(ZZ(4), ZZ(2)) 2 >>> ZZ.exquo(ZZ(5), ZZ(2)) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 5 in ZZ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero divisor) is always exact so in that case ``/`` can be used instead of :py:meth:`~.Domain.exquo`. >>> from sympy import QQ >>> QQ.exquo(QQ(5), QQ(2)) 5/2 >>> QQ(5) / QQ(2) 5/2 Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= q: domain element The exact quotient Raises ====== ExactQuotientFailed: if exact division is not possible. ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` Notes ===== Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int`` (or ``mpz``) division as ``a / b`` should not be used as it would give a ``float``. >>> ZZ(4) / ZZ(2) 2.0 >>> ZZ(5) / ZZ(2) 2.5 Using ``/`` with :ref:`ZZ` will lead to incorrect results so :py:meth:`~.Domain.exquo` should be used instead. """ raise NotImplementedError def quo(self, a, b): """Quotient of *a* and *b*. Analogue of ``a // b``. ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def rem(self, a, b): """Modulo division of *a* and *b*. Analogue of ``a % b``. ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== quo: Analogue of ``a // b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def div(self, a, b): """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)`` Explanation =========== This is essentially the same as ``divmod(a, b)`` except that is more consistent when working over some :py:class:`~.Field` domains such as :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the :py:meth:`~.Domain.div` method should be used instead of ``divmod``. The key invariant is that if ``q, r = K.div(a, b)`` then ``a == b*q + r``. The result of ``K.div(a, b)`` is the same as the tuple ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and remainder are needed then it is more efficient to use :py:meth:`~.Domain.div`. Examples ======== We can use ``K.div`` instead of ``divmod`` for floor division and remainder. >>> from sympy import ZZ, QQ >>> ZZ.div(ZZ(5), ZZ(2)) (2, 1) If ``K`` is a :py:class:`~.Field` then the division is always exact with a remainder of :py:attr:`~.Domain.zero`. >>> QQ.div(QQ(5), QQ(2)) (5/2, 0) Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= (q, r): tuple of domain elements The quotient and remainder Raises ====== ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` exquo: Analogue of ``a / b`` Notes ===== If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type defines ``divmod`` in a way that is undesirable so :py:meth:`~.Domain.div` should be used instead of ``divmod``. >>> a = QQ(1) >>> b = QQ(3, 2) >>> a # doctest: +SKIP mpq(1,1) >>> b # doctest: +SKIP mpq(3,2) >>> divmod(a, b) # doctest: +SKIP (mpz(0), mpq(1,1)) >>> QQ.div(a, b) # doctest: +SKIP (mpq(2,3), mpq(0,1)) Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so :py:meth:`~.Domain.div` should be used instead. """ raise NotImplementedError def invert(self, a, b): """Returns inversion of ``a mod b``, implies something. """ raise NotImplementedError def revert(self, a): """Returns ``a**(-1)`` if possible. """ raise NotImplementedError def numer(self, a): """Returns numerator of ``a``. """ raise NotImplementedError def denom(self, a): """Returns denominator of ``a``. """ raise NotImplementedError def half_gcdex(self, a, b): """Half extended GCD of ``a`` and ``b``. """ s, t, h = self.gcdex(a, b) return s, h def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ raise NotImplementedError def cofactors(self, a, b): """Returns GCD and cofactors of ``a`` and ``b``. """ gcd = self.gcd(a, b) cfa = self.quo(a, gcd) cfb = self.quo(b, gcd) return gcd, cfa, cfb def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ raise NotImplementedError def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ raise NotImplementedError def log(self, a, b): """Returns b-base logarithm of ``a``. """ raise NotImplementedError def sqrt(self, a): """Returns square root of ``a``. """ raise NotImplementedError def evalf(self, a, prec=None, **options): """Returns numerical approximation of ``a``. """ return self.to_sympy(a).evalf(prec, **options) n = evalf def real(self, a): return a def imag(self, a): return self.zero def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return a == b def characteristic(self): """Return the characteristic of this domain. """ raise NotImplementedError('characteristic()') __all__ = ['Domain']
16,605
3,246
package org.datatransferproject.transfer.koofr.common; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.Credential; import com.google.common.collect.ImmutableList; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.apache.commons.io.IOUtils; import org.datatransferproject.api.launcher.Monitor; import org.datatransferproject.spi.transfer.types.DestinationMemoryFullException; import org.datatransferproject.spi.transfer.types.InvalidTokenException; import org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class KoofrClientTest { private MockWebServer server; private KoofrClient client; private KoofrCredentialFactory credentialFactory; private Monitor monitor; private OkHttpClient httpClient; private ObjectMapper mapper; private Credential credential; private TokensAndUrlAuthData authData; @Before public void setUp() throws IOException { server = new MockWebServer(); server.start(); httpClient = new OkHttpClient.Builder().build(); mapper = new ObjectMapper(); monitor = mock(Monitor.class); credentialFactory = mock(KoofrCredentialFactory.class); credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).build(); credential.setAccessToken("acc"); credential.setExpirationTimeMilliseconds(null); when(credentialFactory.createCredential(any())).thenReturn(credential); client = new KoofrClient( server.url("").toString(), httpClient, httpClient, mapper, monitor, credentialFactory); authData = new TokensAndUrlAuthData("acc", "refresh", ""); client.getOrCreateCredential(authData); } @After public void tearDown() throws Exception { server.shutdown(); } @Test public void testFileExists() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); boolean exists = client.fileExists("/path/to/file"); Assert.assertTrue(exists); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("GET", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); } @Test public void testFileExistsNonExistent() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); boolean exists = client.fileExists("/path/to/file"); Assert.assertFalse(exists); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("GET", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); } @Test public void testFileExistsTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return cred; }); server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse().setResponseCode(200)); boolean exists = client.fileExists("/path/to/file"); Assert.assertTrue(exists); Assert.assertEquals(2, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("GET", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); recordedRequest = server.takeRequest(); Assert.assertEquals("GET", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); Assert.assertEquals("Bearer acc1", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); } @Test public void testFileExistsRefreshTokenNotFound() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { throw new InvalidTokenException("Unable to refresh token.", null); }); server.enqueue(new MockResponse().setResponseCode(401)); InvalidTokenException caughtExc = null; try { client.fileExists("/path/to/file"); } catch (InvalidTokenException exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals("Unable to refresh token.", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("GET", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/info?path=%2Fpath%2Fto%2Ffile", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); } @Test public void testFileExistsError() throws Exception { server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error")); Exception caughtExc = null; try { client.fileExists("/path/to/file"); } catch (Exception exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals( "Got error code: 500 message: Server Error body: Internal error", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); } @Test public void testEnsureFolder() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.ensureFolder("/path/to/folder", "name"); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"name\"}", recordedRequest.getBody().readUtf8()); } @Test public void testEnsureFolderAlreadyExists() throws Exception { server.enqueue(new MockResponse().setResponseCode(409)); client.ensureFolder("/path/to/folder", "name"); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"name\"}", recordedRequest.getBody().readUtf8()); } @Test public void testEnsureFolderTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return cred; }); server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse().setResponseCode(200)); client.ensureFolder("/path/to/folder", "name"); Assert.assertEquals(2, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"name\"}", recordedRequest.getBody().readUtf8()); recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc1", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"name\"}", recordedRequest.getBody().readUtf8()); } @Test public void testEnsureFolderError() throws Exception { server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error")); Exception caughtExc = null; try { client.ensureFolder("/path/to/folder", "name"); } catch (Exception exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals( "Got error code: 500 message: Server Error body: Internal error", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); } @Test public void testAddDescription() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.addDescription("/path/to/folder", "Test description"); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/tags/add?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals( "{\"tags\":{\"description\":[\"Test description\"]}}", recordedRequest.getBody().readUtf8()); } @Test public void testAddDescriptionTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return cred; }); server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse().setResponseCode(200)); client.addDescription("/path/to/folder", "Test description"); Assert.assertEquals(2, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/tags/add?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals( "{\"tags\":{\"description\":[\"Test description\"]}}", recordedRequest.getBody().readUtf8()); recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/tags/add?path=%2Fpath%2Fto%2Ffolder", recordedRequest.getPath()); Assert.assertEquals("Bearer acc1", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals( "{\"tags\":{\"description\":[\"Test description\"]}}", recordedRequest.getBody().readUtf8()); } @Test public void testAddDescriptionError() throws Exception { server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error")); Exception caughtExc = null; try { client.addDescription("/path/to/folder", "Test description"); } catch (Exception exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals( "Got error code: 500 message: Server Error body: Internal error", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); } @Test public void testUploadFile() throws Exception { server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"name\":\"image.jpg\",\"type\":\"file\",\"modified\":1591868314156,\"size\":5,\"contentType\":\"image/jpeg\",\"hash\":\"d05374dc381d9b52806446a71c8e79b1\",\"tags\":{}}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); String fullPath = client.uploadFile("/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, null); Assert.assertEquals("/path/to/folder/image.jpg", fullPath); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileModified() throws Exception { server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"name\":\"image.jpg\",\"type\":\"file\",\"modified\":1591868314156,\"size\":5,\"contentType\":\"image/jpeg\",\"hash\":\"d05374dc381d9b52806446a71c8e79b1\",\"tags\":{}}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); final Date modified = new Date(1596450052000L); String fullPath = client.uploadFile( "/path/to/folder", "image.jpg", inputStream, "image/jpeg", modified, null); Assert.assertEquals("/path/to/folder/image.jpg", fullPath); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true&modified=1596450052000", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileDescription() throws Exception { server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"name\":\"image.jpg\",\"type\":\"file\",\"modified\":1591868314156,\"size\":5,\"contentType\":\"image/jpeg\",\"hash\":\"d05374dc381d9b52806446a71c8e79b1\",\"tags\":{}}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); String fullPath = client.uploadFile( "/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, "Test description"); Assert.assertEquals("/path/to/folder/image.jpg", fullPath); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true&tags=description%3DTest+description", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileRenamed() throws Exception { server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"name\":\"image (1).jpg\",\"type\":\"file\",\"modified\":1591868314156,\"size\":5,\"contentType\":\"image/jpeg\",\"hash\":\"d05374dc381d9b52806446a71c8e79b1\",\"tags\":{}}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); String fullPath = client.uploadFile("/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, null); Assert.assertEquals("/path/to/folder/image (1).jpg", fullPath); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileOutOfSpace() throws Exception { server.enqueue( new MockResponse() .setResponseCode(413) .setHeader("Content-Type", "application/json") .setBody( "{\"error\":{\"code\":\"QuotaExceeded\",\"message\":\"Quota exceeded\"},\"requestId\":\"bad2465e-300e-4079-57ad-46b256e74d21\"}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); DestinationMemoryFullException caughtExc = null; try { client.uploadFile("/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, null); } catch (DestinationMemoryFullException exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals("Koofr quota exceeded", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return cred; }); server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"name\":\"image.jpg\",\"type\":\"file\",\"modified\":1591868314156,\"size\":5,\"contentType\":\"image/jpeg\",\"hash\":\"d05374dc381d9b52806446a71c8e79b1\",\"tags\":{}}")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); String fullPath = client.uploadFile("/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, null); Assert.assertEquals("/path/to/folder/image.jpg", fullPath); Assert.assertEquals(2, server.getRequestCount()); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/content/api/v2/mounts/primary/files/put?path=%2Fpath%2Fto%2Ffolder&filename=image.jpg&autorename=true&info=true", recordedRequest.getPath()); Assert.assertEquals("Bearer acc1", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals("image/jpeg", recordedRequest.getHeader("Content-Type")); Assert.assertEquals(5, recordedRequest.getBodySize()); } @Test public void testUploadFileError() throws Exception { server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error")); final InputStream inputStream = new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4}); Exception caughtExc = null; try { client.uploadFile("/path/to/folder", "image.jpg", inputStream, "image/jpeg", null, null); } catch (Exception exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals( "Got error code: 500 message: Server Error body: Internal error", caughtExc.getMessage()); Assert.assertEquals(1, server.getRequestCount()); } @Test public void testListRecursive() throws Exception { final String listRecursiveResponse = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("listrecursive.jsonl"), StandardCharsets.UTF_8); server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/x-ndjson; charset=utf-8") .setChunkedBody(listRecursiveResponse, 1024)); List<FilesListRecursiveItem> items = client.listRecursive("/Data transfer"); Assert.assertEquals(Fixtures.listRecursiveItems, items); } @Test public void testListRecursiveNotFound() throws Exception { server.enqueue( new MockResponse() .setResponseCode(404) .setHeader("Content-Type", "application/json") .setBody( "{\"error\":{\"code\":\"NotFound\",\"message\":\"File not found\"},\"requestId\":\"bad2465e-300e-4079-57ad-46b256e74d21\"}")); List<FilesListRecursiveItem> items = client.listRecursive("/Data transfer"); Assert.assertEquals(ImmutableList.of(), items); } @Test public void testFileLink() throws Exception { server.enqueue( new MockResponse() .setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody( "{\"link\":\"https://app-1.koofr.net/content/files/get/Video+1.mp4?base=TESTBASE\"}")); String link = client.fileLink("/Data transfer/Videos/Video 1.mp4"); Assert.assertEquals( "https://app-1.koofr.net/content/files/get/Video+1.mp4?base=TESTBASE", link); } @Test public void testEnsureRootFolder() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals("/api/v2/mounts/primary/files/folder?path=%2F", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"Data transfer\"}", recordedRequest.getBody().readUtf8()); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); } @Test public void testEnsureVideosFolder() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); server.takeRequest(); server.enqueue(new MockResponse().setResponseCode(200)); client.ensureVideosFolder(); Assert.assertEquals(2, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2FData+transfer", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"Videos\"}", recordedRequest.getBody().readUtf8()); client.ensureVideosFolder(); Assert.assertEquals(2, server.getRequestCount()); } }
10,349
841
# Copyright (c) 2012 iQIYI Inc. # Copyright (c) 2013 Tencent Inc. # All rights reserved. # # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # Date: October 13, 2012 """ A helper class to get the files generated from thrift IDL files. """ import os import blade import configparse import console import build_rules import java_jar_target import py_targets from blade_util import var_to_list from cc_targets import CcTarget from thrift_helper import ThriftHelper class ThriftLibrary(CcTarget): """A scons thrift library target subclass. This class is derived from CcTarget. """ def __init__(self, name, srcs, deps, optimize, deprecated, blade, kwargs): """Init method. Init the thrift target. """ srcs = var_to_list(srcs) self._check_thrift_srcs_name(srcs) CcTarget.__init__(self, name, 'thrift_library', srcs, deps, '', [], [], [], optimize, [], [], blade, kwargs) self.data['python_vars'] = [] self.data['python_sources'] = [] thrift_config = configparse.blade_config.get_config('thrift_config') thrift_lib = var_to_list(thrift_config['thrift_libs']) thrift_bin = thrift_config['thrift'] if thrift_bin.startswith("//"): dkey = self._convert_string_to_target_helper(thrift_bin) if dkey not in self.expanded_deps: self.expanded_deps.append(dkey) if dkey not in self.deps: self.deps.append(dkey) # Hardcode deps rule to thrift libraries. self._add_hardcode_library(thrift_lib) # Link all the symbols by default self.data['link_all_symbols'] = True self.data['deprecated'] = deprecated self.data['java_sources_explict_dependency'] = [] # For each thrift file initialize a ThriftHelper, which will be used # to get the source files generated from thrift file. self.thrift_helpers = {} for src in srcs: self.thrift_helpers[src] = ThriftHelper( os.path.join(self.path, src)) def _check_thrift_srcs_name(self, srcs): """_check_thrift_srcs_name. Checks whether the thrift file's name ends with 'thrift'. """ error = 0 for src in srcs: base_name = os.path.basename(src) pos = base_name.rfind('.') if pos == -1: console.error('invalid thrift file name %s' % src) error += 1 file_suffix = base_name[pos + 1:] if file_suffix != 'thrift': console.error('invalid thrift file name %s' % src) error += 1 if error > 0: console.error_exit('invalid thrift file names found.') def _generate_header_files(self): """Whether this target generates header files during building.""" return True def _thrift_gen_cpp_files(self, path, src): """_thrift_gen_cpp_files. Get the c++ files generated from thrift file. """ return [self._target_file_path(path, f) for f in self.thrift_helpers[src].get_generated_cpp_files()] def _thrift_gen_py_files(self, path, src): """_thrift_gen_py_files. Get the python files generated from thrift file. """ return [self._target_file_path(path, f) for f in self.thrift_helpers[src].get_generated_py_files()] def _thrift_gen_java_files(self, path, src): """_thrift_gen_java_files. Get the java files generated from thrift file. """ return [self._target_file_path(path, f) for f in self.thrift_helpers[src].get_generated_java_files()] def _thrift_java_rules(self): """_thrift_java_rules. Generate scons rules for the java files from thrift file. """ for src in self.srcs: src_path = os.path.join(self.path, src) thrift_java_src_files = self._thrift_gen_java_files(self.path, src) self._write_rule('%s.ThriftJava(%s, "%s")' % ( self._env_name(), str(thrift_java_src_files), src_path)) self.data['java_sources'] = ( os.path.dirname(thrift_java_src_files[0]), os.path.join(self.build_path, self.path), self.name) self.data['java_sources_explict_dependency'] += thrift_java_src_files def _thrift_python_rules(self): """_thrift_python_rules. Generate python files. """ for src in self.srcs: src_path = os.path.join(self.path, src) thrift_py_src_files = self._thrift_gen_py_files(self.path, src) py_cmd_var = '%s_python' % self._generate_variable_name( self.path, self.name) self._write_rule('%s = %s.ThriftPython(%s, "%s")' % ( py_cmd_var, self._env_name(), str(thrift_py_src_files), src_path)) self.data['python_vars'].append(py_cmd_var) self.data['python_sources'] += thrift_py_src_files def scons_rules(self): """scons_rules. It outputs the scons rules according to user options. """ self._prepare_to_generate_rule() # Build java source according to its option env_name = self._env_name() self.options = self.blade.get_options() self.direct_targets = self.blade.get_direct_targets() if (getattr(self.options, 'generate_java', False) or self.data.get('generate_java') or self.key in self.direct_targets): self._thrift_java_rules() if (getattr(self.options, 'generate_python', False) or self.data.get('generate_python') or self.key in self.direct_targets): self._thrift_python_rules() self._setup_cc_flags() sources = [] obj_names = [] for src in self.srcs: thrift_cpp_files = self._thrift_gen_cpp_files(self.path, src) thrift_cpp_src_files = [f for f in thrift_cpp_files if f.endswith('.cpp')] self._write_rule('%s.Thrift(%s, "%s")' % ( env_name, str(thrift_cpp_files), os.path.join(self.path, src))) for thrift_cpp_src in thrift_cpp_src_files: obj_name = '%s_object' % self._generate_variable_name( self.path, thrift_cpp_src) obj_names.append(obj_name) self._write_rule( '%s = %s.SharedObject(target="%s" + top_env["OBJSUFFIX"], ' 'source="%s")' % (obj_name, env_name, thrift_cpp_src, thrift_cpp_src)) sources.append(thrift_cpp_src) self._write_rule('%s = [%s]' % (self._objs_name(), ','.join(obj_names))) self._write_rule('%s.Depends(%s, %s)' % ( env_name, self._objs_name(), sources)) self._cc_library() options = self.blade.get_options() if (getattr(options, 'generate_dynamic', False) or self.data.get('build_dynamic')): self._dynamic_cc_library() def thrift_library(name, srcs=[], deps=[], optimize=[], deprecated=False, **kwargs): """thrift_library target. """ thrift_library_target = ThriftLibrary(name, srcs, deps, optimize, deprecated, blade.blade, kwargs) blade.blade.register_target(thrift_library_target) build_rules.register_function(thrift_library)
4,533
852
<gh_stars>100-1000 #ifndef ElectronMomentumCorrector_H #define ElectronMomentumCorrector_H //=================================================================== // Author: <NAME> - INFN Milano, Bicocca university // <NAME> - FESB, Split // 12/2005 //adapted to CMSSW by U.Berthon, dec 2006 //=================================================================== #include "DataFormats/EgammaCandidates/interface/GsfElectron.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "DataFormats/Math/interface/LorentzVector.h" namespace egamma { struct ElectronMomentum { const math::XYZTLorentzVector momentum; const float trackError; const float finalError; }; ElectronMomentum correctElectronMomentum(reco::GsfElectron const&, TrajectoryStateOnSurface const&); } // namespace egamma #endif
272
2,151
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrVkVaryingHandler.h" /** Returns the number of locations take up by a given GrSLType. We assume that all scalar values are 32 bits. */ static inline int grsltype_to_location_size(GrSLType type) { switch(type) { case kVoid_GrSLType: return 0; case kFloat_GrSLType: // fall through case kHalf_GrSLType: return 1; case kFloat2_GrSLType: // fall through case kHalf2_GrSLType: return 1; case kFloat3_GrSLType: case kHalf3_GrSLType: return 1; case kFloat4_GrSLType: case kHalf4_GrSLType: return 1; case kUint2_GrSLType: return 1; case kInt2_GrSLType: case kShort2_GrSLType: case kUShort2_GrSLType: return 1; case kInt3_GrSLType: case kShort3_GrSLType: case kUShort3_GrSLType: return 1; case kInt4_GrSLType: case kShort4_GrSLType: case kUShort4_GrSLType: return 1; case kFloat2x2_GrSLType: case kHalf2x2_GrSLType: return 2; case kFloat3x3_GrSLType: case kHalf3x3_GrSLType: return 3; case kFloat4x4_GrSLType: case kHalf4x4_GrSLType: return 4; case kTexture2DSampler_GrSLType: return 0; case kTextureExternalSampler_GrSLType: return 0; case kTexture2DRectSampler_GrSLType: return 0; case kBufferSampler_GrSLType: return 0; case kBool_GrSLType: return 1; case kInt_GrSLType: // fall through case kShort_GrSLType: return 1; case kUint_GrSLType: case kUShort_GrSLType: // fall through return 1; case kTexture2D_GrSLType: return 0; case kSampler_GrSLType: return 0; } SK_ABORT("Unexpected type"); return -1; } void finalize_helper(GrVkVaryingHandler::VarArray& vars) { int locationIndex = 0; for (int i = 0; i < vars.count(); ++i) { GrShaderVar& var = vars[i]; SkString location; location.appendf("location = %d", locationIndex); var.addLayoutQualifier(location.c_str()); int elementSize = grsltype_to_location_size(var.getType()); SkASSERT(elementSize > 0); int numElements = 1; if (var.isArray() && !var.isUnsizedArray()) { numElements = var.getArrayCount(); } SkASSERT(numElements > 0); locationIndex += elementSize * numElements; } // Vulkan requires at least 64 locations to be supported for both vertex output and fragment // input. If we ever hit this assert, then we'll need to add a cap to actually check the // supported input and output values and adjust our supported shaders based on those values. SkASSERT(locationIndex <= 64); } void GrVkVaryingHandler::onFinalize() { finalize_helper(fVertexInputs); finalize_helper(fVertexOutputs); finalize_helper(fGeomInputs); finalize_helper(fGeomOutputs); finalize_helper(fFragInputs); finalize_helper(fFragOutputs); }
1,596
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.customerinsights.implementation; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.customerinsights.fluent.ImagesClient; import com.azure.resourcemanager.customerinsights.fluent.models.ImageDefinitionInner; import com.azure.resourcemanager.customerinsights.models.GetImageUploadUrlInput; import com.azure.resourcemanager.customerinsights.models.ImageDefinition; import com.azure.resourcemanager.customerinsights.models.Images; import com.fasterxml.jackson.annotation.JsonIgnore; public final class ImagesImpl implements Images { @JsonIgnore private final ClientLogger logger = new ClientLogger(ImagesImpl.class); private final ImagesClient innerClient; private final com.azure.resourcemanager.customerinsights.CustomerInsightsManager serviceManager; public ImagesImpl( ImagesClient innerClient, com.azure.resourcemanager.customerinsights.CustomerInsightsManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public ImageDefinition getUploadUrlForEntityType( String resourceGroupName, String hubName, GetImageUploadUrlInput parameters) { ImageDefinitionInner inner = this.serviceClient().getUploadUrlForEntityType(resourceGroupName, hubName, parameters); if (inner != null) { return new ImageDefinitionImpl(inner, this.manager()); } else { return null; } } public Response<ImageDefinition> getUploadUrlForEntityTypeWithResponse( String resourceGroupName, String hubName, GetImageUploadUrlInput parameters, Context context) { Response<ImageDefinitionInner> inner = this.serviceClient().getUploadUrlForEntityTypeWithResponse(resourceGroupName, hubName, parameters, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new ImageDefinitionImpl(inner.getValue(), this.manager())); } else { return null; } } public ImageDefinition getUploadUrlForData( String resourceGroupName, String hubName, GetImageUploadUrlInput parameters) { ImageDefinitionInner inner = this.serviceClient().getUploadUrlForData(resourceGroupName, hubName, parameters); if (inner != null) { return new ImageDefinitionImpl(inner, this.manager()); } else { return null; } } public Response<ImageDefinition> getUploadUrlForDataWithResponse( String resourceGroupName, String hubName, GetImageUploadUrlInput parameters, Context context) { Response<ImageDefinitionInner> inner = this.serviceClient().getUploadUrlForDataWithResponse(resourceGroupName, hubName, parameters, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new ImageDefinitionImpl(inner.getValue(), this.manager())); } else { return null; } } private ImagesClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.customerinsights.CustomerInsightsManager manager() { return this.serviceManager; } }
1,334
471
/////////////////////////////////////////////////////////////////////////////// // Name: tests/intl/intltest.cpp // Purpose: wxLocale unit test // Author: <NAME> // Created: 2007-03-26 // Copyright: (c) 2007 <NAME> /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "testprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif // WX_PRECOMP #include "wx/intl.h" #if wxUSE_INTL // ---------------------------------------------------------------------------- // test class // ---------------------------------------------------------------------------- class IntlTestCase : public CppUnit::TestCase { public: IntlTestCase() { m_locale=NULL; } virtual void setUp(); virtual void tearDown(); private: CPPUNIT_TEST_SUITE( IntlTestCase ); CPPUNIT_TEST( RestoreLocale ); CPPUNIT_TEST( Domain ); CPPUNIT_TEST( Headers ); CPPUNIT_TEST( DateTimeFmtFrench ); CPPUNIT_TEST( DateTimeFmtC ); CPPUNIT_TEST( IsAvailable ); CPPUNIT_TEST_SUITE_END(); void RestoreLocale(); void Domain(); void Headers(); void DateTimeFmtFrench(); void DateTimeFmtC(); void IsAvailable(); static wxString GetDecimalPoint() { return wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER); } wxLocale *m_locale; DECLARE_NO_COPY_CLASS(IntlTestCase) }; // register in the unnamed registry so that these tests are run by default CPPUNIT_TEST_SUITE_REGISTRATION( IntlTestCase ); // also include in its own registry so that these tests can be run alone CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( IntlTestCase, "IntlTestCase" ); void IntlTestCase::setUp() { // Check that French locale is supported, this test doesn't work without it // and all the other function need to check whether m_locale is non-NULL // before continuing if ( !wxLocale::IsAvailable(wxLANGUAGE_FRENCH) ) return; wxLocale::AddCatalogLookupPathPrefix("./intl"); m_locale = new wxLocale; CPPUNIT_ASSERT( m_locale ); // don't load default catalog, it may be unavailable: bool loaded = m_locale->Init(wxLANGUAGE_FRENCH, wxLOCALE_DONT_LOAD_DEFAULT); CPPUNIT_ASSERT( loaded ); m_locale->AddCatalog("internat"); } void IntlTestCase::tearDown() { if (m_locale) { delete m_locale; m_locale = NULL; } } void IntlTestCase::RestoreLocale() { if ( !m_locale ) return; // We must be using the French locale now, it was changed in setUp(). CPPUNIT_ASSERT_EQUAL( ",", GetDecimalPoint() ); // Switch to the English locale. { wxLocale locEn(wxLANGUAGE_ENGLISH); CPPUNIT_ASSERT_EQUAL( ".", GetDecimalPoint() ); } // Verify that after destroying the English locale object, French locale is // restored. CPPUNIT_ASSERT_EQUAL( ",", GetDecimalPoint() ); } void IntlTestCase::Domain() { if (!m_locale) return; // _() searches all domains by default: CPPUNIT_ASSERT_EQUAL( "&Ouvrir un fichier", _("&Open bogus file") ); // search in our domain only: CPPUNIT_ASSERT_EQUAL( "&Ouvrir un fichier", wxGetTranslation("&Open bogus file", "internat") ); // search in a domain that doesn't have this string: CPPUNIT_ASSERT_EQUAL( "&Open bogus file", wxGetTranslation("&Open bogus file", "BogusDomain") ); } void IntlTestCase::Headers() { if ( !m_locale ) return; CPPUNIT_ASSERT_EQUAL( "wxWindows 2.0 i18n sample", m_locale->GetHeaderValue("Project-Id-Version") ); CPPUNIT_ASSERT_EQUAL( "1999-01-13 18:19+0100", m_locale->GetHeaderValue("POT-Creation-Date") ); CPPUNIT_ASSERT_EQUAL( "YEAR-MO-DA HO:MI+ZONE", m_locale->GetHeaderValue("PO-Revision-Date") ); CPPUNIT_ASSERT_EQUAL( "<NAME> <<EMAIL>>", m_locale->GetHeaderValue("Last-Translator") ); CPPUNIT_ASSERT_EQUAL( "1.0", m_locale->GetHeaderValue("MIME-Version") ); CPPUNIT_ASSERT_EQUAL( "text/plain; charset=utf-8", m_locale->GetHeaderValue("Content-Type") ); CPPUNIT_ASSERT_EQUAL( "8bit", m_locale->GetHeaderValue("Content-Transfer-Encoding") ); // check that it fails with a bogus domain: CPPUNIT_ASSERT_EQUAL( "", m_locale->GetHeaderValue("POT-Creation-Date", "Bogus") ); // and that it fails for nonexisting header: CPPUNIT_ASSERT_EQUAL( "", m_locale->GetHeaderValue("X-Not-Here") ); } static wxString NormalizeFormat(const wxString& fmtOrig) { wxString fmt(fmtOrig); #ifdef __GLIBC__ // glibc uses some extensions in its formats which we need to convert to // standard form fmt.Replace("%T", "%H:%M:%S"); fmt.Replace("%e", "%d"); #endif // __GLIBC__ return fmt; } #define WX_ASSERT_EQUAL_FORMAT(msg, expected, actual) \ if ( !actual.empty() ) \ CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, expected, NormalizeFormat(actual)) void IntlTestCase::DateTimeFmtFrench() { if ( !m_locale ) return; #ifdef __GLIBC__ // Versions of glibc up to 2.7 wrongly used periods for French locale // separator. #if __GLIBC__ > 2 || __GLIBC_MINOR__ >= 8 static const char *FRENCH_DATE_FMT = "%d/%m/%Y"; #else static const char *FRENCH_DATE_FMT = "%d.%m.%Y"; #endif static const char *FRENCH_LONG_DATE_FMT = "%a %d %b %Y"; static const char *FRENCH_DATE_TIME_FMT = "%a %d %b %Y %H:%M:%S %Z"; #else static const char *FRENCH_DATE_FMT = "%d/%m/%Y"; static const char *FRENCH_LONG_DATE_FMT = "%A %d %B %Y"; #ifdef __WXOSX__ static const char *FRENCH_DATE_TIME_FMT = "%A %d %B %Y %H:%M:%S"; #else static const char *FRENCH_DATE_TIME_FMT = "%d/%m/%Y %H:%M:%S"; #endif #endif WX_ASSERT_EQUAL_FORMAT( "French short date", FRENCH_DATE_FMT, m_locale->GetInfo(wxLOCALE_SHORT_DATE_FMT) ); WX_ASSERT_EQUAL_FORMAT( "French long date", FRENCH_LONG_DATE_FMT, m_locale->GetInfo(wxLOCALE_LONG_DATE_FMT) ); WX_ASSERT_EQUAL_FORMAT( "French date and time", FRENCH_DATE_TIME_FMT, m_locale->GetInfo(wxLOCALE_DATE_TIME_FMT) ); WX_ASSERT_EQUAL_FORMAT( "French time", "%H:%M:%S", m_locale->GetInfo(wxLOCALE_TIME_FMT) ); } void IntlTestCase::DateTimeFmtC() { // again, glibc uses different defaults #ifdef __GLIBC__ static const char *C_DATE_FMT = "%m/%d/%y"; static const char *C_LONG_DATE_FMT = "%a %b %d %Y"; static const char *C_DATE_TIME_FMT = "%a %b %d %H:%M:%S %Y"; #else static const char *C_DATE_FMT = "%d/%m/%Y"; static const char *C_LONG_DATE_FMT = "%A %d %B %Y"; #ifdef __WXOSX__ static const char *C_DATE_TIME_FMT = "%A %d %B %Y %H:%M:%S"; #else static const char *C_DATE_TIME_FMT = "%d/%m/%Y %H:%M:%S"; #endif #endif setlocale(LC_ALL, "C"); WX_ASSERT_EQUAL_FORMAT( "C short date", C_DATE_FMT, m_locale->GetInfo(wxLOCALE_SHORT_DATE_FMT) ); WX_ASSERT_EQUAL_FORMAT( "C long date", C_LONG_DATE_FMT, m_locale->GetInfo(wxLOCALE_LONG_DATE_FMT) ); WX_ASSERT_EQUAL_FORMAT( "C date and time", C_DATE_TIME_FMT, m_locale->GetInfo(wxLOCALE_DATE_TIME_FMT) ); WX_ASSERT_EQUAL_FORMAT( "C time", "%H:%M:%S", m_locale->GetInfo(wxLOCALE_TIME_FMT) ); } void IntlTestCase::IsAvailable() { const wxString origLocale(setlocale(LC_ALL, NULL)); // Calling IsAvailable() shouldn't change the locale. wxLocale::IsAvailable(wxLANGUAGE_ENGLISH); CPPUNIT_ASSERT_EQUAL( origLocale, setlocale(LC_ALL, NULL) ); } #endif // wxUSE_INTL
3,355
550
package play.data.validation; import java.lang.reflect.Constructor; import java.util.Map; import java.util.TreeMap; import net.sf.oval.Validator; import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; import net.sf.oval.context.OValContext; import play.exceptions.UnexpectedException; @SuppressWarnings("serial") public class CheckWithCheck extends AbstractAnnotationCheck<CheckWith> { final static String mes = "validation.invalid"; Map<String, String> variables = new TreeMap<String, String>(); Check check; @Override public void configure(CheckWith checkWith) { setMessage(checkWith.message()); try { Constructor<?> constructor = checkWith.value().getDeclaredConstructor(); constructor.setAccessible(true); check = (Check)constructor.newInstance(); check.checkWithCheck = this; } catch(Exception e) { throw new UnexpectedException(e); } } @Override protected Map<String, String> createMessageVariables() { return variables; } public boolean isSatisfied(Object validatedObject, Object value, OValContext context, Validator validator) { return check.isSatisfied(validatedObject, value); } public void setVariables() { requireMessageVariablesRecreation(); } }
481
357
<reponame>wfu8/lightwave /* * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.sts.ws; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.util.HashSet; import java.util.Set; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import junit.framework.Assert; import org.junit.Test; import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0.SecurityHeaderType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import com.vmware.identity.diagnostics.DiagnosticsLoggerFactory; import com.vmware.identity.diagnostics.IDiagnosticsLogger; public class SignatureValidatorTest { private static final IDiagnosticsLogger logger = DiagnosticsLoggerFactory .getLogger(SignatureValidatorTest.class); private static final String REQUEST_DIR = "/request/"; private static final String WSSE_PACKAGE = "org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0"; private static final String WSU_PACKAGE = "org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_utility_1_0"; private static final String XMLDSIG_PACKAGE = "org.w3._2000._09.xmldsig_"; private static final String SAML_PACKAGE = "oasis.names.tc.saml._2_0.assertion"; private static final String VALID_REQUEST_BST = "valid_bst.xml"; private static final String VALID_REQUEST2_BST = "valid_bst2.xml"; private static final String VALID_REQUEST_ASSERTION = "valid_assertion.xml"; private final SignatureValidator validator = new SignatureValidator(); private final JAXBContext jaxbCtx; public SignatureValidatorTest() throws JAXBException { jaxbCtx = JAXBContext.newInstance(WSSE_PACKAGE + ":" + WSU_PACKAGE + ":" + XMLDSIG_PACKAGE + ":" + SAML_PACKAGE); } @Test public void validSignatureBST() throws Exception { validSignatureBSTInt(VALID_REQUEST_BST); validSignatureBSTInt(VALID_REQUEST2_BST); } private void validSignatureBSTInt(String requestFileName) throws Exception { Node securityHeader = getSecurityHeader(requestFileName); validator.validate(securityHeader, parseSecurityHeader(securityHeader)); } @Test public void validSignatureAssertion() throws Exception { Node securityHeader = getSecurityHeader(VALID_REQUEST_ASSERTION); validator.validate(securityHeader, parseSecurityHeader(securityHeader)); } @Test public void testInvalid() throws Exception { Set<String> invalidFileNames = getInvalidFileNames(); logger.info("Got {} invalid tests.", invalidFileNames.size()); for (String filename : invalidFileNames) { logger.info("Loading test input {}", filename); Node securityHeader = getSecurityHeader(filename); boolean gotException = false; try { validator.validate(securityHeader, parseSecurityHeader(securityHeader)); } catch (WSFaultException e) { logger.info("Got fault key {}", e.getFaultKey().toString()); gotException = true; } if (!gotException) { Assert.fail("Expected exception not thrown"); } } } @Test(expected = IllegalArgumentException.class) public void testNullSoapHeader() throws Exception { Node securityHeader = getSecurityHeader(VALID_REQUEST_BST); validator.validate(null, parseSecurityHeader(securityHeader)); } @Test(expected = IllegalArgumentException.class) public void testNullSignatureElement() throws Exception { Node securityHeader = getSecurityHeader(VALID_REQUEST_BST); validator.validate(securityHeader, null); } private Set<String> getInvalidFileNames() { Set<String> result = new HashSet<String>(); File requestDirectory = new File(SignatureValidatorTest.class .getResource(REQUEST_DIR).getFile()); for (String fileName : requestDirectory.list()) { if (fileName.contains("invalid")) { result.add(fileName); } } return result; } private SecurityHeaderType parseSecurityHeader(Node element) throws Exception { @SuppressWarnings("unchecked") JAXBElement<SecurityHeaderType> parsedHeader = (JAXBElement<SecurityHeaderType>) jaxbCtx .createUnmarshaller().unmarshal(element); return parsedHeader.getValue(); } private Node getSecurityHeader(String filename) throws Exception { return getRequestElement(filename).getElementsByTagNameNS( WsConstants.WSSE_NS, WsConstants.WSSE_SECURITY_ELEMENT_NAME).item(0); } /** * Loads a file into string * * @param fileName * @return String content of the file * @throws IOException */ private static String loadStreamContent(InputStream stream) throws IOException { StringBuilder content = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { char[] buff = new char[1024]; int i = 0; while ((i = reader.read(buff)) != -1) { content.append(buff, 0, i); } } finally { reader.close(); } return content.toString(); } /** * Load a valid request DOM element. * * @return */ private Element getRequestElement(String filename) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // TODO define a profiled version of SOAP-ENV schema and specify it here // to fix reported errors from XML schema validation, which by default // result in error logs SchemaFactory sf = SchemaFactory .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); InputStream resourceAsStream = SignatureValidatorTest.class .getClassLoader().getResourceAsStream( "WEB-INF/wsdl/sts_xsd/oasis-200401-wss-wssecurity-utility-1.0.xsd"); assert resourceAsStream != null; try { Schema schemaStream = sf.newSchema(new StreamSource(resourceAsStream)); dbf.setSchema(schemaStream); } finally { resourceAsStream.close(); } DocumentBuilder docBuilder = dbf.newDocumentBuilder(); String requestAsString = loadStreamContent(SignatureValidatorTest.class .getResourceAsStream(REQUEST_DIR + filename)); InputSource src = new InputSource(new StringReader(requestAsString)); return docBuilder.parse(src).getDocumentElement(); } }
2,721
1,553
# -*- coding: utf-8 -*- """ SubRip's time format parser: HH:MM:SS,mmm """ import re from datetime import time from pysrt.srtexc import InvalidTimeString from pysrt.comparablemixin import ComparableMixin from pysrt.compat import str, basestring class TimeItemDescriptor(object): # pylint: disable-msg=R0903 def __init__(self, ratio, super_ratio=0): self.ratio = int(ratio) self.super_ratio = int(super_ratio) def _get_ordinal(self, instance): if self.super_ratio: return instance.ordinal % self.super_ratio return instance.ordinal def __get__(self, instance, klass): if instance is None: raise AttributeError return self._get_ordinal(instance) // self.ratio def __set__(self, instance, value): part = self._get_ordinal(instance) - instance.ordinal % self.ratio instance.ordinal += value * self.ratio - part class SubRipTime(ComparableMixin): TIME_PATTERN = '%02d:%02d:%02d,%03d' TIME_REPR = 'SubRipTime(%d, %d, %d, %d)' RE_TIME_SEP = re.compile(r'\:|\.|\,') RE_INTEGER = re.compile(r'^(\d+)') SECONDS_RATIO = 1000 MINUTES_RATIO = SECONDS_RATIO * 60 HOURS_RATIO = MINUTES_RATIO * 60 hours = TimeItemDescriptor(HOURS_RATIO) minutes = TimeItemDescriptor(MINUTES_RATIO, HOURS_RATIO) seconds = TimeItemDescriptor(SECONDS_RATIO, MINUTES_RATIO) milliseconds = TimeItemDescriptor(1, SECONDS_RATIO) def __init__(self, hours=0, minutes=0, seconds=0, milliseconds=0): """ SubRipTime(hours, minutes, seconds, milliseconds) All arguments are optional and have a default value of 0. """ super(SubRipTime, self).__init__() self.ordinal = hours * self.HOURS_RATIO \ + minutes * self.MINUTES_RATIO \ + seconds * self.SECONDS_RATIO \ + milliseconds def __repr__(self): return self.TIME_REPR % tuple(self) def __str__(self): if self.ordinal < 0: # Represent negative times as zero return str(SubRipTime.from_ordinal(0)) return self.TIME_PATTERN % tuple(self) def _compare(self, other, method): return super(SubRipTime, self)._compare(self.coerce(other), method) def _cmpkey(self): return self.ordinal def __add__(self, other): return self.from_ordinal(self.ordinal + self.coerce(other).ordinal) def __iadd__(self, other): self.ordinal += self.coerce(other).ordinal return self def __sub__(self, other): return self.from_ordinal(self.ordinal - self.coerce(other).ordinal) def __isub__(self, other): self.ordinal -= self.coerce(other).ordinal return self def __mul__(self, ratio): return self.from_ordinal(int(round(self.ordinal * ratio))) def __imul__(self, ratio): self.ordinal = int(round(self.ordinal * ratio)) return self @classmethod def coerce(cls, other): """ Coerce many types to SubRipTime instance. Supported types: - str/unicode - int/long - datetime.time - any iterable - dict """ if isinstance(other, SubRipTime): return other if isinstance(other, basestring): return cls.from_string(other) if isinstance(other, int): return cls.from_ordinal(other) if isinstance(other, time): return cls.from_time(other) try: return cls(**other) except TypeError: return cls(*other) def __iter__(self): yield self.hours yield self.minutes yield self.seconds yield self.milliseconds def shift(self, *args, **kwargs): """ shift(hours, minutes, seconds, milliseconds) All arguments are optional and have a default value of 0. """ if 'ratio' in kwargs: self *= kwargs.pop('ratio') self += self.__class__(*args, **kwargs) @classmethod def from_ordinal(cls, ordinal): """ int -> SubRipTime corresponding to a total count of milliseconds """ return cls(milliseconds=int(ordinal)) @classmethod def from_string(cls, source): """ str/unicode(HH:MM:SS,mmm) -> SubRipTime corresponding to serial raise InvalidTimeString """ items = cls.RE_TIME_SEP.split(source) if len(items) != 4: raise InvalidTimeString return cls(*(cls.parse_int(i) for i in items)) @classmethod def parse_int(cls, digits): try: return int(digits) except ValueError: match = cls.RE_INTEGER.match(digits) if match: return int(match.group()) return 0 @classmethod def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000) def to_time(self): """ Convert SubRipTime instance into a pure datetime.time object """ return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
2,477
373
/** @file Header file for PCH PCI Express helpers library Copyright (c) 2019 Intel Corporation. All rights reserved. <BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _PCH_PCI_EXPRESS_HELPERS_LIB_H_ #define _PCH_PCI_EXPRESS_HELPERS_LIB_H_ #include <PchPolicyCommon.h> typedef enum { TpoScale2us, TpoScale10us, TpoScale100us, TpoScaleMax } T_PO_SCALE; typedef struct { UINT32 Value; T_PO_SCALE Scale; } T_POWER_ON; // // Function prototypes // /** Get PCIe port number for enabled port. @param[in] RpBase Root Port pci segment base address @return Root Port number (1 based) **/ UINT32 PciePortNum ( IN UINT64 RpBase ); /** Get PCIe root port index @param[in] RpBase Root Port pci segment base address @return Root Port index (0 based) **/ UINT32 PciePortIndex ( IN UINT64 RpBase ); /** Translate PCIe Port/Lane pair to 0-based PCIe lane number. @param[in] RpIndex Root Port index @param[in] RpLane Root Port Lane (0-3) @retval PCIe lane number (0-based) **/ UINT32 PchPciePhysicalLane ( UINT32 RpIndex, UINT32 RpLane ); /** Checks if lane reversal is enabled on a given root port @param[in] RpIndex Root port index (0-based) @retval TRUE if lane reversal is enbabled, FALSE otherwise **/ BOOLEAN IsPcieLaneReversalEnabled ( IN UINT32 RpIndex ); /** Calculates the index of the first port on the same controller. @param[in] RpIndex Root Port Number (0-based) @retval Index of the first port on the first controller. **/ UINT32 PchGetPcieFirstPortIndex ( IN UINT32 RpIndex ); /* Returns Tpower_on capability of device @param[in] DeviceBase device's PCI segment base address @param[in] L1ssCapOffset offset to L1substates capability in device's extended config space @retval structure containing Tpoweron scale and value */ T_POWER_ON GetTpoCapability ( UINT64 DeviceBase, UINT32 L1ssCapOffset ); /* Converts Tpower_on from value:scale notation to microseconds @param[in] TpoScale T power on scale @param[in] TpoValue T power on value @retval number of microseconds */ UINT32 TpoToUs ( UINT32 TpoScale, UINT32 TpoValue ); /** Find the Offset to a given Capabilities ID CAPID list: 0x01 = PCI Power Management Interface 0x04 = Slot Identification 0x05 = MSI Capability 0x10 = PCI Express Capability @param[in] DeviceBase device's base address @param[in] CapId CAPID to search for @retval 0 CAPID not found @retval Other CAPID found, Offset of desired CAPID **/ UINT8 PcieBaseFindCapId ( IN UINT64 DeviceBase, IN UINT8 CapId ); /** Find the Offset to a given Capabilities ID CAPID list: 0x01 = PCI Power Management Interface 0x04 = Slot Identification 0x05 = MSI Capability 0x10 = PCI Express Capability @param[in] Segment Pci Segment Number @param[in] Bus Pci Bus Number @param[in] Device Pci Device Number @param[in] Function Pci Function Number @param[in] CapId CAPID to search for @retval 0 CAPID not found @retval Other CAPID found, Offset of desired CAPID **/ UINT8 PcieFindCapId ( IN UINT8 Segment, IN UINT8 Bus, IN UINT8 Device, IN UINT8 Function, IN UINT8 CapId ); /** Search and return the offset of desired Pci Express Capability ID CAPID list: 0x0001 = Advanced Error Reporting Capability 0x0002 = Virtual Channel Capability 0x0003 = Device Serial Number Capability 0x0004 = Power Budgeting Capability @param[in] DeviceBase device base address @param[in] CapId Extended CAPID to search for @retval 0 CAPID not found, this includes situation where device doesn't exist @retval Other CAPID found, Offset of desired CAPID **/ UINT16 PcieBaseFindExtendedCapId ( IN UINT64 DeviceBase, IN UINT16 CapId ); /** Search and return the offset of desired Pci Express Capability ID CAPID list: 0x0001 = Advanced Error Rreporting Capability 0x0002 = Virtual Channel Capability 0x0003 = Device Serial Number Capability 0x0004 = Power Budgeting Capability @param[in] Segment Pci Segment Number @param[in] Bus Pci Bus Number @param[in] Device Pci Device Number @param[in] Function Pci Function Number @param[in] CapId Extended CAPID to search for @retval 0 CAPID not found @retval Other CAPID found, Offset of desired CAPID **/ UINT16 PcieFindExtendedCapId ( IN UINT8 Segment, IN UINT8 Bus, IN UINT8 Device, IN UINT8 Function, IN UINT16 CapId ); /* Checks device's Slot Clock Configuration @param[in] Base device's base address @retval TRUE when device device uses slot clock, FALSE otherwise */ BOOLEAN GetScc ( UINT64 Base, UINT8 PcieCapOffset ); /* Sets Common Clock Configuration bit for given device. @param[in] Base device's base address */ VOID EnableCcc ( UINT64 Base, UINT8 PcieCapOffset ); /* Retrains link behind given device. It only makes sense to call it for downstream ports. If called for upstream port nothing will happen, it won't enter infinite loop. @param[in] Base device's base address */ VOID RetrainLink ( UINT64 Base, UINT8 PcieCapOffset, BOOLEAN WaitUntilDone ); /* Checks if device at given address exists @retval TRUE when device exists; FALSE otherwise */ BOOLEAN IsDevicePresent ( UINT64 Base ); /* Checks if device is a multifunction device @param[in] Base device's base address @retval TRUE if multifunction; FALSE otherwise */ BOOLEAN IsMultifunctionDevice ( UINT64 Base ); /* Initializes the following features in rootport and devices behind it: Maximum Payload Size (generic) Rootport packet split (proprietary) EonOfInterrupt forwarding (proprietary) Common Clock Configuration (generic) Generic: any code written according to PCIE Express base specification can do that. Proprietary: code uses registers and features that are specific to Intel silicon and probably only this Reference Code knows how to handle that. If OEM implemented generic feature enabling in his platform code or trusts Operating System to do it, then those features can be deleted from here. CCC requires link retrain, which takes a while. CCC must happen before L0s/L1 programming. If there was guarantee no code would access PCI while links retrain, it would be possible to skip this waiting @param[in] RpSegment address of rootport on PCIe @param[in] RpBus address of rootport on PCIe @param[in] RpDevice address of rootport on PCIe @param[in] RpFunction address of rootport on PCIe @param[in] BusMin minimum Bus number that can be assigned below this rootport @param[in] BusMax maximum Bus number that can be assigned below this rootport */ VOID RootportDownstreamConfiguration ( UINT8 RpSegment, UINT8 RpBus, UINT8 RpDevice, UINT8 RpFunction, UINT8 BusMin, UINT8 BusMax ); /* Configures the following power-management related features in rootport and devices behind it: LTR limit (generic) LTR override (proprietary) Clock Power Management (generic) L1 substates (generic except for the override table) L1.LOW substate (proprietary) L0s and L1 (generic) Generic: any code written according to PCIE Express base specification can do that. Proprietary: code uses registers and features that are specific to Intel silicon and probably only this Reference Code knows how to handle that. If OEM implemented generic feature enabling in his platform code or trusts Operating System to do it, then those features can be deleted from here. @param[in] RpSegment address of rootport on PCIe @param[in] RpBus address of rootport on PCIe @param[in] RpDevice address of rootport on PCIe @param[in] RpFunction address of rootport on PCIe @param[in] BusLimit maximum Bus number that can be assigned below this rootport @param[in] AspmOverrideTableSize size of override array @param[in] AspmOverrideTable array of device that need exceptions in configuration */ VOID RootportDownstreamPmConfiguration ( UINT8 RpSegment, UINT8 RpBus, UINT8 RpDevice, UINT8 RpFunction, UINT8 BusMin, UINT8 BusMax, PCH_PCIE_ROOT_PORT_CONFIG *RpConfig, UINT32 AspmOverrideTableSize, PCH_PCIE_DEVICE_OVERRIDE *AspmOverrideTable ); /** Get current PCIe link speed. @param[in] RpBase Root Port base address @return Link speed **/ UINT32 GetLinkSpeed ( UINT64 RpBase ); /** Get max PCIe link speed supported by the root port. @param[in] RpBase Root Port pci segment base address @return Max link speed **/ UINT32 GetMaxLinkSpeed ( UINT64 RpBase ); /** PCIe controller configuration. **/ typedef enum { Pcie4x1 = 0, Pcie1x2_2x1 = 1, Pcie2x2 = 2, Pcie1x4 = 3 } PCIE_CONTROLLER_CONFIG; #endif // _PEI_DXE_SMM_PCH_PCI_EXPRESS_HELPERS_LIB_H_
4,202
390
import numpy as np from genrl.agents.bandits.multiarmed.base import MABAgent from genrl.core.bandit import MultiArmedBandit class UCBMABAgent(MABAgent): """ Multi-Armed Bandit Solver with Upper Confidence Bound based Action Selection Strategy. Refer to Section 2.7 of Reinforcement Learning: An Introduction. :param bandit: The Bandit to solve :param c: Confidence level which controls degree of exploration :type bandit: MultiArmedlBandit type object :type c: float """ def __init__(self, bandit: MultiArmedBandit, confidence: float = 1.0): super(UCBMABAgent, self).__init__(bandit) self._c = confidence self._quality = np.zeros(shape=(bandit.bandits, bandit.arms)) self._counts = np.zeros(shape=(bandit.bandits, bandit.arms)) self._t = 0 @property def confidence(self) -> float: """float: Confidence level which weights the exploration term""" return self._c @property def quality(self) -> np.ndarray: """numpy.ndarray: q values assigned by the policy to all actions""" return self._quality def select_action(self, context: int) -> int: """ Select an action according to upper confidence bound action selction Take action that maximises a weighted sum of the Q values for the action and an exploration encouragement term controlled by c. :param context: the context to select action for :type context: int :returns: Selected action :rtype: int """ self._t += 1 action = np.argmax( self.quality[context] + self.confidence * np.sqrt(2 * np.log(self._t + 1) / (self.counts[context] + 1)) ) self.action_hist.append((context, action)) return action def update_params(self, context: int, action: int, reward: float) -> None: """ Update parmeters for the policy Updates the regret as the difference between max Q value and that of the action. Updates the Q values according to the reward recieved in this step. :param context: context for which action is taken :param action: action taken for the step :param reward: reward obtained for the step :type context: int :type action: int :type reward: float """ self.reward_hist.append(reward) self._regret += max(self.quality[context]) - self.quality[context, action] self.regret_hist.append(self.regret) self.quality[context, action] += (reward - self.quality[context, action]) / ( self.counts[context, action] + 1 ) self.counts[context, action] += 1
1,066
1,020
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "LICENSE" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.blox.test; import com.fasterxml.jackson.databind.JsonNode; import java.util.function.Function; import org.assertj.core.api.AbstractAssert; public class JsonNodeAssert extends AbstractAssert<JsonNodeAssert, JsonNode> { public JsonNodeAssert(final JsonNode actual) { super(actual, JsonNodeAssert.class); } public static JsonNodeAssert assertThat(JsonNode actual) { return new JsonNodeAssert(actual); } public JsonNodeAssert isObject() { isNotNull(); if (!actual.isObject()) { failWithMessage("Expected node to be an Object node, but was not"); } return this; } public JsonNodeAssert hasNoField(String name) { if (actual.has(name)) { failWithMessage("Expected no field named <%s>, but found a field with that name.", name); } return this; } public JsonNodeAssert hasField(String name) { if (!actual.has(name)) { failWithMessage( "Expected a field named <%s>, but did not find a field with that name.", name); } return this; } public JsonNodeAssert hasField(String name, String expected) { return hasField(name, JsonNode::asText, expected); } public JsonNodeAssert hasField(String name, Integer expected) { return hasField(name, JsonNode::asInt, expected); } private <T> JsonNodeAssert hasField(String name, Function<JsonNode, T> extractor, T expected) { isObject(); hasField(name); JsonNode node = actual.get(name); if (!extractor.apply(node).equals(expected)) { failWithMessage( "Expected field <%s> to have value <%s>, but was <%s>", name, expected, actual); } return this; } public JsonNodeAssert hasNullField(final String name) { isObject(); hasField(name); JsonNode node = actual.get(name); if (!node.isNull()) { failWithMessage("Expected field <%s> to be null, but was <%s>", name, node); } return this; } }
869
1,093
/* * Copyright 2017 Google, 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.kayenta.google.security; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.monitoring.v3.Monitoring; import com.google.api.services.monitoring.v3.MonitoringScopes; import com.google.api.services.storage.Storage; import com.google.api.services.storage.StorageScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.util.Collection; import java.util.Optional; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; @ToString @Slf4j public class GoogleClientFactory { private static String applicationVersion = Optional.ofNullable(GoogleClientFactory.class.getPackage().getImplementationVersion()) .orElse("Unknown"); @Getter private String project; public GoogleClientFactory(String project) { this.project = project; } public Monitoring getMonitoring() throws IOException { HttpTransport httpTransport = buildHttpTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleCredentials credentials = getCredentials(MonitoringScopes.all()); HttpRequestInitializer reqInit = setHttpTimeout(credentials); String applicationName = "Spinnaker/" + applicationVersion; return new Monitoring.Builder(httpTransport, jsonFactory, reqInit) .setApplicationName(applicationName) .build(); } public Storage getStorage() throws IOException { HttpTransport httpTransport = buildHttpTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleCredentials credentials = getCredentials(StorageScopes.all()); HttpRequestInitializer reqInit = setHttpTimeout(credentials); String applicationName = "Spinnaker/" + applicationVersion; return new Storage.Builder(httpTransport, jsonFactory, reqInit) .setApplicationName(applicationName) .build(); } protected GoogleCredentials getCredentials(Collection<String> scopes) throws IOException { log.debug( "Loading credentials for project {} using application default credentials, with scopes {}.", project, scopes); // No JSON key was specified in matching config on key server, so use application default // credentials. return GoogleCredentials.getApplicationDefault().createScoped(scopes); } protected HttpTransport buildHttpTransport() { try { return GoogleNetHttpTransport.newTrustedTransport(); } catch (Exception e) { throw new RuntimeException("Failed to create trusted transport", e); } } static HttpRequestInitializer setHttpTimeout(final GoogleCredentials credentials) { return new HttpCredentialsAdapter(credentials) { @Override public void initialize(HttpRequest httpRequest) throws IOException { super.initialize(httpRequest); httpRequest.setConnectTimeout(2 * 60000); // 2 minutes connect timeout httpRequest.setReadTimeout(2 * 60000); // 2 minutes read timeout } }; } }
1,201
607
<filename>theming/src/main/java/org/pushingpixels/radiance/theming/internal/contrib/randelshofer/quaqua/Quaqua14ColorChooserUI.java /* * @(#)QuaquaColorChooserUI.java 1.1 2005-12-18 * * Copyright (c) 2004 <NAME> * Staldenmattweg 2, Immensee, CH-6405, Switzerland. * All rights reserved. * * This software is the confidential and proprietary information of * Werner Randelshofer. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Werner Randelshofer. */ package org.pushingpixels.radiance.theming.internal.contrib.randelshofer.quaqua; import org.pushingpixels.radiance.theming.internal.contrib.randelshofer.quaqua.colorchooser.RadianceColorChooserPanel; import javax.swing.*; import javax.swing.colorchooser.AbstractColorChooserPanel; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * QuaquaColorChooserUI with enhancements for Java 1.4. * * @author <NAME> * @version 1.1 2005-12-18 Gracefully handle instantiation failures of * color chooser panels. * <br>1.0 29 March 2005 Created. */ public class Quaqua14ColorChooserUI extends Quaqua13ColorChooserUI { private static TransferHandler defaultTransferHandler = new ColorTransferHandler(); private MouseListener previewMouseListener; public static ComponentUI createUI(JComponent c) { return new Quaqua14ColorChooserUI(); } public void installUI(JComponent c) { super.installUI(c); chooser.applyComponentOrientation(c.getComponentOrientation()); } protected void installDefaults() { super.installDefaults(); TransferHandler th = chooser.getTransferHandler(); if (th == null || th instanceof UIResource) { chooser.setTransferHandler(defaultTransferHandler); } } protected void uninstallDefaults() { if (chooser.getTransferHandler() instanceof UIResource) { chooser.setTransferHandler(null); } } protected void installListeners() { super.installListeners(); previewMouseListener = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (chooser.getDragEnabled()) { TransferHandler th = chooser.getTransferHandler(); th.exportAsDrag(chooser, e, TransferHandler.COPY); } } }; } protected void uninstallListeners() { super.uninstallListeners(); previewPanel.removeMouseListener(previewMouseListener); } protected void installPreviewPanel() { if (previewPanel != null) { previewPanel.removeMouseListener(previewMouseListener); } super.installPreviewPanel(); previewPanel.addMouseListener(previewMouseListener); } protected PropertyChangeListener createPropertyChangeListener() { return new PropertyHandler(); } public class PropertyHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { if ( e.getPropertyName().equals( JColorChooser.CHOOSER_PANELS_PROPERTY ) ) { AbstractColorChooserPanel[] oldPanels = (AbstractColorChooserPanel[]) e.getOldValue(); AbstractColorChooserPanel[] newPanels = (AbstractColorChooserPanel[]) e.getNewValue(); for (int i = 0; i < oldPanels.length; i++) { // remove old panels if (oldPanels[i] != null) { Container wrapper = oldPanels[i].getParent(); if (wrapper != null) { Container parent = wrapper.getParent(); if (parent != null) parent.remove(wrapper); // remove from hierarchy oldPanels[i].uninstallChooserPanel(chooser); // uninstall } } } mainPanel.removeAllColorChooserPanels(); for (int i = 0; i < newPanels.length; i++) { if (newPanels[i] != null) { mainPanel.addColorChooserPanel((RadianceColorChooserPanel) newPanels[i]); } } chooser.applyComponentOrientation(chooser.getComponentOrientation()); for (int i = 0; i < newPanels.length; i++) { if (newPanels[i] != null) { newPanels[i].installChooserPanel(chooser); } } } if ( e.getPropertyName().equals( JColorChooser.PREVIEW_PANEL_PROPERTY ) ) { if (e.getNewValue() != previewPanel) { installPreviewPanel(); } } if (e.getPropertyName().equals("componentOrientation")) { ComponentOrientation o = (ComponentOrientation)e.getNewValue(); JColorChooser cc = (JColorChooser)e.getSource(); if (o != e.getOldValue()) { cc.applyComponentOrientation(o); cc.updateUI(); } } } } static class ColorTransferHandler extends TransferHandler implements UIResource { ColorTransferHandler() { super("color"); } } }
2,589
6,034
<filename>user-service-project/user-service-api/src/main/java/cn/iocoder/mall/userservice/rpc/address/dto/UserAddressCreateReqDTO.java package cn.iocoder.mall.userservice.rpc.address.dto; import lombok.Data; import lombok.experimental.Accessors; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * 用户收件地址创建 Request DTO */ @Data @Accessors(chain = true) public class UserAddressCreateReqDTO implements Serializable { /** * 用户编号 */ @NotNull(message = "用户编号不能为空") private Integer userId; /** * 收件人名称 */ @NotEmpty(message = "收件人名称不能为空") private String name; /** * 手机号 */ @NotEmpty(message = "手机号不能为空") private String mobile; /** * 地区编码 */ @NotNull(message = "地区编码不能为空") private Integer areaCode; /** * 收件详细地址 */ @NotEmpty(message = "收件详细地址不能为空") private String detailAddress; /** * 地址类型 */ @NotNull(message = "地址类型不能为空") private Integer type; }
599
2,937
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Tor<NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __Vector_H__ #define __Vector_H__ #include "OgrePrerequisites.h" #include "OgreMath.h" #include "OgreQuaternion.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Math * @{ */ /// helper class to implement legacy API. Notably x, y, z access template <int dims, typename T> struct VectorBase { VectorBase() {} VectorBase(T _x, T _y) { static_assert(dims > 1, "must have at least 2 dimensions"); data[0] = _x; data[1] = _y; } VectorBase(T _x, T _y, T _z) { static_assert(dims > 2, "must have at least 3 dimensions"); data[0] = _x; data[1] = _y; data[2] = _z; } VectorBase(T _x, T _y, T _z, T _w) { static_assert(dims > 3, "must have at least 4 dimensions"); data[0] = _x; data[1] = _y; data[2] = _z; data[3] = _w; } T data[dims]; T* ptr() { return data; } const T* ptr() const { return data; } }; template <> struct _OgreExport VectorBase<2, Real> { VectorBase() {} VectorBase(Real _x, Real _y) : x(_x), y(_y) {} Real x, y; Real* ptr() { return &x; } const Real* ptr() const { return &x; } /** Returns a vector at a point half way between this and the passed in vector. */ Vector2 midPoint( const Vector2& vec ) const; /** Calculates the 2 dimensional cross-product of 2 vectors, which results in a single floating point value which is 2 times the area of the triangle. */ Real crossProduct( const VectorBase& rkVector ) const { return x * rkVector.y - y * rkVector.x; } /** Generates a vector perpendicular to this vector (eg an 'up' vector). @remarks This method will return a vector which is perpendicular to this vector. There are an infinite number of possibilities but this method will guarantee to generate one of them. If you need more control you should use the Quaternion class. */ Vector2 perpendicular(void) const; /** Generates a new random vector which deviates from this vector by a given angle in a random direction. @remarks This method assumes that the random number generator has already been seeded appropriately. @param angle The angle at which to deviate in radians @return A random vector which deviates from this vector by angle. This vector will not be normalised, normalise it if you wish afterwards. */ Vector2 randomDeviant(Radian angle) const; /** Gets the oriented angle between 2 vectors. @remarks Vectors do not have to be unit-length but must represent directions. The angle is comprised between 0 and 2 PI. */ Radian angleTo(const Vector2& other) const; // special points static const Vector2 ZERO; static const Vector2 UNIT_X; static const Vector2 UNIT_Y; static const Vector2 NEGATIVE_UNIT_X; static const Vector2 NEGATIVE_UNIT_Y; static const Vector2 UNIT_SCALE; }; template <> struct _OgreExport VectorBase<3, Real> { VectorBase() {} VectorBase(Real _x, Real _y, Real _z) : x(_x), y(_y), z(_z) {} Real x, y, z; Real* ptr() { return &x; } const Real* ptr() const { return &x; } /** Calculates the cross-product of 2 vectors, i.e. the vector that lies perpendicular to them both. @remarks The cross-product is normally used to calculate the normal vector of a plane, by calculating the cross-product of 2 non-equivalent vectors which lie on the plane (e.g. 2 edges of a triangle). @param rkVector Vector which, together with this one, will be used to calculate the cross-product. @return A vector which is the result of the cross-product. This vector will <b>NOT</b> be normalised, to maximise efficiency - call Vector3::normalise on the result if you wish this to be done. As for which side the resultant vector will be on, the returned vector will be on the side from which the arc from 'this' to rkVector is anticlockwise, e.g. UNIT_Y.crossProduct(UNIT_Z) = UNIT_X, whilst UNIT_Z.crossProduct(UNIT_Y) = -UNIT_X. This is because OGRE uses a right-handed coordinate system. @par For a clearer explanation, look a the left and the bottom edges of your monitor's screen. Assume that the first vector is the left edge and the second vector is the bottom edge, both of them starting from the lower-left corner of the screen. The resulting vector is going to be perpendicular to both of them and will go <i>inside</i> the screen, towards the cathode tube (assuming you're using a CRT monitor, of course). */ Vector3 crossProduct( const Vector3& rkVector ) const; /** Generates a vector perpendicular to this vector (eg an 'up' vector). @remarks This method will return a vector which is perpendicular to this vector. There are an infinite number of possibilities but this method will guarantee to generate one of them. If you need more control you should use the Quaternion class. */ Vector3 perpendicular(void) const; Vector3& operator = ( const Real fScaler ) { x = fScaler; y = fScaler; z = fScaler; return (Vector3&)*this; } /** Calculates the absolute dot (scalar) product of this vector with another. @remarks This function work similar dotProduct, except it use absolute value of each component of the vector to computing. @param vec Vector with which to calculate the absolute dot product (together with this one). @return A Real representing the absolute dot product value. */ Real absDotProduct(const VectorBase& vec) const { return Math::Abs(x * vec.x) + Math::Abs(y * vec.y) + Math::Abs(z * vec.z); } /** Returns a vector at a point half way between this and the passed in vector. */ Vector3 midPoint( const Vector3& vec ) const; /** Generates a new random vector which deviates from this vector by a given angle in a random direction. @remarks This method assumes that the random number generator has already been seeded appropriately. @param angle The angle at which to deviate @param up Any vector perpendicular to this one (which could generated by cross-product of this vector and any other non-colinear vector). If you choose not to provide this the function will derive one on it's own, however if you provide one yourself the function will be faster (this allows you to reuse up vectors if you call this method more than once) @return A random vector which deviates from this vector by angle. This vector will not be normalised, normalise it if you wish afterwards. */ Vector3 randomDeviant(const Radian& angle, const Vector3& up = ZERO) const; /** Gets the shortest arc quaternion to rotate this vector to the destination vector. @remarks If you call this with a dest vector that is close to the inverse of this vector, we will rotate 180 degrees around the 'fallbackAxis' (if specified, or a generated axis if not) since in this case ANY axis of rotation is valid. */ Quaternion getRotationTo(const Vector3& dest, const Vector3& fallbackAxis = ZERO) const; /** Returns whether this vector is within a positional tolerance of another vector, also take scale of the vectors into account. @param rhs The vector to compare with @param tolerance The amount (related to the scale of vectors) that distance of the vector may vary by and still be considered close */ bool positionCloses(const Vector3& rhs, Real tolerance = 1e-03f) const; /** Returns whether this vector is within a directional tolerance of another vector. @param rhs The vector to compare with @param tolerance The maximum angle by which the vectors may vary and still be considered equal @note Both vectors should be normalised. */ bool directionEquals(const Vector3& rhs, const Radian& tolerance) const; /// Extract the primary (dominant) axis from this direction vector const Vector3& primaryAxis() const; // special points static const Vector3 ZERO; static const Vector3 UNIT_X; static const Vector3 UNIT_Y; static const Vector3 UNIT_Z; static const Vector3 NEGATIVE_UNIT_X; static const Vector3 NEGATIVE_UNIT_Y; static const Vector3 NEGATIVE_UNIT_Z; static const Vector3 UNIT_SCALE; }; template <> struct _OgreExport VectorBase<4, Real> { VectorBase() {} VectorBase(Real _x, Real _y, Real _z, Real _w) : x(_x), y(_y), z(_z), w(_w) {} Real x, y, z, w; Real* ptr() { return &x; } const Real* ptr() const { return &x; } Vector4& operator = ( const Real fScalar) { x = fScalar; y = fScalar; z = fScalar; w = fScalar; return (Vector4&)*this; } Vector4& operator = (const VectorBase<3, Real>& rhs) { x = rhs.x; y = rhs.y; z = rhs.z; w = 1.0f; return (Vector4&)*this; } // special points static const Vector4 ZERO; }; /** Standard N-dimensional vector. A direction in N-D space represented as distances along the orthogonal axes. Note that positions, directions and scaling factors can be represented by a vector, depending on how you interpret the values. */ template<int dims, typename T> class Vector : public VectorBase<dims, T> { public: using VectorBase<dims, T>::ptr; /** Default constructor. @note It does <b>NOT</b> initialize the vector for efficiency. */ Vector() {} Vector(T _x, T _y) : VectorBase<dims, T>(_x, _y) {} Vector(T _x, T _y, T _z) : VectorBase<dims, T>(_x, _y, _z) {} Vector(T _x, T _y, T _z, T _w) : VectorBase<dims, T>(_x, _y, _z, _w) {} // use enable_if as function parameter for VC < 2017 compatibility template <int N = dims> explicit Vector(const typename std::enable_if<N == 4, Vector3>::type& rhs, T fW = 1.0f) : VectorBase<dims, T>(rhs.x, rhs.y, rhs.z, fW) {} template<typename U> explicit Vector(const U* _ptr) { for (int i = 0; i < dims; i++) ptr()[i] = T(_ptr[i]); } template<typename U> explicit Vector(const Vector<dims, U>& o) : Vector(o.ptr()) {} explicit Vector(T s) { for (int i = 0; i < dims; i++) ptr()[i] = s; } /** Swizzle-like narrowing operations */ Vector<3, T> xyz() const { static_assert(dims > 3, "just use assignment"); return Vector<3, T>(ptr()); } Vector<2, T> xy() const { static_assert(dims > 2, "just use assignment"); return Vector<2, T>(ptr()); } T operator[](size_t i) const { assert(i < dims); return ptr()[i]; } T& operator[](size_t i) { assert(i < dims); return ptr()[i]; } bool operator==(const Vector& v) const { for (int i = 0; i < dims; i++) if (ptr()[i] != v[i]) return false; return true; } /** Returns whether this vector is within a positional tolerance of another vector. @param rhs The vector to compare with @param tolerance The amount that each element of the vector may vary by and still be considered equal */ bool positionEquals(const Vector& rhs, Real tolerance = 1e-03f) const { for (int i = 0; i < dims; i++) if (!Math::RealEqual(ptr()[i], rhs[i], tolerance)) return false; return true; } bool operator!=(const Vector& v) const { return !(*this == v); } /** Returns true if the vector's scalar components are all greater that the ones of the vector it is compared against. */ bool operator<(const Vector& rhs) const { for (int i = 0; i < dims; i++) if (!(ptr()[i] < rhs[i])) return false; return true; } /** Returns true if the vector's scalar components are all smaller that the ones of the vector it is compared against. */ bool operator>(const Vector& rhs) const { for (int i = 0; i < dims; i++) if (!(ptr()[i] > rhs[i])) return false; return true; } /** Sets this vector's components to the minimum of its own and the ones of the passed in vector. @remarks 'Minimum' in this case means the combination of the lowest value of x, y and z from both vectors. Lowest is taken just numerically, not magnitude, so -1 < 0. */ void makeFloor(const Vector& cmp) { for (int i = 0; i < dims; i++) if (cmp[i] < ptr()[i]) ptr()[i] = cmp[i]; } /** Sets this vector's components to the maximum of its own and the ones of the passed in vector. @remarks 'Maximum' in this case means the combination of the highest value of x, y and z from both vectors. Highest is taken just numerically, not magnitude, so 1 > -3. */ void makeCeil(const Vector& cmp) { for (int i = 0; i < dims; i++) if (cmp[i] > ptr()[i]) ptr()[i] = cmp[i]; } /** Calculates the dot (scalar) product of this vector with another. @remarks The dot product can be used to calculate the angle between 2 vectors. If both are unit vectors, the dot product is the cosine of the angle; otherwise the dot product must be divided by the product of the lengths of both vectors to get the cosine of the angle. This result can further be used to calculate the distance of a point from a plane. @param vec Vector with which to calculate the dot product (together with this one). @return A float representing the dot product value. */ T dotProduct(const VectorBase<dims, T>& vec) const { T ret = 0; for (int i = 0; i < dims; i++) ret += ptr()[i] * vec.ptr()[i]; return ret; } /** Returns the square of the length(magnitude) of the vector. @remarks This method is for efficiency - calculating the actual length of a vector requires a square root, which is expensive in terms of the operations required. This method returns the square of the length of the vector, i.e. the same as the length but before the square root is taken. Use this if you want to find the longest / shortest vector without incurring the square root. */ T squaredLength() const { return dotProduct(*this); } /** Returns true if this vector is zero length. */ bool isZeroLength() const { return squaredLength() < 1e-06 * 1e-06; } /** Returns the length (magnitude) of the vector. @warning This operation requires a square root and is expensive in terms of CPU operations. If you don't need to know the exact length (e.g. for just comparing lengths) use squaredLength() instead. */ Real length() const { return Math::Sqrt(squaredLength()); } /** Returns the distance to another vector. @warning This operation requires a square root and is expensive in terms of CPU operations. If you don't need to know the exact distance (e.g. for just comparing distances) use squaredDistance() instead. */ Real distance(const Vector& rhs) const { return (*this - rhs).length(); } /** Returns the square of the distance to another vector. @remarks This method is for efficiency - calculating the actual distance to another vector requires a square root, which is expensive in terms of the operations required. This method returns the square of the distance to another vector, i.e. the same as the distance but before the square root is taken. Use this if you want to find the longest / shortest distance without incurring the square root. */ T squaredDistance(const Vector& rhs) const { return (*this - rhs).squaredLength(); } /** Normalises the vector. @remarks This method normalises the vector such that it's length / magnitude is 1. The result is called a unit vector. @note This function will not crash for zero-sized vectors, but there will be no changes made to their components. @return The previous length of the vector. */ Real normalise() { Real fLength = length(); // Will also work for zero-sized vectors, but will change nothing // We're not using epsilons because we don't need to. // Read http://www.ogre3d.org/forums/viewtopic.php?f=4&t=61259 if (fLength > Real(0.0f)) { Real fInvLength = 1.0f / fLength; for (int i = 0; i < dims; i++) ptr()[i] *= fInvLength; } return fLength; } /** As normalise, except that this vector is unaffected and the normalised vector is returned as a copy. */ Vector normalisedCopy() const { Vector ret = *this; ret.normalise(); return ret; } /// Check whether this vector contains valid values bool isNaN() const { for (int i = 0; i < dims; i++) if (Math::isNaN(ptr()[i])) return true; return false; } /** Gets the angle between 2 vectors. @remarks Vectors do not have to be unit-length but must represent directions. */ Radian angleBetween(const Vector& dest) const { Real lenProduct = length() * dest.length(); // Divide by zero check if(lenProduct < 1e-6f) lenProduct = 1e-6f; Real f = dotProduct(dest) / lenProduct; f = Math::Clamp(f, (Real)-1.0, (Real)1.0); return Math::ACos(f); } /** Calculates a reflection vector to the plane with the given normal . @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not. */ Vector reflect(const Vector& normal) const { return *this - (2 * dotProduct(normal) * normal); } // Vector: arithmetic updates Vector& operator*=(Real s) { for (int i = 0; i < dims; i++) ptr()[i] *= s; return *this; } Vector& operator/=(Real s) { assert( s != 0.0 ); // legacy assert Real fInv = 1.0f/s; for (int i = 0; i < dims; i++) ptr()[i] *= fInv; return *this; } Vector& operator+=(Real s) { for (int i = 0; i < dims; i++) ptr()[i] += s; return *this; } Vector& operator-=(Real s) { for (int i = 0; i < dims; i++) ptr()[i] -= s; return *this; } Vector& operator+=(const Vector& b) { for (int i = 0; i < dims; i++) ptr()[i] += b[i]; return *this; } Vector& operator-=(const Vector& b) { for (int i = 0; i < dims; i++) ptr()[i] -= b[i]; return *this; } Vector& operator*=(const Vector& b) { for (int i = 0; i < dims; i++) ptr()[i] *= b[i]; return *this; } Vector& operator/=(const Vector& b) { for (int i = 0; i < dims; i++) ptr()[i] /= b[i]; return *this; } // Scalar * Vector friend Vector operator*(Real s, Vector v) { v *= s; return v; } friend Vector operator+(Real s, Vector v) { v += s; return v; } friend Vector operator-(Real s, const Vector& v) { Vector ret; for (int i = 0; i < dims; i++) ret[i] = s - v[i]; return ret; } friend Vector operator/(Real s, const Vector& v) { Vector ret; for (int i = 0; i < dims; i++) ret[i] = s / v[i]; return ret; } // Vector * Scalar Vector operator-() const { return -1 * *this; } const Vector& operator+() const { return *this; } Vector operator*(Real s) const { return s * *this; } Vector operator/(Real s) const { assert( s != 0.0 ); // legacy assert Real fInv = 1.0f / s; return fInv * *this; } Vector operator-(Real s) const { return -s + *this; } Vector operator+(Real s) const { return s + *this; } // Vector * Vector Vector operator+(const Vector& b) const { Vector ret = *this; ret += b; return ret; } Vector operator-(const Vector& b) const { Vector ret = *this; ret -= b; return ret; } Vector operator*(const Vector& b) const { Vector ret = *this; ret *= b; return ret; } Vector operator/(const Vector& b) const { Vector ret = *this; ret /= b; return ret; } friend std::ostream& operator<<(std::ostream& o, const Vector& v) { o << "Vector" << dims << "("; for (int i = 0; i < dims; i++) { o << v[i]; if(i != dims - 1) o << ", "; } o << ")"; return o; } }; inline Vector2 VectorBase<2, Real>::midPoint( const Vector2& vec ) const { return Vector2( ( x + vec.x ) * 0.5f, ( y + vec.y ) * 0.5f ); } inline Vector2 VectorBase<2, Real>::randomDeviant(Radian angle) const { angle *= Math::RangeRandom(-1, 1); Real cosa = Math::Cos(angle); Real sina = Math::Sin(angle); return Vector2(cosa * x - sina * y, sina * x + cosa * y); } inline Radian VectorBase<2, Real>::angleTo(const Vector2& other) const { Radian angle = ((const Vector2*)this)->angleBetween(other); if (crossProduct(other)<0) angle = Radian(Math::TWO_PI) - angle; return angle; } inline Vector2 VectorBase<2, Real>::perpendicular(void) const { return Vector2(-y, x); } inline Vector3 VectorBase<3, Real>::perpendicular() const { // From <NAME>'s article "On picking an orthogonal // vector (and combing coconuts)" Vector3 perp = Math::Abs(x) > Math::Abs(z) ? Vector3(-y, x, 0.0) : Vector3(0.0, -z, y); return perp.normalisedCopy(); } inline Vector3 VectorBase<3, Real>::crossProduct( const Vector3& rkVector ) const { return Vector3( y * rkVector.z - z * rkVector.y, z * rkVector.x - x * rkVector.z, x * rkVector.y - y * rkVector.x); } inline Vector3 VectorBase<3, Real>::midPoint( const Vector3& vec ) const { return Vector3( ( x + vec.x ) * 0.5f, ( y + vec.y ) * 0.5f, ( z + vec.z ) * 0.5f ); } inline Vector3 VectorBase<3, Real>::randomDeviant(const Radian& angle, const Vector3& up) const { Vector3 newUp; if (up == ZERO) { // Generate an up vector newUp = ((const Vector3*)this)->perpendicular(); } else { newUp = up; } // Rotate up vector by random amount around this Quaternion q; q.FromAngleAxis( Radian(Math::UnitRandom() * Math::TWO_PI), (const Vector3&)*this ); newUp = q * newUp; // Finally rotate this by given angle around randomised up q.FromAngleAxis( angle, newUp ); return q * (const Vector3&)(*this); } inline Quaternion VectorBase<3, Real>::getRotationTo(const Vector3& dest, const Vector3& fallbackAxis) const { // From <NAME>'s article "Quaternion from two vectors: // the final version" Real a = Math::Sqrt(((const Vector3*)this)->squaredLength() * dest.squaredLength()); Real b = a + dest.dotProduct(*this); if (Math::RealEqual(b, 2 * a) || a == 0) return Quaternion::IDENTITY; Vector3 axis; if (b < (Real)1e-06 * a) { b = (Real)0.0; axis = fallbackAxis != Vector3::ZERO ? fallbackAxis : Math::Abs(x) > Math::Abs(z) ? Vector3(-y, x, (Real)0.0) : Vector3((Real)0.0, -z, y); } else { axis = this->crossProduct(dest); } Quaternion q(b, axis.x, axis.y, axis.z); q.normalise(); return q; } inline bool VectorBase<3, Real>::positionCloses(const Vector3& rhs, Real tolerance) const { return ((const Vector3*)this)->squaredDistance(rhs) <= (((const Vector3*)this)->squaredLength() + rhs.squaredLength()) * tolerance; } inline bool VectorBase<3, Real>::directionEquals(const Vector3& rhs, const Radian& tolerance) const { Real dot = rhs.dotProduct(*this); Radian angle = Math::ACos(dot); return Math::Abs(angle.valueRadians()) <= tolerance.valueRadians(); } inline const Vector3& VectorBase<3, Real>::primaryAxis() const { Real absx = Math::Abs(x); Real absy = Math::Abs(y); Real absz = Math::Abs(z); if (absx > absy) if (absx > absz) return x > 0 ? UNIT_X : NEGATIVE_UNIT_X; else return z > 0 ? UNIT_Z : NEGATIVE_UNIT_Z; else // absx <= absy if (absy > absz) return y > 0 ? UNIT_Y : NEGATIVE_UNIT_Y; else return z > 0 ? UNIT_Z : NEGATIVE_UNIT_Z; } // Math functions inline Vector3 Math::calculateBasicFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3) { Vector3 normal = (v2 - v1).crossProduct(v3 - v1); normal.normalise(); return normal; } inline Vector4 Math::calculateFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3) { Vector3 normal = calculateBasicFaceNormal(v1, v2, v3); // Now set up the w (distance of tri from origin return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1))); } inline Vector3 Math::calculateBasicFaceNormalWithoutNormalize( const Vector3& v1, const Vector3& v2, const Vector3& v3) { return (v2 - v1).crossProduct(v3 - v1); } inline Vector4 Math::calculateFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3) { Vector3 normal = calculateBasicFaceNormalWithoutNormalize(v1, v2, v3); // Now set up the w (distance of tri from origin) return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1))); } /** @} */ /** @} */ } #endif
14,759
778
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: <NAME> // // System includes // External includes // Project includes #include "geometries/geometry.h" #include "includes/define.h" #include "includes/kratos_flags.h" #include "includes/node.h" #include "includes/ublas_interface.h" #include "includes/variables.h" #include "utilities/coordinate_transformation_utilities.h" // Application includes #include "custom_utilities/fluid_calculation_utilities.h" #include "fluid_dynamics_application_variables.h" // Include base h #include "fluid_adjoint_slip_utilities.h" namespace Kratos { FluidAdjointSlipUtilities::FluidAdjointSlipUtilities( const IndexType Dimension, const IndexType BlockSize) : mDimension(Dimension), mBlockSize(BlockSize), mRotationTool(Dimension, mBlockSize) { KRATOS_TRY if (Dimension == 2) { this->mAddNodalRotationDerivativesMethod = &FluidAdjointSlipUtilities::TemplatedAddNodalRotationDerivatives<2>; } else if (Dimension == 3) { this->mAddNodalRotationDerivativesMethod = &FluidAdjointSlipUtilities::TemplatedAddNodalRotationDerivatives<3>; } else { KRATOS_ERROR << "Unsupported dimensionality requested. Only 2D and 3D " "supported. [ Dimension = " << Dimension << " ].\n"; } KRATOS_CATCH(""); } void FluidAdjointSlipUtilities::CalculateRotatedSlipConditionAppliedSlipVariableDerivatives( Matrix& rOutput, const Matrix& rResidualDerivatives, const GeometryType& rGeometry) const { if (rOutput.size1() != rResidualDerivatives.size1() || rOutput.size2() != rResidualDerivatives.size2()) { rOutput.resize(rResidualDerivatives.size1(), rResidualDerivatives.size2(), false); } rOutput.clear(); const IndexType number_of_nodes = rGeometry.PointsNumber(); // add residual derivative contributions for (IndexType a = 0; a < number_of_nodes; ++a) { const auto& r_node = rGeometry[a]; const IndexType block_index = a * mBlockSize; if (r_node.Is(SLIP)) { AddNodalRotationDerivatives(rOutput, rResidualDerivatives, block_index, r_node); if (!r_node.IsFixed(ADJOINT_FLUID_VECTOR_1_X)) { // in here we have to check whether SLIP and not INLET // At the inlet ADJOINT_FLUID_VECTOR_1_X is fixed. // There can be a situation where a node is // shared among both inlet and slip (corner node). In this case // AddNodalApplySlipConditionDerivatives will set all the values in the // column corresponding to ADJOINT_FLUID_VECTOR_1_X of the common node to zero except for the // nodal normal derivative contributions. If the normal is perpendicular to the X direction, then // this will set the diagonal in the column corresponding to this node's ADJOINT_FLUID_VECTOR_1_X dof // to zero. But there can be non-zero off-diagonal due to normal not being zero. Eventhough // ADJOINT_FLUID_VECTOR_1_X will be fixed in the block builder and solver // it will not recognize this column as empty, so diagonal won't be fixed by B&S to 1.0. // Since ADJOINT_FLUID_VECTOR_1_X of this node is fixed, B&S will set all the off-diagonals // to zero. This will create a zero column in the system matrix which makes it singular. // So this check is performed here to avoid this. // In here inlets are alsways assumed to be dirichlet. AddNodalApplySlipConditionDerivatives(rOutput, block_index, r_node); } } else { AddNodalResidualDerivatives(rOutput, rResidualDerivatives, block_index); } } } void FluidAdjointSlipUtilities::CalculateRotatedSlipConditionAppliedNonSlipVariableDerivatives( Matrix& rOutput, const Matrix& rResidualDerivatives, const GeometryType& rGeometry) const { if (rOutput.size1() != rResidualDerivatives.size1() || rOutput.size2() != rResidualDerivatives.size2()) { rOutput.resize(rResidualDerivatives.size1(), rResidualDerivatives.size2(), false); } rOutput.clear(); const IndexType number_of_nodes = rGeometry.PointsNumber(); // add residual derivative contributions for (IndexType a = 0; a < number_of_nodes; ++a) { const auto& r_node = rGeometry[a]; const IndexType block_index = a * mBlockSize; if (r_node.Is(SLIP)) { AddNodalRotationDerivatives(rOutput, rResidualDerivatives, block_index, r_node); // since slip condition is only based on first derivative // variable, make the column zero for all derivatives if (!r_node.IsFixed(ADJOINT_FLUID_VECTOR_1_X)) { // in here we have to check whether SLIP and not INLET. // At the inlet ADJOINT_FLUID_VECTOR_1_X is fixed. // There can be a situation where a node is // shared among both inlet and slip (corner node). In this case // AddNodalApplySlipConditionDerivatives will set all the values in the // column corresponding to ADJOINT_FLUID_VECTOR_1_X of the common node to zero except for the // nodal normal derivative contributions. If the normal is perpendicular to the X direction, then // this will set the diagonal in the column corresponding to this node's ADJOINT_FLUID_VECTOR_1_X dof // to zero. But there can be non-zero off-diagonal due to normal not being zero. Eventhough // ADJOINT_FLUID_VECTOR_1_X will be fixed in the block builder and solver // it will not recognize this column as empty, so diagonal won't be fixed by B&S to 1.0. // Since ADJOINT_FLUID_VECTOR_1_X of this node is fixed, B&S will set all the off-diagonals // to zero. This will create a zero column in the system matrix which makes it singular. // So this check is performed here to avoid this. // In here inlets are alsways assumed to be dirichlet. ClearNodalResidualDerivatives(rOutput, block_index); } } else { AddNodalResidualDerivatives(rOutput, rResidualDerivatives, block_index); } } } void FluidAdjointSlipUtilities::AddNodalApplySlipConditionDerivatives( Matrix& rOutput, const IndexType NodeStartIndex, const NodeType& rNode) const { KRATOS_TRY // Apply slip condition in primal scheme makes first momentum dof // fixed, making the velocity in the normal direction as rhs. // first clear the residual derivative ClearNodalResidualDerivatives(rOutput, NodeStartIndex); auto normal = rNode.FastGetSolutionStepValue(NORMAL); normal /= norm_2(normal); for (IndexType i = 0; i < mDimension; ++i) { rOutput(NodeStartIndex + i, NodeStartIndex) -= normal[i]; } KRATOS_CATCH(""); } void FluidAdjointSlipUtilities::AddNodalResidualDerivatives( Matrix& rOutput, const Matrix& rResidualDerivatives, const IndexType NodeStartIndex) const { KRATOS_TRY // add non-rotated residual derivative contributions for (IndexType c = 0; c < rResidualDerivatives.size1(); ++c) { for (IndexType i = 0; i < mBlockSize; ++i) { rOutput(c, NodeStartIndex + i) += rResidualDerivatives(c, NodeStartIndex + i); } } KRATOS_CATCH(""); } void FluidAdjointSlipUtilities::ClearNodalResidualDerivatives( Matrix& rOutput, const IndexType ResidualIndex) const { for (IndexType c = 0; c < rOutput.size1(); ++c) { rOutput(c, ResidualIndex) = 0.0; } } } // namespace Kratos
3,365
663
<gh_stars>100-1000 /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 <NAME> * * 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. */ #include <stdint.h> #include "py/gc.h" #include "py/mphal.h" #include "py/runtime.h" #include "irq.h" #include "softtimer.h" #define TICKS_PERIOD 0x80000000 #define TICKS_DIFF(t1, t0) ((int32_t)(((t1 - t0 + TICKS_PERIOD / 2) & (TICKS_PERIOD - 1)) - TICKS_PERIOD / 2)) extern __IO uint32_t uwTick; volatile uint32_t soft_timer_next; // Pointer to the pairheap of soft timer objects. // This may contain bss/data pointers as well as GC-heap pointers, // and is explicitly GC traced by soft_timer_gc_mark_all(). STATIC soft_timer_entry_t *soft_timer_heap; STATIC int soft_timer_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) { soft_timer_entry_t *e1 = (soft_timer_entry_t *)n1; soft_timer_entry_t *e2 = (soft_timer_entry_t *)n2; return TICKS_DIFF(e1->expiry_ms, e2->expiry_ms) < 0; } STATIC void soft_timer_schedule_systick(uint32_t ticks_ms) { uint32_t irq_state = disable_irq(); uint32_t uw_tick = uwTick; if (TICKS_DIFF(ticks_ms, uw_tick) <= 0) { soft_timer_next = uw_tick + 1; } else { soft_timer_next = ticks_ms; } enable_irq(irq_state); } void soft_timer_deinit(void) { // Pop off all the nodes which are allocated on the GC-heap. uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV); soft_timer_entry_t *heap_from = soft_timer_heap; soft_timer_entry_t *heap_to = (soft_timer_entry_t *)mp_pairheap_new(soft_timer_lt); while (heap_from != NULL) { soft_timer_entry_t *entry = (soft_timer_entry_t *)mp_pairheap_peek(soft_timer_lt, &heap_from->pairheap); heap_from = (soft_timer_entry_t *)mp_pairheap_pop(soft_timer_lt, &heap_from->pairheap); if (!(entry->flags & SOFT_TIMER_FLAG_GC_ALLOCATED)) { heap_to = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &heap_to->pairheap, &entry->pairheap); } } soft_timer_heap = heap_to; restore_irq_pri(irq_state); } // Must be executed at IRQ_PRI_PENDSV void soft_timer_handler(void) { uint32_t ticks_ms = uwTick; soft_timer_entry_t *heap = soft_timer_heap; while (heap != NULL && TICKS_DIFF(heap->expiry_ms, ticks_ms) <= 0) { soft_timer_entry_t *entry = heap; heap = (soft_timer_entry_t *)mp_pairheap_pop(soft_timer_lt, &heap->pairheap); if (entry->flags & SOFT_TIMER_FLAG_PY_CALLBACK) { mp_sched_schedule(entry->py_callback, MP_OBJ_FROM_PTR(entry)); } else { entry->c_callback(entry); } if (entry->mode == SOFT_TIMER_MODE_PERIODIC) { entry->expiry_ms += entry->delta_ms; heap = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &heap->pairheap, &entry->pairheap); } } soft_timer_heap = heap; if (heap == NULL) { // No more timers left, set largest delay possible soft_timer_next = uwTick; } else { // Set soft_timer_next so SysTick calls us back at the correct time soft_timer_schedule_systick(heap->expiry_ms); } } void soft_timer_gc_mark_all(void) { // Mark all soft timer nodes that are allocated on the GC-heap. // To avoid deep C recursion, pop and recreate the pairheap as nodes are marked. uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV); soft_timer_entry_t *heap_from = soft_timer_heap; soft_timer_entry_t *heap_to = (soft_timer_entry_t *)mp_pairheap_new(soft_timer_lt); while (heap_from != NULL) { soft_timer_entry_t *entry = (soft_timer_entry_t *)mp_pairheap_peek(soft_timer_lt, &heap_from->pairheap); heap_from = (soft_timer_entry_t *)mp_pairheap_pop(soft_timer_lt, &heap_from->pairheap); if (entry->flags & SOFT_TIMER_FLAG_GC_ALLOCATED) { gc_collect_root((void **)&entry, 1); } heap_to = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &heap_to->pairheap, &entry->pairheap); } soft_timer_heap = heap_to; restore_irq_pri(irq_state); } void soft_timer_static_init(soft_timer_entry_t *entry, uint16_t mode, uint32_t delta_ms, void (*cb)(soft_timer_entry_t *)) { entry->flags = 0; entry->mode = mode; entry->delta_ms = delta_ms; entry->c_callback = cb; } void soft_timer_insert(soft_timer_entry_t *entry, uint32_t initial_delta_ms) { mp_pairheap_init_node(soft_timer_lt, &entry->pairheap); entry->expiry_ms = mp_hal_ticks_ms() + initial_delta_ms; uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV); soft_timer_heap = (soft_timer_entry_t *)mp_pairheap_push(soft_timer_lt, &soft_timer_heap->pairheap, &entry->pairheap); if (entry == soft_timer_heap) { // This new timer became the earliest one so set soft_timer_next soft_timer_schedule_systick(entry->expiry_ms); } restore_irq_pri(irq_state); } void soft_timer_remove(soft_timer_entry_t *entry) { uint32_t irq_state = raise_irq_pri(IRQ_PRI_PENDSV); soft_timer_heap = (soft_timer_entry_t *)mp_pairheap_delete(soft_timer_lt, &soft_timer_heap->pairheap, &entry->pairheap); restore_irq_pri(irq_state); }
2,639
973
/*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet; import org.pcap4j.packet.LlcPacket.LlcControl; import org.pcap4j.util.ByteArrays; /** * The Control field of an LLC header in I-format. * * <pre>{@code * 0 1 2 3 4 5 6 7 * +-----+-----+-----+-----+-----+-----+-----+-----+ * | receive sequence number | P/F | * +-----+-----+-----+-----+-----+-----+-----+-----+ * | send sequence number | 0 | * +-----+-----+-----+-----+-----+-----+-----+-----+ * }</pre> * * @see <a href="http://standards.ieee.org/about/get/802/802.2.html">IEEE 802.2</a> * @author <NAME> * @since pcap4j 1.6.5 */ public final class LlcControlInformation implements LlcControl { /** */ private static final long serialVersionUID = -4014592337107864662L; private final byte receiveSequenceNumber; private final boolean pfBit; private final byte sendSequenceNumber; /** * @param value value * @return a new LlcControlInformation object. * @throws IllegalRawDataException if parsing the value fails. */ public static LlcControlInformation newInstance(short value) throws IllegalRawDataException { return new LlcControlInformation(value); } private LlcControlInformation(short value) throws IllegalRawDataException { if ((value & 0x0100) != 0) { StringBuilder sb = new StringBuilder(50); sb.append("value & 0x0100 must be 0. value: ").append(ByteArrays.toHexString(value, " ")); throw new IllegalRawDataException(sb.toString()); } this.receiveSequenceNumber = (byte) ((value >> 1) & 0x7F); if ((value & 0x0001) == 0) { this.pfBit = false; } else { this.pfBit = true; } this.sendSequenceNumber = (byte) ((value >> 9) & 0x7F); } private LlcControlInformation(Builder builder) { if (builder == null) { throw new NullPointerException("builder must not be null."); } if (builder.receiveSequenceNumber < 0) { throw new IllegalArgumentException( "receiveSequenceNumber must be positive. receiveSequenceNumber: " + builder.receiveSequenceNumber); } if (builder.sendSequenceNumber < 0) { throw new IllegalArgumentException( "sendSequenceNumber must be positive. sendSequenceNumber: " + builder.sendSequenceNumber); } this.receiveSequenceNumber = builder.receiveSequenceNumber; this.pfBit = builder.pfBit; this.sendSequenceNumber = builder.sendSequenceNumber; } /** @return receiveSequenceNumber */ public byte getReceiveSequenceNumber() { return receiveSequenceNumber; } /** @return receiveSequenceNumber */ public int getReceiveSequenceNumberAsInt() { return receiveSequenceNumber; } /** @return true if the P/F bit is set to 1; otherwise false. */ public boolean getPfBit() { return pfBit; } /** @return sendSequenceNumber */ public byte getSendSequenceNumber() { return sendSequenceNumber; } /** @return sendSequenceNumber */ public int getSendSequenceNumberAsInt() { return sendSequenceNumber; } @Override public int length() { return 2; } @Override public byte[] getRawData() { byte[] data = new byte[2]; data[1] = (byte) (receiveSequenceNumber << 1); if (pfBit) { data[1] |= 0x01; } data[0] = (byte) (sendSequenceNumber << 1); return data; } /** @return a new Builder object populated with this object's fields. */ public Builder getBuilder() { return new Builder(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[receive sequence number: ") .append(receiveSequenceNumber) .append("] [P/F bit: ") .append(pfBit ? 1 : 0) .append("] [send sequence number: ") .append(sendSequenceNumber) .append("]"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + receiveSequenceNumber; result = prime * result + (pfBit ? 1231 : 1237); result = prime * result + sendSequenceNumber; return result; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!this.getClass().isInstance(obj)) { return false; } LlcControlInformation other = (LlcControlInformation) obj; return receiveSequenceNumber == other.receiveSequenceNumber && sendSequenceNumber == other.sendSequenceNumber && pfBit == other.pfBit; } /** * @author <NAME> * @since pcap4j 1.6.5 */ public static final class Builder { private byte receiveSequenceNumber; private boolean pfBit; private byte sendSequenceNumber; /** */ public Builder() {} private Builder(LlcControlInformation ctrl) { this.receiveSequenceNumber = ctrl.receiveSequenceNumber; this.pfBit = ctrl.pfBit; this.sendSequenceNumber = ctrl.sendSequenceNumber; } /** * @param receiveSequenceNumber receiveSequenceNumber * @return this Builder object for method chaining. */ public Builder receiveSequenceNumber(byte receiveSequenceNumber) { this.receiveSequenceNumber = receiveSequenceNumber; return this; } /** * @param pfBit pfBit * @return this Builder object for method chaining. */ public Builder pfBit(boolean pfBit) { this.pfBit = pfBit; return this; } /** * @param sendSequenceNumber sendSequenceNumber * @return this Builder object for method chaining. */ public Builder sendSequenceNumber(byte sendSequenceNumber) { this.sendSequenceNumber = sendSequenceNumber; return this; } /** @return a new LlcControlInformation object. */ public LlcControlInformation build() { return new LlcControlInformation(this); } } }
2,218
763
package org.batfish.vendor.check_point_management.parsing.parboiled; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.testing.EqualsTester; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; /** Test of {@link DisjunctionAstNode}. */ public final class DisjunctionAstNodeTest { @Test public void testJavaSerialization() { DisjunctionAstNode obj = new DisjunctionAstNode(); assertThat(SerializationUtils.clone(obj), equalTo(obj)); } @Test public void testEquals() { DisjunctionAstNode obj = new DisjunctionAstNode(); new EqualsTester() .addEqualityGroup(obj, new DisjunctionAstNode()) .addEqualityGroup(new DisjunctionAstNode(TcpAstNode.instance())) .testEquals(); } @Test public void testOr() { assertThat( new DisjunctionAstNode().or(TcpAstNode.instance()), equalTo(new DisjunctionAstNode(TcpAstNode.instance()))); assertThat( TcpAstNode.instance().or(UdpAstNode.instance()), equalTo(new DisjunctionAstNode(TcpAstNode.instance(), UdpAstNode.instance()))); } }
429
1,144
<gh_stars>1000+ package de.metas.rest_api.v1.ordercandidates.impl; import de.metas.bpartner.BPartnerId; import de.metas.bpartner.BPartnerLocationId; import de.metas.bpartner.GLN; import de.metas.document.DocBaseAndSubType; import de.metas.impex.model.I_AD_InputDataSource; import de.metas.location.CountryId; import de.metas.location.LocationId; import de.metas.money.CurrencyId; import de.metas.organization.OrgId; import de.metas.payment.PaymentRule; import de.metas.payment.paymentterm.PaymentTermId; import de.metas.pricing.PriceListId; import de.metas.pricing.PriceListVersionId; import de.metas.pricing.PricingSystemId; import de.metas.pricing.rules.IPricingRule; import de.metas.pricing.rules.PriceListVersion; import de.metas.shipping.ShipperId; import de.metas.tax.api.TaxCategoryId; import de.metas.uom.UomId; import lombok.Builder; import lombok.NonNull; import org.adempiere.ad.wrapper.POJOLookupMap; import org.adempiere.ad.wrapper.POJOWrapper; import org.adempiere.pricing.model.I_C_PricingRule; import org.adempiere.warehouse.WarehouseId; import org.adempiere.warehouse.model.I_M_Warehouse; import org.compiere.model.I_C_BP_Group; import org.compiere.model.I_C_BPartner; import org.compiere.model.I_C_BPartner_Location; import org.compiere.model.I_C_DocType; import org.compiere.model.I_C_Location; import org.compiere.model.I_C_PaymentTerm; import org.compiere.model.I_C_TaxCategory; import org.compiere.model.I_M_PriceList; import org.compiere.model.I_M_PriceList_Version; import org.compiere.model.I_M_PricingSystem; import org.compiere.model.I_M_Product; import org.compiere.model.I_M_Shipper; import org.compiere.util.TimeUtil; import org.junit.Ignore; import javax.annotation.Nullable; import java.time.LocalDate; import static de.metas.common.util.CoalesceUtil.coalesce; import static org.adempiere.model.InterfaceWrapperHelper.newInstance; import static org.adempiere.model.InterfaceWrapperHelper.saveRecord; /* * #%L * de.metas.business.rest-api-impl * %% * Copyright (C) 2019 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% */ @Ignore final class TestMasterdata { public static final String RESOURCE_PATH = "/de/metas/rest_api/v1/ordercandidates/impl/"; public void createDataSource(final String internalName) { final I_AD_InputDataSource dataSourceRecord = newInstance(I_AD_InputDataSource.class); dataSourceRecord.setInternalName(internalName); saveRecord(dataSourceRecord); } public void createDocType(final DocBaseAndSubType docBaseAndSubType) { final I_C_DocType docTypeRecord = newInstance(I_C_DocType.class); docTypeRecord.setDocBaseType(docBaseAndSubType.getDocBaseType()); docTypeRecord.setDocSubType(docBaseAndSubType.getDocSubType()); saveRecord(docTypeRecord); } @Builder(builderMethodName = "prepareBPartnerAndLocation", builderClassName = "_BPartnerAndLocationBuilder") private BPartnerLocationId createBPartnerAndLocation( @Nullable final OrgId orgId, @NonNull final String bpValue, @Nullable final String bpExternalId, @Nullable final PricingSystemId salesPricingSystemId, @NonNull final CountryId countryId, @Nullable final GLN gln, @Nullable final String bpLocationExternalId, @Nullable final String vatId) { final I_C_BP_Group groupRecord = newInstance(I_C_BP_Group.class); groupRecord.setName(bpValue + "-name"); if (orgId != null) { groupRecord.setAD_Org_ID(orgId.getRepoId()); } saveRecord(groupRecord); final I_C_BPartner bpRecord = newInstance(I_C_BPartner.class); POJOWrapper.setInstanceName(bpRecord, bpValue); if (orgId != null) { bpRecord.setAD_Org_ID(orgId.getRepoId()); } bpRecord.setValue(bpValue); bpRecord.setName(bpValue + "-name"); bpRecord.setExternalId(bpExternalId); bpRecord.setIsCustomer(true); bpRecord.setM_PricingSystem_ID(PricingSystemId.toRepoId(salesPricingSystemId)); bpRecord.setPaymentRule(PaymentRule.OnCredit.getCode()); bpRecord.setPaymentRulePO(PaymentRule.OnCredit.getCode()); bpRecord.setC_BP_Group_ID(groupRecord.getC_BP_Group_ID()); bpRecord.setVATaxID(vatId); saveRecord(bpRecord); return prepareBPartnerLocation() .orgId(orgId) .bpartnerId(BPartnerId.ofRepoId(bpRecord.getC_BPartner_ID())) .countryId(countryId) .gln(gln) .externalId(bpLocationExternalId) .build(); } @Builder(builderMethodName = "prepareBPartner", builderClassName = "_BPartnerBuilder") private BPartnerId createBPartner( @Nullable final OrgId orgId, @NonNull final String bpValue, @Nullable final String bpExternalId, @Nullable final String bpGroupExistingName, @Nullable final PricingSystemId salesPricingSystemId) { final I_C_BP_Group groupRecord; if (bpGroupExistingName != null) { groupRecord = POJOLookupMap.get() .getFirstOnly(I_C_BP_Group.class, bp -> bp.getName().equals(bpGroupExistingName)); } else { groupRecord = newInstance(I_C_BP_Group.class); groupRecord.setName(bpValue + "-name"); if (orgId != null) { groupRecord.setAD_Org_ID(orgId.getRepoId()); } saveRecord(groupRecord); } final I_C_BPartner bpRecord = newInstance(I_C_BPartner.class); POJOWrapper.setInstanceName(bpRecord, bpValue); if (orgId != null) { bpRecord.setAD_Org_ID(orgId.getRepoId()); } bpRecord.setValue(bpValue); bpRecord.setName(bpValue + "-name"); bpRecord.setExternalId(bpExternalId); bpRecord.setIsCustomer(true); bpRecord.setM_PricingSystem_ID(PricingSystemId.toRepoId(salesPricingSystemId)); bpRecord.setPaymentRule(PaymentRule.OnCredit.getCode()); bpRecord.setPaymentRulePO(PaymentRule.OnCredit.getCode()); bpRecord.setC_BP_Group_ID(groupRecord.getC_BP_Group_ID()); saveRecord(bpRecord); return BPartnerId.ofRepoId(bpRecord.getC_BPartner_ID()); } @Builder(builderMethodName = "prepareBPartnerLocation", builderClassName = "_BPartnerLocationBuilder") private BPartnerLocationId createBPartnerLocation( @Nullable final OrgId orgId, @NonNull final BPartnerId bpartnerId, @NonNull final CountryId countryId, @Nullable final GLN gln, @Nullable final String externalId, final boolean billTo, final boolean billToDefault, final boolean shipTo, final boolean shipToDefault) { final LocationId locationId = createLocation(countryId); final I_C_BPartner_Location bplRecord = newInstance(I_C_BPartner_Location.class); if (orgId != null) { bplRecord.setAD_Org_ID(orgId.getRepoId()); } bplRecord.setC_BPartner_ID(bpartnerId.getRepoId()); bplRecord.setC_Location_ID(locationId.getRepoId()); bplRecord.setGLN(gln != null ? gln.getCode() : null); bplRecord.setExternalId(externalId); bplRecord.setIsBillTo(billTo); bplRecord.setIsBillToDefault(billToDefault); bplRecord.setIsShipTo(shipTo); bplRecord.setIsShipToDefault(shipToDefault); POJOWrapper.setInstanceName(bplRecord, coalesce(bplRecord.getGLN(), bplRecord.getExternalId())); saveRecord(bplRecord); return BPartnerLocationId.ofRepoId(bplRecord.getC_BPartner_ID(), bplRecord.getC_BPartner_Location_ID()); } private LocationId createLocation(final CountryId countryId) { final I_C_Location record = newInstance(I_C_Location.class); record.setC_Country_ID(countryId.getRepoId()); saveRecord(record); return LocationId.ofRepoId(record.getC_Location_ID()); } public void createProduct(final String value, final UomId uomId) { final I_M_Product record = newInstance(I_M_Product.class); record.setValue(value); record.setC_UOM_ID(uomId.getRepoId()); saveRecord(record); } public PricingSystemId createPricingSystem(@NonNull final String pricinSystemCode) { final I_M_PricingSystem record = newInstance(I_M_PricingSystem.class); record.setValue(pricinSystemCode); saveRecord(record); return PricingSystemId.ofRepoId(record.getM_PricingSystem_ID()); } public PriceListId createSalesPriceList( @NonNull final PricingSystemId pricingSystemId, @NonNull final CountryId countryId, @NonNull final CurrencyId currencyId, @Nullable final TaxCategoryId defaultTaxCategoryId) { final I_M_PriceList record = newInstance(I_M_PriceList.class); record.setM_PricingSystem_ID(pricingSystemId.getRepoId()); record.setC_Country_ID(countryId.getRepoId()); record.setC_Currency_ID(currencyId.getRepoId()); record.setIsSOPriceList(true); record.setPricePrecision(2); record.setDefault_TaxCategory_ID(TaxCategoryId.toRepoId(defaultTaxCategoryId)); saveRecord(record); return PriceListId.ofRepoId(record.getM_PriceList_ID()); } public PriceListVersionId createPriceListVersion( @NonNull final PriceListId priceListId, @NonNull final LocalDate validFrom) { I_M_PriceList_Version record = newInstance(I_M_PriceList_Version.class); record.setM_PriceList_ID(priceListId.getRepoId()); record.setValidFrom(TimeUtil.asTimestamp(validFrom)); saveRecord(record); return PriceListVersionId.ofRepoId(record.getM_PriceList_Version_ID()); } public TaxCategoryId createTaxCategory() { final I_C_TaxCategory record = newInstance(I_C_TaxCategory.class); saveRecord(record); return TaxCategoryId.ofRepoId(record.getC_TaxCategory_ID()); } public void createPricingRules() { createPricingRule(PriceListVersion.class, 10); } private void createPricingRule( @NonNull final Class<? extends IPricingRule> clazz, int seqNo) { final String classname = clazz.getName(); final I_C_PricingRule pricingRule = newInstance(I_C_PricingRule.class); pricingRule.setName(classname); pricingRule.setClassname(classname); pricingRule.setIsActive(true); pricingRule.setSeqNo(seqNo); saveRecord(pricingRule); } public WarehouseId createWarehouse(final String value) { final I_M_Warehouse record = newInstance(I_M_Warehouse.class); record.setValue(value); saveRecord(record); return WarehouseId.ofRepoId(record.getM_Warehouse_ID()); } public ShipperId createShipper(final String shipperName) { final I_M_Shipper shipper = newInstance(I_M_Shipper.class); shipper.setName(shipperName); shipper.setValue(shipperName); saveRecord(shipper); return ShipperId.ofRepoId(shipper.getM_Shipper_ID()); } public PaymentTermId createPaymentTerm(final String value, final String externalId) { final I_C_PaymentTerm paymentTerm = newInstance(I_C_PaymentTerm.class); paymentTerm.setValue(value); paymentTerm.setExternalId(externalId); saveRecord(paymentTerm); return PaymentTermId.ofRepoId(paymentTerm.getC_PaymentTerm_ID()); } public BPartnerId createSalesRep(final String salesRepCode) { final I_C_BPartner partner = newInstance(I_C_BPartner.class); partner.setSalesPartnerCode(salesRepCode); partner.setIsSalesRep(true); saveRecord(partner); return BPartnerId.ofRepoId(partner.getC_BPartner_ID()); } }
4,223
348
<filename>docs/data/t2/0ZZ/ZZ061.json {"nom":"Damas","dpt":"Français établis hors de France","inscrits":807,"abs":792,"votants":15,"blancs":1,"nuls":0,"exp":14,"res":[{"panneau":"2","voix":9},{"panneau":"1","voix":5}]}
92
348
<filename>docs/data/leg-t2/054/05405140.json<gh_stars>100-1000 {"nom":"Courcelles","circ":"5ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":85,"abs":34,"votants":51,"blancs":4,"nuls":0,"exp":47,"res":[{"nuance":"SOC","nom":"<NAME>","voix":30},{"nuance":"REM","nom":"<NAME>","voix":17}]}
127
1,350
<filename>sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomEventsTrigger.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.util.List; /** Trigger that runs every time a custom event is received. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("CustomEventsTrigger") @JsonFlatten @Fluent public class CustomEventsTrigger extends MultiplePipelineTrigger { /* * The event subject must begin with the pattern provided for trigger to * fire. At least one of these must be provided: subjectBeginsWith, * subjectEndsWith. */ @JsonProperty(value = "typeProperties.subjectBeginsWith") private String subjectBeginsWith; /* * The event subject must end with the pattern provided for trigger to * fire. At least one of these must be provided: subjectBeginsWith, * subjectEndsWith. */ @JsonProperty(value = "typeProperties.subjectEndsWith") private String subjectEndsWith; /* * The list of event types that cause this trigger to fire. */ @JsonProperty(value = "typeProperties.events", required = true) private List<Object> events; /* * The ARM resource ID of the Azure Event Grid Topic. */ @JsonProperty(value = "typeProperties.scope", required = true) private String scope; /** * Get the subjectBeginsWith property: The event subject must begin with the pattern provided for trigger to fire. * At least one of these must be provided: subjectBeginsWith, subjectEndsWith. * * @return the subjectBeginsWith value. */ public String getSubjectBeginsWith() { return this.subjectBeginsWith; } /** * Set the subjectBeginsWith property: The event subject must begin with the pattern provided for trigger to fire. * At least one of these must be provided: subjectBeginsWith, subjectEndsWith. * * @param subjectBeginsWith the subjectBeginsWith value to set. * @return the CustomEventsTrigger object itself. */ public CustomEventsTrigger setSubjectBeginsWith(String subjectBeginsWith) { this.subjectBeginsWith = subjectBeginsWith; return this; } /** * Get the subjectEndsWith property: The event subject must end with the pattern provided for trigger to fire. At * least one of these must be provided: subjectBeginsWith, subjectEndsWith. * * @return the subjectEndsWith value. */ public String getSubjectEndsWith() { return this.subjectEndsWith; } /** * Set the subjectEndsWith property: The event subject must end with the pattern provided for trigger to fire. At * least one of these must be provided: subjectBeginsWith, subjectEndsWith. * * @param subjectEndsWith the subjectEndsWith value to set. * @return the CustomEventsTrigger object itself. */ public CustomEventsTrigger setSubjectEndsWith(String subjectEndsWith) { this.subjectEndsWith = subjectEndsWith; return this; } /** * Get the events property: The list of event types that cause this trigger to fire. * * @return the events value. */ public List<Object> getEvents() { return this.events; } /** * Set the events property: The list of event types that cause this trigger to fire. * * @param events the events value to set. * @return the CustomEventsTrigger object itself. */ public CustomEventsTrigger setEvents(List<Object> events) { this.events = events; return this; } /** * Get the scope property: The ARM resource ID of the Azure Event Grid Topic. * * @return the scope value. */ public String getScope() { return this.scope; } /** * Set the scope property: The ARM resource ID of the Azure Event Grid Topic. * * @param scope the scope value to set. * @return the CustomEventsTrigger object itself. */ public CustomEventsTrigger setScope(String scope) { this.scope = scope; return this; } }
1,550
1,041
<gh_stars>1000+ package io.ebeaninternal.server.core; import java.sql.SQLException; /** * Read a row building a result for that row. */ public interface RowReader<T> { /** * Build and return a result for a row. */ T read() throws SQLException; }
92
818
/* * Copyright 2021 Red Hat, Inc. 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. */ package org.kie.kogito.codegen.prediction; import java.util.Collection; import org.kie.kogito.codegen.api.context.KogitoBuildContext; import org.kie.kogito.codegen.api.template.InvalidTemplateException; import org.kie.kogito.codegen.api.template.TemplatedGenerator; import org.kie.kogito.codegen.core.AbstractApplicationSection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.InitializerDeclaration; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.utils.StringEscapeUtils; public class PredictionModelsGenerator extends AbstractApplicationSection { private static final Logger LOGGER = LoggerFactory.getLogger(PredictionModelsGenerator.class); private static final String SECTION_CLASS_NAME = "PredictionModels"; protected final Collection<PMMLResource> resources; protected final String applicationCanonicalName; protected final TemplatedGenerator templatedGenerator; public PredictionModelsGenerator(KogitoBuildContext context, String applicationCanonicalName, Collection<PMMLResource> resources) { super(context, SECTION_CLASS_NAME); this.applicationCanonicalName = applicationCanonicalName; this.resources = resources; this.templatedGenerator = TemplatedGenerator.builder().build(context, SECTION_CLASS_NAME); } @Override public CompilationUnit compilationUnit() { CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("Invalid Template: No CompilationUnit"); populateStaticKieRuntimeFactoryFunctionInit(compilationUnit); return compilationUnit; } private void populateStaticKieRuntimeFactoryFunctionInit(CompilationUnit compilationUnit) { final InitializerDeclaration staticDeclaration = compilationUnit .findFirst(InitializerDeclaration.class) .orElseThrow(() -> new InvalidTemplateException( templatedGenerator, "Missing static block")); final MethodCallExpr initMethod = staticDeclaration .findFirst(MethodCallExpr.class, mtd -> "init".equals(mtd.getNameAsString())) .orElseThrow(() -> new InvalidTemplateException( templatedGenerator, "Missing init() method")); for (PMMLResource resource : resources) { StringLiteralExpr getResAsStream = getReadResourceMethod(resource); initMethod.addArgument(getResAsStream); } } private StringLiteralExpr getReadResourceMethod(PMMLResource resource) { String source = resource.getModelPath(); LOGGER.trace("Original source path: {}", source); source = StringEscapeUtils.escapeJava(source); LOGGER.trace("Escaped source path: {}", source); return new StringLiteralExpr(source); } }
1,245
352
<filename>PepperPlugin/src/PepperPlugin/pepper_entrypoints.cpp /* Copyright (c) 2016 Xamarin. */ /* NOTE: this is auto-generated from IDL */ #include "pepper_entrypoints.h" #include "ppapi/c/ppb.h" #include "ppapi/c/ppb_audio.h" #include "ppapi/c/ppb_audio_buffer.h" #include "ppapi/c/ppb_audio_config.h" #include "ppapi/c/ppb_audio_encoder.h" #include "ppapi/c/ppb_console.h" #include "ppapi/c/ppb_core.h" #include "ppapi/c/ppb_file_io.h" #include "ppapi/c/ppb_file_ref.h" #include "ppapi/c/ppb_file_system.h" #include "ppapi/c/ppb_fullscreen.h" #include "ppapi/c/ppb_gamepad.h" #include "ppapi/c/ppb_graphics_2d.h" #include "ppapi/c/ppb_host_resolver.h" #include "ppapi/c/ppb_image_data.h" #include "ppapi/c/ppb_input_event.h" #include "ppapi/c/ppb_instance.h" #include "ppapi/c/ppb_media_stream_audio_track.h" #include "ppapi/c/ppb_media_stream_video_track.h" #include "ppapi/c/ppb_message_loop.h" #include "ppapi/c/ppb_messaging.h" #include "ppapi/c/ppb_mouse_cursor.h" #include "ppapi/c/ppb_mouse_lock.h" #include "ppapi/c/ppb_net_address.h" #include "ppapi/c/ppb_network_list.h" #include "ppapi/c/ppb_network_monitor.h" #include "ppapi/c/ppb_network_proxy.h" #include "ppapi/c/ppb_tcp_socket.h" #include "ppapi/c/ppb_udp_socket.h" #include "ppapi/c/ppb_url_loader.h" #include "ppapi/c/ppb_url_request_info.h" #include "ppapi/c/ppb_url_response_info.h" #include "ppapi/c/ppb_var.h" #include "ppapi/c/ppb_var_array.h" #include "ppapi/c/ppb_var_array_buffer.h" #include "ppapi/c/ppb_var_dictionary.h" #include "ppapi/c/ppb_video_decoder.h" #include "ppapi/c/ppb_video_encoder.h" #include "ppapi/c/ppb_video_frame.h" #include "ppapi/c/ppb_view.h" #include "ppapi/c/ppb_websocket.h" #include "ppapi/c/ppp_input_event.h" #include "ppapi/c/ppp_messaging.h" #include "ppapi/c/ppp_mouse_lock.h" #ifndef PEPPER_EXPORT #define PEPPER_EXPORT __declspec(dllexport) #endif using namespace pp; namespace Pepper { namespace { // Specialize this function to return the interface string corresponding to the // PP?_XXX structure. template <typename T> const char* interface_name() { return NULL; } template <typename T> inline T const* get_interface() { static T const* funcs = reinterpret_cast<T const*>( pp::Module::Get()->GetBrowserInterface(interface_name<T>())); return funcs; } template <typename T> inline bool has_interface() { return get_interface<T>() != NULL; } } } /* BEGIN Declarations for all Interface Definitions. */ namespace Pepper { namespace { template <> const char* interface_name<PPB_Audio_1_0>() { return PPB_AUDIO_INTERFACE_1_0; } template <> const char* interface_name<PPB_Audio_1_1>() { return PPB_AUDIO_INTERFACE_1_1; } template <> const char* interface_name<PPB_AudioBuffer_0_1>() { return PPB_AUDIOBUFFER_INTERFACE_0_1; } template <> const char* interface_name<PPB_AudioConfig_1_0>() { return PPB_AUDIO_CONFIG_INTERFACE_1_0; } template <> const char* interface_name<PPB_AudioConfig_1_1>() { return PPB_AUDIO_CONFIG_INTERFACE_1_1; } template <> const char* interface_name<PPB_AudioEncoder_0_1>() { return PPB_AUDIOENCODER_INTERFACE_0_1; } template <> const char* interface_name<PPB_Console_1_0>() { return PPB_CONSOLE_INTERFACE_1_0; } template <> const char* interface_name<PPB_Core_1_0>() { return PPB_CORE_INTERFACE_1_0; } template <> const char* interface_name<PPB_FileIO_1_0>() { return PPB_FILEIO_INTERFACE_1_0; } template <> const char* interface_name<PPB_FileIO_1_1>() { return PPB_FILEIO_INTERFACE_1_1; } template <> const char* interface_name<PPB_FileRef_1_0>() { return PPB_FILEREF_INTERFACE_1_0; } template <> const char* interface_name<PPB_FileRef_1_1>() { return PPB_FILEREF_INTERFACE_1_1; } template <> const char* interface_name<PPB_FileRef_1_2>() { return PPB_FILEREF_INTERFACE_1_2; } template <> const char* interface_name<PPB_FileSystem_1_0>() { return PPB_FILESYSTEM_INTERFACE_1_0; } template <> const char* interface_name<PPB_Fullscreen_1_0>() { return PPB_FULLSCREEN_INTERFACE_1_0; } template <> const char* interface_name<PPB_Gamepad_1_0>() { return PPB_GAMEPAD_INTERFACE_1_0; } template <> const char* interface_name<PPB_Graphics2D_1_0>() { return PPB_GRAPHICS_2D_INTERFACE_1_0; } template <> const char* interface_name<PPB_Graphics2D_1_1>() { return PPB_GRAPHICS_2D_INTERFACE_1_1; } template <> const char* interface_name<PPB_Graphics2D_1_2>() { return PPB_GRAPHICS_2D_INTERFACE_1_2; } template <> const char* interface_name<PPB_HostResolver_1_0>() { return PPB_HOSTRESOLVER_INTERFACE_1_0; } template <> const char* interface_name<PPB_ImageData_1_0>() { return PPB_IMAGEDATA_INTERFACE_1_0; } template <> const char* interface_name<PPB_InputEvent_1_0>() { return PPB_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_MouseInputEvent_1_0>() { return PPB_MOUSE_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_MouseInputEvent_1_1>() { return PPB_MOUSE_INPUT_EVENT_INTERFACE_1_1; } template <> const char* interface_name<PPB_WheelInputEvent_1_0>() { return PPB_WHEEL_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_KeyboardInputEvent_1_0>() { return PPB_KEYBOARD_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_KeyboardInputEvent_1_2>() { return PPB_KEYBOARD_INPUT_EVENT_INTERFACE_1_2; } template <> const char* interface_name<PPB_TouchInputEvent_1_0>() { return PPB_TOUCH_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_IMEInputEvent_1_0>() { return PPB_IME_INPUT_EVENT_INTERFACE_1_0; } template <> const char* interface_name<PPB_Instance_1_0>() { return PPB_INSTANCE_INTERFACE_1_0; } template <> const char* interface_name<PPB_MediaStreamAudioTrack_0_1>() { return PPB_MEDIASTREAMAUDIOTRACK_INTERFACE_0_1; } template <> const char* interface_name<PPB_MediaStreamVideoTrack_0_1>() { return PPB_MEDIASTREAMVIDEOTRACK_INTERFACE_0_1; } template <> const char* interface_name<PPB_MediaStreamVideoTrack_1_0>() { return PPB_MEDIASTREAMVIDEOTRACK_INTERFACE_1_0; } template <> const char* interface_name<PPB_MessageLoop_1_0>() { return PPB_MESSAGELOOP_INTERFACE_1_0; } template <> const char* interface_name<PPB_Messaging_1_0>() { return PPB_MESSAGING_INTERFACE_1_0; } template <> const char* interface_name<PPB_Messaging_1_2>() { return PPB_MESSAGING_INTERFACE_1_2; } template <> const char* interface_name<PPB_MouseCursor_1_0>() { return PPB_MOUSECURSOR_INTERFACE_1_0; } template <> const char* interface_name<PPB_MouseLock_1_0>() { return PPB_MOUSELOCK_INTERFACE_1_0; } template <> const char* interface_name<PPB_NetAddress_1_0>() { return PPB_NETADDRESS_INTERFACE_1_0; } template <> const char* interface_name<PPB_NetworkList_1_0>() { return PPB_NETWORKLIST_INTERFACE_1_0; } template <> const char* interface_name<PPB_NetworkMonitor_1_0>() { return PPB_NETWORKMONITOR_INTERFACE_1_0; } template <> const char* interface_name<PPB_NetworkProxy_1_0>() { return PPB_NETWORKPROXY_INTERFACE_1_0; } template <> const char* interface_name<PPB_TCPSocket_1_0>() { return PPB_TCPSOCKET_INTERFACE_1_0; } template <> const char* interface_name<PPB_TCPSocket_1_1>() { return PPB_TCPSOCKET_INTERFACE_1_1; } template <> const char* interface_name<PPB_TCPSocket_1_2>() { return PPB_TCPSOCKET_INTERFACE_1_2; } template <> const char* interface_name<PPB_UDPSocket_1_0>() { return PPB_UDPSOCKET_INTERFACE_1_0; } template <> const char* interface_name<PPB_UDPSocket_1_1>() { return PPB_UDPSOCKET_INTERFACE_1_1; } template <> const char* interface_name<PPB_UDPSocket_1_2>() { return PPB_UDPSOCKET_INTERFACE_1_2; } template <> const char* interface_name<PPB_URLLoader_1_0>() { return PPB_URLLOADER_INTERFACE_1_0; } template <> const char* interface_name<PPB_URLRequestInfo_1_0>() { return PPB_URLREQUESTINFO_INTERFACE_1_0; } template <> const char* interface_name<PPB_URLResponseInfo_1_0>() { return PPB_URLRESPONSEINFO_INTERFACE_1_0; } template <> const char* interface_name<PPB_Var_1_0>() { return PPB_VAR_INTERFACE_1_0; } template <> const char* interface_name<PPB_Var_1_1>() { return PPB_VAR_INTERFACE_1_1; } template <> const char* interface_name<PPB_Var_1_2>() { return PPB_VAR_INTERFACE_1_2; } template <> const char* interface_name<PPB_VarArray_1_0>() { return PPB_VAR_ARRAY_INTERFACE_1_0; } template <> const char* interface_name<PPB_VarArrayBuffer_1_0>() { return PPB_VAR_ARRAY_BUFFER_INTERFACE_1_0; } template <> const char* interface_name<PPB_VarDictionary_1_0>() { return PPB_VAR_DICTIONARY_INTERFACE_1_0; } template <> const char* interface_name<PPB_VideoDecoder_0_1>() { return PPB_VIDEODECODER_INTERFACE_0_1; } template <> const char* interface_name<PPB_VideoDecoder_0_2>() { return PPB_VIDEODECODER_INTERFACE_0_2; } template <> const char* interface_name<PPB_VideoDecoder_1_0>() { return PPB_VIDEODECODER_INTERFACE_1_0; } template <> const char* interface_name<PPB_VideoDecoder_1_1>() { return PPB_VIDEODECODER_INTERFACE_1_1; } template <> const char* interface_name<PPB_VideoEncoder_0_1>() { return PPB_VIDEOENCODER_INTERFACE_0_1; } template <> const char* interface_name<PPB_VideoEncoder_0_2>() { return PPB_VIDEOENCODER_INTERFACE_0_2; } template <> const char* interface_name<PPB_VideoFrame_0_1>() { return PPB_VIDEOFRAME_INTERFACE_0_1; } template <> const char* interface_name<PPB_View_1_0>() { return PPB_VIEW_INTERFACE_1_0; } template <> const char* interface_name<PPB_View_1_1>() { return PPB_VIEW_INTERFACE_1_1; } template <> const char* interface_name<PPB_View_1_2>() { return PPB_VIEW_INTERFACE_1_2; } template <> const char* interface_name<PPB_WebSocket_1_0>() { return PPB_WEBSOCKET_INTERFACE_1_0; } template <> const char* interface_name<PPP_InputEvent_0_1>() { return PPP_INPUT_EVENT_INTERFACE_0_1; } template <> const char* interface_name<PPP_Messaging_1_0>() { return PPP_MESSAGING_INTERFACE_1_0; } template <> const char* interface_name<PPP_MouseLock_1_0>() { return PPP_MOUSELOCK_INTERFACE_1_0; } } } /* END Declarations for all Interface Definitions. */ namespace Pepper { /* We don't want name mangling for these external functions. We only need * 'extern "C"' if we're compiling with a C++ compiler. */ #ifdef __cplusplus extern "C" { #endif namespace { #pragma region /* Begin entry point methods for PPB_Audio */ PEPPER_EXPORT PP_Resource PPB_Audio_Create(PP_Instance instance, PP_Resource config, PPB_Audio_Callback audio_callback, void* user_data) { if (has_interface<PPB_Audio_1_1>()) { return get_interface<PPB_Audio_1_1>()->Create(instance, config, audio_callback, user_data); } return NULL; } PEPPER_EXPORT PP_Bool PPB_Audio_IsAudio(PP_Resource resource) { if (has_interface<PPB_Audio_1_1>()) { return get_interface<PPB_Audio_1_1>()->IsAudio(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Resource PPB_Audio_GetCurrentConfig(PP_Resource audio) { if (has_interface<PPB_Audio_1_1>()) { return get_interface<PPB_Audio_1_1>()->GetCurrentConfig(audio); } return NULL; } PEPPER_EXPORT PP_Bool PPB_Audio_StartPlayback(PP_Resource audio) { if (has_interface<PPB_Audio_1_1>()) { return get_interface<PPB_Audio_1_1>()->StartPlayback(audio); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_Audio_StopPlayback(PP_Resource audio) { if (has_interface<PPB_Audio_1_1>()) { return get_interface<PPB_Audio_1_1>()->StopPlayback(audio); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_Audio */ #pragma region /* Begin entry point methods for PPB_AudioBuffer */ PEPPER_EXPORT PP_Bool PPB_AudioBuffer_IsAudioBuffer(PP_Resource resource) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->IsAudioBuffer(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_TimeDelta PPB_AudioBuffer_GetTimestamp(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetTimestamp(buffer); } return NULL; } PEPPER_EXPORT void PPB_AudioBuffer_SetTimestamp(PP_Resource buffer, PP_TimeDelta timestamp) { if (has_interface<PPB_AudioBuffer_0_1>()) { get_interface<PPB_AudioBuffer_0_1>()->SetTimestamp(buffer, timestamp); } return ; } PEPPER_EXPORT PP_AudioBuffer_SampleRate PPB_AudioBuffer_GetSampleRate(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetSampleRate(buffer); } return PP_AUDIOBUFFER_SAMPLERATE_UNKNOWN; } PEPPER_EXPORT PP_AudioBuffer_SampleSize PPB_AudioBuffer_GetSampleSize(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetSampleSize(buffer); } return PP_AUDIOBUFFER_SAMPLESIZE_UNKNOWN; } PEPPER_EXPORT uint32_t PPB_AudioBuffer_GetNumberOfChannels(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetNumberOfChannels(buffer); } return NULL; } PEPPER_EXPORT uint32_t PPB_AudioBuffer_GetNumberOfSamples(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetNumberOfSamples(buffer); } return NULL; } PEPPER_EXPORT void* PPB_AudioBuffer_GetDataBuffer(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetDataBuffer(buffer); } return NULL; } PEPPER_EXPORT uint32_t PPB_AudioBuffer_GetDataBufferSize(PP_Resource buffer) { if (has_interface<PPB_AudioBuffer_0_1>()) { return get_interface<PPB_AudioBuffer_0_1>()->GetDataBufferSize(buffer); } return NULL; } #pragma endregion /* End entry point generation for PPB_AudioBuffer */ #pragma region /* Begin entry point methods for PPB_AudioConfig */ PEPPER_EXPORT PP_Resource PPB_AudioConfig_CreateStereo16Bit(PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->CreateStereo16Bit(instance, sample_rate, sample_frame_count); } else if (has_interface<PPB_AudioConfig_1_0>()) { return get_interface<PPB_AudioConfig_1_0>()->CreateStereo16Bit(instance, sample_rate, sample_frame_count); } return NULL; } PEPPER_EXPORT uint32_t PPB_AudioConfig_RecommendSampleFrameCount(PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t requested_sample_frame_count) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->RecommendSampleFrameCount(instance, sample_rate, requested_sample_frame_count); } return NULL; } PEPPER_EXPORT PP_Bool PPB_AudioConfig_IsAudioConfig(PP_Resource resource) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->IsAudioConfig(resource); } else if (has_interface<PPB_AudioConfig_1_0>()) { return get_interface<PPB_AudioConfig_1_0>()->IsAudioConfig(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_AudioSampleRate PPB_AudioConfig_GetSampleRate(PP_Resource config) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->GetSampleRate(config); } else if (has_interface<PPB_AudioConfig_1_0>()) { return get_interface<PPB_AudioConfig_1_0>()->GetSampleRate(config); } return PP_AUDIOSAMPLERATE_NONE; } PEPPER_EXPORT uint32_t PPB_AudioConfig_GetSampleFrameCount(PP_Resource config) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->GetSampleFrameCount(config); } else if (has_interface<PPB_AudioConfig_1_0>()) { return get_interface<PPB_AudioConfig_1_0>()->GetSampleFrameCount(config); } return NULL; } PEPPER_EXPORT PP_AudioSampleRate PPB_AudioConfig_RecommendSampleRate(PP_Instance instance) { if (has_interface<PPB_AudioConfig_1_1>()) { return get_interface<PPB_AudioConfig_1_1>()->RecommendSampleRate(instance); } return PP_AUDIOSAMPLERATE_NONE; } #pragma endregion /* End entry point generation for PPB_AudioConfig */ #pragma region /* Begin entry point methods for PPB_AudioEncoder */ PEPPER_EXPORT PP_Resource PPB_AudioEncoder_Create(PP_Instance instance) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_AudioEncoder_IsAudioEncoder(PP_Resource resource) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->IsAudioEncoder(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_AudioEncoder_GetSupportedProfiles(PP_Resource audio_encoder, struct PP_ArrayOutput output, struct PP_CompletionCallback callback) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->GetSupportedProfiles(audio_encoder, output, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_AudioEncoder_Initialize(PP_Resource audio_encoder, uint32_t channels, PP_AudioBuffer_SampleRate input_sample_rate, PP_AudioBuffer_SampleSize input_sample_size, PP_AudioProfile output_profile, uint32_t initial_bitrate, PP_HardwareAcceleration acceleration, struct PP_CompletionCallback callback) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->Initialize(audio_encoder, channels, input_sample_rate, input_sample_size, output_profile, initial_bitrate, acceleration, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_AudioEncoder_GetNumberOfSamples(PP_Resource audio_encoder) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->GetNumberOfSamples(audio_encoder); } return NULL; } PEPPER_EXPORT int32_t PPB_AudioEncoder_GetBuffer(PP_Resource audio_encoder, PP_Resource* audio_buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->GetBuffer(audio_encoder, audio_buffer, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_AudioEncoder_Encode(PP_Resource audio_encoder, PP_Resource audio_buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->Encode(audio_encoder, audio_buffer, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_AudioEncoder_GetBitstreamBuffer(PP_Resource audio_encoder, struct PP_AudioBitstreamBuffer* bitstream_buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_AudioEncoder_0_1>()) { return get_interface<PPB_AudioEncoder_0_1>()->GetBitstreamBuffer(audio_encoder, bitstream_buffer, callback); } return NULL; } PEPPER_EXPORT void PPB_AudioEncoder_RecycleBitstreamBuffer(PP_Resource audio_encoder, struct PP_AudioBitstreamBuffer bitstream_buffer) { if (has_interface<PPB_AudioEncoder_0_1>()) { get_interface<PPB_AudioEncoder_0_1>()->RecycleBitstreamBuffer(audio_encoder, &bitstream_buffer); } return ; } PEPPER_EXPORT void PPB_AudioEncoder_RequestBitrateChange(PP_Resource audio_encoder, uint32_t bitrate) { if (has_interface<PPB_AudioEncoder_0_1>()) { get_interface<PPB_AudioEncoder_0_1>()->RequestBitrateChange(audio_encoder, bitrate); } return ; } PEPPER_EXPORT void PPB_AudioEncoder_Close(PP_Resource audio_encoder) { if (has_interface<PPB_AudioEncoder_0_1>()) { get_interface<PPB_AudioEncoder_0_1>()->Close(audio_encoder); } return ; } #pragma endregion /* End entry point generation for PPB_AudioEncoder */ #pragma region /* Begin entry point methods for PPB_Console */ PEPPER_EXPORT void PPB_Console_Log(PP_Instance instance, PP_LogLevel level, struct PP_Var value) { if (has_interface<PPB_Console_1_0>()) { get_interface<PPB_Console_1_0>()->Log(instance, level, value); } return ; } PEPPER_EXPORT void PPB_Console_LogWithSource(PP_Instance instance, PP_LogLevel level, struct PP_Var source, struct PP_Var value) { if (has_interface<PPB_Console_1_0>()) { get_interface<PPB_Console_1_0>()->LogWithSource(instance, level, source, value); } return ; } #pragma endregion /* End entry point generation for PPB_Console */ #pragma region /* Begin entry point methods for PPB_Core */ PEPPER_EXPORT void PPB_Core_AddRefResource(PP_Resource resource) { if (has_interface<PPB_Core_1_0>()) { get_interface<PPB_Core_1_0>()->AddRefResource(resource); } return ; } PEPPER_EXPORT void PPB_Core_ReleaseResource(PP_Resource resource) { if (has_interface<PPB_Core_1_0>()) { get_interface<PPB_Core_1_0>()->ReleaseResource(resource); } return ; } PEPPER_EXPORT PP_Time PPB_Core_GetTime(void) { if (has_interface<PPB_Core_1_0>()) { return get_interface<PPB_Core_1_0>()->GetTime(); } return NULL; } PEPPER_EXPORT PP_TimeTicks PPB_Core_GetTimeTicks(void) { if (has_interface<PPB_Core_1_0>()) { return get_interface<PPB_Core_1_0>()->GetTimeTicks(); } return NULL; } PEPPER_EXPORT void PPB_Core_CallOnMainThread(int32_t delay_in_milliseconds, struct PP_CompletionCallback callback, int32_t result) { if (has_interface<PPB_Core_1_0>()) { get_interface<PPB_Core_1_0>()->CallOnMainThread(delay_in_milliseconds, callback, result); } return ; } PEPPER_EXPORT PP_Bool PPB_Core_IsMainThread(void) { if (has_interface<PPB_Core_1_0>()) { return get_interface<PPB_Core_1_0>()->IsMainThread(); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_Core */ #pragma region /* Begin entry point methods for PPB_FileIO */ PEPPER_EXPORT PP_Resource PPB_FileIO_Create(PP_Instance instance) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Create(instance); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_FileIO_IsFileIO(PP_Resource resource) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->IsFileIO(resource); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->IsFileIO(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_FileIO_Open(PP_Resource file_io, PP_Resource file_ref, int32_t open_flags, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Open(file_io, file_ref, open_flags, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Open(file_io, file_ref, open_flags, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_Query(PP_Resource file_io, struct PP_FileInfo* info, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Query(file_io, info, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Query(file_io, info, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_Touch(PP_Resource file_io, PP_Time last_access_time, PP_Time last_modified_time, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Touch(file_io, last_access_time, last_modified_time, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Touch(file_io, last_access_time, last_modified_time, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_Read(PP_Resource file_io, int64_t offset, char* buffer, int32_t bytes_to_read, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Read(file_io, offset, buffer, bytes_to_read, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Read(file_io, offset, buffer, bytes_to_read, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_Write(PP_Resource file_io, int64_t offset, const char* buffer, int32_t bytes_to_write, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Write(file_io, offset, buffer, bytes_to_write, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Write(file_io, offset, buffer, bytes_to_write, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_SetLength(PP_Resource file_io, int64_t length, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->SetLength(file_io, length, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->SetLength(file_io, length, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileIO_Flush(PP_Resource file_io, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->Flush(file_io, callback); } else if (has_interface<PPB_FileIO_1_0>()) { return get_interface<PPB_FileIO_1_0>()->Flush(file_io, callback); } return NULL; } PEPPER_EXPORT void PPB_FileIO_Close(PP_Resource file_io) { if (has_interface<PPB_FileIO_1_1>()) { get_interface<PPB_FileIO_1_1>()->Close(file_io); } else if (has_interface<PPB_FileIO_1_0>()) { get_interface<PPB_FileIO_1_0>()->Close(file_io); } return ; } PEPPER_EXPORT int32_t PPB_FileIO_ReadToArray(PP_Resource file_io, int64_t offset, int32_t max_read_length, struct PP_ArrayOutput* output, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileIO_1_1>()) { return get_interface<PPB_FileIO_1_1>()->ReadToArray(file_io, offset, max_read_length, output, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_FileIO */ #pragma region /* Begin entry point methods for PPB_FileRef */ PEPPER_EXPORT PP_Resource PPB_FileRef_Create(PP_Resource file_system, const char* path) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->Create(file_system, path); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->Create(file_system, path); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->Create(file_system, path); } return NULL; } PEPPER_EXPORT PP_Bool PPB_FileRef_IsFileRef(PP_Resource resource) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->IsFileRef(resource); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->IsFileRef(resource); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->IsFileRef(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_FileSystemType PPB_FileRef_GetFileSystemType(PP_Resource file_ref) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->GetFileSystemType(file_ref); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->GetFileSystemType(file_ref); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->GetFileSystemType(file_ref); } return PP_FILESYSTEMTYPE_EXTERNAL; } PEPPER_EXPORT struct PP_Var PPB_FileRef_GetName(PP_Resource file_ref) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->GetName(file_ref); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->GetName(file_ref); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->GetName(file_ref); } return PP_MakeNull(); } PEPPER_EXPORT struct PP_Var PPB_FileRef_GetPath(PP_Resource file_ref) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->GetPath(file_ref); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->GetPath(file_ref); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->GetPath(file_ref); } return PP_MakeNull(); } PEPPER_EXPORT PP_Resource PPB_FileRef_GetParent(PP_Resource file_ref) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->GetParent(file_ref); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->GetParent(file_ref); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->GetParent(file_ref); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_MakeDirectory(PP_Resource directory_ref, int32_t make_directory_flags, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->MakeDirectory(directory_ref, make_directory_flags, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_Touch(PP_Resource file_ref, PP_Time last_access_time, PP_Time last_modified_time, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->Touch(file_ref, last_access_time, last_modified_time, callback); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->Touch(file_ref, last_access_time, last_modified_time, callback); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->Touch(file_ref, last_access_time, last_modified_time, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_Delete(PP_Resource file_ref, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->Delete(file_ref, callback); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->Delete(file_ref, callback); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->Delete(file_ref, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_Rename(PP_Resource file_ref, PP_Resource new_file_ref, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->Rename(file_ref, new_file_ref, callback); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->Rename(file_ref, new_file_ref, callback); } else if (has_interface<PPB_FileRef_1_0>()) { return get_interface<PPB_FileRef_1_0>()->Rename(file_ref, new_file_ref, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_Query(PP_Resource file_ref, struct PP_FileInfo* info, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->Query(file_ref, info, callback); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->Query(file_ref, info, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_FileRef_ReadDirectoryEntries(PP_Resource file_ref, struct PP_ArrayOutput output, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileRef_1_2>()) { return get_interface<PPB_FileRef_1_2>()->ReadDirectoryEntries(file_ref, output, callback); } else if (has_interface<PPB_FileRef_1_1>()) { return get_interface<PPB_FileRef_1_1>()->ReadDirectoryEntries(file_ref, output, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_FileRef */ #pragma region /* Begin entry point methods for PPB_FileSystem */ PEPPER_EXPORT PP_Resource PPB_FileSystem_Create(PP_Instance instance, PP_FileSystemType type) { if (has_interface<PPB_FileSystem_1_0>()) { return get_interface<PPB_FileSystem_1_0>()->Create(instance, type); } return NULL; } PEPPER_EXPORT PP_Bool PPB_FileSystem_IsFileSystem(PP_Resource resource) { if (has_interface<PPB_FileSystem_1_0>()) { return get_interface<PPB_FileSystem_1_0>()->IsFileSystem(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_FileSystem_Open(PP_Resource file_system, int64_t expected_size, struct PP_CompletionCallback callback) { if (has_interface<PPB_FileSystem_1_0>()) { return get_interface<PPB_FileSystem_1_0>()->Open(file_system, expected_size, callback); } return NULL; } PEPPER_EXPORT PP_FileSystemType PPB_FileSystem_GetType(PP_Resource file_system) { if (has_interface<PPB_FileSystem_1_0>()) { return get_interface<PPB_FileSystem_1_0>()->GetType(file_system); } return PP_FILESYSTEMTYPE_EXTERNAL; } #pragma endregion /* End entry point generation for PPB_FileSystem */ #pragma region /* Begin entry point methods for PPB_Fullscreen */ PEPPER_EXPORT PP_Bool PPB_Fullscreen_IsFullscreen(PP_Instance instance) { if (has_interface<PPB_Fullscreen_1_0>()) { return get_interface<PPB_Fullscreen_1_0>()->IsFullscreen(instance); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_Fullscreen_SetFullscreen(PP_Instance instance, PP_Bool fullscreen) { if (has_interface<PPB_Fullscreen_1_0>()) { return get_interface<PPB_Fullscreen_1_0>()->SetFullscreen(instance, fullscreen); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_Fullscreen_GetScreenSize(PP_Instance instance, struct PP_Size* size) { if (has_interface<PPB_Fullscreen_1_0>()) { return get_interface<PPB_Fullscreen_1_0>()->GetScreenSize(instance, size); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_Fullscreen */ #pragma region /* Begin entry point methods for PPB_Gamepad */ PEPPER_EXPORT void PPB_Gamepad_Sample(PP_Instance instance, struct PP_GamepadsSampleData* data) { if (has_interface<PPB_Gamepad_1_0>()) { get_interface<PPB_Gamepad_1_0>()->Sample(instance, data); } return ; } #pragma endregion /* End entry point generation for PPB_Gamepad */ #pragma region /* Begin entry point methods for PPB_Graphics2D */ PEPPER_EXPORT PP_Resource PPB_Graphics2D_Create(PP_Instance instance, struct PP_Size size, PP_Bool is_always_opaque) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->Create(instance, &size, is_always_opaque); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->Create(instance, &size, is_always_opaque); } else if (has_interface<PPB_Graphics2D_1_0>()) { return get_interface<PPB_Graphics2D_1_0>()->Create(instance, &size, is_always_opaque); } return NULL; } PEPPER_EXPORT PP_Bool PPB_Graphics2D_IsGraphics2D(PP_Resource resource) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->IsGraphics2D(resource); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->IsGraphics2D(resource); } else if (has_interface<PPB_Graphics2D_1_0>()) { return get_interface<PPB_Graphics2D_1_0>()->IsGraphics2D(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_Graphics2D_Describe(PP_Resource graphics_2d, struct PP_Size* size, PP_Bool* is_always_opaque) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->Describe(graphics_2d, size, is_always_opaque); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->Describe(graphics_2d, size, is_always_opaque); } else if (has_interface<PPB_Graphics2D_1_0>()) { return get_interface<PPB_Graphics2D_1_0>()->Describe(graphics_2d, size, is_always_opaque); } return PP_FromBool(false); } PEPPER_EXPORT void PPB_Graphics2D_PaintImageData(PP_Resource graphics_2d, PP_Resource image_data, struct PP_Point top_left, struct PP_Rect src_rect) { if (has_interface<PPB_Graphics2D_1_2>()) { get_interface<PPB_Graphics2D_1_2>()->PaintImageData(graphics_2d, image_data, &top_left, &src_rect); } else if (has_interface<PPB_Graphics2D_1_1>()) { get_interface<PPB_Graphics2D_1_1>()->PaintImageData(graphics_2d, image_data, &top_left, &src_rect); } else if (has_interface<PPB_Graphics2D_1_0>()) { get_interface<PPB_Graphics2D_1_0>()->PaintImageData(graphics_2d, image_data, &top_left, &src_rect); } return ; } PEPPER_EXPORT void PPB_Graphics2D_Scroll(PP_Resource graphics_2d, struct PP_Rect clip_rect, struct PP_Point amount) { if (has_interface<PPB_Graphics2D_1_2>()) { get_interface<PPB_Graphics2D_1_2>()->Scroll(graphics_2d, &clip_rect, &amount); } else if (has_interface<PPB_Graphics2D_1_1>()) { get_interface<PPB_Graphics2D_1_1>()->Scroll(graphics_2d, &clip_rect, &amount); } else if (has_interface<PPB_Graphics2D_1_0>()) { get_interface<PPB_Graphics2D_1_0>()->Scroll(graphics_2d, &clip_rect, &amount); } return ; } PEPPER_EXPORT void PPB_Graphics2D_ReplaceContents(PP_Resource graphics_2d, PP_Resource image_data) { if (has_interface<PPB_Graphics2D_1_2>()) { get_interface<PPB_Graphics2D_1_2>()->ReplaceContents(graphics_2d, image_data); } else if (has_interface<PPB_Graphics2D_1_1>()) { get_interface<PPB_Graphics2D_1_1>()->ReplaceContents(graphics_2d, image_data); } else if (has_interface<PPB_Graphics2D_1_0>()) { get_interface<PPB_Graphics2D_1_0>()->ReplaceContents(graphics_2d, image_data); } return ; } PEPPER_EXPORT int32_t PPB_Graphics2D_Flush(PP_Resource graphics_2d, struct PP_CompletionCallback callback) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->Flush(graphics_2d, callback); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->Flush(graphics_2d, callback); } else if (has_interface<PPB_Graphics2D_1_0>()) { return get_interface<PPB_Graphics2D_1_0>()->Flush(graphics_2d, callback); } return NULL; } PEPPER_EXPORT PP_Bool PPB_Graphics2D_SetScale(PP_Resource resource, float scale) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->SetScale(resource, scale); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->SetScale(resource, scale); } return PP_FromBool(false); } PEPPER_EXPORT float PPB_Graphics2D_GetScale(PP_Resource resource) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->GetScale(resource); } else if (has_interface<PPB_Graphics2D_1_1>()) { return get_interface<PPB_Graphics2D_1_1>()->GetScale(resource); } return NULL; } PEPPER_EXPORT PP_Bool PPB_Graphics2D_SetLayerTransform(PP_Resource resource, float scale, struct PP_Point origin, struct PP_Point translate) { if (has_interface<PPB_Graphics2D_1_2>()) { return get_interface<PPB_Graphics2D_1_2>()->SetLayerTransform(resource, scale, &origin, &translate); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_Graphics2D */ #pragma region /* Begin entry point methods for PPB_HostResolver */ PEPPER_EXPORT PP_Resource PPB_HostResolver_Create(PP_Instance instance) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_HostResolver_IsHostResolver(PP_Resource resource) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->IsHostResolver(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_HostResolver_Resolve(PP_Resource host_resolver, const char* host, uint16_t port, struct PP_HostResolver_Hint hint, struct PP_CompletionCallback callback) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->Resolve(host_resolver, host, port, &hint, callback); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_HostResolver_GetCanonicalName(PP_Resource host_resolver) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->GetCanonicalName(host_resolver); } return PP_MakeNull(); } PEPPER_EXPORT uint32_t PPB_HostResolver_GetNetAddressCount(PP_Resource host_resolver) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->GetNetAddressCount(host_resolver); } return NULL; } PEPPER_EXPORT PP_Resource PPB_HostResolver_GetNetAddress(PP_Resource host_resolver, uint32_t index) { if (has_interface<PPB_HostResolver_1_0>()) { return get_interface<PPB_HostResolver_1_0>()->GetNetAddress(host_resolver, index); } return NULL; } #pragma endregion /* End entry point generation for PPB_HostResolver */ #pragma region /* Begin entry point methods for PPB_ImageData */ PEPPER_EXPORT PP_ImageDataFormat PPB_ImageData_GetNativeImageDataFormat(void) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->GetNativeImageDataFormat(); } return PP_IMAGEDATAFORMAT_BGRA_PREMUL; } PEPPER_EXPORT PP_Bool PPB_ImageData_IsImageDataFormatSupported(PP_ImageDataFormat format) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->IsImageDataFormatSupported(format); } return PP_FromBool(false); } PEPPER_EXPORT PP_Resource PPB_ImageData_Create(PP_Instance instance, PP_ImageDataFormat format, struct PP_Size size, PP_Bool init_to_zero) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->Create(instance, format, &size, init_to_zero); } return NULL; } PEPPER_EXPORT PP_Bool PPB_ImageData_IsImageData(PP_Resource image_data) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->IsImageData(image_data); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_ImageData_Describe(PP_Resource image_data, struct PP_ImageDataDesc* desc) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->Describe(image_data, desc); } return PP_FromBool(false); } PEPPER_EXPORT void* PPB_ImageData_Map(PP_Resource image_data) { if (has_interface<PPB_ImageData_1_0>()) { return get_interface<PPB_ImageData_1_0>()->Map(image_data); } return NULL; } PEPPER_EXPORT void PPB_ImageData_Unmap(PP_Resource image_data) { if (has_interface<PPB_ImageData_1_0>()) { get_interface<PPB_ImageData_1_0>()->Unmap(image_data); } return ; } #pragma endregion /* End entry point generation for PPB_ImageData */ #pragma region /* Begin entry point methods for PPB_InputEvent */ PEPPER_EXPORT int32_t PPB_InputEvent_RequestInputEvents(PP_Instance instance, uint32_t event_classes) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->RequestInputEvents(instance, event_classes); } return NULL; } PEPPER_EXPORT int32_t PPB_InputEvent_RequestFilteringInputEvents(PP_Instance instance, uint32_t event_classes) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->RequestFilteringInputEvents(instance, event_classes); } return NULL; } PEPPER_EXPORT void PPB_InputEvent_ClearInputEventRequest(PP_Instance instance, uint32_t event_classes) { if (has_interface<PPB_InputEvent_1_0>()) { get_interface<PPB_InputEvent_1_0>()->ClearInputEventRequest(instance, event_classes); } return ; } PEPPER_EXPORT PP_Bool PPB_InputEvent_IsInputEvent(PP_Resource resource) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->IsInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_InputEvent_Type PPB_InputEvent_GetType(PP_Resource event) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->GetType(event); } return PP_INPUTEVENT_TYPE_UNDEFINED; } PEPPER_EXPORT PP_TimeTicks PPB_InputEvent_GetTimeStamp(PP_Resource event) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->GetTimeStamp(event); } return NULL; } PEPPER_EXPORT uint32_t PPB_InputEvent_GetModifiers(PP_Resource event) { if (has_interface<PPB_InputEvent_1_0>()) { return get_interface<PPB_InputEvent_1_0>()->GetModifiers(event); } return NULL; } #pragma endregion /* End entry point generation for PPB_InputEvent */ #pragma region /* Begin entry point methods for PPB_MouseInputEvent */ PEPPER_EXPORT PP_Resource PPB_MouseInputEvent_Create(PP_Instance instance, PP_InputEvent_Type type, PP_TimeTicks time_stamp, uint32_t modifiers, PP_InputEvent_MouseButton mouse_button, struct PP_Point mouse_position, int32_t click_count, struct PP_Point mouse_movement) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->Create(instance, type, time_stamp, modifiers, mouse_button, &mouse_position, click_count, &mouse_movement); } return NULL; } PEPPER_EXPORT PP_Bool PPB_MouseInputEvent_IsMouseInputEvent(PP_Resource resource) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->IsMouseInputEvent(resource); } else if (has_interface<PPB_MouseInputEvent_1_0>()) { return get_interface<PPB_MouseInputEvent_1_0>()->IsMouseInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_InputEvent_MouseButton PPB_MouseInputEvent_GetButton(PP_Resource mouse_event) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->GetButton(mouse_event); } else if (has_interface<PPB_MouseInputEvent_1_0>()) { return get_interface<PPB_MouseInputEvent_1_0>()->GetButton(mouse_event); } return PP_INPUTEVENT_MOUSEBUTTON_NONE; } PEPPER_EXPORT struct PP_Point PPB_MouseInputEvent_GetPosition(PP_Resource mouse_event) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->GetPosition(mouse_event); } else if (has_interface<PPB_MouseInputEvent_1_0>()) { return get_interface<PPB_MouseInputEvent_1_0>()->GetPosition(mouse_event); } return PP_MakePoint(0,0); } PEPPER_EXPORT int32_t PPB_MouseInputEvent_GetClickCount(PP_Resource mouse_event) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->GetClickCount(mouse_event); } else if (has_interface<PPB_MouseInputEvent_1_0>()) { return get_interface<PPB_MouseInputEvent_1_0>()->GetClickCount(mouse_event); } return NULL; } PEPPER_EXPORT struct PP_Point PPB_MouseInputEvent_GetMovement(PP_Resource mouse_event) { if (has_interface<PPB_MouseInputEvent_1_1>()) { return get_interface<PPB_MouseInputEvent_1_1>()->GetMovement(mouse_event); } return PP_MakePoint(0,0); } #pragma endregion /* End entry point generation for PPB_MouseInputEvent */ #pragma region /* Begin entry point methods for PPB_WheelInputEvent */ PEPPER_EXPORT PP_Resource PPB_WheelInputEvent_Create(PP_Instance instance, PP_TimeTicks time_stamp, uint32_t modifiers, struct PP_FloatPoint wheel_delta, struct PP_FloatPoint wheel_ticks, PP_Bool scroll_by_page) { if (has_interface<PPB_WheelInputEvent_1_0>()) { return get_interface<PPB_WheelInputEvent_1_0>()->Create(instance, time_stamp, modifiers, &wheel_delta, &wheel_ticks, scroll_by_page); } return NULL; } PEPPER_EXPORT PP_Bool PPB_WheelInputEvent_IsWheelInputEvent(PP_Resource resource) { if (has_interface<PPB_WheelInputEvent_1_0>()) { return get_interface<PPB_WheelInputEvent_1_0>()->IsWheelInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT struct PP_FloatPoint PPB_WheelInputEvent_GetDelta(PP_Resource wheel_event) { if (has_interface<PPB_WheelInputEvent_1_0>()) { return get_interface<PPB_WheelInputEvent_1_0>()->GetDelta(wheel_event); } return PP_MakeFloatPoint(0,0); } PEPPER_EXPORT struct PP_FloatPoint PPB_WheelInputEvent_GetTicks(PP_Resource wheel_event) { if (has_interface<PPB_WheelInputEvent_1_0>()) { return get_interface<PPB_WheelInputEvent_1_0>()->GetTicks(wheel_event); } return PP_MakeFloatPoint(0,0); } PEPPER_EXPORT PP_Bool PPB_WheelInputEvent_GetScrollByPage(PP_Resource wheel_event) { if (has_interface<PPB_WheelInputEvent_1_0>()) { return get_interface<PPB_WheelInputEvent_1_0>()->GetScrollByPage(wheel_event); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_WheelInputEvent */ #pragma region /* Begin entry point methods for PPB_KeyboardInputEvent */ PEPPER_EXPORT PP_Resource PPB_KeyboardInputEvent_Create(PP_Instance instance, PP_InputEvent_Type type, PP_TimeTicks time_stamp, uint32_t modifiers, uint32_t key_code, struct PP_Var character_text, struct PP_Var code) { if (has_interface<PPB_KeyboardInputEvent_1_2>()) { return get_interface<PPB_KeyboardInputEvent_1_2>()->Create(instance, type, time_stamp, modifiers, key_code, character_text, code); } return NULL; } PEPPER_EXPORT PP_Bool PPB_KeyboardInputEvent_IsKeyboardInputEvent(PP_Resource resource) { if (has_interface<PPB_KeyboardInputEvent_1_2>()) { return get_interface<PPB_KeyboardInputEvent_1_2>()->IsKeyboardInputEvent(resource); } else if (has_interface<PPB_KeyboardInputEvent_1_0>()) { return get_interface<PPB_KeyboardInputEvent_1_0>()->IsKeyboardInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT uint32_t PPB_KeyboardInputEvent_GetKeyCode(PP_Resource key_event) { if (has_interface<PPB_KeyboardInputEvent_1_2>()) { return get_interface<PPB_KeyboardInputEvent_1_2>()->GetKeyCode(key_event); } else if (has_interface<PPB_KeyboardInputEvent_1_0>()) { return get_interface<PPB_KeyboardInputEvent_1_0>()->GetKeyCode(key_event); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_KeyboardInputEvent_GetCharacterText(PP_Resource character_event) { if (has_interface<PPB_KeyboardInputEvent_1_2>()) { return get_interface<PPB_KeyboardInputEvent_1_2>()->GetCharacterText(character_event); } else if (has_interface<PPB_KeyboardInputEvent_1_0>()) { return get_interface<PPB_KeyboardInputEvent_1_0>()->GetCharacterText(character_event); } return PP_MakeNull(); } PEPPER_EXPORT struct PP_Var PPB_KeyboardInputEvent_GetCode(PP_Resource key_event) { if (has_interface<PPB_KeyboardInputEvent_1_2>()) { return get_interface<PPB_KeyboardInputEvent_1_2>()->GetCode(key_event); } return PP_MakeNull(); } #pragma endregion /* End entry point generation for PPB_KeyboardInputEvent */ #pragma region /* Begin entry point methods for PPB_TouchInputEvent */ PEPPER_EXPORT PP_Resource PPB_TouchInputEvent_Create(PP_Instance instance, PP_InputEvent_Type type, PP_TimeTicks time_stamp, uint32_t modifiers) { if (has_interface<PPB_TouchInputEvent_1_0>()) { return get_interface<PPB_TouchInputEvent_1_0>()->Create(instance, type, time_stamp, modifiers); } return NULL; } PEPPER_EXPORT void PPB_TouchInputEvent_AddTouchPoint(PP_Resource touch_event, PP_TouchListType list, struct PP_TouchPoint point) { if (has_interface<PPB_TouchInputEvent_1_0>()) { get_interface<PPB_TouchInputEvent_1_0>()->AddTouchPoint(touch_event, list, &point); } return ; } PEPPER_EXPORT PP_Bool PPB_TouchInputEvent_IsTouchInputEvent(PP_Resource resource) { if (has_interface<PPB_TouchInputEvent_1_0>()) { return get_interface<PPB_TouchInputEvent_1_0>()->IsTouchInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT uint32_t PPB_TouchInputEvent_GetTouchCount(PP_Resource resource, PP_TouchListType list) { if (has_interface<PPB_TouchInputEvent_1_0>()) { return get_interface<PPB_TouchInputEvent_1_0>()->GetTouchCount(resource, list); } return NULL; } PEPPER_EXPORT struct PP_TouchPoint PPB_TouchInputEvent_GetTouchByIndex(PP_Resource resource, PP_TouchListType list, uint32_t index) { if (has_interface<PPB_TouchInputEvent_1_0>()) { return get_interface<PPB_TouchInputEvent_1_0>()->GetTouchByIndex(resource, list, index); } return PP_MakeTouchPoint(); } PEPPER_EXPORT struct PP_TouchPoint PPB_TouchInputEvent_GetTouchById(PP_Resource resource, PP_TouchListType list, uint32_t touch_id) { if (has_interface<PPB_TouchInputEvent_1_0>()) { return get_interface<PPB_TouchInputEvent_1_0>()->GetTouchById(resource, list, touch_id); } return PP_MakeTouchPoint(); } #pragma endregion /* End entry point generation for PPB_TouchInputEvent */ #pragma region /* Begin entry point methods for PPB_IMEInputEvent */ PEPPER_EXPORT PP_Resource PPB_IMEInputEvent_Create(PP_Instance instance, PP_InputEvent_Type type, PP_TimeTicks time_stamp, struct PP_Var text, uint32_t segment_number, const uint32_t segment_offsets[], int32_t target_segment, uint32_t selection_start, uint32_t selection_end) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->Create(instance, type, time_stamp, text, segment_number, segment_offsets, target_segment, selection_start, selection_end); } return NULL; } PEPPER_EXPORT PP_Bool PPB_IMEInputEvent_IsIMEInputEvent(PP_Resource resource) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->IsIMEInputEvent(resource); } return PP_FromBool(false); } PEPPER_EXPORT struct PP_Var PPB_IMEInputEvent_GetText(PP_Resource ime_event) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->GetText(ime_event); } return PP_MakeNull(); } PEPPER_EXPORT uint32_t PPB_IMEInputEvent_GetSegmentNumber(PP_Resource ime_event) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->GetSegmentNumber(ime_event); } return NULL; } PEPPER_EXPORT uint32_t PPB_IMEInputEvent_GetSegmentOffset(PP_Resource ime_event, uint32_t index) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->GetSegmentOffset(ime_event, index); } return NULL; } PEPPER_EXPORT int32_t PPB_IMEInputEvent_GetTargetSegment(PP_Resource ime_event) { if (has_interface<PPB_IMEInputEvent_1_0>()) { return get_interface<PPB_IMEInputEvent_1_0>()->GetTargetSegment(ime_event); } return NULL; } PEPPER_EXPORT void PPB_IMEInputEvent_GetSelection(PP_Resource ime_event, uint32_t* start, uint32_t* end) { if (has_interface<PPB_IMEInputEvent_1_0>()) { get_interface<PPB_IMEInputEvent_1_0>()->GetSelection(ime_event, start, end); } return ; } #pragma endregion /* End entry point generation for PPB_IMEInputEvent */ #pragma region /* Begin entry point methods for PPB_Instance */ PEPPER_EXPORT PP_Bool PPB_Instance_BindGraphics(PP_Instance instance, PP_Resource device) { if (has_interface<PPB_Instance_1_0>()) { return get_interface<PPB_Instance_1_0>()->BindGraphics(instance, device); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_Instance_IsFullFrame(PP_Instance instance) { if (has_interface<PPB_Instance_1_0>()) { return get_interface<PPB_Instance_1_0>()->IsFullFrame(instance); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_Instance */ #pragma region /* Begin entry point methods for PPB_MediaStreamAudioTrack */ PEPPER_EXPORT PP_Bool PPB_MediaStreamAudioTrack_IsMediaStreamAudioTrack(PP_Resource resource) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->IsMediaStreamAudioTrack(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_MediaStreamAudioTrack_Configure(PP_Resource audio_track, const int32_t attrib_list[], struct PP_CompletionCallback callback) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->Configure(audio_track, attrib_list, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_MediaStreamAudioTrack_GetAttrib(PP_Resource audio_track, PP_MediaStreamAudioTrack_Attrib attrib, int32_t* value) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->GetAttrib(audio_track, attrib, value); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_MediaStreamAudioTrack_GetId(PP_Resource audio_track) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->GetId(audio_track); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_MediaStreamAudioTrack_HasEnded(PP_Resource audio_track) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->HasEnded(audio_track); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_MediaStreamAudioTrack_GetBuffer(PP_Resource audio_track, PP_Resource* buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->GetBuffer(audio_track, buffer, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_MediaStreamAudioTrack_RecycleBuffer(PP_Resource audio_track, PP_Resource buffer) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { return get_interface<PPB_MediaStreamAudioTrack_0_1>()->RecycleBuffer(audio_track, buffer); } return NULL; } PEPPER_EXPORT void PPB_MediaStreamAudioTrack_Close(PP_Resource audio_track) { if (has_interface<PPB_MediaStreamAudioTrack_0_1>()) { get_interface<PPB_MediaStreamAudioTrack_0_1>()->Close(audio_track); } return ; } #pragma endregion /* End entry point generation for PPB_MediaStreamAudioTrack */ #pragma region /* Begin entry point methods for PPB_MediaStreamVideoTrack */ PEPPER_EXPORT PP_Resource PPB_MediaStreamVideoTrack_Create(PP_Instance instance) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_MediaStreamVideoTrack_IsMediaStreamVideoTrack(PP_Resource resource) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->IsMediaStreamVideoTrack(resource); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->IsMediaStreamVideoTrack(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_Configure(PP_Resource video_track, const int32_t attrib_list[], struct PP_CompletionCallback callback) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->Configure(video_track, attrib_list, callback); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->Configure(video_track, attrib_list, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_GetAttrib(PP_Resource video_track, PP_MediaStreamVideoTrack_Attrib attrib, int32_t* value) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->GetAttrib(video_track, attrib, value); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->GetAttrib(video_track, attrib, value); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_MediaStreamVideoTrack_GetId(PP_Resource video_track) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->GetId(video_track); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->GetId(video_track); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_MediaStreamVideoTrack_HasEnded(PP_Resource video_track) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->HasEnded(video_track); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->HasEnded(video_track); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_GetFrame(PP_Resource video_track, PP_Resource* frame, struct PP_CompletionCallback callback) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->GetFrame(video_track, frame, callback); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->GetFrame(video_track, frame, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_RecycleFrame(PP_Resource video_track, PP_Resource frame) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->RecycleFrame(video_track, frame); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { return get_interface<PPB_MediaStreamVideoTrack_0_1>()->RecycleFrame(video_track, frame); } return NULL; } PEPPER_EXPORT void PPB_MediaStreamVideoTrack_Close(PP_Resource video_track) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { get_interface<PPB_MediaStreamVideoTrack_1_0>()->Close(video_track); } else if (has_interface<PPB_MediaStreamVideoTrack_0_1>()) { get_interface<PPB_MediaStreamVideoTrack_0_1>()->Close(video_track); } return ; } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_GetEmptyFrame(PP_Resource video_track, PP_Resource* frame, struct PP_CompletionCallback callback) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->GetEmptyFrame(video_track, frame, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_MediaStreamVideoTrack_PutFrame(PP_Resource video_track, PP_Resource frame) { if (has_interface<PPB_MediaStreamVideoTrack_1_0>()) { return get_interface<PPB_MediaStreamVideoTrack_1_0>()->PutFrame(video_track, frame); } return NULL; } #pragma endregion /* End entry point generation for PPB_MediaStreamVideoTrack */ #pragma region /* Begin entry point methods for PPB_MessageLoop */ PEPPER_EXPORT PP_Resource PPB_MessageLoop_Create(PP_Instance instance) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Resource PPB_MessageLoop_GetForMainThread(void) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->GetForMainThread(); } return NULL; } PEPPER_EXPORT PP_Resource PPB_MessageLoop_GetCurrent(void) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->GetCurrent(); } return NULL; } PEPPER_EXPORT int32_t PPB_MessageLoop_AttachToCurrentThread(PP_Resource message_loop) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->AttachToCurrentThread(message_loop); } return NULL; } PEPPER_EXPORT int32_t PPB_MessageLoop_Run(PP_Resource message_loop) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->Run(message_loop); } return NULL; } PEPPER_EXPORT int32_t PPB_MessageLoop_PostWork(PP_Resource message_loop, struct PP_CompletionCallback callback, int64_t delay_ms) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->PostWork(message_loop, callback, delay_ms); } return NULL; } PEPPER_EXPORT int32_t PPB_MessageLoop_PostQuit(PP_Resource message_loop, PP_Bool should_destroy) { if (has_interface<PPB_MessageLoop_1_0>()) { return get_interface<PPB_MessageLoop_1_0>()->PostQuit(message_loop, should_destroy); } return NULL; } #pragma endregion /* End entry point generation for PPB_MessageLoop */ #pragma region /* Begin entry point methods for PPB_Messaging */ PEPPER_EXPORT void PPB_Messaging_PostMessage(PP_Instance instance, struct PP_Var message) { if (has_interface<PPB_Messaging_1_2>()) { get_interface<PPB_Messaging_1_2>()->PostMessage(instance, message); } else if (has_interface<PPB_Messaging_1_0>()) { get_interface<PPB_Messaging_1_0>()->PostMessage(instance, message); } return ; } PEPPER_EXPORT int32_t PPB_Messaging_RegisterMessageHandler(PP_Instance instance, void* user_data, const struct PPP_MessageHandler_0_2* handler, PP_Resource message_loop) { if (has_interface<PPB_Messaging_1_2>()) { return get_interface<PPB_Messaging_1_2>()->RegisterMessageHandler(instance, user_data, handler, message_loop); } return NULL; } PEPPER_EXPORT void PPB_Messaging_UnregisterMessageHandler(PP_Instance instance) { if (has_interface<PPB_Messaging_1_2>()) { get_interface<PPB_Messaging_1_2>()->UnregisterMessageHandler(instance); } return ; } #pragma endregion /* End entry point generation for PPB_Messaging */ #pragma region /* Begin entry point methods for PPB_MouseCursor */ PEPPER_EXPORT PP_Bool PPB_MouseCursor_SetCursor(PP_Instance instance, enum PP_MouseCursor_Type type, PP_Resource image, struct PP_Point hot_spot) { if (has_interface<PPB_MouseCursor_1_0>()) { return get_interface<PPB_MouseCursor_1_0>()->SetCursor(instance, type, image, &hot_spot); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_MouseCursor */ #pragma region /* Begin entry point methods for PPB_MouseLock */ PEPPER_EXPORT int32_t PPB_MouseLock_LockMouse(PP_Instance instance, struct PP_CompletionCallback callback) { if (has_interface<PPB_MouseLock_1_0>()) { return get_interface<PPB_MouseLock_1_0>()->LockMouse(instance, callback); } return NULL; } PEPPER_EXPORT void PPB_MouseLock_UnlockMouse(PP_Instance instance) { if (has_interface<PPB_MouseLock_1_0>()) { get_interface<PPB_MouseLock_1_0>()->UnlockMouse(instance); } return ; } #pragma endregion /* End entry point generation for PPB_MouseLock */ #pragma region /* Begin entry point methods for PPB_NetAddress */ PEPPER_EXPORT PP_Resource PPB_NetAddress_CreateFromIPv4Address(PP_Instance instance, struct PP_NetAddress_IPv4 ipv4_addr) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->CreateFromIPv4Address(instance, &ipv4_addr); } return NULL; } PEPPER_EXPORT PP_Resource PPB_NetAddress_CreateFromIPv6Address(PP_Instance instance, struct PP_NetAddress_IPv6 ipv6_addr) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->CreateFromIPv6Address(instance, &ipv6_addr); } return NULL; } PEPPER_EXPORT PP_Bool PPB_NetAddress_IsNetAddress(PP_Resource resource) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->IsNetAddress(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_NetAddress_Family PPB_NetAddress_GetFamily(PP_Resource addr) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->GetFamily(addr); } return PP_NETADDRESS_FAMILY_UNSPECIFIED; } PEPPER_EXPORT struct PP_Var PPB_NetAddress_DescribeAsString(PP_Resource addr, PP_Bool include_port) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->DescribeAsString(addr, include_port); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_NetAddress_DescribeAsIPv4Address(PP_Resource addr, struct PP_NetAddress_IPv4* ipv4_addr) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->DescribeAsIPv4Address(addr, ipv4_addr); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_NetAddress_DescribeAsIPv6Address(PP_Resource addr, struct PP_NetAddress_IPv6* ipv6_addr) { if (has_interface<PPB_NetAddress_1_0>()) { return get_interface<PPB_NetAddress_1_0>()->DescribeAsIPv6Address(addr, ipv6_addr); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_NetAddress */ #pragma region /* Begin entry point methods for PPB_NetworkList */ PEPPER_EXPORT PP_Bool PPB_NetworkList_IsNetworkList(PP_Resource resource) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->IsNetworkList(resource); } return PP_FromBool(false); } PEPPER_EXPORT uint32_t PPB_NetworkList_GetCount(PP_Resource resource) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetCount(resource); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_NetworkList_GetName(PP_Resource resource, uint32_t index) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetName(resource, index); } return PP_MakeNull(); } PEPPER_EXPORT PP_NetworkList_Type PPB_NetworkList_GetType(PP_Resource resource, uint32_t index) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetType(resource, index); } return PP_NETWORKLIST_TYPE_ETHERNET; } PEPPER_EXPORT PP_NetworkList_State PPB_NetworkList_GetState(PP_Resource resource, uint32_t index) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetState(resource, index); } return PP_NETWORKLIST_STATE_DOWN; } PEPPER_EXPORT int32_t PPB_NetworkList_GetIpAddresses(PP_Resource resource, uint32_t index, struct PP_ArrayOutput output) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetIpAddresses(resource, index, output); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_NetworkList_GetDisplayName(PP_Resource resource, uint32_t index) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetDisplayName(resource, index); } return PP_MakeNull(); } PEPPER_EXPORT uint32_t PPB_NetworkList_GetMTU(PP_Resource resource, uint32_t index) { if (has_interface<PPB_NetworkList_1_0>()) { return get_interface<PPB_NetworkList_1_0>()->GetMTU(resource, index); } return NULL; } #pragma endregion /* End entry point generation for PPB_NetworkList */ #pragma region /* Begin entry point methods for PPB_NetworkMonitor */ PEPPER_EXPORT PP_Resource PPB_NetworkMonitor_Create(PP_Instance instance) { if (has_interface<PPB_NetworkMonitor_1_0>()) { return get_interface<PPB_NetworkMonitor_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT int32_t PPB_NetworkMonitor_UpdateNetworkList(PP_Resource network_monitor, PP_Resource* network_list, struct PP_CompletionCallback callback) { if (has_interface<PPB_NetworkMonitor_1_0>()) { return get_interface<PPB_NetworkMonitor_1_0>()->UpdateNetworkList(network_monitor, network_list, callback); } return NULL; } PEPPER_EXPORT PP_Bool PPB_NetworkMonitor_IsNetworkMonitor(PP_Resource resource) { if (has_interface<PPB_NetworkMonitor_1_0>()) { return get_interface<PPB_NetworkMonitor_1_0>()->IsNetworkMonitor(resource); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_NetworkMonitor */ #pragma region /* Begin entry point methods for PPB_NetworkProxy */ PEPPER_EXPORT int32_t PPB_NetworkProxy_GetProxyForURL(PP_Instance instance, struct PP_Var url, struct PP_Var* proxy_string, struct PP_CompletionCallback callback) { if (has_interface<PPB_NetworkProxy_1_0>()) { return get_interface<PPB_NetworkProxy_1_0>()->GetProxyForURL(instance, url, proxy_string, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_NetworkProxy */ #pragma region /* Begin entry point methods for PPB_TCPSocket */ PEPPER_EXPORT PP_Resource PPB_TCPSocket_Create(PP_Instance instance) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Create(instance); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Create(instance); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_TCPSocket_IsTCPSocket(PP_Resource resource) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->IsTCPSocket(resource); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->IsTCPSocket(resource); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->IsTCPSocket(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_TCPSocket_Bind(PP_Resource tcp_socket, PP_Resource addr, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Bind(tcp_socket, addr, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Bind(tcp_socket, addr, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_TCPSocket_Connect(PP_Resource tcp_socket, PP_Resource addr, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Connect(tcp_socket, addr, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Connect(tcp_socket, addr, callback); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->Connect(tcp_socket, addr, callback); } return NULL; } PEPPER_EXPORT PP_Resource PPB_TCPSocket_GetLocalAddress(PP_Resource tcp_socket) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->GetLocalAddress(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->GetLocalAddress(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->GetLocalAddress(tcp_socket); } return NULL; } PEPPER_EXPORT PP_Resource PPB_TCPSocket_GetRemoteAddress(PP_Resource tcp_socket) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->GetRemoteAddress(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->GetRemoteAddress(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->GetRemoteAddress(tcp_socket); } return NULL; } PEPPER_EXPORT int32_t PPB_TCPSocket_Read(PP_Resource tcp_socket, char* buffer, int32_t bytes_to_read, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Read(tcp_socket, buffer, bytes_to_read, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Read(tcp_socket, buffer, bytes_to_read, callback); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->Read(tcp_socket, buffer, bytes_to_read, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_TCPSocket_Write(PP_Resource tcp_socket, const char* buffer, int32_t bytes_to_write, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Write(tcp_socket, buffer, bytes_to_write, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Write(tcp_socket, buffer, bytes_to_write, callback); } else if (has_interface<PPB_TCPSocket_1_0>()) { return get_interface<PPB_TCPSocket_1_0>()->Write(tcp_socket, buffer, bytes_to_write, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_TCPSocket_Listen(PP_Resource tcp_socket, int32_t backlog, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Listen(tcp_socket, backlog, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Listen(tcp_socket, backlog, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_TCPSocket_Accept(PP_Resource tcp_socket, PP_Resource* accepted_tcp_socket, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->Accept(tcp_socket, accepted_tcp_socket, callback); } else if (has_interface<PPB_TCPSocket_1_1>()) { return get_interface<PPB_TCPSocket_1_1>()->Accept(tcp_socket, accepted_tcp_socket, callback); } return NULL; } PEPPER_EXPORT void PPB_TCPSocket_Close(PP_Resource tcp_socket) { if (has_interface<PPB_TCPSocket_1_2>()) { get_interface<PPB_TCPSocket_1_2>()->Close(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_1>()) { get_interface<PPB_TCPSocket_1_1>()->Close(tcp_socket); } else if (has_interface<PPB_TCPSocket_1_0>()) { get_interface<PPB_TCPSocket_1_0>()->Close(tcp_socket); } return ; } PEPPER_EXPORT int32_t PPB_TCPSocket_SetOption(PP_Resource tcp_socket, PP_TCPSocket_Option name, struct PP_Var value, struct PP_CompletionCallback callback) { if (has_interface<PPB_TCPSocket_1_2>()) { return get_interface<PPB_TCPSocket_1_2>()->SetOption(tcp_socket, name, value, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_TCPSocket */ #pragma region /* Begin entry point methods for PPB_UDPSocket */ PEPPER_EXPORT PP_Resource PPB_UDPSocket_Create(PP_Instance instance) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->Create(instance); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->Create(instance); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_UDPSocket_IsUDPSocket(PP_Resource resource) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->IsUDPSocket(resource); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->IsUDPSocket(resource); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->IsUDPSocket(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_UDPSocket_Bind(PP_Resource udp_socket, PP_Resource addr, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->Bind(udp_socket, addr, callback); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->Bind(udp_socket, addr, callback); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->Bind(udp_socket, addr, callback); } return NULL; } PEPPER_EXPORT PP_Resource PPB_UDPSocket_GetBoundAddress(PP_Resource udp_socket) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->GetBoundAddress(udp_socket); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->GetBoundAddress(udp_socket); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->GetBoundAddress(udp_socket); } return NULL; } PEPPER_EXPORT int32_t PPB_UDPSocket_RecvFrom(PP_Resource udp_socket, char* buffer, int32_t num_bytes, PP_Resource* addr, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->RecvFrom(udp_socket, buffer, num_bytes, addr, callback); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->RecvFrom(udp_socket, buffer, num_bytes, addr, callback); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->RecvFrom(udp_socket, buffer, num_bytes, addr, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_UDPSocket_SendTo(PP_Resource udp_socket, const char* buffer, int32_t num_bytes, PP_Resource addr, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->SendTo(udp_socket, buffer, num_bytes, addr, callback); } else if (has_interface<PPB_UDPSocket_1_1>()) { return get_interface<PPB_UDPSocket_1_1>()->SendTo(udp_socket, buffer, num_bytes, addr, callback); } else if (has_interface<PPB_UDPSocket_1_0>()) { return get_interface<PPB_UDPSocket_1_0>()->SendTo(udp_socket, buffer, num_bytes, addr, callback); } return NULL; } PEPPER_EXPORT void PPB_UDPSocket_Close(PP_Resource udp_socket) { if (has_interface<PPB_UDPSocket_1_2>()) { get_interface<PPB_UDPSocket_1_2>()->Close(udp_socket); } else if (has_interface<PPB_UDPSocket_1_1>()) { get_interface<PPB_UDPSocket_1_1>()->Close(udp_socket); } else if (has_interface<PPB_UDPSocket_1_0>()) { get_interface<PPB_UDPSocket_1_0>()->Close(udp_socket); } return ; } PEPPER_EXPORT int32_t PPB_UDPSocket_SetOption(PP_Resource udp_socket, PP_UDPSocket_Option name, struct PP_Var value, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->SetOption(udp_socket, name, value, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_UDPSocket_JoinGroup(PP_Resource udp_socket, PP_Resource group, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->JoinGroup(udp_socket, group, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_UDPSocket_LeaveGroup(PP_Resource udp_socket, PP_Resource group, struct PP_CompletionCallback callback) { if (has_interface<PPB_UDPSocket_1_2>()) { return get_interface<PPB_UDPSocket_1_2>()->LeaveGroup(udp_socket, group, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_UDPSocket */ #pragma region /* Begin entry point methods for PPB_URLLoader */ PEPPER_EXPORT PP_Resource PPB_URLLoader_Create(PP_Instance instance) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_URLLoader_IsURLLoader(PP_Resource resource) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->IsURLLoader(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_URLLoader_Open(PP_Resource loader, PP_Resource request_info, struct PP_CompletionCallback callback) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->Open(loader, request_info, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_URLLoader_FollowRedirect(PP_Resource loader, struct PP_CompletionCallback callback) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->FollowRedirect(loader, callback); } return NULL; } PEPPER_EXPORT PP_Bool PPB_URLLoader_GetUploadProgress(PP_Resource loader, int64_t* bytes_sent, int64_t* total_bytes_to_be_sent) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->GetUploadProgress(loader, bytes_sent, total_bytes_to_be_sent); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_URLLoader_GetDownloadProgress(PP_Resource loader, int64_t* bytes_received, int64_t* total_bytes_to_be_received) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->GetDownloadProgress(loader, bytes_received, total_bytes_to_be_received); } return PP_FromBool(false); } PEPPER_EXPORT PP_Resource PPB_URLLoader_GetResponseInfo(PP_Resource loader) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->GetResponseInfo(loader); } return NULL; } PEPPER_EXPORT int32_t PPB_URLLoader_ReadResponseBody(PP_Resource loader, void* buffer, int32_t bytes_to_read, struct PP_CompletionCallback callback) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->ReadResponseBody(loader, buffer, bytes_to_read, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_URLLoader_FinishStreamingToFile(PP_Resource loader, struct PP_CompletionCallback callback) { if (has_interface<PPB_URLLoader_1_0>()) { return get_interface<PPB_URLLoader_1_0>()->FinishStreamingToFile(loader, callback); } return NULL; } PEPPER_EXPORT void PPB_URLLoader_Close(PP_Resource loader) { if (has_interface<PPB_URLLoader_1_0>()) { get_interface<PPB_URLLoader_1_0>()->Close(loader); } return ; } #pragma endregion /* End entry point generation for PPB_URLLoader */ #pragma region /* Begin entry point methods for PPB_URLRequestInfo */ PEPPER_EXPORT PP_Resource PPB_URLRequestInfo_Create(PP_Instance instance) { if (has_interface<PPB_URLRequestInfo_1_0>()) { return get_interface<PPB_URLRequestInfo_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_URLRequestInfo_IsURLRequestInfo(PP_Resource resource) { if (has_interface<PPB_URLRequestInfo_1_0>()) { return get_interface<PPB_URLRequestInfo_1_0>()->IsURLRequestInfo(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_URLRequestInfo_SetProperty(PP_Resource request, PP_URLRequestProperty property, struct PP_Var value) { if (has_interface<PPB_URLRequestInfo_1_0>()) { return get_interface<PPB_URLRequestInfo_1_0>()->SetProperty(request, property, value); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_URLRequestInfo_AppendDataToBody(PP_Resource request, const void* data, uint32_t len) { if (has_interface<PPB_URLRequestInfo_1_0>()) { return get_interface<PPB_URLRequestInfo_1_0>()->AppendDataToBody(request, data, len); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_URLRequestInfo_AppendFileToBody(PP_Resource request, PP_Resource file_ref, int64_t start_offset, int64_t number_of_bytes, PP_Time expected_last_modified_time) { if (has_interface<PPB_URLRequestInfo_1_0>()) { return get_interface<PPB_URLRequestInfo_1_0>()->AppendFileToBody(request, file_ref, start_offset, number_of_bytes, expected_last_modified_time); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_URLRequestInfo */ #pragma region /* Begin entry point methods for PPB_URLResponseInfo */ PEPPER_EXPORT PP_Bool PPB_URLResponseInfo_IsURLResponseInfo(PP_Resource resource) { if (has_interface<PPB_URLResponseInfo_1_0>()) { return get_interface<PPB_URLResponseInfo_1_0>()->IsURLResponseInfo(resource); } return PP_FromBool(false); } PEPPER_EXPORT struct PP_Var PPB_URLResponseInfo_GetProperty(PP_Resource response, PP_URLResponseProperty property) { if (has_interface<PPB_URLResponseInfo_1_0>()) { return get_interface<PPB_URLResponseInfo_1_0>()->GetProperty(response, property); } return PP_MakeNull(); } PEPPER_EXPORT PP_Resource PPB_URLResponseInfo_GetBodyAsFileRef(PP_Resource response) { if (has_interface<PPB_URLResponseInfo_1_0>()) { return get_interface<PPB_URLResponseInfo_1_0>()->GetBodyAsFileRef(response); } return NULL; } #pragma endregion /* End entry point generation for PPB_URLResponseInfo */ #pragma region /* Begin entry point methods for PPB_Var */ PEPPER_EXPORT void PPB_Var_AddRef(struct PP_Var var) { if (has_interface<PPB_Var_1_2>()) { get_interface<PPB_Var_1_2>()->AddRef(var); } else if (has_interface<PPB_Var_1_1>()) { get_interface<PPB_Var_1_1>()->AddRef(var); } else if (has_interface<PPB_Var_1_0>()) { get_interface<PPB_Var_1_0>()->AddRef(var); } return ; } PEPPER_EXPORT void PPB_Var_Release(struct PP_Var var) { if (has_interface<PPB_Var_1_2>()) { get_interface<PPB_Var_1_2>()->Release(var); } else if (has_interface<PPB_Var_1_1>()) { get_interface<PPB_Var_1_1>()->Release(var); } else if (has_interface<PPB_Var_1_0>()) { get_interface<PPB_Var_1_0>()->Release(var); } return ; } PEPPER_EXPORT struct PP_Var PPB_Var_VarFromUtf8(const char* data, uint32_t len) { if (has_interface<PPB_Var_1_2>()) { return get_interface<PPB_Var_1_2>()->VarFromUtf8(data, len); } else if (has_interface<PPB_Var_1_1>()) { return get_interface<PPB_Var_1_1>()->VarFromUtf8(data, len); } return PP_MakeNull(); } PEPPER_EXPORT const char* PPB_Var_VarToUtf8(struct PP_Var var, uint32_t* len) { if (has_interface<PPB_Var_1_2>()) { return get_interface<PPB_Var_1_2>()->VarToUtf8(var, len); } else if (has_interface<PPB_Var_1_1>()) { return get_interface<PPB_Var_1_1>()->VarToUtf8(var, len); } else if (has_interface<PPB_Var_1_0>()) { return get_interface<PPB_Var_1_0>()->VarToUtf8(var, len); } return NULL; } PEPPER_EXPORT PP_Resource PPB_Var_VarToResource(struct PP_Var var) { if (has_interface<PPB_Var_1_2>()) { return get_interface<PPB_Var_1_2>()->VarToResource(var); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_Var_VarFromResource(PP_Resource resource) { if (has_interface<PPB_Var_1_2>()) { return get_interface<PPB_Var_1_2>()->VarFromResource(resource); } return PP_MakeNull(); } #pragma endregion /* End entry point generation for PPB_Var */ #pragma region /* Begin entry point methods for PPB_VarArray */ PEPPER_EXPORT struct PP_Var PPB_VarArray_Create(void) { if (has_interface<PPB_VarArray_1_0>()) { return get_interface<PPB_VarArray_1_0>()->Create(); } return PP_MakeNull(); } PEPPER_EXPORT struct PP_Var PPB_VarArray_Get(struct PP_Var array, uint32_t index) { if (has_interface<PPB_VarArray_1_0>()) { return get_interface<PPB_VarArray_1_0>()->Get(array, index); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_VarArray_Set(struct PP_Var array, uint32_t index, struct PP_Var value) { if (has_interface<PPB_VarArray_1_0>()) { return get_interface<PPB_VarArray_1_0>()->Set(array, index, value); } return PP_FromBool(false); } PEPPER_EXPORT uint32_t PPB_VarArray_GetLength(struct PP_Var array) { if (has_interface<PPB_VarArray_1_0>()) { return get_interface<PPB_VarArray_1_0>()->GetLength(array); } return NULL; } PEPPER_EXPORT PP_Bool PPB_VarArray_SetLength(struct PP_Var array, uint32_t length) { if (has_interface<PPB_VarArray_1_0>()) { return get_interface<PPB_VarArray_1_0>()->SetLength(array, length); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_VarArray */ #pragma region /* Begin entry point methods for PPB_VarArrayBuffer */ PEPPER_EXPORT struct PP_Var PPB_VarArrayBuffer_Create(uint32_t size_in_bytes) { if (has_interface<PPB_VarArrayBuffer_1_0>()) { return get_interface<PPB_VarArrayBuffer_1_0>()->Create(size_in_bytes); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_VarArrayBuffer_ByteLength(struct PP_Var array, uint32_t* byte_length) { if (has_interface<PPB_VarArrayBuffer_1_0>()) { return get_interface<PPB_VarArrayBuffer_1_0>()->ByteLength(array, byte_length); } return PP_FromBool(false); } PEPPER_EXPORT void* PPB_VarArrayBuffer_Map(struct PP_Var array) { if (has_interface<PPB_VarArrayBuffer_1_0>()) { return get_interface<PPB_VarArrayBuffer_1_0>()->Map(array); } return NULL; } PEPPER_EXPORT void PPB_VarArrayBuffer_Unmap(struct PP_Var array) { if (has_interface<PPB_VarArrayBuffer_1_0>()) { get_interface<PPB_VarArrayBuffer_1_0>()->Unmap(array); } return ; } #pragma endregion /* End entry point generation for PPB_VarArrayBuffer */ #pragma region /* Begin entry point methods for PPB_VarDictionary */ PEPPER_EXPORT struct PP_Var PPB_VarDictionary_Create(void) { if (has_interface<PPB_VarDictionary_1_0>()) { return get_interface<PPB_VarDictionary_1_0>()->Create(); } return PP_MakeNull(); } PEPPER_EXPORT struct PP_Var PPB_VarDictionary_Get(struct PP_Var dict, struct PP_Var key) { if (has_interface<PPB_VarDictionary_1_0>()) { return get_interface<PPB_VarDictionary_1_0>()->Get(dict, key); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_VarDictionary_Set(struct PP_Var dict, struct PP_Var key, struct PP_Var value) { if (has_interface<PPB_VarDictionary_1_0>()) { return get_interface<PPB_VarDictionary_1_0>()->Set(dict, key, value); } return PP_FromBool(false); } PEPPER_EXPORT void PPB_VarDictionary_Delete(struct PP_Var dict, struct PP_Var key) { if (has_interface<PPB_VarDictionary_1_0>()) { get_interface<PPB_VarDictionary_1_0>()->Delete(dict, key); } return ; } PEPPER_EXPORT PP_Bool PPB_VarDictionary_HasKey(struct PP_Var dict, struct PP_Var key) { if (has_interface<PPB_VarDictionary_1_0>()) { return get_interface<PPB_VarDictionary_1_0>()->HasKey(dict, key); } return PP_FromBool(false); } PEPPER_EXPORT struct PP_Var PPB_VarDictionary_GetKeys(struct PP_Var dict) { if (has_interface<PPB_VarDictionary_1_0>()) { return get_interface<PPB_VarDictionary_1_0>()->GetKeys(dict); } return PP_MakeNull(); } #pragma endregion /* End entry point generation for PPB_VarDictionary */ #pragma region /* Begin entry point methods for PPB_VideoDecoder */ PEPPER_EXPORT PP_Resource PPB_VideoDecoder_Create(PP_Instance instance) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->Create(instance); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->Create(instance); } else if (has_interface<PPB_VideoDecoder_0_2>()) { return get_interface<PPB_VideoDecoder_0_2>()->Create(instance); } else if (has_interface<PPB_VideoDecoder_0_1>()) { return get_interface<PPB_VideoDecoder_0_1>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_VideoDecoder_IsVideoDecoder(PP_Resource resource) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->IsVideoDecoder(resource); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->IsVideoDecoder(resource); } else if (has_interface<PPB_VideoDecoder_0_2>()) { return get_interface<PPB_VideoDecoder_0_2>()->IsVideoDecoder(resource); } else if (has_interface<PPB_VideoDecoder_0_1>()) { return get_interface<PPB_VideoDecoder_0_1>()->IsVideoDecoder(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_VideoDecoder_Initialize(PP_Resource video_decoder, PP_Resource graphics3d_context, PP_VideoProfile profile, PP_HardwareAcceleration acceleration, uint32_t min_picture_count, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->Initialize(video_decoder, graphics3d_context, profile, acceleration, min_picture_count, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoDecoder_Decode(PP_Resource video_decoder, uint32_t decode_id, uint32_t size, const void* buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->Decode(video_decoder, decode_id, size, buffer, callback); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->Decode(video_decoder, decode_id, size, buffer, callback); } else if (has_interface<PPB_VideoDecoder_0_2>()) { return get_interface<PPB_VideoDecoder_0_2>()->Decode(video_decoder, decode_id, size, buffer, callback); } else if (has_interface<PPB_VideoDecoder_0_1>()) { return get_interface<PPB_VideoDecoder_0_1>()->Decode(video_decoder, decode_id, size, buffer, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoDecoder_GetPicture(PP_Resource video_decoder, struct PP_VideoPicture* picture, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->GetPicture(video_decoder, picture, callback); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->GetPicture(video_decoder, picture, callback); } return NULL; } PEPPER_EXPORT void PPB_VideoDecoder_RecyclePicture(PP_Resource video_decoder, struct PP_VideoPicture picture) { if (has_interface<PPB_VideoDecoder_1_1>()) { get_interface<PPB_VideoDecoder_1_1>()->RecyclePicture(video_decoder, &picture); } else if (has_interface<PPB_VideoDecoder_1_0>()) { get_interface<PPB_VideoDecoder_1_0>()->RecyclePicture(video_decoder, &picture); } else if (has_interface<PPB_VideoDecoder_0_2>()) { get_interface<PPB_VideoDecoder_0_2>()->RecyclePicture(video_decoder, &picture); } else if (has_interface<PPB_VideoDecoder_0_1>()) { get_interface<PPB_VideoDecoder_0_1>()->RecyclePicture(video_decoder, &picture); } return ; } PEPPER_EXPORT int32_t PPB_VideoDecoder_Flush(PP_Resource video_decoder, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->Flush(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->Flush(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_0_2>()) { return get_interface<PPB_VideoDecoder_0_2>()->Flush(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_0_1>()) { return get_interface<PPB_VideoDecoder_0_1>()->Flush(video_decoder, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoDecoder_Reset(PP_Resource video_decoder, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoDecoder_1_1>()) { return get_interface<PPB_VideoDecoder_1_1>()->Reset(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_1_0>()) { return get_interface<PPB_VideoDecoder_1_0>()->Reset(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_0_2>()) { return get_interface<PPB_VideoDecoder_0_2>()->Reset(video_decoder, callback); } else if (has_interface<PPB_VideoDecoder_0_1>()) { return get_interface<PPB_VideoDecoder_0_1>()->Reset(video_decoder, callback); } return NULL; } #pragma endregion /* End entry point generation for PPB_VideoDecoder */ #pragma region /* Begin entry point methods for PPB_VideoEncoder */ PEPPER_EXPORT PP_Resource PPB_VideoEncoder_Create(PP_Instance instance) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->Create(instance); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_VideoEncoder_IsVideoEncoder(PP_Resource resource) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->IsVideoEncoder(resource); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->IsVideoEncoder(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_VideoEncoder_GetSupportedProfiles(PP_Resource video_encoder, struct PP_ArrayOutput output, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->GetSupportedProfiles(video_encoder, output, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_Initialize(PP_Resource video_encoder, PP_VideoFrame_Format input_format, struct PP_Size input_visible_size, PP_VideoProfile output_profile, uint32_t initial_bitrate, PP_HardwareAcceleration acceleration, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->Initialize(video_encoder, input_format, &input_visible_size, output_profile, initial_bitrate, acceleration, callback); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->Initialize(video_encoder, input_format, &input_visible_size, output_profile, initial_bitrate, acceleration, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_GetFramesRequired(PP_Resource video_encoder) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->GetFramesRequired(video_encoder); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->GetFramesRequired(video_encoder); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_GetFrameCodedSize(PP_Resource video_encoder, struct PP_Size* coded_size) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->GetFrameCodedSize(video_encoder, coded_size); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->GetFrameCodedSize(video_encoder, coded_size); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_GetVideoFrame(PP_Resource video_encoder, PP_Resource* video_frame, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->GetVideoFrame(video_encoder, video_frame, callback); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->GetVideoFrame(video_encoder, video_frame, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_Encode(PP_Resource video_encoder, PP_Resource video_frame, PP_Bool force_keyframe, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->Encode(video_encoder, video_frame, force_keyframe, callback); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->Encode(video_encoder, video_frame, force_keyframe, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_VideoEncoder_GetBitstreamBuffer(PP_Resource video_encoder, struct PP_BitstreamBuffer* bitstream_buffer, struct PP_CompletionCallback callback) { if (has_interface<PPB_VideoEncoder_0_2>()) { return get_interface<PPB_VideoEncoder_0_2>()->GetBitstreamBuffer(video_encoder, bitstream_buffer, callback); } else if (has_interface<PPB_VideoEncoder_0_1>()) { return get_interface<PPB_VideoEncoder_0_1>()->GetBitstreamBuffer(video_encoder, bitstream_buffer, callback); } return NULL; } PEPPER_EXPORT void PPB_VideoEncoder_RecycleBitstreamBuffer(PP_Resource video_encoder, struct PP_BitstreamBuffer bitstream_buffer) { if (has_interface<PPB_VideoEncoder_0_2>()) { get_interface<PPB_VideoEncoder_0_2>()->RecycleBitstreamBuffer(video_encoder, &bitstream_buffer); } else if (has_interface<PPB_VideoEncoder_0_1>()) { get_interface<PPB_VideoEncoder_0_1>()->RecycleBitstreamBuffer(video_encoder, &bitstream_buffer); } return ; } PEPPER_EXPORT void PPB_VideoEncoder_RequestEncodingParametersChange(PP_Resource video_encoder, uint32_t bitrate, uint32_t framerate) { if (has_interface<PPB_VideoEncoder_0_2>()) { get_interface<PPB_VideoEncoder_0_2>()->RequestEncodingParametersChange(video_encoder, bitrate, framerate); } else if (has_interface<PPB_VideoEncoder_0_1>()) { get_interface<PPB_VideoEncoder_0_1>()->RequestEncodingParametersChange(video_encoder, bitrate, framerate); } return ; } PEPPER_EXPORT void PPB_VideoEncoder_Close(PP_Resource video_encoder) { if (has_interface<PPB_VideoEncoder_0_2>()) { get_interface<PPB_VideoEncoder_0_2>()->Close(video_encoder); } else if (has_interface<PPB_VideoEncoder_0_1>()) { get_interface<PPB_VideoEncoder_0_1>()->Close(video_encoder); } return ; } #pragma endregion /* End entry point generation for PPB_VideoEncoder */ #pragma region /* Begin entry point methods for PPB_VideoFrame */ PEPPER_EXPORT PP_Bool PPB_VideoFrame_IsVideoFrame(PP_Resource resource) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->IsVideoFrame(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_TimeDelta PPB_VideoFrame_GetTimestamp(PP_Resource frame) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->GetTimestamp(frame); } return NULL; } PEPPER_EXPORT void PPB_VideoFrame_SetTimestamp(PP_Resource frame, PP_TimeDelta timestamp) { if (has_interface<PPB_VideoFrame_0_1>()) { get_interface<PPB_VideoFrame_0_1>()->SetTimestamp(frame, timestamp); } return ; } PEPPER_EXPORT PP_VideoFrame_Format PPB_VideoFrame_GetFormat(PP_Resource frame) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->GetFormat(frame); } return PP_VIDEOFRAME_FORMAT_UNKNOWN; } PEPPER_EXPORT PP_Bool PPB_VideoFrame_GetSize(PP_Resource frame, struct PP_Size* size) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->GetSize(frame, size); } return PP_FromBool(false); } PEPPER_EXPORT void* PPB_VideoFrame_GetDataBuffer(PP_Resource frame) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->GetDataBuffer(frame); } return NULL; } PEPPER_EXPORT uint32_t PPB_VideoFrame_GetDataBufferSize(PP_Resource frame) { if (has_interface<PPB_VideoFrame_0_1>()) { return get_interface<PPB_VideoFrame_0_1>()->GetDataBufferSize(frame); } return NULL; } #pragma endregion /* End entry point generation for PPB_VideoFrame */ #pragma region /* Begin entry point methods for PPB_View */ PEPPER_EXPORT PP_Bool PPB_View_IsView(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->IsView(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->IsView(resource); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->IsView(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_View_GetRect(PP_Resource resource, struct PP_Rect* rect) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->GetRect(resource, rect); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->GetRect(resource, rect); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->GetRect(resource, rect); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_View_IsFullscreen(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->IsFullscreen(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->IsFullscreen(resource); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->IsFullscreen(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_View_IsVisible(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->IsVisible(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->IsVisible(resource); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->IsVisible(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_View_IsPageVisible(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->IsPageVisible(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->IsPageVisible(resource); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->IsPageVisible(resource); } return PP_FromBool(false); } PEPPER_EXPORT PP_Bool PPB_View_GetClipRect(PP_Resource resource, struct PP_Rect* clip) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->GetClipRect(resource, clip); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->GetClipRect(resource, clip); } else if (has_interface<PPB_View_1_0>()) { return get_interface<PPB_View_1_0>()->GetClipRect(resource, clip); } return PP_FromBool(false); } PEPPER_EXPORT float PPB_View_GetDeviceScale(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->GetDeviceScale(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->GetDeviceScale(resource); } return NULL; } PEPPER_EXPORT float PPB_View_GetCSSScale(PP_Resource resource) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->GetCSSScale(resource); } else if (has_interface<PPB_View_1_1>()) { return get_interface<PPB_View_1_1>()->GetCSSScale(resource); } return NULL; } PEPPER_EXPORT PP_Bool PPB_View_GetScrollOffset(PP_Resource resource, struct PP_Point* offset) { if (has_interface<PPB_View_1_2>()) { return get_interface<PPB_View_1_2>()->GetScrollOffset(resource, offset); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPB_View */ #pragma region /* Begin entry point methods for PPB_WebSocket */ PEPPER_EXPORT PP_Resource PPB_WebSocket_Create(PP_Instance instance) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->Create(instance); } return NULL; } PEPPER_EXPORT PP_Bool PPB_WebSocket_IsWebSocket(PP_Resource resource) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->IsWebSocket(resource); } return PP_FromBool(false); } PEPPER_EXPORT int32_t PPB_WebSocket_Connect(PP_Resource web_socket, struct PP_Var url, const struct PP_Var protocols[], uint32_t protocol_count, struct PP_CompletionCallback callback) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->Connect(web_socket, url, protocols, protocol_count, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_WebSocket_Close(PP_Resource web_socket, uint16_t code, struct PP_Var reason, struct PP_CompletionCallback callback) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->Close(web_socket, code, reason, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_WebSocket_ReceiveMessage(PP_Resource web_socket, struct PP_Var* message, struct PP_CompletionCallback callback) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->ReceiveMessage(web_socket, message, callback); } return NULL; } PEPPER_EXPORT int32_t PPB_WebSocket_SendMessage(PP_Resource web_socket, struct PP_Var message) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->SendMessage(web_socket, message); } return NULL; } PEPPER_EXPORT uint64_t PPB_WebSocket_GetBufferedAmount(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetBufferedAmount(web_socket); } return NULL; } PEPPER_EXPORT uint16_t PPB_WebSocket_GetCloseCode(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetCloseCode(web_socket); } return NULL; } PEPPER_EXPORT struct PP_Var PPB_WebSocket_GetCloseReason(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetCloseReason(web_socket); } return PP_MakeNull(); } PEPPER_EXPORT PP_Bool PPB_WebSocket_GetCloseWasClean(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetCloseWasClean(web_socket); } return PP_FromBool(false); } PEPPER_EXPORT struct PP_Var PPB_WebSocket_GetExtensions(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetExtensions(web_socket); } return PP_MakeNull(); } PEPPER_EXPORT struct PP_Var PPB_WebSocket_GetProtocol(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetProtocol(web_socket); } return PP_MakeNull(); } PEPPER_EXPORT PP_WebSocketReadyState PPB_WebSocket_GetReadyState(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetReadyState(web_socket); } return PP_WEBSOCKETREADYSTATE_INVALID; } PEPPER_EXPORT struct PP_Var PPB_WebSocket_GetURL(PP_Resource web_socket) { if (has_interface<PPB_WebSocket_1_0>()) { return get_interface<PPB_WebSocket_1_0>()->GetURL(web_socket); } return PP_MakeNull(); } #pragma endregion /* End entry point generation for PPB_WebSocket */ #pragma region /* Begin entry point methods for PPP_InputEvent */ PEPPER_EXPORT PP_Bool PPP_InputEvent_HandleInputEvent(PP_Instance instance, PP_Resource input_event) { if (has_interface<PPP_InputEvent_0_1>()) { return get_interface<PPP_InputEvent_0_1>()->HandleInputEvent(instance, input_event); } return PP_FromBool(false); } #pragma endregion /* End entry point generation for PPP_InputEvent */ /* Not generating entry point methods for PPP_MessageHandler_0_2 */ #pragma region /* Begin entry point methods for PPP_Messaging */ PEPPER_EXPORT void PPP_Messaging_HandleMessage(PP_Instance instance, struct PP_Var message) { if (has_interface<PPP_Messaging_1_0>()) { get_interface<PPP_Messaging_1_0>()->HandleMessage(instance, message); } return ; } #pragma endregion /* End entry point generation for PPP_Messaging */ #pragma region /* Begin entry point methods for PPP_MouseLock */ PEPPER_EXPORT void PPP_MouseLock_MouseLockLost(PP_Instance instance) { if (has_interface<PPP_MouseLock_1_0>()) { get_interface<PPP_MouseLock_1_0>()->MouseLockLost(instance); } return ; } #pragma endregion /* End entry point generation for PPP_MouseLock */ } #ifdef __cplusplus } /* extern "C" */ #endif }
48,821
360
<reponame>tigertv/Cube-Engine #ifndef TZW_FONTENGINE_H #define TZW_FONTENGINE_H #include <ft2build.h> #include FT_FREETYPE_H #include <string> namespace tzw { class Font; class FontEngine { public: static FontEngine *shared(); void initFont(Font* font, std::string fontFilePath, unsigned int fontSize); private: FontEngine(); static FontEngine * m_instance; FT_Library * m_library; }; } // namespace tzw #endif // TZW_FONTENGINE_H
184
2,228
/* * Copyright 2013-2021 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.jpa.repository.support; import static org.assertj.core.api.Assertions.*; import java.io.Serializable; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.data.jpa.domain.AbstractPersistable; import org.springframework.test.context.ContextConfiguration; /** * EclipseLink execution for {@link JpaMetamodelEntityInformationIntegrationTests}. * * @author <NAME> * @author <NAME> */ @ContextConfiguration("classpath:eclipselink.xml") class EclipseLinkJpaMetamodelEntityInformationIntegrationTests extends JpaMetamodelEntityInformationIntegrationTests { /** * Re-activate test. Change to check for {@link String} as OpenJpa defaults {@link Serializable}s to {@link String}. */ @Test void reactivatedDetectsIdTypeForMappedSuperclass() { JpaEntityInformation<?, ?> information = JpaEntityInformationSupport.getEntityInformation(AbstractPersistable.class, em); assertThat(information.getIdType()).isEqualTo(String.class); } /** * Ignored due to https://bugs.eclipse.org/bugs/show_bug.cgi?id=411231. */ @Override @Disabled void findsIdClassOnMappedSuperclass() {} /** * Ignored due to https://bugs.eclipse.org/bugs/show_bug.cgi?id=415027 */ @Override @Disabled void detectsNewStateForEntityWithPrimitiveId() {} @Override @Disabled void considersEntityWithUnsetCompundIdNew() {} /** * Re-activate test for DATAJPA-820. */ @Test @Override void detectsVersionPropertyOnMappedSuperClass() { super.detectsVersionPropertyOnMappedSuperClass(); } /** * This test fails due to https://bugs.eclipse.org/bugs/show_bug.cgi?id=531528 IdentifiableType.hasSingleIdAttribute() * returns true when IdClass references an inner class. This bug is supposedly fixed, but the test still fails. */ @Disabled @Test @Override void correctlyDeterminesIdValueForNestedIdClassesWithNonPrimitiveNonManagedType() { super.correctlyDeterminesIdValueForNestedIdClassesWithNonPrimitiveNonManagedType(); } /** * This test fails due to https://bugs.eclipse.org/bugs/show_bug.cgi?id=531528 IdentifiableType.hasSingleIdAttribute() * returns true when IdClass references an inner class. This bug is supposedly fixed, but the test still fails. */ @Disabled @Test @Override void proxiedIdClassElement() { super.proxiedIdClassElement(); } @Override String getMetadadataPersitenceUnitName() { return "metadata_el"; } }
961
2,180
package com.xiaojukeji.kafka.manager.common.entity.dto.normal; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.xiaojukeji.kafka.manager.common.constant.TopicSampleConstant; import com.xiaojukeji.kafka.manager.common.utils.ValidateUtils; import io.swagger.annotations.ApiModelProperty; /** * Topic采样 * @author zengqiao * @date 19/4/8 */ @JsonIgnoreProperties(ignoreUnknown = true) public class TopicDataSampleDTO { @ApiModelProperty(value = "分区Id") private Integer partitionId; @ApiModelProperty(value = "最大采样条数[必须小于100]") private Integer maxMsgNum; @ApiModelProperty(value = "采样超时时间[必须小于10000]") private Integer timeout; @ApiModelProperty(value = "采样offset") private Long offset; @ApiModelProperty(value = "截断") private Boolean truncate; @ApiModelProperty(value = "是否是集群ID, 默认不是") private Boolean isPhysicalClusterId; public Integer getPartitionId() { return partitionId; } public void setPartitionId(Integer partitionId) { this.partitionId = partitionId; } public Integer getMaxMsgNum() { return maxMsgNum; } public void setMaxMsgNum(Integer maxMsgNum) { this.maxMsgNum = maxMsgNum; } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public Long getOffset() { return offset; } public void setOffset(Long offset) { this.offset = offset; } public Boolean getTruncate() { return truncate; } public void setTruncate(Boolean truncate) { this.truncate = truncate; } public Boolean getIsPhysicalClusterId() { return isPhysicalClusterId; } public void setIsPhysicalClusterId(Boolean isPhysicalClusterId) { this.isPhysicalClusterId = isPhysicalClusterId; } @Override public String toString() { return "TopicDataSampleDTO{" + "partitionId=" + partitionId + ", maxMsgNum=" + maxMsgNum + ", timeout=" + timeout + ", offset=" + offset + ", truncate=" + truncate + ", isPhysicalClusterId=" + isPhysicalClusterId + '}'; } public void adjustConfig() { timeout = Math.min(timeout, TopicSampleConstant.MAX_TIMEOUT_UNIT_MS); maxMsgNum = Math.min(maxMsgNum, TopicSampleConstant.MAX_MSG_NUM); if (ValidateUtils.isNull(isPhysicalClusterId)) { isPhysicalClusterId = false; } } }
1,125
3,777
from supervisor.options import ClientOptions from jadi import component from aj.plugins.services.api import ServiceManager, Service, ServiceOperationError @component(ServiceManager) class SupervisorServiceManager(ServiceManager): id = 'supervisor' name = 'Supervisor' def __init__(self, context): options = ClientOptions() options.realize([]) self.supervisor = options.getServerProxy().supervisor def list(self): for info in self.supervisor.getAllProcessInfo(): yield self.__make_service(info) def __make_service(self, info): svc = Service(self) svc.id = info['name'] svc.name = info['name'] svc.state = info['statename'] svc.running = svc.state == 'RUNNING' return svc def get_service(self, _id): return self.__make_service(self.supervisor.getProcessInfo(_id)) def start(self, _id): if not self.supervisor.startProcess(_id): raise ServiceOperationError('Supervisor operation failed') def stop(self, _id): if not self.supervisor.stopProcess(_id): raise ServiceOperationError('Supervisor operation failed') def restart(self, _id): self.stop(_id) self.start(_id)
488
1,958
<reponame>stephenkid/LeetCode-Sol package com.freetymekiyan.algorithms.level.easy; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array * such that nums[i] = nums[j] and the difference between i and j is at most k. * <p> * Tags: Array, Hash Table * Similar Problems: (E) Contains Duplicate, (M) Contains Duplicate III */ public class ContainsDuplicate2 { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } else { map.put(nums[i], i); } } return false; } /** * Don't need to save number and index in a map. * Just loop through the array with a sliding window(set of size k). */ public boolean containsNearbyDuplicate2(int[] nums, int k) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { if (i > k) { set.remove(nums[i - k - 1]); } if (!set.add(nums[i])) { return true; } } return false; } }
640
343
class EnclosingMethodTest { public String text; public static void main(String[] args) { new EnclosingMethodTest() {{ this.text = "Hello World!"; callHelloWorld(); }}; } public void callHelloWorld() { System.out.println(this.text); } }
143
611
<reponame>packagesdev/dejalu // DejaLu // Copyright (c) 2015 <NAME>. All rights reserved. #import <Cocoa/Cocoa.h> @interface NSImage (DJLColored) - (NSImage *) djl_imageWithColor:(NSColor *)color; @end
82
310
{ "name": "Diva Lite 200", "description": "A lighting fixture for video recording.", "url": "https://www.amazon.com/Diva-Lite-200-120-volt/dp/B0089X7NEG" }
63
442
#This file is part of ElectricEye. #SPDX-License-Identifier: Apache-2.0 #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. import boto3 import datetime from check_register import CheckRegister from dateutil.parser import parse from botocore.config import Config # Adding backoff and retries for SSM - this API gets throttled a lot config = Config( retries = { 'max_attempts': 10, 'mode': 'adaptive' } ) registry = CheckRegister() # create boto3 clients ec2 = boto3.client("ec2",config=config) ssm = boto3.client("ssm",config=config) # loop through ec2 instances def describe_instances(cache): response = cache.get("describe_instances") if response: return response cache["describe_instances"] = ec2.describe_instances(DryRun=False, MaxResults=1000) return cache["describe_instances"] @registry.register_check("ec2") def ec2_instance_ssm_managed_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[EC2-SSM.1] EC2 Instances should be managed by Systems Manager""" response = describe_instances(cache) myEc2InstanceReservations = response["Reservations"] for reservations in myEc2InstanceReservations: for instances in reservations["Instances"]: instanceId = str(instances["InstanceId"]) instanceArn = ( f"arn:{awsPartition}:ec2:{awsRegion}:{awsAccountId}:instance/{instanceId}" ) instanceType = str(instances["InstanceType"]) instanceImage = str(instances["ImageId"]) instanceVpc = str(instances["VpcId"]) instanceSubnet = str(instances["SubnetId"]) instanceLaunchedAt = str(instances["LaunchTime"]) try: response = ssm.describe_instance_information( InstanceInformationFilterList=[ {"key": "InstanceIds", "valueSet": [instanceId]}, ] ) # ISO Time iso8601Time = ( datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat() ) if str(response["InstanceInformationList"]) == "[]": finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-managed-by-ssm-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "LOW"}, "Confidence": 99, "Title": "[EC2-SSM.1] EC2 Instances should be managed by Systems Manager", "Description": "EC2 Instance " + instanceId + " is not managed by Systems Manager. Refer to the remediation instructions if this configuration is not intended", "Remediation": { "Recommendation": { "Text": "To learn how to configure Systems Manager and associated instances refer to the Setting Up AWS Systems Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/en_us/systems-manager/latest/userguide/systems-manager-setting-up.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "FAILED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "NEW"}, "RecordState": "ACTIVE" } yield finding else: finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-managed-by-ssm-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "INFORMATIONAL"}, "Confidence": 99, "Title": "[EC2-SSM.1] EC2 Instances should be managed by Systems Manager", "Description": "EC2 Instance " + instanceId + " is managed by Systems Manager.", "Remediation": { "Recommendation": { "Text": "To learn how to configure Systems Manager and associated instances refer to the Setting Up AWS Systems Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/en_us/systems-manager/latest/userguide/systems-manager-setting-up.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "PASSED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1", ] }, "Workflow": {"Status": "RESOLVED"}, "RecordState": "ARCHIVED" } yield finding except Exception as e: print(e) @registry.register_check("ec2") def ssm_instace_agent_update_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[EC2-SSM.2] EC2 Instances managed by Systems Manager should have the latest SSM Agent installed""" response = describe_instances(cache) myEc2InstanceReservations = response["Reservations"] for reservations in myEc2InstanceReservations: for instances in reservations["Instances"]: instanceId = str(instances["InstanceId"]) instanceArn = ( f"arn:{awsPartition}:ec2:{awsRegion}:{awsAccountId}:instance/{instanceId}" ) instanceType = str(instances["InstanceType"]) instanceImage = str(instances["ImageId"]) instanceVpc = str(instances["VpcId"]) instanceSubnet = str(instances["SubnetId"]) instanceLaunchedAt = str(instances["LaunchTime"]) response = ssm.describe_instance_information() myManagedInstances = response["InstanceInformationList"] for instances in myManagedInstances: latestVersionCheck = str(instances["IsLatestVersion"]) # ISO Time iso8601Time = ( datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat() ) if latestVersionCheck == "False": finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-ssm-agent-latest-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "MEDIUM"}, "Confidence": 99, "Title": "[EC2-SSM.2] EC2 Instances managed by Systems Manager should have the latest SSM Agent installed", "Description": "EC2 Instance " + instanceId + " does not have the latest SSM Agent installed. Refer to the remediation instructions if this configuration is not intended", "Remediation": { "Recommendation": { "Text": "For information on automating updates to the SSM Agent refer to the Automate Updates to SSM Agent section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent-automatic-updates.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "FAILED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "NEW"}, "RecordState": "ACTIVE" } yield finding else: finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-ssm-agent-latest-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "INFORMATIONAL"}, "Confidence": 99, "Title": "[EC2-SSM.2] EC2 Instances managed by Systems Manager should have the latest SSM Agent installed", "Description": "EC2 Instance " + instanceId + " has the latest SSM Agent installed.", "Remediation": { "Recommendation": { "Text": "For information on automating updates to the SSM Agent refer to the Automate Updates to SSM Agent section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent-automatic-updates.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "PASSED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "RESOLVED"}, "RecordState": "ARCHIVED" } yield finding @registry.register_check("ec2") def ssm_instance_association_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[EC2-SSM.3] EC2 Instances managed by Systems Manager should have a successful Association status""" response = describe_instances(cache) myEc2InstanceReservations = response["Reservations"] for reservations in myEc2InstanceReservations: for instances in reservations["Instances"]: instanceId = str(instances["InstanceId"]) instanceArn = ( f"arn:{awsPartition}:ec2:{awsRegion}:{awsAccountId}:instance/{instanceId}" ) instanceType = str(instances["InstanceType"]) instanceImage = str(instances["ImageId"]) instanceVpc = str(instances["VpcId"]) instanceSubnet = str(instances["SubnetId"]) instanceLaunchedAt = str(instances["LaunchTime"]) response = ssm.describe_instance_information() myManagedInstances = response["InstanceInformationList"] for instances in myManagedInstances: associationStatusCheck = str(instances["AssociationStatus"]) # ISO Time iso8601Time = ( datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat() ) if associationStatusCheck != "Success": finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-ssm-association-success-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "LOW"}, "Confidence": 99, "Title": "[EC2-SSM.3] EC2 Instances managed by Systems Manager should have a successful Association status", "Description": "EC2 Instance " + instanceId + " does not have a successful Association status. Refer to the remediation instructions if this configuration is not intended", "Remediation": { "Recommendation": { "Text": "For information on Systems Manager Associations refer to the Working with Associations in Systems Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "FAILED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "NEW"}, "RecordState": "ACTIVE" } yield finding else: finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-ssm-association-success-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "INFORMATIONAL"}, "Confidence": 99, "Title": "[EC2-SSM.3] EC2 Instances managed by Systems Manager should have a successful Association status", "Description": "EC2 Instance " + instanceId + " has a successful Association status.", "Remediation": { "Recommendation": { "Text": "For information on Systems Manager Associations refer to the Working with Associations in Systems Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "PASSED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "RESOLVED"}, "RecordState": "ARCHIVED" } yield finding @registry.register_check("ec2") def ssm_instance_patch_state_state(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[EC2-SSM.4] EC2 Instances managed by Systems Manager should have the latest patches installed by Patch Manager""" response = describe_instances(cache) myEc2InstanceReservations = response["Reservations"] for reservations in myEc2InstanceReservations: for instances in reservations["Instances"]: instanceId = str(instances["InstanceId"]) instanceArn = ( f"arn:{awsPartition}:ec2:{awsRegion}:{awsAccountId}:instance/{instanceId}" ) instanceType = str(instances["InstanceType"]) instanceImage = str(instances["ImageId"]) instanceVpc = str(instances["VpcId"]) instanceSubnet = str(instances["SubnetId"]) instanceLaunchedAt = str(instances["LaunchTime"]) response = ssm.describe_instance_information() try: response = ssm.describe_instance_patch_states(InstanceIds=[instanceId]) patchStatesCheck = str(response["InstancePatchStates"]) # ISO Time iso8601Time = ( datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat() ) if patchStatesCheck == "[]": finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-patch-manager-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": ["Software and Configuration Checks/AWS Security Best Practices"], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "LOW"}, "Confidence": 99, "Title": "[EC2-SSM.4] EC2 Instances managed by Systems Manager should have the latest patches installed by Patch Manager", "Description": "EC2 Instance " + instanceId + " does not have any patch information recorded and is likely not managed by Patch Manager. Refer to the remediation instructions if this configuration is not intended", "Remediation": { "Recommendation": { "Text": "For information on Patch Manager refer to the AWS Systems Manager Patch Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-patch.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "FAILED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1", ] }, "Workflow": {"Status": "NEW"}, "RecordState": "ACTIVE" } yield finding else: patchStates = response["InstancePatchStates"] for patches in patchStates: failedPatchCheck = str(patches["FailedCount"]) missingPatchCheck = str(patches["MissingCount"]) if failedPatchCheck != "0" or missingPatchCheck != "0": finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-patch-manager-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": [ "Software and Configuration Checks/AWS Security Best Practices" ], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "MEDIUM"}, "Confidence": 99, "Title": "[EC2-SSM.4] EC2 Instances managed by Systems Manager should have the latest patches installed by Patch Manager", "Description": "EC2 Instance " + instanceId + " is missing patches or has patches that failed to apply. Refer to the remediation instructions if this configuration is not intended", "Remediation": { "Recommendation": { "Text": "For information on Patch Manager refer to the AWS Systems Manager Patch Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-patch.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "FAILED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "NEW"}, "RecordState": "ACTIVE" } yield finding else: finding = { "SchemaVersion": "2018-10-08", "Id": instanceArn + "/ec2-patch-manager-check", "ProductArn": f"arn:{awsPartition}:securityhub:{awsRegion}:{awsAccountId}:product/{awsAccountId}/default", "GeneratorId": instanceArn, "AwsAccountId": awsAccountId, "Types": [ "Software and Configuration Checks/AWS Security Best Practices" ], "FirstObservedAt": iso8601Time, "CreatedAt": iso8601Time, "UpdatedAt": iso8601Time, "Severity": {"Label": "INFORMATIONAL"}, "Confidence": 99, "Title": "[EC2-SSM.4] EC2 Instances managed by Systems Manager should have the latest patches installed by Patch Manager", "Description": "EC2 Instance " + instanceId + " has the latest patches installed by Patch Manager.", "Remediation": { "Recommendation": { "Text": "For information on Patch Manager refer to the AWS Systems Manager Patch Manager section of the AWS Systems Manager User Guide", "Url": "https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-patch.html", } }, "ProductFields": {"Product Name": "ElectricEye"}, "Resources": [ { "Type": "AwsEc2Instance", "Id": instanceArn, "Partition": awsPartition, "Region": awsRegion, "Details": { "AwsEc2Instance": { "Type": instanceType, "ImageId": instanceImage, "VpcId": instanceVpc, "SubnetId": instanceSubnet, "LaunchedAt": parse(instanceLaunchedAt).isoformat() } } } ], "Compliance": { "Status": "PASSED", "RelatedRequirements": [ "NIST CSF ID.AM-2", "NIST SP 800-53 CM-8", "NIST SP 800-53 PM-5", "AICPA TSC CC3.2", "AICPA TSC CC6.1", "ISO 27001:2013 A.8.1.1", "ISO 27001:2013 A.8.1.2", "ISO 27001:2013 A.12.5.1" ] }, "Workflow": {"Status": "RESOLVED"}, "RecordState": "ARCHIVED" } yield finding except Exception as e: print(e)
23,687
575
<reponame>timmylinux/Fast-DDS<filename>include/fastdds/dds/domain/qos/DomainParticipantQos.hpp // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file DomainParticipantQos.hpp * */ #ifndef _FASTDDS_PARTICIPANTQOS_HPP_ #define _FASTDDS_PARTICIPANTQOS_HPP_ #include <string> #include <fastrtps/fastrtps_dll.h> #include <fastdds/dds/core/policy/QosPolicies.hpp> #include <fastdds/rtps/flowcontrol/FlowControllerDescriptor.hpp> namespace eprosima { namespace fastdds { namespace dds { /** * Class DomainParticipantQos, contains all the possible Qos that can be set for a determined participant. * Please consult each of them to check for implementation details and default values. * * @ingroup FASTDDS_QOS_MODULE */ class DomainParticipantQos { public: /*! * User defined flow controllers to use alongside. * * @since 2.4.0 */ using FlowControllerDescriptorList = std::vector<std::shared_ptr<fastdds::rtps::FlowControllerDescriptor>>; /** * @brief Constructor */ RTPS_DllAPI DomainParticipantQos() { #ifdef FASTDDS_STATISTICS /* * In the case of Statistics, the following properties are set with an empty value. This is because if these * properties are set and empty during the enabling of the DomainParticipant, they are fill with the default * mechanism */ properties_.properties().emplace_back(parameter_policy_physical_data_host, ""); properties_.properties().emplace_back(parameter_policy_physical_data_user, ""); properties_.properties().emplace_back(parameter_policy_physical_data_process, ""); #endif // ifdef FASTDDS_STATISTICS } /** * @brief Destructor */ RTPS_DllAPI virtual ~DomainParticipantQos() { } bool operator ==( const DomainParticipantQos& b) const { return (this->user_data_ == b.user_data()) && (this->entity_factory_ == b.entity_factory()) && (this->allocation_ == b.allocation()) && (this->properties_ == b.properties()) && (this->wire_protocol_ == b.wire_protocol()) && (this->transport_ == b.transport()) && (this->name_ == b.name()) && (this->flow_controllers_ == b.flow_controllers()); } /** * Getter for UserDataQosPolicy * * @return UserDataQosPolicy reference */ const UserDataQosPolicy& user_data() const { return user_data_; } /** * Getter for UserDataQosPolicy * * @return UserDataQosPolicy reference */ UserDataQosPolicy& user_data() { return user_data_; } /** * Setter for UserDataQosPolicy * * @param value UserDataQosPolicy */ void user_data( const UserDataQosPolicy& value) { user_data_ = value; } /** * Getter for EntityFactoryQosPolicy * * @return EntityFactoryQosPolicy reference */ const EntityFactoryQosPolicy& entity_factory() const { return entity_factory_; } /** * Getter for EntityFactoryQosPolicy * * @return EntityFactoryQosPolicy reference */ EntityFactoryQosPolicy& entity_factory() { return entity_factory_; } /** * Setter for EntityFactoryQosPolicy * * @param value EntityFactoryQosPolicy */ void entity_factory( const EntityFactoryQosPolicy& value) { entity_factory_ = value; } /** * Getter for ParticipantResourceLimitsQos * * @return ParticipantResourceLimitsQos reference */ const ParticipantResourceLimitsQos& allocation() const { return allocation_; } /** * Getter for ParticipantResourceLimitsQos * * @return ParticipantResourceLimitsQos reference */ ParticipantResourceLimitsQos& allocation() { return allocation_; } /** * Setter for ParticipantResourceLimitsQos * * @param allocation ParticipantResourceLimitsQos */ void allocation( const ParticipantResourceLimitsQos& allocation) { allocation_ = allocation; } /** * Getter for PropertyPolicyQos * * @return PropertyPolicyQos reference */ const PropertyPolicyQos& properties() const { return properties_; } /** * Getter for PropertyPolicyQos * * @return PropertyPolicyQos reference */ PropertyPolicyQos& properties() { return properties_; } /** * Setter for PropertyPolicyQos * * @param properties PropertyPolicyQos */ void properties( const PropertyPolicyQos& properties) { properties_ = properties; } /** * Getter for WireProtocolConfigQos * * @return WireProtocolConfigQos reference */ const WireProtocolConfigQos& wire_protocol() const { return wire_protocol_; } /** * Getter for WireProtocolConfigQos * * @return WireProtocolConfigQos reference */ WireProtocolConfigQos& wire_protocol() { return wire_protocol_; } /** * Setter for WireProtocolConfigQos * * @param wire_protocol WireProtocolConfigQos */ void wire_protocol( const WireProtocolConfigQos& wire_protocol) { wire_protocol_ = wire_protocol; } /** * Getter for TransportConfigQos * * @return TransportConfigQos reference */ const TransportConfigQos& transport() const { return transport_; } /** * Getter for TransportConfigQos * * @return TransportConfigQos reference */ TransportConfigQos& transport() { return transport_; } /** * Setter for TransportConfigQos * * @param transport TransportConfigQos */ void transport( const TransportConfigQos& transport) { transport_ = transport; } /** * Getter for the Participant name * * @return name */ const fastrtps::string_255& name() const { return name_; } /** * Getter for the Participant name * * @return name */ fastrtps::string_255& name() { return name_; } /** * Setter for the Participant name * * @param value New name to be set */ void name( const fastrtps::string_255& value) { name_ = value; } /** * Getter for FlowControllerDescriptorList * * @return FlowControllerDescriptorList reference */ FlowControllerDescriptorList& flow_controllers() { return flow_controllers_; } /** * Getter for FlowControllerDescriptorList * * @return FlowControllerDescriptorList reference */ const FlowControllerDescriptorList& flow_controllers() const { return flow_controllers_; } private: //!UserData Qos, implemented in the library. UserDataQosPolicy user_data_; //!EntityFactory Qos, implemented in the library. EntityFactoryQosPolicy entity_factory_; //!Participant allocation limits ParticipantResourceLimitsQos allocation_; //!Property policies PropertyPolicyQos properties_; //!Wire Protocol options WireProtocolConfigQos wire_protocol_; //!Transport options TransportConfigQos transport_; //!Name of the participant. fastrtps::string_255 name_ = "RTPSParticipant"; /*! User defined flow controller to use alongside. * * @since 2.4.0 */ FlowControllerDescriptorList flow_controllers_; }; RTPS_DllAPI extern const DomainParticipantQos PARTICIPANT_QOS_DEFAULT; } /* namespace dds */ } /* namespace fastdds */ } /* namespace eprosima */ #endif /* _FASTDDS_PARTICIPANTQOS_HPP_ */
3,412
303
/** * 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.codelibs.elasticsearch.taste.eval; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import org.codelibs.elasticsearch.taste.common.FullRunningAverageAndStdDev; import org.codelibs.elasticsearch.taste.common.LongPrimitiveIterator; import org.codelibs.elasticsearch.taste.common.RunningAverageAndStdDev; import org.codelibs.elasticsearch.taste.common.SamplingLongPrimitiveIterator; import org.codelibs.elasticsearch.taste.model.DataModel; import org.codelibs.elasticsearch.taste.recommender.Recommender; import com.google.common.collect.Lists; /** * Simple helper class for running load on a Recommender. */ public final class LoadEvaluator { private LoadEvaluator() { } public static LoadStatistics runLoad(final Recommender recommender) { return runLoad(recommender, 10); } public static LoadStatistics runLoad(final Recommender recommender, final int howMany) { final DataModel dataModel = recommender.getDataModel(); final int numUsers = dataModel.getNumUsers(); final double sampleRate = 1000.0 / numUsers; final LongPrimitiveIterator userSampler = SamplingLongPrimitiveIterator .maybeWrapIterator(dataModel.getUserIDs(), sampleRate); recommender.recommend(userSampler.next(), howMany); // Warm up final Collection<Callable<Void>> callables = Lists.newArrayList(); while (userSampler.hasNext()) { callables.add(new LoadCallable(recommender, userSampler.next())); } final AtomicInteger noEstimateCounter = new AtomicInteger(); final RunningAverageAndStdDev timing = new FullRunningAverageAndStdDev(); AbstractDifferenceRecommenderEvaluator.execute(callables, noEstimateCounter, timing); return new LoadStatistics(timing); } }
867
570
package com.luck.picture.lib.instagram.adapter; import android.graphics.Bitmap; import android.view.View; import android.view.ViewGroup; import com.luck.picture.lib.R; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * ================================================ * Created by JessYan on 2020/6/24 17:27 * <a href="mailto:<EMAIL>">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public class VideoTrimmerAdapter extends RecyclerView.Adapter { private List<Bitmap> mBitmaps = new ArrayList<>(); private int mItemCount; @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new Holder(new FrameItemView(parent.getContext())); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if (position < mBitmaps.size()) { ((FrameItemView) holder.itemView).setImage(mBitmaps.get(position)); } else { ((FrameItemView) holder.itemView).setImageResource((R.drawable.picture_image_placeholder)); } } public void setItemCount(int itemCount) { mItemCount = itemCount; } @Override public int getItemCount() { return mItemCount > 0 ? mItemCount : mBitmaps.size(); } public void addBitmaps(Bitmap bitmap) { mBitmaps.add(bitmap); notifyDataSetChanged(); } public static class Holder extends RecyclerView.ViewHolder { public Holder(@NonNull View itemView) { super(itemView); } } }
645
2,602
<gh_stars>1000+ { "compilerOptions": { "noEmit": true, "module": "None", "experimentalDecorators": false, "noImplicitReturns": true, "noImplicitOverride": true, "noUnusedLocals": true, "allowUnreachableCode": false, "strict": true, "exactOptionalPropertyTypes": false, "useUnknownInCatchVariables": false, "forceConsistentCasingInFileNames": true, "types": [], "lib": [ "es5", ], }, "include": [ "vscode-dts/vscode.d.ts" ] }
205
598
'''Generic class for models that take the form of a set of (potentially overlapping) rules. '''
24
713
package org.infinispan.distribution; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.RemoteException; import org.infinispan.remoting.transport.Address; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.data.BrokenMarshallingPojo; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Test single owner distributed cache configurations. * * @author <NAME> * @since 4.0 */ @Test(groups = "functional", testName = "distribution.SingleOwnerTest") public class SingleOwnerTest extends BaseDistFunctionalTest<Object, String> { @Override protected void createCacheManagers() throws Throwable { cacheName = "dist"; configuration = getDefaultClusteredCacheConfig(cacheMode, transactional); if (!testRetVals) { configuration.unsafe().unreliableReturnValues(true); // we also need to use repeatable read for tests to work when we dont have reliable return values, since the // tests repeatedly queries changes configuration.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); } configuration.clustering().remoteTimeout(3, TimeUnit.SECONDS); configuration.clustering().hash().numOwners(1); configuration.locking().lockAcquisitionTimeout(45, TimeUnit.SECONDS); createClusteredCaches(2, cacheName, configuration); caches = caches(cacheName); c1 = caches.get(0); c2 = caches.get(1); cacheAddresses = new ArrayList<Address>(2); for (Cache cache : caches) { EmbeddedCacheManager cacheManager = cache.getCacheManager(); cacheAddresses.add(cacheManager.getAddress()); } waitForClusterToForm(cacheName); } public void testPutOnKeyOwner() { Cache[] caches = getOwners("mykey", 1); assert caches.length == 1; Cache ownerCache = caches[0]; ownerCache.put("mykey", new Object()); } public void testClearOnKeyOwner() { Cache[] caches = getOwners("mykey", 1); assert caches.length == 1; Cache ownerCache = caches[0]; ownerCache.clear(); } public void testRetrieveNonSerializableValueFromNonOwner() { Cache[] owners = getOwners("yourkey", 1); Cache[] nonOwners = getNonOwners("yourkey", 1); assert owners.length == 1; assert nonOwners.length == 1; Cache ownerCache = owners[0]; Cache nonOwnerCache = nonOwners[0]; ownerCache.put("yourkey", new Object()); try { nonOwnerCache.get("yourkey"); fail("Should have failed with a org.infinispan.commons.marshall.MarshallingException"); } catch (RemoteException e) { assertTrue(e.getCause() instanceof MarshallingException); } } public void testErrorWhenRetrievingKeyFromNonOwner() { log.trace("Before test"); Cache[] owners = getOwners("diffkey", 1); Cache[] nonOwners = getNonOwners("diffkey", 1); assert owners.length == 1; assert nonOwners.length == 1; Cache ownerCache = owners[0]; Cache nonOwnerCache = nonOwners[0]; ownerCache.put("diffkey", new BrokenMarshallingPojo()); Exceptions.expectException(RemoteException.class, MarshallingException.class, () -> nonOwnerCache.get("diffkey")); } }
1,261
318
package org.webbitserver.stub; import static org.junit.Assert.assertEquals; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class StubHttpRequestTest { @Test public void testUri() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals("/", target.uri()); target.uri("https://github.com/joewalnes/webbit"); assertEquals("https://github.com/joewalnes/webbit", target.uri()); StubHttpRequest targetUri = new StubHttpRequest("https://github.com/joewalnes/webbit"); assertEquals("https://github.com/joewalnes/webbit", targetUri.uri()); } @Test public void testHeader() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals(false, target.hasHeader("Content-Length")); assertEquals(null, target.header("Content-Length")); target.header("Content-Length", "23"); assertEquals(true, target.hasHeader("Content-Length")); List<Map.Entry<String, String>> expected = new ArrayList<Map.Entry<String, String>>(); expected.add(new AbstractMap.SimpleEntry<String, String>("Content-Length", "23")); assertEquals(expected, target.allHeaders()); assertEquals(null, target.header("charset")); assertEquals("23", target.header("Content-Length")); target.header("charset", "utf8"); expected.add(new AbstractMap.SimpleEntry<String, String>("charset", "utf8")); assertEquals(expected, target.allHeaders()); } @Test public void testQueryParam() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals(null, target.queryParam(null)); StubHttpRequest targetUri = new StubHttpRequest("https://g.com/?a=12"); assertEquals("12", targetUri.queryParam("a")); } @Test public void testQueryParamKeys() throws Exception { StubHttpRequest target = new StubHttpRequest("https://g.com/?a=12&b=hello"); Set<String> expected = new HashSet<String>(); expected.add("b"); expected.add("a"); assertEquals(expected, target.queryParamKeys()); } @Test public void testMethod() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals("GET", target.method()); target.method("POST"); assertEquals("POST", target.method()); } @Test public void testBody() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals(null, target.body()); target.body("<h1>Hello World!</h1>"); assertEquals("<h1>Hello World!</h1>", target.body()); } @Test public void testData() throws Exception { StubHttpRequest target = new StubHttpRequest(); Map<String, Object> expected = new HashMap<String, Object>(); expected.put("joe", "bloggs"); assertEquals(expected, target.data("joe", "bloggs").data()); } @Test public void testRemoteAddress() throws Exception { StubHttpRequest target = new StubHttpRequest(); SocketAddress expected = new InetSocketAddress("localhost", 0); assertEquals(expected, target.remoteAddress()); target.remoteAddress(null); assertEquals(null, target.remoteAddress()); SocketAddress newRemote = new InetSocketAddress("mysite.com", 80); assertEquals(newRemote, target.remoteAddress(newRemote).remoteAddress()); } @Test public void testId() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals("StubID", target.id()); target.id(1234); assertEquals(1234, target.id()); } @Test public void testTimestamp() throws Exception { StubHttpRequest target = new StubHttpRequest(); assertEquals(0L, target.timestamp()); target.timestamp(50L); assertEquals(50L, target.timestamp()); } }
1,407
4,098
<filename>Siv3D/src/ThirdParty/angelscript/as_atomic.cpp /* AngelCode Scripting Library Copyright (c) 2003-2014 <NAME> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ <NAME> <EMAIL> */ // // as_atomic.cpp // // The implementation of the atomic class for thread safe reference counting // #include "as_atomic.h" BEGIN_AS_NAMESPACE asCAtomic::asCAtomic() { value = 0; } asDWORD asCAtomic::get() const { // A very high ref count is highly unlikely. It most likely a problem with // memory that has been overwritten or is being accessed after it was deleted. asASSERT(value < 1000000); return value; } void asCAtomic::set(asDWORD val) { // A very high ref count is highly unlikely. It most likely a problem with // memory that has been overwritten or is being accessed after it was deleted. asASSERT(value < 1000000); value = val; } asDWORD asCAtomic::atomicInc() { // A very high ref count is highly unlikely. It most likely a problem with // memory that has been overwritten or is being accessed after it was deleted. asASSERT(value < 1000000); return asAtomicInc((int&)value); } asDWORD asCAtomic::atomicDec() { // A very high ref count is highly unlikely. It most likely a problem with // memory that has been overwritten or is being accessed after it was deleted. asASSERT(value < 1000000); return asAtomicDec((int&)value); } // // The following code implements the atomicInc and atomicDec on different platforms // #if defined(AS_NO_THREADS) || defined(AS_NO_ATOMIC) int asAtomicInc(int &value) { return ++value; } int asAtomicDec(int &value) { return --value; } #elif defined(AS_XENON) /// XBox360 END_AS_NAMESPACE #include <xtl.h> BEGIN_AS_NAMESPACE int asAtomicInc(int &value) { return InterlockedIncrement((LONG*)&value); } int asAtomicDec(int &value) { return InterlockedDecrement((LONG*)&value); } #elif defined(AS_WIN) END_AS_NAMESPACE #define WIN32_MEAN_AND_LEAN #include <windows.h> BEGIN_AS_NAMESPACE int asAtomicInc(int &value) { return InterlockedIncrement((LONG*)&value); } int asAtomicDec(int &value) { asASSERT(value > 0); return InterlockedDecrement((LONG*)&value); } #elif defined(AS_LINUX) || defined(AS_BSD) || defined(AS_ILLUMOS) || defined(AS_ANDROID) // // atomic_inc_and_test() and atomic_dec_and_test() from asm/atomic.h is not meant // to be used outside the Linux kernel. Instead we should use the GNUC provided // __sync_add_and_fetch() and __sync_sub_and_fetch() functions. // // Reference: http://golubenco.org/blog/atomic-operations/ // // These are only available in GCC 4.1 and above, so for older versions we // use the critical sections, though it is a lot slower. // int asAtomicInc(int &value) { return __sync_add_and_fetch(&value, 1); } int asAtomicDec(int &value) { return __sync_sub_and_fetch(&value, 1); } #elif defined(AS_MAC) || defined(AS_IPHONE) END_AS_NAMESPACE #include <libkern/OSAtomic.h> BEGIN_AS_NAMESPACE int asAtomicInc(int &value) { return OSAtomicIncrement32((int32_t*)&value); } int asAtomicDec(int &value) { return OSAtomicDecrement32((int32_t*)&value); } #else // If we get here, then the configuration in as_config.h // is wrong for the compiler/platform combination. int ERROR_PleaseFixTheConfig[-1]; #endif END_AS_NAMESPACE
1,409
1,338
<reponame>Kirishikesan/haiku<gh_stars>1000+ // BApplicationTestApp1b.cpp #include <stdio.h> #include <Application.h> int main() { status_t error = B_OK; BApplication app((const char*)NULL, &error); printf("error: %lx\n", error); printf("InitCheck(): %lx\n", app.InitCheck()); return 0; }
123
825
<gh_stars>100-1000 package com.didi.hummer.adapter.tracker; import java.io.Serializable; /** * 页面性能相关自定义信息 * * Created by XiaoFeng on 2021/8/27. */ public class PerfCustomInfo implements Serializable { /** * 分类 */ public String category; /** * 名称 */ public String name; /** * 值 */ public Object value; /** * 单位 */ public String unit; public PerfCustomInfo(String category, String name) { this.category = category; this.name = name; } public PerfCustomInfo(String category, String name, String unit) { this.category = category; this.name = name; this.unit = unit; } public PerfCustomInfo(String category, String name, String unit, Object value) { this.category = category; this.name = name; this.unit = unit; this.value = value; } }
418
3,921
package com.alibaba.luaview.debugger.ui; import java.util.Hashtable; import javax.swing.JTabbedPane; import com.alibaba.luaview.debugger.Center; public class SrcCodeCenter { public final Center center; public SrcCodeCenter(Center center) { this.center = center; } final Hashtable<String, SrcCodeViewer> table = new Hashtable<String, SrcCodeViewer>(); public void showHelpTab() { String s = "h help info" + "\n" + // "c continue run" + "\n" + // "s trace" + "\n" + // "n next" + "\n" + // "p var print variable" + "\n" + // "b src:line add breakpoint" + "\n" + // "rb src:line remove breakpoint" + "\n" + // "bl list breakpoint" + "\n" + // "bt print traceback" + "\n"; loadfile("帮助信息", s).canBreakPoint = false; } public SrcCodeViewer loadfile(String fileName, String content) { content = content.replace("\t", " "); JTabbedPane tabbedPane = center.frame.getTabbedPane(); if (fileName != null) { SrcCodeViewer temp = table.get(fileName); tabbedPane.remove(temp); table.remove(fileName); } SrcCodeViewer viewer = new SrcCodeViewer(fileName, content, this.center); this.addToTabbedPane(tabbedPane, fileName, viewer); table.put(fileName, viewer); return viewer; } private void addToTabbedPane(JTabbedPane tabbedPane, String fileName, SrcCodeViewer viewer) { int num = tabbedPane.getTabCount(); String newTitle = this.shortName(fileName); for (int i = 0; i < num; i++) { String title = tabbedPane.getTitleAt(i); if (newTitle.compareTo(title) > 0) { tabbedPane.insertTab(newTitle, null, viewer, null, i); return; } } tabbedPane.addTab(newTitle, viewer); } private String shortName(String s) { int index = s.lastIndexOf('/'); if (index >= 0) { s = s.substring(index + 1); } s = s.trim(); if (s.endsWith(".lua")) { s = s.substring(0, s.length() - 4); } if (s.endsWith(".lv")) { s = s.substring(0, s.length() - 3); } return s.trim(); } public void running(String fileName, String lineNumber) { try { if (fileName != null) { SrcCodeViewer viewer = table.get(fileName); if (viewer != null) { viewer.gotoLine(Integer.parseInt(lineNumber.trim())); JTabbedPane tabbedPane = center.frame.getTabbedPane(); tabbedPane.setSelectedComponent(viewer); if (center.frame.isAlwaysOnTop()) { center.frame.setAlwaysOnTop(true); } if (center.frame.isVisible()) { center.frame.setVisible(true); } center.frame.setIsDebugging(true); } } } catch (Exception e) { e.printStackTrace(); } // System.out.println(fileName + lineNumber); } public void clearGotoLine() { try { JTabbedPane tabbedPane = center.frame.getTabbedPane(); SrcCodeViewer viewer = (SrcCodeViewer) tabbedPane.getSelectedComponent(); if (viewer != null) { viewer.clearGotoLine(); } } catch (Exception e) { e.printStackTrace(); } } }
1,330
2,414
/* * Copyright 2019 WeBank * * 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.webank.wedatasphere.linkis.cs.highavailable.test; import com.google.gson.Gson; import com.webank.wedatasphere.linkis.DataWorkCloudApplication; import com.webank.wedatasphere.linkis.common.ServiceInstance; import com.webank.wedatasphere.linkis.common.conf.BDPConfiguration; import com.webank.wedatasphere.linkis.common.conf.Configuration; import com.webank.wedatasphere.linkis.common.exception.LinkisException; import com.webank.wedatasphere.linkis.common.utils.Utils; import com.webank.wedatasphere.linkis.cs.common.entity.source.HAContextID; import com.webank.wedatasphere.linkis.cs.common.exception.CSErrorException; import com.webank.wedatasphere.linkis.cs.highavailable.AbstractContextHAManager; import com.webank.wedatasphere.linkis.cs.highavailable.test.haid.TestHAID; import com.webank.wedatasphere.linkis.cs.highavailable.test.persist.TestPersistence; import com.webank.wedatasphere.linkis.server.BDPJettyServerHelper; import com.webank.wedatasphere.linkis.server.conf.ServerConfiguration; import org.apache.commons.lang.StringUtils; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.webapp.WebAppContext; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.event.ApplicationPreparedEvent; import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.web.filter.CharacterEncodingFilter; import javax.servlet.DispatcherType; import java.util.EnumSet; @SpringBootApplication @EnableDiscoveryClient @ComponentScan(basePackages = "com.webank.wedatasphere.linkis") public class TestContextHAManager extends SpringBootServletInitializer { private static ConfigurableApplicationContext applicationContext; private static ServiceInstance serviceInstance; private static final Gson gson = new Gson(); public static void main(String [] args) throws ReflectiveOperationException { final SpringApplication application = new SpringApplication(TestContextHAManager.class); application.addListeners(new ApplicationListener<ApplicationPreparedEvent>(){ public void onApplicationEvent(ApplicationPreparedEvent applicationPreparedEvent) { System.out.println("add config from config server..."); if(applicationContext == null) { applicationContext = applicationPreparedEvent.getApplicationContext(); } System.out.println("initialize DataWorkCloud spring application..."); initDWCApplication(); } }); application.addListeners(new ApplicationListener<RefreshScopeRefreshedEvent>() { public void onApplicationEvent(RefreshScopeRefreshedEvent applicationEvent) { System.out.println("refresh config from config server..."); updateRemoteConfig(); } }); String listeners = ServerConfiguration.BDP_SERVER_SPRING_APPLICATION_LISTENERS().getValue(); if(StringUtils.isNotBlank(listeners)) { for (String listener : listeners.split(",")) { application.addListeners((ApplicationListener<?>) Class.forName(listener).newInstance()); } } applicationContext = application.run(args); try { // Thread.sleep(3000l); AbstractContextHAManager haManager = (AbstractContextHAManager) applicationContext.getBean(AbstractContextHAManager.class); if (null == haManager) { System.err.println("Null haManager!"); return ; } testHAManager(haManager); } catch (Exception e) { e.printStackTrace(); } } private static void initDWCApplication() { serviceInstance = new ServiceInstance(); serviceInstance.setApplicationName(applicationContext.getEnvironment().getProperty("spring.application.name")); serviceInstance.setInstance(Utils.getComputerName() + ":" + applicationContext.getEnvironment().getProperty("server.port")); LinkisException.setApplicationName(serviceInstance.getApplicationName()); LinkisException.setHostname(Utils.getComputerName()); LinkisException.setHostPort(Integer.parseInt(applicationContext.getEnvironment().getProperty("server.port"))); } public static void updateRemoteConfig() { addOrUpdateRemoteConfig(applicationContext.getEnvironment(), true); } public static void addRemoteConfig() { addOrUpdateRemoteConfig(applicationContext.getEnvironment(), false); } private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrNot) { StandardEnvironment environment = (StandardEnvironment) env; PropertySource propertySource = environment.getPropertySources().get("bootstrapProperties"); if(propertySource == null) { return; } CompositePropertySource source = (CompositePropertySource) propertySource; for (String key: source.getPropertyNames()) { Object val = source.getProperty(key); if(val == null) { continue; } if(isUpdateOrNot) { System.out.println("update remote config => " + key + " = " + source.getProperty(key)); BDPConfiguration.set(key, val.toString()); } else { System.out.println("add remote config => " + key + " = " + source.getProperty(key)); BDPConfiguration.setIfNotExists(key, val.toString()); } } } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(DataWorkCloudApplication.class); } @Bean public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettyFactoryCustomizer() { return new WebServerFactoryCustomizer<JettyServletWebServerFactory>() { public void customize(JettyServletWebServerFactory jettyServletWebServerFactory) { jettyServletWebServerFactory.addServerCustomizers(new JettyServerCustomizer() { public void customize(Server server) { Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class); final WebAppContext webApp = (WebAppContext) childHandlersByClass[0]; FilterHolder filterHolder = new FilterHolder(CharacterEncodingFilter.class); filterHolder.setInitParameter("encoding", Configuration.BDP_ENCODING().getValue()); filterHolder.setInitParameter("forceEncoding", "true"); webApp.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class)); BDPJettyServerHelper.setupRestApiContextHandler(webApp); if(ServerConfiguration.BDP_SERVER_SOCKET_MODE().getValue()) { BDPJettyServerHelper.setupControllerServer(webApp); } if(!ServerConfiguration.BDP_SERVER_DISTINCT_MODE().getValue()) { BDPJettyServerHelper.setupWebAppContext(webApp); } } }); } }; } // test private static void testHAManager(AbstractContextHAManager contextHAManager) { // 1 test create TestHAID haid = new TestHAID(); try { TestPersistence testPersistence = contextHAManager.getContextHAProxy(new TestPersistence()); HAContextID haContextID = testPersistence.createHAID(haid); testPersistence.passHAID(haContextID); testPersistence.setContextId(haContextID.getContextId()); } catch (CSErrorException e) { e.printStackTrace(); } System.out.println("Test HaManager End."); } public static ServiceInstance getServiceInstance() { return serviceInstance; } }
3,588
1,652
package com.ctrip.xpipe.redis.checker; import com.ctrip.xpipe.api.email.EmailResponse; import com.ctrip.xpipe.api.server.Server; import com.ctrip.xpipe.redis.checker.alert.AlertMessageEntity; import com.ctrip.xpipe.redis.checker.healthcheck.RedisHealthCheckInstance; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author lishanglin * date 2021/3/14 */ public class TestPersistenceCache implements PersistenceCache { private Set<String> sentinelCheckWhiteList = new HashSet<>(); private Set<String> clusterAlertWhitelist = new HashSet<>(); private boolean sentinelAutoProcess = true; private boolean alertSystemOn = true; public void setSentinelAutoProcess(boolean val) { this.sentinelAutoProcess = val; } public void setAlertSystemOn(boolean val) { this.alertSystemOn = val; } @Override public boolean isClusterOnMigration(String clusterId) { return false; } @Override public void updateRedisRole(RedisHealthCheckInstance instance, Server.SERVER_ROLE role) { } @Override public Set<String> sentinelCheckWhiteList() { return sentinelCheckWhiteList; } @Override public Set<String> clusterAlertWhiteList() { return clusterAlertWhitelist; } @Override public boolean isSentinelAutoProcess() { return sentinelAutoProcess; } @Override public boolean isAlertSystemOn() { return alertSystemOn; } @Override public Date getClusterCreateTime(String clusterId) { return null; } @Override public Map<String, Date> loadAllClusterCreateTime() { return null; } @Override public void recordAlert(String eventOperator, AlertMessageEntity message, EmailResponse response) { } }
658
333
import copy import os import re import sys import ustrings if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import shutil from .resource_suite import ResourceBase from .. import lib class Test_iRsync(ResourceBase, unittest.TestCase): def setUp(self): super(Test_iRsync, self).setUp() self.testing_tmp_dir = '/tmp/irods-test-irsync' shutil.rmtree(self.testing_tmp_dir, ignore_errors=True) os.mkdir(self.testing_tmp_dir) def tearDown(self): shutil.rmtree(self.testing_tmp_dir) super(Test_iRsync, self).tearDown() def test_irsync(self): filepath = os.path.join(self.admin.local_session_dir, 'file') lib.make_file(filepath, 1) self.admin.assert_icommand('iput ' + filepath) self.admin.assert_icommand('irsync -l ' + filepath + ' i:file') def test_irsync_checksum_behavior(self): # set user0's checksum scheme to MD5 to mismatch with server scheme user0_env_backup = copy.deepcopy(self.user0.environment_file_contents) self.user0.environment_file_contents['irods_default_hash_scheme'] = 'MD5' self.user0.environment_file_contents['irods_match_hash_policy'] = 'compatible' # test settings depth = 1 files_per_level = 5 file_size = 1024*1024*40 # make local nested dirs base_name = 'test_irsync_checksum_behavior' local_dir = os.path.join(self.testing_tmp_dir, base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # sync dir to coll self.user0.assert_icommand("irsync -r -K {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) self.user0.assert_icommand("ils -L {base_name}".format(**locals()), "STDOUT_SINGLELINE", "ec8bb3b24d5b0f1b5bdf8c8f0f541ee6") out, err, ec = self.user0.run_icommand("ichksum -r -K {base_name}".format(**locals())) self.assertEqual(ec, 0) self.assertTrue('C- ' in out) self.assertTrue('WARNING: ' not in out and 'WARNING: ' not in err) self.assertTrue('ERROR: ' not in out and 'ERROR: ' not in err) self.user0.assert_icommand("irsync -v -r -K -l {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 40.000 MB --- a match no sync required") self.user0.assert_icommand("irm -f {base_name}/junk0001".format(**locals()), "EMPTY") self.user0.assert_icommand_fail("ils -L {base_name}".format(**locals()), "STDOUT_SINGLELINE", "junk0001") self.user0.assert_icommand("irsync -v -r -K -l {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 41943040 N") self.user0.assert_icommand("irsync -v -r -K {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 40.000 MB ") self.user0.assert_icommand("irsync -v -r -K -l {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 40.000 MB --- a match no sync required") path = '{local_dir}/junk0001'.format(**locals()) if os.path.exists(path): os.unlink(path) self.user0.assert_icommand("irsync -v -r -K -l i:{base_name} {local_dir}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 41943040 N") self.user0.assert_icommand("irsync -v -r -K i:{base_name} {local_dir}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 40.000 MB ") self.user0.assert_icommand("irsync -v -r -K -l i:{base_name} {local_dir}".format(**locals()), "STDOUT_SINGLELINE", "junk0001 40.000 MB --- a match no sync required") self.user0.environment_file_contents = user0_env_backup def test_irsync_r_nested_dir_to_coll(self): # test settings depth = 10 files_per_level = 100 file_size = 100 # make local nested dirs base_name = "test_irsync_r_nested_dir_to_coll" local_dir = os.path.join(self.testing_tmp_dir, base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # sync dir to coll self.user0.assert_icommand("irsync -r {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # compare files at each level for dir, files in local_dirs.items(): partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) # run ils on subcollection self.user0.assert_icommand(['ils', partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_nested_dir_to_coll_large_files(self): # test settings depth = 4 files_per_level = 4 file_size = 1024*1024*40 # make local nested dirs base_name = "test_irsync_r_nested_dir_to_coll" local_dir = os.path.join(self.testing_tmp_dir, base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # sync dir to coll self.user0.assert_icommand("irsync -r {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # compare files at each level for dir, files in local_dirs.items(): partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) # run ils on subcollection self.user0.assert_icommand(['ils', partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_nested_coll_to_coll(self): # test settings depth = 10 files_per_level = 100 file_size = 100 # make local nested dirs source_base_name = "test_irsync_r_nested_coll_to_coll_source" dest_base_name = "test_irsync_r_nested_coll_to_coll_dest" local_dir = os.path.join(self.testing_tmp_dir, source_base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # iput dir self.user0.assert_icommand("iput -r {local_dir}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # sync collections self.user0.assert_icommand("irsync -r i:{source_base_name} i:{dest_base_name}".format(**locals()), "EMPTY") # compare files at each level for dir, files in local_dirs.items(): source_partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) dest_partial_path = dir.replace(self.testing_tmp_dir+'/'+source_base_name, dest_base_name, 1) # run ils on source subcollection self.user0.assert_icommand(['ils', source_partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(source_partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) # now the same thing with dest subcollection self.user0.assert_icommand(['ils', dest_partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(dest_partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_nested_coll_to_coll_large_files(self): # test settings depth = 4 files_per_level = 4 file_size = 1024*1024*40 # make local nested dirs source_base_name = "test_irsync_r_nested_coll_to_coll_source" dest_base_name = "test_irsync_r_nested_coll_to_coll_dest" local_dir = os.path.join(self.testing_tmp_dir, source_base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # iput dir self.user0.assert_icommand("iput -r {local_dir}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # sync collections self.user0.assert_icommand("irsync -r i:{source_base_name} i:{dest_base_name}".format(**locals()), "EMPTY") # compare files at each level for dir, files in local_dirs.items(): source_partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) dest_partial_path = dir.replace(self.testing_tmp_dir+'/'+source_base_name, dest_base_name, 1) # run ils on source subcollection self.user0.assert_icommand(['ils', source_partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(source_partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) # now the same thing with dest subcollection self.user0.assert_icommand(['ils', dest_partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(dest_partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_nested_coll_to_dir(self): # test settings depth = 10 files_per_level = 100 file_size = 100 # make local nested dirs base_name = "test_irsync_r_nested_dir_to_coll" local_dir = os.path.join(self.testing_tmp_dir, base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # sync dir to coll self.user0.assert_icommand("irsync -r {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # remove local coll shutil.rmtree(local_dir) # now sync back coll to dir self.user0.assert_icommand("irsync -r i:{base_name} {local_dir}".format(**locals()), "EMPTY") # compare files at each level for dir, files in local_dirs.items(): partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) # run ils on subcollection self.user0.assert_icommand(['ils', partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_nested_coll_to_dir_large_files(self): # test settings depth = 4 files_per_level = 4 file_size = 1024*1024*40 # make local nested dirs base_name = "test_irsync_r_nested_dir_to_coll" local_dir = os.path.join(self.testing_tmp_dir, base_name) local_dirs = lib.make_deep_local_tmp_dir(local_dir, depth, files_per_level, file_size) # sync dir to coll self.user0.assert_icommand("irsync -r {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) # remove local coll shutil.rmtree(local_dir) # now sync back coll to dir self.user0.assert_icommand("irsync -r i:{base_name} {local_dir}".format(**locals()), "EMPTY") # compare files at each level for dir, files in local_dirs.items(): partial_path = dir.replace(self.testing_tmp_dir+'/', '', 1) # run ils on subcollection self.user0.assert_icommand(['ils', partial_path], 'STDOUT_SINGLELINE') ils_out = self.user0.get_entries_in_collection(partial_path) # compare local files with irods objects local_files = set(files) rods_files = set(lib.get_object_names_from_entries(ils_out)) self.assertTrue(local_files == rods_files, msg="Files missing:\n" + str(local_files - rods_files) + "\n\n" + "Extra files:\n" + str(rods_files - local_files)) def test_irsync_r_symlink(self): # make local dir base_name = "test_irsync_r_symlink" local_dir = os.path.join(self.testing_tmp_dir, base_name) lib.make_dir_p(local_dir) # make file file_name = os.path.join(local_dir, 'the_file') lib.make_file(file_name, 10) # make symlink with relative path link_path_1 = os.path.join(local_dir, 'link1') lib.execute_command(['ln', '-s', 'the_file', link_path_1]) # make symlink with fully qualified path link_path_2 = os.path.join(local_dir, 'link2') lib.execute_command(['ln', '-s', file_name, link_path_2]) # sync dir to coll self.user0.assert_icommand("irsync -r {local_dir} i:{base_name}".format(**locals()), "STDOUT_SINGLELINE", ustrings.recurse_ok_string())
6,944
2,900
<reponame>implydata/jackson-databind<gh_stars>1000+ package perf; import java.io.IOException; import java.io.OutputStream; public class NopOutputStream extends OutputStream { protected int size = 0; public NopOutputStream() { } @Override public void write(int b) throws IOException { ++size; } @Override public void write(byte[] b) throws IOException { size += b.length; } @Override public void write(byte[] b, int offset, int len) throws IOException { size += len; } public int size() { return size; } }
188