max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
556
<reponame>fengjixuchui/Ghost-In-The-Logs<gh_stars>100-1000 /* * Module Name: * stdafx.h * * Abstract: * Precompiled header. * * Authors: * <NAME> <<EMAIL>> | http://everdox.net/ * * Special thanks to Nemanja (Nemi) Mulasmajic <<EMAIL>> * for his help with the POC. * */ #pragma once /// /// Includes. /// #pragma warning(push, 0) #include <ntifs.h> #include <ntdef.h> #include <ntddk.h> #include <ntstatus.h> //#include "ntint.h" #pragma warning(pop) #include "helpers.h"
224
2,151
<filename>remoting/host/remote_input_filter.cc // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/remote_input_filter.h" #include <stdint.h> #include "base/logging.h" #include "remoting/proto/event.pb.h" namespace { // The number of remote mouse events to record for the purpose of eliminating // "echoes" detected by the local input detector. The value should be large // enough to cope with the fact that multiple events might be injected before // any echoes are detected. const unsigned int kNumRemoteMousePositions = 50; // The number of milliseconds for which to block remote input when local input // is received. const int64_t kRemoteBlockTimeoutMillis = 2000; } // namespace namespace remoting { RemoteInputFilter::RemoteInputFilter(protocol::InputEventTracker* event_tracker) : event_tracker_(event_tracker), expect_local_echo_(true) { } RemoteInputFilter::~RemoteInputFilter() = default; void RemoteInputFilter::LocalMouseMoved( const webrtc::DesktopVector& mouse_pos) { // If this is a genuine local input event (rather than an echo of a remote // input event that we've just injected), then ignore remote inputs for a // short time. if (expect_local_echo_) { std::list<webrtc::DesktopVector>::iterator found_position = injected_mouse_positions_.begin(); while (found_position != injected_mouse_positions_.end() && !mouse_pos.equals(*found_position)) { ++found_position; } if (found_position != injected_mouse_positions_.end()) { // Remove it from the list, and any positions that were added before it, // if any. This is because the local input monitor is assumed to receive // injected mouse position events in the order in which they were injected // (if at all). If the position is found somewhere other than the front // of the queue, this would be because the earlier positions weren't // successfully injected (or the local input monitor might have skipped // over some positions), and not because the events were out-of-sequence. // These spurious positions should therefore be discarded. injected_mouse_positions_.erase(injected_mouse_positions_.begin(), ++found_position); return; } } // Release all pressed buttons or keys, disable inputs, and note the time. event_tracker_->ReleaseAll(); latest_local_input_time_ = base::TimeTicks::Now(); } void RemoteInputFilter::SetExpectLocalEcho(bool expect_local_echo) { expect_local_echo_ = expect_local_echo; if (!expect_local_echo_) injected_mouse_positions_.clear(); } void RemoteInputFilter::InjectKeyEvent(const protocol::KeyEvent& event) { if (ShouldIgnoreInput()) return; event_tracker_->InjectKeyEvent(event); } void RemoteInputFilter::InjectTextEvent(const protocol::TextEvent& event) { if (ShouldIgnoreInput()) return; event_tracker_->InjectTextEvent(event); } void RemoteInputFilter::InjectMouseEvent(const protocol::MouseEvent& event) { if (ShouldIgnoreInput()) return; if (expect_local_echo_ && event.has_x() && event.has_y()) { injected_mouse_positions_.push_back( webrtc::DesktopVector(event.x(), event.y())); if (injected_mouse_positions_.size() > kNumRemoteMousePositions) { VLOG(1) << "Injected mouse positions queue full."; injected_mouse_positions_.pop_front(); } } event_tracker_->InjectMouseEvent(event); } void RemoteInputFilter::InjectTouchEvent(const protocol::TouchEvent& event) { if (ShouldIgnoreInput()) return; event_tracker_->InjectTouchEvent(event); } bool RemoteInputFilter::ShouldIgnoreInput() const { // Ignore remote events if the local mouse moved recently. int64_t millis = (base::TimeTicks::Now() - latest_local_input_time_).InMilliseconds(); if (millis < kRemoteBlockTimeoutMillis) return true; return false; } } // namespace remoting
1,319
555
<filename>security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ranger.entity; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import java.util.Objects; @Entity @Cacheable @XmlRootElement @Table(name = "x_policy_ref_datamask_type") public class XXPolicyRefDataMaskType extends XXDBBase implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * id of the XXPolicyRefDataMaskType * <ul> * </ul> * */ @Id @SequenceGenerator(name = "x_policy_ref_datamask_type_SEQ", sequenceName = "x_policy_ref_datamask_type_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_datamask_type_SEQ") @Column(name = "id") protected Long id; /** * policyId of the XXPolicyRefDataMaskType * <ul> * </ul> * */ @Column(name = "policy_id") protected Long policyId; /** * DatamaskDefId of the XXPolicyRefDataMaskType * <ul> * </ul> * */ @Column(name = "datamask_def_id") protected Long dataMaskDefId; /** * dataMaskTypeName of the XXPolicyRefDataMaskType * <ul> * </ul> * */ @Column(name = "datamask_type_name") protected String dataMaskTypeName; /** * This method sets the value to the member attribute <b> id</b> . You * cannot set null to the attribute. * * @param id * Value to set member attribute <b> id</b> */ public void setId(Long id) { this.id = id; } /** * Returns the value for the member attribute <b>id</b> * * @return Date - value of member attribute <b>id</b> . */ public Long getId() { return this.id; } /** * This method sets the value to the member attribute <b> policyId</b> . * You cannot set null to the attribute. * * @param policyId * Value to set member attribute <b> policyId</b> */ public void setPolicyId(Long policyId) { this.policyId = policyId; } /** * Returns the value for the member attribute <b>policyId</b> * * @return Date - value of member attribute <b>policyId</b> . */ public Long getPolicyId() { return this.policyId; } /** * This method sets the value to the member attribute <b> dataMaskDefId</b> . * You cannot set null to the attribute. * * @param dataMaskDefId * Value to set member attribute <b> dataMaskDefId</b> */ public void setDataMaskDefId(Long dataMaskDefId) { this.dataMaskDefId = dataMaskDefId; } /** * Returns the value for the member attribute <b>dataMaskDefId</b> * * @return Date - value of member attribute <b>dataMaskDefId</b> . */ public Long getDataMaskDefId() { return dataMaskDefId; } /** * This method sets the value to the member attribute <b> dataMaskTypeName</b> . * You cannot set null to the attribute. * * @param dataMaskTypeName * Value to set member attribute <b> dataMaskTypeName</b> */ public void setDataMaskTypeName(String dataMaskTypeName) { this.dataMaskTypeName = dataMaskTypeName; } /** * Returns the value for the member attribute <b>dataMaskTypeName</b> * * @return Date - value of member attribute <b>dataMaskTypeName</b> . */ public String getDataMaskTypeName() { return dataMaskTypeName; } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, policyId, dataMaskDefId, dataMaskTypeName); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } XXPolicyRefDataMaskType other = (XXPolicyRefDataMaskType) obj; return super.equals(obj) && Objects.equals(id, other.id) && Objects.equals(policyId, other.policyId) && Objects.equals(dataMaskDefId, other.dataMaskDefId) && Objects.equals(dataMaskTypeName, other.dataMaskTypeName); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "XXPolicyRefDataMaskType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", dataMaskDefId=" + dataMaskDefId + ", dataMaskTypeName=" + dataMaskTypeName + "]"; } }
1,743
1,350
<filename>sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/WebTestImpl.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.implementation; import com.azure.core.management.Region; import com.azure.core.util.Context; import com.azure.resourcemanager.applicationinsights.fluent.models.WebTestInner; import com.azure.resourcemanager.applicationinsights.models.TagsResource; import com.azure.resourcemanager.applicationinsights.models.WebTest; import com.azure.resourcemanager.applicationinsights.models.WebTestGeolocation; import com.azure.resourcemanager.applicationinsights.models.WebTestKind; import com.azure.resourcemanager.applicationinsights.models.WebTestPropertiesConfiguration; import java.util.Collections; import java.util.List; import java.util.Map; public final class WebTestImpl implements WebTest, WebTest.Definition, WebTest.Update { private WebTestInner innerObject; private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public String location() { return this.innerModel().location(); } public Map<String, String> tags() { Map<String, String> inner = this.innerModel().tags(); if (inner != null) { return Collections.unmodifiableMap(inner); } else { return Collections.emptyMap(); } } public WebTestKind kind() { return this.innerModel().kind(); } public String syntheticMonitorId() { return this.innerModel().syntheticMonitorId(); } public String webTestName() { return this.innerModel().webTestName(); } public String description() { return this.innerModel().description(); } public Boolean enabled() { return this.innerModel().enabled(); } public Integer frequency() { return this.innerModel().frequency(); } public Integer timeout() { return this.innerModel().timeout(); } public WebTestKind webTestKind() { return this.innerModel().webTestKind(); } public Boolean retryEnabled() { return this.innerModel().retryEnabled(); } public List<WebTestGeolocation> locations() { List<WebTestGeolocation> inner = this.innerModel().locations(); if (inner != null) { return Collections.unmodifiableList(inner); } else { return Collections.emptyList(); } } public WebTestPropertiesConfiguration configuration() { return this.innerModel().configuration(); } public String provisioningState() { return this.innerModel().provisioningState(); } public Region region() { return Region.fromName(this.regionName()); } public String regionName() { return this.location(); } public WebTestInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { return this.serviceManager; } private String resourceGroupName; private String webTestName; private TagsResource updateWebTestTags; public WebTestImpl withExistingResourceGroup(String resourceGroupName) { this.resourceGroupName = resourceGroupName; return this; } public WebTest create() { this.innerObject = serviceManager .serviceClient() .getWebTests() .createOrUpdateWithResponse(resourceGroupName, webTestName, this.innerModel(), Context.NONE) .getValue(); return this; } public WebTest create(Context context) { this.innerObject = serviceManager .serviceClient() .getWebTests() .createOrUpdateWithResponse(resourceGroupName, webTestName, this.innerModel(), context) .getValue(); return this; } WebTestImpl(String name, com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { this.innerObject = new WebTestInner(); this.serviceManager = serviceManager; this.webTestName = name; } public WebTestImpl update() { this.updateWebTestTags = new TagsResource(); return this; } public WebTest apply() { this.innerObject = serviceManager .serviceClient() .getWebTests() .updateTagsWithResponse(resourceGroupName, webTestName, updateWebTestTags, Context.NONE) .getValue(); return this; } public WebTest apply(Context context) { this.innerObject = serviceManager .serviceClient() .getWebTests() .updateTagsWithResponse(resourceGroupName, webTestName, updateWebTestTags, context) .getValue(); return this; } WebTestImpl( WebTestInner innerObject, com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups"); this.webTestName = Utils.getValueFromIdByName(innerObject.id(), "webtests"); } public WebTest refresh() { this.innerObject = serviceManager .serviceClient() .getWebTests() .getByResourceGroupWithResponse(resourceGroupName, webTestName, Context.NONE) .getValue(); return this; } public WebTest refresh(Context context) { this.innerObject = serviceManager .serviceClient() .getWebTests() .getByResourceGroupWithResponse(resourceGroupName, webTestName, context) .getValue(); return this; } public WebTestImpl withRegion(Region location) { this.innerModel().withLocation(location.toString()); return this; } public WebTestImpl withRegion(String location) { this.innerModel().withLocation(location); return this; } public WebTestImpl withTags(Map<String, String> tags) { if (isInCreateMode()) { this.innerModel().withTags(tags); return this; } else { this.updateWebTestTags.withTags(tags); return this; } } public WebTestImpl withKind(WebTestKind kind) { this.innerModel().withKind(kind); return this; } public WebTestImpl withSyntheticMonitorId(String syntheticMonitorId) { this.innerModel().withSyntheticMonitorId(syntheticMonitorId); return this; } public WebTestImpl withWebTestName(String webTestName) { this.innerModel().withWebTestName(webTestName); return this; } public WebTestImpl withDescription(String description) { this.innerModel().withDescription(description); return this; } public WebTestImpl withEnabled(Boolean enabled) { this.innerModel().withEnabled(enabled); return this; } public WebTestImpl withFrequency(Integer frequency) { this.innerModel().withFrequency(frequency); return this; } public WebTestImpl withTimeout(Integer timeout) { this.innerModel().withTimeout(timeout); return this; } public WebTestImpl withWebTestKind(WebTestKind webTestKind) { this.innerModel().withWebTestKind(webTestKind); return this; } public WebTestImpl withRetryEnabled(Boolean retryEnabled) { this.innerModel().withRetryEnabled(retryEnabled); return this; } public WebTestImpl withLocations(List<WebTestGeolocation> locations) { this.innerModel().withLocations(locations); return this; } public WebTestImpl withConfiguration(WebTestPropertiesConfiguration configuration) { this.innerModel().withConfiguration(configuration); return this; } private boolean isInCreateMode() { return this.innerModel().id() == null; } }
3,370
14,668
<gh_stars>1000+ // 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 "ui/base/clipboard/test/clipboard_test_util.h" #include <vector> #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" #include "base/test/bind.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard.h" namespace ui { namespace clipboard_test_util { namespace { class ReadImageHelper { public: ReadImageHelper() = default; ~ReadImageHelper() = default; std::vector<uint8_t> ReadPng(Clipboard* clipboard) { base::RunLoop loop; std::vector<uint8_t> png; clipboard->ReadPng( ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, base::BindLambdaForTesting([&](const std::vector<uint8_t>& result) { png = result; loop.Quit(); })); loop.Run(); return png; } }; } // namespace std::vector<uint8_t> ReadPng(Clipboard* clipboard) { ReadImageHelper read_image_helper; return read_image_helper.ReadPng(clipboard); } } // namespace clipboard_test_util } // namespace ui
474
2,531
<gh_stars>1000+ #include "../../private_api.h" #ifdef FLECS_EXPR char* ecs_chresc( char *out, char in, char delimiter) { char *bptr = out; switch(in) { case '\a': *bptr++ = '\\'; *bptr = 'a'; break; case '\b': *bptr++ = '\\'; *bptr = 'b'; break; case '\f': *bptr++ = '\\'; *bptr = 'f'; break; case '\n': *bptr++ = '\\'; *bptr = 'n'; break; case '\r': *bptr++ = '\\'; *bptr = 'r'; break; case '\t': *bptr++ = '\\'; *bptr = 't'; break; case '\v': *bptr++ = '\\'; *bptr = 'v'; break; case '\\': *bptr++ = '\\'; *bptr = '\\'; break; default: if (in == delimiter) { *bptr++ = '\\'; *bptr = delimiter; } else { *bptr = in; } break; } *(++bptr) = '\0'; return bptr; } const char* ecs_chrparse( const char *in, char *out) { const char *result = in + 1; char ch; if (in[0] == '\\') { result ++; switch(in[1]) { case 'a': ch = '\a'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case 'v': ch = '\v'; break; case '\\': ch = '\\'; break; case '"': ch = '"'; break; case '0': ch = '\0'; break; case ' ': ch = ' '; break; case '$': ch = '$'; break; default: goto error; } } else { ch = in[0]; } if (out) { *out = ch; } return result; error: return NULL; } ecs_size_t ecs_stresc( char *out, ecs_size_t n, char delimiter, const char *in) { const char *ptr = in; char ch, *bptr = out, buff[3]; ecs_size_t written = 0; while ((ch = *ptr++)) { if ((written += (ecs_size_t)(ecs_chresc(buff, ch, delimiter) - buff)) <= n) { /* If size != 0, an out buffer must be provided. */ ecs_assert(out != NULL, ECS_INVALID_PARAMETER, NULL); *bptr++ = buff[0]; if ((ch = buff[1])) { *bptr = ch; bptr++; } } } if (bptr) { while (written < n) { *bptr = '\0'; bptr++; written++; } } return written; } char* ecs_astresc( char delimiter, const char *in) { if (!in) { return NULL; } ecs_size_t len = ecs_stresc(NULL, 0, delimiter, in); char *out = ecs_os_malloc_n(char, len + 1); ecs_stresc(out, len, delimiter, in); out[len] = '\0'; return out; } #endif
1,930
653
<gh_stars>100-1000 // Copyright (c) 2020 by Chrono // // https://github.com/whoshuu/cpr/ // cmake . -DUSE_SYSTEM_CURL=ON -DBUILD_CPR_TESTS=OFF // make && make install // // g++ cpr.cpp -std=c++14 -lcpr -lpthread -lcurl -o a.out;./a.out #include <cassert> #include <iostream> #include <cpr/cpr.h> using namespace std; void case1() { //const auto url = "http://nginx.org"s; const auto url = "http://openresty.org"s; auto res = cpr::Get( cpr::Url{url} ); cout << res.elapsed << endl; cout << res.url << endl; cout << res.status_code << endl; //cout << res.header["server"] << endl; cout << res.text.length() << endl; for(auto& x : res.header) { cout << x.first << "=>" << x.second << endl; } cout << endl; } void case2() { //const auto url = "http://www.163.com"s; const auto url = "http://openresty.org"s; auto res1 = cpr::Head( cpr::Url{url} ); assert(res1.text.empty()); auto res2 = cpr::Get( cpr::Url{url}, cpr::Parameters{ {"a", "1"}, {"b", "2"}} ); auto res3 = cpr::Post( cpr::Url{url}, cpr::Header{{"x", "xxx"},{"expect",""}}, cpr::Body{"post data"}, cpr::Timeout{200ms} ); } void case3() { auto f = cpr::GetAsync( cpr::Url{"http://openresty.org"} ); auto res = f.get(); cout << res.elapsed << endl; for(auto& x : res.header) { cout << x.first << "=>" << x.second << endl; } } int main() { case1(); case2(); case3(); cout << "libcpr demo" << endl; }
878
418
/* * Copyright (c) 2015 <NAME> (gfx). * * 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.github.gfx.android.orma.rx; import com.github.gfx.android.orma.ModelFactory; import com.github.gfx.android.orma.OrmaConnection; import com.github.gfx.android.orma.Schema; import com.github.gfx.android.orma.SingleAssociation; import com.github.gfx.android.orma.exception.NoValueException; import com.github.gfx.android.orma.internal.Schemas; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.RestrictTo; import java.util.concurrent.Callable; import io.reactivex.Single; /** * Lazy has-one association with RxJava support. * The {@code Model} is assumed to have a primary key with the `long` type. * This is typically created from factory methods. * * @param <Model> The type of a model */ public class RxSingleAssociation<Model> extends SingleAssociation<Model> { final Single<Model> single = Single.fromCallable(new Callable<Model>() { @Override public Model call() throws Exception { return get(); } }); @RestrictTo(RestrictTo.Scope.LIBRARY) public RxSingleAssociation(long id, @NonNull Model model) { super(id, model); } @RestrictTo(RestrictTo.Scope.LIBRARY) public RxSingleAssociation(long id, @NonNull ModelFactory<Model> factory) { super(id, factory); } // may be called from *_Schema public RxSingleAssociation(@NonNull final OrmaConnection conn, @NonNull final Schema<Model> schema, final long id) { super(conn, schema, id); } /** * The most typical factory method to create a {@code RxSingleAssociation} instance, * just wrapping the model with it. * * @param model A model to wrap, which must have a valid primary key * @param <T> The type of the model to wrap * @return An instance of {@code RxSingleAssociation} */ @SuppressWarnings("unchecked") @NonNull public static <T> RxSingleAssociation<T> just(@NonNull T model) { Schema<T> schema = Schemas.get((Class<T>) model.getClass()); return just(schema, model); } @NonNull public static <T> RxSingleAssociation<T> just(long id, @NonNull T model) { return new RxSingleAssociation<>(id, model); } @NonNull public static <T> RxSingleAssociation<T> just(@NonNull Schema<T> schema, @NonNull T model) { return new RxSingleAssociation<>((long) schema.getPrimaryKey().getSerialized(model), model); } @NonNull public static <T> RxSingleAssociation<T> just(final long id) { return new RxSingleAssociation<>(id, new ModelFactory<T>() { @NonNull @Override public T call() { throw new NoValueException("No value set for id=" + id); } }); } // use just(id) instead @Deprecated @NonNull public static <T> RxSingleAssociation<T> id(final long id) { return just(id); } @CheckResult @NonNull public Single<Model> single() { return single; } }
1,314
493
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef CPPIPC_UTIL_GENERICS_MEMBER_FUNCTION_RETURN_TYPE_HPP #define CPPIPC_UTIL_GENERICS_MEMBER_FUNCTION_RETURN_TYPE_HPP namespace cppipc { namespace detail { template <typename MemFn> struct member_function_return_type { typedef typename boost::remove_member_pointer<MemFn>::type fntype; typedef typename boost::function_traits<fntype>::result_type type; }; } // detail } // cppipc #endif
210
374
<gh_stars>100-1000 { "name": "openfb", "main": "openfb.js", "version": "0.5.0", "homepage": "https://github.com/ccoenraets/OpenFB", "authors": [ "<NAME> <<EMAIL>>" ], "description": "Micro-Library for Facebook integration in JavaScript apps running in the browser and in Cordova", "keywords": [ "OpenFB", "Facebook", "Cordova", "Hybrid", "Graph", "OAuth" ], "license": "MIT", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ] }
228
661
<gh_stars>100-1000 /* Copyright (c) 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. <NAME> <EMAIL> */ #ifndef __GAMEPAD_PRIVATE_H__ #define __GAMEPAD_PRIVATE_H__ enum Gamepad_eventType { GAMEPAD_EVENT_DEVICE_ATTACHED, GAMEPAD_EVENT_DEVICE_REMOVED, GAMEPAD_EVENT_BUTTON_DOWN, GAMEPAD_EVENT_BUTTON_UP, GAMEPAD_EVENT_AXIS_MOVED }; struct Gamepad_buttonEvent { // Device that generated the event struct Gamepad_device * device; // Relative time of the event, in seconds double timestamp; // Button being pushed or released unsigned int buttonID; // True if button is down bool down; }; struct Gamepad_axisEvent { // Device that generated the event struct Gamepad_device * device; // Relative time of the event, in seconds double timestamp; // Axis being moved unsigned int axisID; // Axis position value, in the range [-1..1] float value; // Previous axis position value, in the range [-1..1] float lastValue; }; extern void (* Gamepad_deviceAttachCallback)(struct Gamepad_device * device, void * context); extern void (* Gamepad_deviceRemoveCallback)(struct Gamepad_device * device, void * context); extern void (* Gamepad_buttonDownCallback)(struct Gamepad_device * device, unsigned int buttonID, double timestamp, void * context); extern void (* Gamepad_buttonUpCallback)(struct Gamepad_device * device, unsigned int buttonID, double timestamp, void * context); extern void (* Gamepad_axisMoveCallback)(struct Gamepad_device * device, unsigned int axisID, float value, float lastValue, double timestamp, void * context); extern void * Gamepad_deviceAttachContext; extern void * Gamepad_deviceRemoveContext; extern void * Gamepad_buttonDownContext; extern void * Gamepad_buttonUpContext; extern void * Gamepad_axisMoveContext; #endif
766
2,637
/** @file swrtc.c * * @brief This file provides Software rtc implementation * * (C) Copyright 2008-2019 Marvell International Ltd. All Rights Reserved. * * MARVELL CONFIDENTIAL * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell * International Ltd or its suppliers and licensors. The Material contains * trade secrets and proprietary and confidential information of Marvell or its * suppliers and licensors. The Material is protected by worldwide copyright * and trade secret laws and treaty provisions. No part of the Material may be * used, copied, reproduced, modified, published, uploaded, posted, * transmitted, distributed, or disclosed in any way without Marvell's prior * express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ /** swrtc.c: Software rtc implementation */ #include <wm_os.h> #include <wmtime.h> #include <rtc.h> static unsigned long n_ticks_per_sec; /** * Global variable to avoid multiple initialization of rtc */ static int swrtc_init_flag = 0; time_t cur_posix_time = 0; unsigned int abs_tick_count = 0; static unsigned int tick_count_ = 0; /** * Update RTC counters on a system clock tick */ void swrtc_tick(void) { abs_tick_count++; /* No protection is required as tick_count_ is not used anywhere else */ if (++tick_count_ >= n_ticks_per_sec) { tick_count_ = 0; cur_posix_time++; } } /** * Initialize Software Real Time Clock */ void swrtc_init(void) { if (swrtc_init_flag) return; swrtc_init_flag = 1; /* Set initial date to 1/1/1970 00:00 */ cur_posix_time = 0; abs_tick_count = 0; n_ticks_per_sec = os_msec_to_ticks(1000); os_setup_tick_function(swrtc_tick); } int swrtc_time_set(time_t time) { cur_posix_time = time; return 0; } time_t swrtc_time_get(void) { return cur_posix_time; }
720
450
import UserDict class jj(UserDict.UserDict) : "jj" def __init__(self): UserDict.UserDict.__init__(self, None) class jj2(UserDict.UserDict) : "jj2" def __init__(self): "Warning don't call UserDict.UserDict.__init__()" print "don't call UserDict.UserDict.__init__()" class jj3(jj) : "jj3" def __init__(self): jj.__init__(self) class jj4(jj) : "jj4" class A: 'should not generate warnings' def __init__(self): pass class B(A): 'should not generate warnings' class C(B): 'should not generate warnings' def __init__(self): B.__init__(self)
288
459
from keras import backend as K from .word_alignment import WordAlignmentEntailment from ...tensors.backend import switch class MultipleChoiceTupleEntailment(WordAlignmentEntailment): '''A kind of decomposable attention where the premise (or background) is in the form of SVO triples, and entailment is computed by finding the answer in a multiple choice setting that aligns best with the tuples that align with the question. This happens in two steps: (1) We use the _align function from WordAlignmentEntailment to find the premise tuples whose SV, or VO pairs align best with the question. (2) We then use the _align function again to find the answer that aligns best with the unaligned part of the tuples, weighed by how much they partially align with the question in step 1. TODO(pradeep): Also match S with question, VO with answer, O with question and SV with answer. ''' def __init__(self, **kwargs): self.tuple_size = None self.num_tuples = None self.num_options = None self.question_length = None super(MultipleChoiceTupleEntailment, self).__init__(**kwargs) def build(self, input_shape): #NOTE: This layer currently has no trainable parameters. super(MultipleChoiceTupleEntailment, self).build(input_shape) # knowledge_shape: (batch_size, num_tuples, tuple_size, embed_dim) # question_shape: (batch_size, question_length, embed_dim) # answer_shape: (batch_size, num_options, embed_dim) knowledge_shape, question_shape, answer_shape = input_shape self.tuple_size = knowledge_shape[2] if self.tuple_size != 3: raise NotImplementedError("Only SVO tuples are currently supported.") self.num_tuples = knowledge_shape[1] self.question_length = question_shape[1] self.num_options = answer_shape[1] self.input_dim = knowledge_shape[-1] def compute_output_shape(self, input_shape): return (input_shape[0][0], self.num_options) def compute_mask(self, x, mask=None): # pylint: disable=unused-argument return None def call(self, x, mask=None): # We assume the tuples are SVO and each slot is represented as vector. # Moreover, we assume each answer option is encoded as a single vector. # knowledge_embedding: (batch_size, num_tuples, tuple_size, embed_dim) # question_embedding: (batch_size, question_length, embed_dim) # answer_embedding: (batch_size, num_options, embed_dim) knowledge_embedding, question_embedding, answer_embedding = x if mask is None: knowledge_mask = question_mask = answer_mask = None else: knowledge_mask, question_mask, answer_mask = mask if knowledge_mask is None: sv_knowledge_mask = vo_knowledge_mask = subj_knowledge_mask = obj_knowledge_mask = None else: # Take out the relevant parts for each part of the tuple and reshape SV and VO masks using # batch_flatten. # (batch_size, num_tuples*2) sv_knowledge_mask = K.batch_flatten(knowledge_mask[:, :, :2]) # (batch_size, num_tuples*2) vo_knowledge_mask = K.batch_flatten(knowledge_mask[:, :, 1:]) # (batch_size, num_tuples) subj_knowledge_mask = knowledge_mask[:, :, 0] # (batch_size, num_tuples) obj_knowledge_mask = knowledge_mask[:, :, 2] batch_size = K.shape(knowledge_embedding)[0] sv_knowledge = K.reshape(knowledge_embedding[:, :, :2, :], (batch_size, self.num_tuples*2, self.input_dim)) vo_knowledge = K.reshape(knowledge_embedding[:, :, 1:, :], (batch_size, self.num_tuples*2, self.input_dim)) # (batch_size, num_tuples, embed_dim) subj_knowledge = knowledge_embedding[:, :, 0, :] # (batch_size, num_tuples, embed_dim) obj_knowledge = knowledge_embedding[:, :, 2, :] ## Step A1: Align SV with question. # Source is question, target is SV knowledge # (batch_size, question_length, num_tuples*2) sv_question_knowledge_alignment = self._align(question_embedding, sv_knowledge, question_mask, sv_knowledge_mask, normalize_alignment=False) # Sum probabilities over S and V slots. This is still a valid probability distribution. # (batch_size, question_length, num_tuples) sv_question_tuple_weights = K.sum(K.reshape(sv_question_knowledge_alignment, (batch_size, self.question_length, self.num_tuples, 2)), axis=-1) # Average over question length. This is essentially the weights of tuples based on how well their # S and V slots align to any word in the question. # Insight: This is essentially \sum_{i} p_align(tuple | q_word_i) * p_imp(q_word_i), where q_word_i is # the ith word in the question, p_align is the alignment weight and p_imp is the importance of the # question word, and p_imp is uniform. # (batch_size, num_tuples) sv_tuple_weights = K.mean(sv_question_tuple_weights, axis=1) ## Step A2: Align answer with Obj. # Source is obj knowledge, target is answer # (batch_size, num_tuples, num_options) obj_knowledge_answer_alignment = self._align(obj_knowledge, answer_embedding, obj_knowledge_mask, answer_mask, normalize_alignment=False) # (batch_size, num_tuples, num_options) tiled_sv_tuple_weights = K.dot(K.expand_dims(sv_tuple_weights), K.ones((1, self.num_options))) # Now we compute a weighted average over the tuples dimension, with the weights coming from how well # the tuples align with the question. # (batch_size, num_options) obj_answer_weights = K.sum(tiled_sv_tuple_weights * obj_knowledge_answer_alignment, axis=1) # Following steps are similar to what we did so far. Just substitute VO for SV and S for O. ## Step B1: Align VO with question vo_question_knowledge_alignment = self._align(question_embedding, vo_knowledge, question_mask, vo_knowledge_mask, normalize_alignment=False) vo_question_tuple_weights = K.sum(K.reshape(vo_question_knowledge_alignment, (batch_size, self.question_length, self.num_tuples, 2)), axis=-1) vo_tuple_weights = K.mean(vo_question_tuple_weights, axis=1) ## Step B2: Align answer with Subj subj_knowledge_answer_alignment = self._align(subj_knowledge, answer_embedding, subj_knowledge_mask, answer_mask, normalize_alignment=False) tiled_vo_tuple_weights = K.dot(K.expand_dims(vo_tuple_weights), K.ones((1, self.num_options))) subj_answer_weights = K.sum(tiled_vo_tuple_weights * subj_knowledge_answer_alignment, axis=1) # We now select the element wise max of obj_answer_weights and subj_answer_weights as our final weights. # (batch_size, num_options) max_answer_weights = switch(K.greater(obj_answer_weights, subj_answer_weights), obj_answer_weights, subj_answer_weights) # Renormalizing max weights. return K.softmax(max_answer_weights)
3,267
14,668
<reponame>chromium/chromium // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/animationworklet/worklet_animation.h" #include <memory> #include <utility> #include "base/time/time_delta_from_string.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/bindings/core/v8/v8_scroll_timeline_options.h" #include "third_party/blink/renderer/bindings/core/v8/v8_union_animationeffect_animationeffectsequence.h" #include "third_party/blink/renderer/bindings/core/v8/v8_union_documenttimeline_scrolltimeline.h" #include "third_party/blink/renderer/core/animation/document_timeline.h" #include "third_party/blink/renderer/core/animation/element_animations.h" #include "third_party/blink/renderer/core/animation/keyframe_effect.h" #include "third_party/blink/renderer/core/animation/keyframe_effect_model.h" #include "third_party/blink/renderer/core/animation/scroll_timeline.h" #include "third_party/blink/renderer/core/animation/worklet_animation_controller.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" namespace blink { namespace { // Only expect precision up to 1 microsecond with an additional epsilon to // account for float conversion error (mainly due to timeline time getting // converted between float and base::TimeDelta). static constexpr double time_error_ms = 0.001 + 1e-13; #define EXPECT_TIME_NEAR(expected, value) \ EXPECT_NEAR(expected, value, time_error_ms) KeyframeEffectModelBase* CreateEffectModel() { StringKeyframeVector frames_mixed_properties; Persistent<StringKeyframe> keyframe = MakeGarbageCollected<StringKeyframe>(); keyframe->SetOffset(0); keyframe->SetCSSPropertyValue(CSSPropertyID::kOpacity, "0", SecureContextMode::kInsecureContext, nullptr); frames_mixed_properties.push_back(keyframe); keyframe = MakeGarbageCollected<StringKeyframe>(); keyframe->SetOffset(1); keyframe->SetCSSPropertyValue(CSSPropertyID::kOpacity, "1", SecureContextMode::kInsecureContext, nullptr); frames_mixed_properties.push_back(keyframe); return MakeGarbageCollected<StringKeyframeEffectModel>( frames_mixed_properties); } KeyframeEffect* CreateKeyframeEffect(Element* element) { Timing timing; timing.iteration_duration = ANIMATION_TIME_DELTA_FROM_SECONDS(30); return MakeGarbageCollected<KeyframeEffect>(element, CreateEffectModel(), timing); } WorkletAnimation* CreateWorkletAnimation( ScriptState* script_state, Element* element, const String& animator_name, ScrollTimeline* scroll_timeline = nullptr) { auto* effects = MakeGarbageCollected<V8UnionAnimationEffectOrAnimationEffectSequence>( CreateKeyframeEffect(element)); V8UnionDocumentTimelineOrScrollTimeline* timeline = nullptr; if (scroll_timeline) { timeline = MakeGarbageCollected<V8UnionDocumentTimelineOrScrollTimeline>( scroll_timeline); } ScriptValue options; ScriptState::Scope scope(script_state); return WorkletAnimation::Create(script_state, animator_name, effects, timeline, options, ASSERT_NO_EXCEPTION); } base::TimeDelta ToTimeDelta(double milliseconds) { return base::Milliseconds(milliseconds); } } // namespace class WorkletAnimationTest : public RenderingTest { public: WorkletAnimationTest() : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {} void SetUp() override { RenderingTest::SetUp(); element_ = GetDocument().CreateElementForBinding("test"); GetDocument().body()->appendChild(element_); // Animator has to be registered before constructing WorkletAnimation. For // unit test this is faked by adding the animator name to // WorkletAnimationController. animator_name_ = "WorkletAnimationTest"; GetDocument().GetWorkletAnimationController().SynchronizeAnimatorName( animator_name_); worklet_animation_ = CreateWorkletAnimation(GetScriptState(), element_, animator_name_); GetDocument().Timeline().ResetForTesting(); GetDocument().GetAnimationClock().ResetTimeForTesting(); } void SimulateFrame(double milliseconds) { base::TimeTicks tick = base::TimeTicks() + GetDocument().Timeline().CalculateZeroTime().since_origin() + ToTimeDelta(milliseconds); GetDocument().GetAnimationClock().UpdateTime(tick); GetDocument().GetWorkletAnimationController().UpdateAnimationStates(); GetDocument().GetWorkletAnimationController().UpdateAnimationTimings( kTimingUpdateForAnimationFrame); } ScriptState* GetScriptState() { return ToScriptStateForMainWorld(&GetFrame()); } Persistent<Element> element_; Persistent<WorkletAnimation> worklet_animation_; String animator_name_; }; TEST_F(WorkletAnimationTest, WorkletAnimationInElementAnimations) { worklet_animation_->play(ASSERT_NO_EXCEPTION); EXPECT_EQ(1u, element_->EnsureElementAnimations().GetWorkletAnimations().size()); worklet_animation_->cancel(); EXPECT_EQ(0u, element_->EnsureElementAnimations().GetWorkletAnimations().size()); } TEST_F(WorkletAnimationTest, ElementHasWorkletAnimation) { EXPECT_FALSE(element_->HasAnimations()); worklet_animation_->play(ASSERT_NO_EXCEPTION); EXPECT_TRUE(element_->HasAnimations()); } // Regression test for crbug.com/1136120, pass if there is no crash. TEST_F(WorkletAnimationTest, SetCurrentTimeInfNotCrash) { absl::optional<base::TimeDelta> seek_time = base::TimeDeltaFromString("inf"); worklet_animation_->SetPlayState(Animation::kRunning); GetDocument().GetAnimationClock().UpdateTime(base::TimeTicks::Max()); worklet_animation_->SetCurrentTime(seek_time); } TEST_F(WorkletAnimationTest, StyleHasCurrentAnimation) { scoped_refptr<ComputedStyle> style1 = GetDocument() .GetStyleResolver() .ResolveStyle(element_, StyleRecalcContext()) .get(); EXPECT_FALSE(style1->HasCurrentOpacityAnimation()); worklet_animation_->play(ASSERT_NO_EXCEPTION); scoped_refptr<ComputedStyle> style2 = GetDocument() .GetStyleResolver() .ResolveStyle(element_, StyleRecalcContext()) .get(); EXPECT_TRUE(style2->HasCurrentOpacityAnimation()); } TEST_F(WorkletAnimationTest, CurrentTimeFromDocumentTimelineIsOffsetByStartTime) { WorkletAnimationId id = worklet_animation_->GetWorkletAnimationId(); SimulateFrame(111); worklet_animation_->play(ASSERT_NO_EXCEPTION); worklet_animation_->UpdateCompositingState(); std::unique_ptr<AnimationWorkletDispatcherInput> state = std::make_unique<AnimationWorkletDispatcherInput>(); worklet_animation_->UpdateInputState(state.get()); // First state request sets the start time and thus current time should be 0. std::unique_ptr<AnimationWorkletInput> input = state->TakeWorkletState(id.worklet_id); EXPECT_TIME_NEAR(0, input->added_and_updated_animations[0].current_time); SimulateFrame(111 + 123.4); state = std::make_unique<AnimationWorkletDispatcherInput>(); worklet_animation_->UpdateInputState(state.get()); input = state->TakeWorkletState(id.worklet_id); EXPECT_TIME_NEAR(123.4, input->updated_animations[0].current_time); } TEST_F(WorkletAnimationTest, DISABLED_CurrentTimeFromScrollTimelineNotOffsetByStartTime) { SetBodyInnerHTML(R"HTML( <style> #scroller { overflow: scroll; width: 100px; height: 100px; } #spacer { width: 200px; height: 200px; } </style> <div id='scroller'> <div id ='spacer'></div> </div> )HTML"); auto* scroller = To<LayoutBoxModelObject>(GetLayoutObjectByElementId("scroller")); ASSERT_TRUE(scroller); ASSERT_TRUE(scroller->IsScrollContainer()); PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea(); ASSERT_TRUE(scrollable_area); scrollable_area->SetScrollOffset(ScrollOffset(0, 20), mojom::blink::ScrollType::kProgrammatic); ScrollTimelineOptions* options = ScrollTimelineOptions::Create(); options->setSource(GetElementById("scroller")); ScrollTimeline* scroll_timeline = ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION); WorkletAnimation* worklet_animation = CreateWorkletAnimation( GetScriptState(), element_, animator_name_, scroll_timeline); worklet_animation->play(ASSERT_NO_EXCEPTION); worklet_animation->UpdateCompositingState(); scrollable_area->SetScrollOffset(ScrollOffset(0, 40), mojom::blink::ScrollType::kProgrammatic); // Simulate a new animation frame which allows the timeline to compute new // current time. GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_TRUE(worklet_animation->currentTime().has_value()); EXPECT_TIME_NEAR(40, worklet_animation->currentTime().value()); scrollable_area->SetScrollOffset(ScrollOffset(0, 70), mojom::blink::ScrollType::kProgrammatic); GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_TRUE(worklet_animation->currentTime().has_value()); EXPECT_TIME_NEAR(70, worklet_animation->currentTime().value()); } // Verifies correctness of current time when playback rate is set while the // animation is in idle state. TEST_F(WorkletAnimationTest, DocumentTimelineSetPlaybackRate) { double playback_rate = 2.0; SimulateFrame(111.0); worklet_animation_->setPlaybackRate(GetScriptState(), playback_rate); worklet_animation_->play(ASSERT_NO_EXCEPTION); worklet_animation_->UpdateCompositingState(); // Zero current time is not impacted by playback rate. ASSERT_TRUE(worklet_animation_->currentTime().has_value()); EXPECT_TIME_NEAR(0, worklet_animation_->currentTime().value()); // Play the animation until second_ticks. SimulateFrame(111.0 + 123.4); // Verify that the current time is updated playback_rate faster than the // timeline time. ASSERT_TRUE(worklet_animation_->currentTime().has_value()); EXPECT_TIME_NEAR(123.4 * playback_rate, worklet_animation_->currentTime().value()); } // Verifies correctness of current time when playback rate is set while the // animation is playing. TEST_F(WorkletAnimationTest, DocumentTimelineSetPlaybackRateWhilePlaying) { SimulateFrame(0); double playback_rate = 0.5; // Start animation. SimulateFrame(111.0); worklet_animation_->play(ASSERT_NO_EXCEPTION); worklet_animation_->UpdateCompositingState(); // Update playback rate after second tick. SimulateFrame(111.0 + 123.4); worklet_animation_->setPlaybackRate(GetScriptState(), playback_rate); // Verify current time after third tick. SimulateFrame(111.0 + 123.4 + 200.0); ASSERT_TRUE(worklet_animation_->currentTime().has_value()); EXPECT_TIME_NEAR(123.4 + 200.0 * playback_rate, worklet_animation_->currentTime().value()); } TEST_F(WorkletAnimationTest, PausePlay) { SimulateFrame(0); worklet_animation_->play(ASSERT_NO_EXCEPTION); EXPECT_EQ(Animation::kPending, worklet_animation_->PlayState()); SimulateFrame(0); EXPECT_EQ(Animation::kRunning, worklet_animation_->PlayState()); EXPECT_TRUE(worklet_animation_->Playing()); EXPECT_TIME_NEAR(0, worklet_animation_->currentTime().value()); SimulateFrame(10); worklet_animation_->pause(ASSERT_NO_EXCEPTION); EXPECT_EQ(Animation::kPaused, worklet_animation_->PlayState()); EXPECT_FALSE(worklet_animation_->Playing()); EXPECT_TIME_NEAR(10, worklet_animation_->currentTime().value()); SimulateFrame(20); EXPECT_EQ(Animation::kPaused, worklet_animation_->PlayState()); EXPECT_TIME_NEAR(10, worklet_animation_->currentTime().value()); worklet_animation_->play(ASSERT_NO_EXCEPTION); EXPECT_EQ(Animation::kPending, worklet_animation_->PlayState()); SimulateFrame(20); EXPECT_EQ(Animation::kRunning, worklet_animation_->PlayState()); EXPECT_TRUE(worklet_animation_->Playing()); EXPECT_TIME_NEAR(10, worklet_animation_->currentTime().value()); SimulateFrame(30); EXPECT_EQ(Animation::kRunning, worklet_animation_->PlayState()); EXPECT_TIME_NEAR(20, worklet_animation_->currentTime().value()); } // Verifies correctness of current time when playback rate is set while // scroll-linked animation is in idle state. TEST_F(WorkletAnimationTest, DISABLED_ScrollTimelineSetPlaybackRate) { SetBodyInnerHTML(R"HTML( <style> #scroller { overflow: scroll; width: 100px; height: 100px; } #spacer { width: 200px; height: 200px; } </style> <div id='scroller'> <div id='spacer'></div> </div> )HTML"); auto* scroller = To<LayoutBoxModelObject>(GetLayoutObjectByElementId("scroller")); ASSERT_TRUE(scroller); ASSERT_TRUE(scroller->IsScrollContainer()); PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea(); ASSERT_TRUE(scrollable_area); scrollable_area->SetScrollOffset(ScrollOffset(0, 20), mojom::blink::ScrollType::kProgrammatic); ScrollTimelineOptions* options = ScrollTimelineOptions::Create(); options->setSource(GetElementById("scroller")); ScrollTimeline* scroll_timeline = ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION); WorkletAnimation* worklet_animation = CreateWorkletAnimation( GetScriptState(), element_, animator_name_, scroll_timeline); DummyExceptionStateForTesting exception_state; double playback_rate = 2.0; // Set playback rate while the animation is in 'idle' state. worklet_animation->setPlaybackRate(GetScriptState(), playback_rate); worklet_animation->play(exception_state); worklet_animation->UpdateCompositingState(); // Initial current time increased by playback rate. ASSERT_TRUE(worklet_animation->currentTime().has_value()); EXPECT_TIME_NEAR(40, worklet_animation->currentTime().value()); // Update scroll offset. scrollable_area->SetScrollOffset(ScrollOffset(0, 40), mojom::blink::ScrollType::kProgrammatic); // Simulate a new animation frame which allows the timeline to compute new // current time. GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); // Verify that the current time is updated playback_rate faster than the // timeline time. ASSERT_TRUE(worklet_animation->currentTime().has_value()); EXPECT_TIME_NEAR(40 + 20 * playback_rate, worklet_animation->currentTime().value()); } // Verifies correctness of current time when playback rate is set while the // scroll-linked animation is playing. TEST_F(WorkletAnimationTest, DISABLED_ScrollTimelineSetPlaybackRateWhilePlaying) { SetBodyInnerHTML(R"HTML( <style> #scroller { overflow: scroll; width: 100px; height: 100px; } #spacer { width: 200px; height: 200px; } </style> <div id='scroller'> <div id='spacer'></div> </div> )HTML"); auto* scroller = To<LayoutBoxModelObject>(GetLayoutObjectByElementId("scroller")); ASSERT_TRUE(scroller); ASSERT_TRUE(scroller->IsScrollContainer()); PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea(); ASSERT_TRUE(scrollable_area); ScrollTimelineOptions* options = ScrollTimelineOptions::Create(); options->setSource(GetElementById("scroller")); ScrollTimeline* scroll_timeline = ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION); WorkletAnimation* worklet_animation = CreateWorkletAnimation( GetScriptState(), element_, animator_name_, scroll_timeline); double playback_rate = 0.5; // Start the animation. DummyExceptionStateForTesting exception_state; worklet_animation->play(exception_state); worklet_animation->UpdateCompositingState(); // Update scroll offset and playback rate. scrollable_area->SetScrollOffset(ScrollOffset(0, 40), mojom::blink::ScrollType::kProgrammatic); // Simulate a new animation frame which allows the timeline to compute new // current time. GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); worklet_animation->setPlaybackRate(GetScriptState(), playback_rate); // Verify the current time after another scroll offset update. scrollable_area->SetScrollOffset(ScrollOffset(0, 80), mojom::blink::ScrollType::kProgrammatic); GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_TRUE(worklet_animation->currentTime().has_value()); EXPECT_TIME_NEAR(40 + 40 * playback_rate, worklet_animation->currentTime().value()); } // Verifies correcteness of worklet animation start and current time when // inactive timeline becomes active. TEST_F(WorkletAnimationTest, DISABLED_ScrollTimelineNewlyActive) { SetBodyInnerHTML(R"HTML( <style> #scroller { overflow: visible; width: 100px; height: 100px; } #spacer { width: 200px; height: 200px; } </style> <div id='scroller'> <div id='spacer'></div> </div> )HTML"); Element* scroller_element = GetElementById("scroller"); ScrollTimelineOptions* options = ScrollTimelineOptions::Create(); options->setSource(scroller_element); ScrollTimeline* scroll_timeline = ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION); ASSERT_FALSE(scroll_timeline->IsActive()); WorkletAnimation* worklet_animation = CreateWorkletAnimation( GetScriptState(), element_, animator_name_, scroll_timeline); // Start the animation. DummyExceptionStateForTesting exception_state; worklet_animation->play(exception_state); worklet_animation->UpdateCompositingState(); // Scroll timeline is inactive, thus the current and start times are // unresolved. ASSERT_FALSE(worklet_animation->currentTime().has_value()); ASSERT_FALSE(worklet_animation->startTime().has_value()); // Make the timeline active. scroller_element->setAttribute(html_names::kStyleAttr, "overflow:scroll;width:100px;height:100px;"); UpdateAllLifecyclePhasesForTest(); // Simulate a new animation frame which allows the timeline to compute new // current time. GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_TRUE(scroll_timeline->IsActive()); // As the timeline becomes newly active, start and current time must be // initialized to zero. auto current_time = worklet_animation->currentTime(); ASSERT_TRUE(current_time.has_value()); EXPECT_TIME_NEAR(0, current_time.value()); auto start_time = worklet_animation->startTime(); ASSERT_TRUE(start_time.has_value()); EXPECT_TIME_NEAR(0, start_time.value()); } // Verifies correcteness of worklet animation start and current time when // active timeline becomes inactive and then active again. TEST_F(WorkletAnimationTest, DISABLED_ScrollTimelineNewlyInactive) { SetBodyInnerHTML(R"HTML( <style> #scroller { overflow: scroll; width: 100px; height: 100px; } #spacer { width: 200px; height: 200px; } </style> <div id='scroller'> <div id='spacer'></div> </div> )HTML"); Element* scroller_element = GetElementById("scroller"); ScrollTimelineOptions* options = ScrollTimelineOptions::Create(); options->setSource(scroller_element); ScrollTimeline* scroll_timeline = ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION); ASSERT_TRUE(scroll_timeline->IsActive()); auto* scroller = To<LayoutBoxModelObject>(GetLayoutObjectByElementId("scroller")); ASSERT_TRUE(scroller); ASSERT_TRUE(scroller->IsScrollContainer()); PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea(); ASSERT_TRUE(scrollable_area); scrollable_area->SetScrollOffset(ScrollOffset(0, 40), mojom::blink::ScrollType::kProgrammatic); // Simulate a new animation frame which allows the timeline to compute new // current time. GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); WorkletAnimation* worklet_animation = CreateWorkletAnimation( GetScriptState(), element_, animator_name_, scroll_timeline); // Start the animation. DummyExceptionStateForTesting exception_state; worklet_animation->play(exception_state); worklet_animation->UpdateCompositingState(); // Scroll timeline is active, thus the current and start times are resolved. auto current_time = worklet_animation->currentTime(); EXPECT_TRUE(current_time.has_value()); EXPECT_TIME_NEAR(40, current_time.value()); auto start_time = worklet_animation->startTime(); EXPECT_TRUE(start_time.has_value()); EXPECT_TIME_NEAR(0, start_time.value()); // Make the timeline inactive. scroller_element->setAttribute(html_names::kStyleAttr, "overflow:visible;width:100px;height:100px;"); UpdateAllLifecyclePhasesForTest(); GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_FALSE(scroll_timeline->IsActive()); // As the timeline becomes newly inactive, start time must be unresolved and // current time the same as previous current time. start_time = worklet_animation->startTime(); EXPECT_FALSE(start_time.has_value()); current_time = worklet_animation->currentTime(); EXPECT_TRUE(current_time.has_value()); EXPECT_TIME_NEAR(40, current_time.value()); // Make the timeline active again. scroller_element->setAttribute(html_names::kStyleAttr, "overflow:scroll;width:100px;height:100px;"); UpdateAllLifecyclePhasesForTest(); GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now()); ASSERT_TRUE(scroll_timeline->IsActive()); // As the timeline becomes newly active, start time must be recalculated and // current time same as the previous current time. start_time = worklet_animation->startTime(); EXPECT_TRUE(start_time.has_value()); EXPECT_TIME_NEAR(0, start_time.value()); current_time = worklet_animation->currentTime(); EXPECT_TRUE(current_time.has_value()); EXPECT_TIME_NEAR(40, current_time.value()); } } // namespace blink
7,940
418
package tmplatform.authorisation; public class ApiClientLink { }
20
785
<reponame>292427558/iot-dc3<filename>dc3-driver/dc3-driver-mqtt/src/main/java/com/dc3/driver/mqtt/bean/MqttPayload.java /* * Copyright 2016-2021 Pnoker. 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.dc3.driver.mqtt.bean; import com.alibaba.fastjson.JSON; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @author pnoker */ @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class MqttPayload { private DataType dataType = DataType.DEFAULT; private String data; public MqttPayload(DataType dataType, Object target) { this.dataType = dataType; this.data = JSON.toJSONString(target); } @NoArgsConstructor public enum DataType { OPC_UA, OPC_DA, MODBUS, PLC, SERIAL, SOCKET, HEARTBEAT, DEFAULT } }
477
3,897
<reponame>mattbrown015/mbed-os /**************************************************************************** * * Copyright 2020 Samsung Electronics All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * 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 MBED_CMSIS_H #define MBED_CMSIS_H #include "s5js100.h" #include "s5js100_type.h" #include "s5js100_rtos.h" /* s5js100 System Core */ #include "system_s5js100.h" #include "system_core_s5js100.h" /* s5js100 System Clock */ #include "s5js100_cmu.h" #include "s5js100_vclk.h" /* Embedded Flash Driver */ #include "sflash_api.h" /* s5js100 Power */ #include "s5js100_pwr.h" /* NVIC Driver */ #include "cmsis_nvic.h" /* System Core Version */ #include "system_core_version.h" /* HAL implementation */ #include "s5js100_hal.h" #endif
429
383
<gh_stars>100-1000 #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <Mmsystem.h> #ifdef min #undef min #endif // min #ifdef max #undef max #endif // max #include "corelib.h" #include <dinput.h> #include <d3d9.h> #include "dxsdk/Include/d3dx9.h" #include "D3DUtils.h" #include "fpstimer.h" #include "input.h" #include "D9Game.h" #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "Winmm.lib") #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") #include "dxsdk/Include/DxErr.h" #pragma comment(lib, "dxerr.lib")
338
190,993
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/eager/tensor_handle_data.h" #include "tensorflow/core/common_runtime/eager/eager_executor.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/profiler/lib/traceme.h" namespace tensorflow { class Status; Status LocalTensorHandleData::Tensor(const tensorflow::Tensor** t) const { TF_RETURN_IF_ERROR(WaitReady("Tensor")); *t = &tensor_; return Status::OK(); } Status LocalTensorHandleData::TensorValue(tensorflow::TensorValue* t) { TF_RETURN_IF_ERROR(WaitReady("TensorValue")); tensorflow::Tensor& tensor = tensor_; *t = tensorflow::TensorValue(&tensor); return Status::OK(); } Status LocalTensorHandleData::Shape(TensorShape* shape) const { TF_RETURN_IF_ERROR(WaitReady("Shape")); *shape = tensor_.shape(); return Status::OK(); } Status LocalTensorHandleData::NumDims(int* num_dims) const { TF_RETURN_IF_ERROR(WaitReady("NumDims")); *num_dims = tensor_.dims(); return Status::OK(); } Status LocalTensorHandleData::Dim(int dim_index, int64_t* dim) const { TF_RETURN_IF_ERROR(WaitReady("Dim")); *dim = tensor_.dim_size(dim_index); return Status::OK(); } Status LocalTensorHandleData::NumElements(int64_t* num_elements) const { TF_RETURN_IF_ERROR(WaitReady("NumElements")); *num_elements = tensor_.NumElements(); return Status::OK(); } Status LocalTensorHandleData::Unprotect() { if (!IsReady()) { return errors::Internal("Cannot unprotect a non-ready tensor"); } forwarding_protection_tensor_ = tensorflow::Tensor(); return Status::OK(); } Status LocalTensorHandleData::SetTensor(tensorflow::Tensor&& t) { DCHECK(!IsReady()) << "SetTensor is only called on non-ready handles."; tensor_ = std::move(t); // Create copy of original tensor to avoid forwarding forwarding_protection_tensor_ = tensor_; auto& state = absl::get<BlockingControl>(ctrl_); state.SetReady(); return Status::OK(); } string LocalTensorHandleData::DebugString() const { if (IsReady()) { return tensor_.DeviceSafeDebugString(); } else { return "LocalTensorHandleData"; } } void LocalTensorHandleData::BlockingControl::SetReady() { mutex_lock l(mu_); is_ready_ = true; } Status LocalTensorHandleData::BlockingControl::WaitReady( const char* caller) const { tf_shared_lock l(mu_); if (!is_ready_) { profiler::TraceMe activity( [caller] { return absl::StrCat(caller, " WaitReady"); }, profiler::TraceMeLevel::kInfo); DVLOG(3) << "WaitReady: " << caller << " " << this; mu_.Await(Condition(&is_ready_)); } return is_poisoned_; } void LocalTensorHandleData::BlockingControl::Poison(Status status) { mutex_lock l(mu_); if (is_ready_) { LOG(ERROR) << "Poison can only be called on non-ready handle: " << this; return; } is_poisoned_ = status; is_ready_ = true; } } // namespace tensorflow
1,210
8,805
../../../../../node_modules/expo-permissions/ios/EXPermissions/EXCalendarRequester.h
28
1,894
# 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. """Functions for getting commit information from Gitiles.""" from __future__ import print_function from __future__ import division from __future__ import absolute_import from dashboard.services import request _URL = 'https://cr-rev.appspot.com/_ah/api/crrev/v1/' def GetNumbering(number, numbering_identifier, numbering_type, project, repo): params = { 'number': number, 'numbering_identifier': numbering_identifier, 'numbering_type': numbering_type, 'project': project, 'repo': repo } return request.RequestJson(_URL + 'get_numbering', 'GET', **params) def GetCommit(git_sha): return request.RequestJson(_URL + 'commit/%s' % git_sha, 'GET', None)
273
879
package org.zstack.core.gc; import org.zstack.header.message.NeedReplyMessage; /** * Created by mingjian.deng on 2018/12/7. */ public class TriggerGcJobMsg extends NeedReplyMessage { private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
137
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_WEBUI_JS_ERROR_WEBUI_JS_ERROR_UI_H_ #define CHROME_BROWSER_UI_WEBUI_WEBUI_JS_ERROR_WEBUI_JS_ERROR_UI_H_ #include "content/public/browser/web_ui_controller.h" // The WebUI that controls chrome://webuijserror. class WebUIJsErrorUI : public content::WebUIController { public: explicit WebUIJsErrorUI(content::WebUI* web_ui); ~WebUIJsErrorUI() override; WebUIJsErrorUI(const WebUIJsErrorUI&) = delete; WebUIJsErrorUI& operator=(const WebUIJsErrorUI&) = delete; private: WEB_UI_CONTROLLER_TYPE_DECL(); }; #endif // CHROME_BROWSER_UI_WEBUI_WEBUI_JS_ERROR_WEBUI_JS_ERROR_UI_H_
302
623
package com.netease.nim.uikit.common.adapter; import android.view.View; import android.view.ViewGroup; /** */ public abstract class DataFreeViewHolder<T> extends BaseViewHolder<T> { public DataFreeViewHolder(ViewGroup parent, int layoutId) { super(parent, layoutId); } public DataFreeViewHolder(View view) { super(view); } public final void bind(T data) { bindViewHolder(data); } }
172
473
<reponame>pingjuiliao/cb-multios /* Author: <NAME> <<EMAIL>> Copyright (c) 2015 Cromulence LLC 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 __MMU_H__ #define __MMU_H__ #define MMU_PAGE_NOT_ALLOC (0) #define MMU_PAGE_READ (1) #define MMU_PAGE_WRITE (2) #define MMU_PAGE_EXEC (4) #define MMU_PAGE_SIZE (512) #define MMU_PAGE_COUNT ((0x10000)/MMU_PAGE_SIZE) class CMMU { public: CMMU( ); ~CMMU( ); bool AddMemorySection( uint16_t address, uint8_t *pData, uint16_t dataLen, uint8_t mmuFlags ); bool Fetch16( uint16_t address, uint16_t &value ); bool Read16( uint16_t address, uint16_t &value ); bool Write16( uint16_t address, uint16_t value ); bool ReadDMA( uint16_t address, uint8_t *pData, uint16_t amount ); bool WriteDMA( uint16_t address, uint8_t *pData, uint16_t amount ); private: typedef struct MMU_PAGE { uint8_t *pageData; uint8_t mmuFlags; } tMMUPage; tMMUPage m_mmuPages[MMU_PAGE_COUNT]; }; #endif // __MMU_H__
684
3,372
<filename>aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/transform/FindingMarshaller.java<gh_stars>1000+ /* * Copyright 2016-2021 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.services.macie2.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.macie2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * FindingMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class FindingMarshaller { private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("accountId").build(); private static final MarshallingInfo<Boolean> ARCHIVED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("archived").build(); private static final MarshallingInfo<String> CATEGORY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("category").build(); private static final MarshallingInfo<StructuredPojo> CLASSIFICATIONDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("classificationDetails").build(); private static final MarshallingInfo<Long> COUNT_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("count").build(); private static final MarshallingInfo<java.util.Date> CREATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("createdAt").timestampFormat("iso8601").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build(); private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("id").build(); private static final MarshallingInfo<String> PARTITION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("partition").build(); private static final MarshallingInfo<StructuredPojo> POLICYDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("policyDetails").build(); private static final MarshallingInfo<String> REGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("region").build(); private static final MarshallingInfo<StructuredPojo> RESOURCESAFFECTED_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("resourcesAffected").build(); private static final MarshallingInfo<Boolean> SAMPLE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("sample").build(); private static final MarshallingInfo<String> SCHEMAVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("schemaVersion").build(); private static final MarshallingInfo<StructuredPojo> SEVERITY_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("severity").build(); private static final MarshallingInfo<String> TITLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("title").build(); private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("type").build(); private static final MarshallingInfo<java.util.Date> UPDATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("updatedAt").timestampFormat("iso8601").build(); private static final FindingMarshaller instance = new FindingMarshaller(); public static FindingMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Finding finding, ProtocolMarshaller protocolMarshaller) { if (finding == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(finding.getAccountId(), ACCOUNTID_BINDING); protocolMarshaller.marshall(finding.getArchived(), ARCHIVED_BINDING); protocolMarshaller.marshall(finding.getCategory(), CATEGORY_BINDING); protocolMarshaller.marshall(finding.getClassificationDetails(), CLASSIFICATIONDETAILS_BINDING); protocolMarshaller.marshall(finding.getCount(), COUNT_BINDING); protocolMarshaller.marshall(finding.getCreatedAt(), CREATEDAT_BINDING); protocolMarshaller.marshall(finding.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(finding.getId(), ID_BINDING); protocolMarshaller.marshall(finding.getPartition(), PARTITION_BINDING); protocolMarshaller.marshall(finding.getPolicyDetails(), POLICYDETAILS_BINDING); protocolMarshaller.marshall(finding.getRegion(), REGION_BINDING); protocolMarshaller.marshall(finding.getResourcesAffected(), RESOURCESAFFECTED_BINDING); protocolMarshaller.marshall(finding.getSample(), SAMPLE_BINDING); protocolMarshaller.marshall(finding.getSchemaVersion(), SCHEMAVERSION_BINDING); protocolMarshaller.marshall(finding.getSeverity(), SEVERITY_BINDING); protocolMarshaller.marshall(finding.getTitle(), TITLE_BINDING); protocolMarshaller.marshall(finding.getType(), TYPE_BINDING); protocolMarshaller.marshall(finding.getUpdatedAt(), UPDATEDAT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
2,512
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.dataprotection.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** Base class for feature object. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType") @JsonTypeName("FeatureValidationRequest") @Fluent public final class FeatureValidationRequest extends FeatureValidationRequestBase { @JsonIgnore private final ClientLogger logger = new ClientLogger(FeatureValidationRequest.class); /* * backup support feature type. */ @JsonProperty(value = "featureType") private FeatureType featureType; /* * backup support feature name. */ @JsonProperty(value = "featureName") private String featureName; /** * Get the featureType property: backup support feature type. * * @return the featureType value. */ public FeatureType featureType() { return this.featureType; } /** * Set the featureType property: backup support feature type. * * @param featureType the featureType value to set. * @return the FeatureValidationRequest object itself. */ public FeatureValidationRequest withFeatureType(FeatureType featureType) { this.featureType = featureType; return this; } /** * Get the featureName property: backup support feature name. * * @return the featureName value. */ public String featureName() { return this.featureName; } /** * Set the featureName property: backup support feature name. * * @param featureName the featureName value to set. * @return the FeatureValidationRequest object itself. */ public FeatureValidationRequest withFeatureName(String featureName) { this.featureName = featureName; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); } }
833
407
package com.alibaba.tesla.appmanager.trait.plugin; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.tesla.appmanager.common.constants.DefaultConstant; import com.alibaba.tesla.appmanager.domain.core.WorkloadResource; import com.alibaba.tesla.appmanager.domain.req.kubectl.KubectlApplyReq; import com.alibaba.tesla.appmanager.domain.schema.TraitDefinition; import com.alibaba.tesla.appmanager.kubernetes.sevice.kubectl.KubectlService; import com.alibaba.tesla.appmanager.spring.util.SpringBeanUtil; import com.alibaba.tesla.appmanager.trait.BaseTrait; import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; @Slf4j public class IntegrateTrait extends BaseTrait { public IntegrateTrait(String name, TraitDefinition traitDefinition, JSONObject spec, WorkloadResource ref) { super(name, traitDefinition, spec, ref); } @Override public void execute() { JSONObject spec = getSpec(); JSONObject content = spec.getJSONObject("content"); JSONArray others = spec.getJSONArray("others"); JSONObject workloadSpec = (JSONObject)getWorkloadRef().getSpec(); mergeJsonObject(workloadSpec, content); applyOthers(others); log.info("IntegrateTrait workloadSpec: \n" + JSONObject.toJSONString(workloadSpec, true) + "\n others: \n" + JSONObject.toJSONString(others, true)); } private void mergeJsonArray(JSONArray j1, JSONArray j2) { try { for (int i = 0; i < j1.size(); i++) { Object v1 = j1.get(i); Object v2 = j2.get(i); mergeJsonObject((JSONObject)v1, (JSONObject)v2); } for (int i = 0; i < j2.size(); i++) { if (i >= j1.size()) { j1.add(j2.get(i)); } } } catch (Exception ignored) { } } private void mergeJsonObject(JSONObject j1, JSONObject j2) { if (CollectionUtils.isEmpty(j2)) { return; } for (String key : j1.keySet()) { if (j2.containsKey(key)) { Object v1 = JSON.toJSON(j1.get(key)); Object v2 = JSON.toJSON(j2.get(key)); if (v1 instanceof JSONObject && v2 instanceof JSONObject) { mergeJsonObject((JSONObject)v1, (JSONObject)v2); } else if (v1 instanceof JSONArray && v2 instanceof JSONArray) { mergeJsonArray((JSONArray)v1, (JSONArray)v2); } else { j1.put(key, v2); } } } for (String key : j2.keySet()) { if (!j1.containsKey(key)) { j1.put(key, j2.get(key)); } } } private void applyOthers(JSONArray others) { if (CollectionUtils.isEmpty(others)) { return; } KubectlService kubectlService = SpringBeanUtil.getBean(KubectlService.class); for (JSONObject other : others.toJavaList(JSONObject.class)) { kubectlService.apply( KubectlApplyReq.builder() .clusterId("master") .namespaceId("default") .content(other) .build(), DefaultConstant.SYSTEM_OPERATOR); } } }
1,658
1,647
<reponame>davidbrochart/pythran<gh_stars>1000+ #ifndef PYTHONIC_NUMPY_INTP_HPP #define PYTHONIC_NUMPY_INTP_HPP #include "pythonic/include/numpy/intp.hpp" #include "pythonic/utils/functor.hpp" #include "pythonic/utils/meta.hpp" #include "pythonic/utils/numpy_traits.hpp" #include "pythonic/types/numpy_op_helper.hpp" PYTHONIC_NS_BEGIN namespace numpy { namespace details { intptr_t intp() { return intptr_t(); } template <class V> intptr_t intp(V v) { return v; } } #define NUMPY_NARY_FUNC_NAME intp #define NUMPY_NARY_FUNC_SYM details::intp #include "pythonic/types/numpy_nary_expr.hpp" } PYTHONIC_NS_END #endif
323
514
/* 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.flowable.common.sql; import java.io.File; import java.io.StringWriter; import java.util.Scanner; import org.apache.commons.io.FileUtils; import liquibase.Liquibase; import liquibase.database.Database; public class SqlScriptUtil { public static void generateUpgradeSqlFile(Liquibase liquibase, Database database, String version, String engine) throws Exception { StringWriter stringWriter = new StringWriter(); liquibase.update(engine, stringWriter); stringWriter.close(); String sqlScript = filterOutComments(stringWriter.toString()); sqlScript = filterOutDatabaseNamePrefix(sqlScript); FileUtils.write(new File("../sql/upgrade/" + engine, "flowable." + getDatabaseName(database) + ".upgradestep." + version + "." + engine + ".sql"), sqlScript, "utf-8"); liquibase.update(engine); } public static void generateCreateSqlFile(Liquibase liquibase, Database database, String engine) throws Exception { StringWriter stringWriter = new StringWriter(); liquibase.update(engine, stringWriter); stringWriter.close(); String sqlScript = SqlScriptUtil.filterOutComments(stringWriter.toString()); sqlScript = SqlScriptUtil.filterOutDatabaseNamePrefix(sqlScript); FileUtils.write(new File("../sql/create/" + engine, "flowable." + getDatabaseName(database) + "." + engine + "-engine.create.sql"), sqlScript, "utf-8"); liquibase.update(engine); } public static String filterOutComments(String sql) { StringBuilder result = new StringBuilder(); Scanner scanner = new Scanner(sql); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (!line.startsWith("--") && !line.startsWith("GO") && !line.startsWith("USE") && !line.startsWith("SET DEFINE OFF")) { result.append(line); result.append(System.lineSeparator()); } } scanner.close(); String s = result.toString(); s = s.trim(); if (s.equals("SET DEFINE OFF;")) { // Oracle return ""; } return result.toString(); } public static String filterOutDatabaseNamePrefix(String sql) { String tempSql = sql.replaceAll("flowableliquibase.", ""); tempSql = tempSql.replaceAll("FLOWABLELIQUIBASE.", ""); tempSql = tempSql.replaceAll("public.", ""); tempSql = tempSql.replaceAll("PUBLIC.", ""); tempSql = tempSql.replaceAll("DB2INST1.", ""); tempSql = tempSql.replaceAll("\\[dbo\\].", ""); return tempSql; } public static String getDatabaseName(Database database) { String dbName = database.getDatabaseProductName().toLowerCase(); if ("postgresql".equals(dbName)) { dbName = "postgres"; } else if (dbName.contains("db2")) { dbName = "db2"; } else if ("microsoft sql server".equals(dbName)) { dbName = "mssql"; } return dbName; } }
1,352
11,356
<filename>src/external/boost/boost_1_68_0/libs/contract/example/features/separate_body.cpp // Copyright (C) 2008-2018 <NAME> // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html #include "separate_body.hpp" #include <cassert> //[separate_body_cpp void iarray::constructor_body(unsigned max, unsigned count) { for(unsigned i = 0; i < count; ++i) values_[i] = int(); size_ = count; } void iarray::destructor_body() { delete[] values_; } void iarray::push_back_body(int value) { values_[size_++] = value; } /* ... */ //] unsigned iarray::capacity_body() const { return capacity_; } unsigned iarray::size_body() const { return size_; } int main() { iarray a(3, 2); assert(a.capacity() == 3); assert(a.size() == 2); a.push_back(-123); assert(a.size() == 3); return 0; }
375
416
// // HKObserverQuery.h // HealthKit // // Copyright (c) 2014 Apple Inc. All rights reserved. // #import <HealthKit/HKQuery.h> NS_ASSUME_NONNULL_BEGIN typedef void(^HKObserverQueryCompletionHandler)(void); HK_EXTERN API_AVAILABLE(ios(8.0), watchos(2.0)) @interface HKObserverQuery : HKQuery /*! @method initWithSampleType:predicate:updateHandler: @abstract This method installs a handler that is called when a sample type has a new sample added. @discussion If you have subscribed to background updates you must call the passed completion block once you have processed data from this notification. Otherwise the system will continue to notify you of this data. */ - (instancetype)initWithSampleType:(HKSampleType *)sampleType predicate:(nullable NSPredicate *)predicate updateHandler:(void(^)(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError * _Nullable error))updateHandler; @end NS_ASSUME_NONNULL_END
379
10,225
package io.quarkus.grpc.health; import static io.restassured.RestAssured.when; import static java.util.Arrays.asList; import static java.util.function.Predicate.isEqual; import static org.awaitility.Awaitility.await; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.function.Function; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.hamcrest.Matchers; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import grpc.health.v1.HealthGrpc; import grpc.health.v1.HealthOuterClass; import grpc.health.v1.HealthOuterClass.HealthCheckResponse.ServingStatus; import grpc.health.v1.MutinyHealthGrpc; import io.grpc.BindableService; import io.grpc.ServerServiceDefinition; import io.quarkus.grpc.GrpcClient; import io.quarkus.grpc.GrpcService; import io.quarkus.test.QuarkusUnitTest; import io.smallrye.mutiny.Multi; /* * MP Health info for gRPC looks as follows (the data section contains entries for each of the available services): * { "status": "UP", "checks": [ { "name": "gRPC Server", "status": "UP", "data": { "grpc.health.v1.Health": true } } ] } */ public class MicroProfileHealthEnabledTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setFlatClassPath(true) .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addPackage(HealthGrpc.class.getPackage()) .addClass(FakeService.class)) .withConfigurationResource("health-config.properties"); @Inject HealthConsumer healthConsumer; @Test public void shouldNotFailMpHealthCheckOnGettingUnknownServiceStatus() { checkHealthOk(); askForHealthOfUnknownService(); checkHealthOk(); } private void checkHealthOk() { // @formatter:off when() .get("/q/health") .then() .statusCode(200) .body("checks[0].name", Matchers.equalTo("gRPC Server")) .body("checks[0].status", Matchers.equalTo("UP")) .body("checks[0].data['grpc.health.v1.Health']", Matchers.equalTo(true)) .body("checks[0].data.size()", Matchers.equalTo(2)); // @formatter:on } private void askForHealthOfUnknownService() { String serviceName = "customService2"; List<ServingStatus> statusList = new CopyOnWriteArrayList<>(); gatherStatusesToList(serviceName, statusList); // to check if the unknown was delivered and we are attached awaitExactStatusList(statusList, ServingStatus.UNKNOWN); } private void gatherStatusesToList(String serviceName, List<ServingStatus> statusList1) { healthConsumer.getStatusStream(builder -> builder.setService(serviceName)) .map(HealthOuterClass.HealthCheckResponse::getStatus).subscribe().with(statusList1::add); } private void awaitExactStatusList(List<ServingStatus> statusList, ServingStatus... statuses) { await("list to be contain exactly " + Arrays.toString(statuses)).atMost(2, TimeUnit.SECONDS) .until(() -> statusList, isEqual(asList(statuses))); } @ApplicationScoped static class HealthConsumer { @GrpcClient("health-service") MutinyHealthGrpc.MutinyHealthStub healthMutiny; public Multi<HealthOuterClass.HealthCheckResponse> getStatusStream( Function<HealthOuterClass.HealthCheckRequest.Builder, HealthOuterClass.HealthCheckRequest.Builder> decorator) { HealthOuterClass.HealthCheckRequest.Builder builder = decorator .apply(HealthOuterClass.HealthCheckRequest.newBuilder()); return healthMutiny.watch(builder.build()); } } @GrpcService public static class FakeService implements BindableService { @Override public ServerServiceDefinition bindService() { return ServerServiceDefinition.builder("fake").build(); } } }
1,761
6,989
<filename>catboost/cuda/cuda_util/partitions.h #pragma once #include <catboost/cuda/cuda_lib/fwd.h> struct TDataPartition; template <class TMapping> void UpdatePartitionDimensions( const NCudaLib::TCudaBuffer<ui32, TMapping>& sortedBins, NCudaLib::TCudaBuffer<TDataPartition, TMapping>& parts, ui32 stream = 0); template <class TMapping> void UpdatePartitionOffsets( const NCudaLib::TCudaBuffer<ui32, TMapping>& sortedBins, NCudaLib::TCudaBuffer<ui32, TMapping>& offsets, ui32 stream = 0); template <class TMapping, class TUi32, NCudaLib::EPtrType DstPtr> void ComputeSegmentSizes( const NCudaLib::TCudaBuffer<TUi32, TMapping>& offsets, NCudaLib::TCudaBuffer<float, TMapping, DstPtr>& dst, ui32 stream = 0); // //template <class TMapping> //inline void WriteInitPartitions(const TMapping& objectsMapping, TCudaBuffer<TDataPartition, TMapping>& parts) { // // const int devId = GetSingleDevId(objectsMapping); // const TDataPartition initialPart(0, objectsMapping->SizeAt(devId)); // TVector<TDataPartition> partitioningInitial; // partitioningInitial.push_back(initialPart); // parts.Write(partitioningInitial); //}
433
308
/* * Copyright(c) 2018 Intel Corporation * SPDX - License - Identifier: BSD - 2 - Clause - Patent */ #include <stdlib.h> #include <string.h> #include "EbPictureBufferDesc.h" #include "EbReferenceObject.h" void EbHevcInitializeSamplesNeighboringReferencePicture16Bit( EB_BYTE reconSamplesBufferPtr, EB_U16 stride, EB_U16 reconWidth, EB_U16 reconHeight, EB_U16 leftPadding, EB_U16 topPadding) { EB_U16 *reconSamplesPtr; EB_U16 sampleCount; // 1. Zero out the top row reconSamplesPtr = (EB_U16*)reconSamplesBufferPtr + (topPadding - 1) * stride + leftPadding - 1; EB_MEMSET((EB_U8*)reconSamplesPtr, 0, sizeof(EB_U16)*(1 + reconWidth + 1)); // 2. Zero out the bottom row reconSamplesPtr = (EB_U16*)reconSamplesBufferPtr + (topPadding + reconHeight) * stride + leftPadding - 1; EB_MEMSET((EB_U8*)reconSamplesPtr, 0, sizeof(EB_U16)*(1 + reconWidth + 1)); // 3. Zero out the left column reconSamplesPtr = (EB_U16*)reconSamplesBufferPtr + topPadding * stride + leftPadding - 1; for (sampleCount = 0; sampleCount < reconHeight; sampleCount++) { reconSamplesPtr[sampleCount * stride] = 0; } // 4. Zero out the right column reconSamplesPtr = (EB_U16*)reconSamplesBufferPtr + topPadding * stride + leftPadding + reconWidth; for (sampleCount = 0; sampleCount < reconHeight; sampleCount++) { reconSamplesPtr[sampleCount * stride] = 0; } } void EbHevcInitializeSamplesNeighboringReferencePicture8Bit( EB_BYTE reconSamplesBufferPtr, EB_U16 stride, EB_U16 reconWidth, EB_U16 reconHeight, EB_U16 leftPadding, EB_U16 topPadding) { EB_U8 *reconSamplesPtr; EB_U16 sampleCount; // 1. Zero out the top row reconSamplesPtr = reconSamplesBufferPtr + (topPadding - 1) * stride + leftPadding - 1; EB_MEMSET(reconSamplesPtr, 0, sizeof(EB_U8)*(1 + reconWidth + 1)); // 2. Zero out the bottom row reconSamplesPtr = reconSamplesBufferPtr + (topPadding + reconHeight) * stride + leftPadding - 1; EB_MEMSET(reconSamplesPtr, 0, sizeof(EB_U8)*(1 + reconWidth + 1)); // 3. Zero out the left column reconSamplesPtr = reconSamplesBufferPtr + topPadding * stride + leftPadding - 1; for (sampleCount = 0; sampleCount < reconHeight; sampleCount++) { reconSamplesPtr[sampleCount * stride] = 0; } // 4. Zero out the right column reconSamplesPtr = reconSamplesBufferPtr + topPadding * stride + leftPadding + reconWidth; for (sampleCount = 0; sampleCount < reconHeight; sampleCount++) { reconSamplesPtr[sampleCount * stride] = 0; } } void EbHevcInitializeSamplesNeighboringReferencePicture( EbReferenceObject_t *referenceObject, EbPictureBufferDescInitData_t *pictureBufferDescInitDataPtr, EB_BITDEPTH bitDepth) { if (bitDepth == EB_10BIT){ EbHevcInitializeSamplesNeighboringReferencePicture16Bit( referenceObject->referencePicture16bit->bufferY, referenceObject->referencePicture16bit->strideY, referenceObject->referencePicture16bit->width, referenceObject->referencePicture16bit->height, pictureBufferDescInitDataPtr->leftPadding, pictureBufferDescInitDataPtr->topPadding); EbHevcInitializeSamplesNeighboringReferencePicture16Bit( referenceObject->referencePicture16bit->bufferCb, referenceObject->referencePicture16bit->strideCb, referenceObject->referencePicture16bit->width >> 1, referenceObject->referencePicture16bit->height >> 1, pictureBufferDescInitDataPtr->leftPadding >> 1, pictureBufferDescInitDataPtr->topPadding >> 1); EbHevcInitializeSamplesNeighboringReferencePicture16Bit( referenceObject->referencePicture16bit->bufferCr, referenceObject->referencePicture16bit->strideCr, referenceObject->referencePicture16bit->width >> 1, referenceObject->referencePicture16bit->height >> 1, pictureBufferDescInitDataPtr->leftPadding >> 1, pictureBufferDescInitDataPtr->topPadding >> 1); } else { EbHevcInitializeSamplesNeighboringReferencePicture8Bit( referenceObject->referencePicture->bufferY, referenceObject->referencePicture->strideY, referenceObject->referencePicture->width, referenceObject->referencePicture->height, pictureBufferDescInitDataPtr->leftPadding, pictureBufferDescInitDataPtr->topPadding); EbHevcInitializeSamplesNeighboringReferencePicture8Bit( referenceObject->referencePicture->bufferCb, referenceObject->referencePicture->strideCb, referenceObject->referencePicture->width >> 1, referenceObject->referencePicture->height >> 1, pictureBufferDescInitDataPtr->leftPadding >> 1, pictureBufferDescInitDataPtr->topPadding >> 1); EbHevcInitializeSamplesNeighboringReferencePicture8Bit( referenceObject->referencePicture->bufferCr, referenceObject->referencePicture->strideCr, referenceObject->referencePicture->width >> 1, referenceObject->referencePicture->height >> 1, pictureBufferDescInitDataPtr->leftPadding >> 1, pictureBufferDescInitDataPtr->topPadding >> 1); } } static void EbReferenceObjectDctor(EB_PTR p) { EbReferenceObject_t *obj = (EbReferenceObject_t*)p; EB_DELETE(obj->refDenSrcPicture); EB_FREE_ARRAY(obj->tmvpMap); EB_DELETE(obj->referencePicture); EB_DELETE(obj->referencePicture16bit); } /***************************************** * EbPictureBufferDescCtor * Initializes the Buffer Descriptor's * values that are fixed for the life of * the descriptor. *****************************************/ EB_ERRORTYPE EbReferenceObjectCtor( EbReferenceObject_t *referenceObject, EB_PTR objectInitDataPtr) { EbPictureBufferDescInitData_t *pictureBufferDescInitDataPtr = (EbPictureBufferDescInitData_t*) objectInitDataPtr; EbPictureBufferDescInitData_t pictureBufferDescInitData16BitPtr = *pictureBufferDescInitDataPtr; referenceObject->dctor = EbReferenceObjectDctor; if (pictureBufferDescInitData16BitPtr.bitDepth == EB_10BIT){ EB_NEW( referenceObject->referencePicture16bit, EbPictureBufferDescCtor, (EB_PTR)&pictureBufferDescInitData16BitPtr); EbHevcInitializeSamplesNeighboringReferencePicture( referenceObject, &pictureBufferDescInitData16BitPtr, pictureBufferDescInitData16BitPtr.bitDepth); } else{ EB_NEW( referenceObject->referencePicture, EbPictureBufferDescCtor, (EB_PTR)pictureBufferDescInitDataPtr); EbHevcInitializeSamplesNeighboringReferencePicture( referenceObject, pictureBufferDescInitDataPtr, pictureBufferDescInitData16BitPtr.bitDepth); } // Allocate LCU based TMVP map EB_MALLOC_ARRAY(referenceObject->tmvpMap, ((pictureBufferDescInitDataPtr->maxWidth + (64 - 1)) >> 6) * ((pictureBufferDescInitDataPtr->maxHeight + (64 - 1)) >> 6)); //RESTRICT THIS TO M4 { EbPictureBufferDescInitData_t bufDesc; bufDesc.maxWidth = pictureBufferDescInitDataPtr->maxWidth; bufDesc.maxHeight = pictureBufferDescInitDataPtr->maxHeight; bufDesc.bitDepth = EB_8BIT; bufDesc.bufferEnableMask = PICTURE_BUFFER_DESC_FULL_MASK; bufDesc.leftPadding = pictureBufferDescInitDataPtr->leftPadding; bufDesc.rightPadding = pictureBufferDescInitDataPtr->rightPadding; bufDesc.topPadding = pictureBufferDescInitDataPtr->topPadding; bufDesc.botPadding = pictureBufferDescInitDataPtr->botPadding; bufDesc.splitMode = 0; bufDesc.colorFormat = pictureBufferDescInitDataPtr->colorFormat; EB_NEW( referenceObject->refDenSrcPicture, EbPictureBufferDescCtor, (EB_PTR)&bufDesc); } return EB_ErrorNone; } EB_ERRORTYPE EbReferenceObjectCreator( EB_PTR *objectDblPtr, EB_PTR objectInitDataPtr) { EbReferenceObject_t* obj; *objectDblPtr = NULL; EB_NEW(obj, EbReferenceObjectCtor, objectInitDataPtr); *objectDblPtr = obj; return EB_ErrorNone; } static void EbPaReferenceObjectDctor(EB_PTR p) { EbPaReferenceObject_t* obj = (EbPaReferenceObject_t*)p; EB_DELETE(obj->inputPaddedPicturePtr); EB_DELETE(obj->quarterDecimatedPicturePtr); EB_DELETE(obj->sixteenthDecimatedPicturePtr); } /***************************************** * EbPaReferenceObjectCtor * Initializes the Buffer Descriptor's * values that are fixed for the life of * the descriptor. *****************************************/ EB_ERRORTYPE EbPaReferenceObjectCtor( EbPaReferenceObject_t *paReferenceObject, EB_PTR objectInitDataPtr) { EbPictureBufferDescInitData_t *pictureBufferDescInitDataPtr = (EbPictureBufferDescInitData_t*)objectInitDataPtr; paReferenceObject->dctor = EbPaReferenceObjectDctor; // Reference picture constructor EB_NEW( paReferenceObject->inputPaddedPicturePtr, EbPictureBufferDescCtor, (EB_PTR)pictureBufferDescInitDataPtr); // Quarter Decim reference picture constructor EB_NEW( paReferenceObject->quarterDecimatedPicturePtr, EbPictureBufferDescCtor, (EB_PTR)(pictureBufferDescInitDataPtr + 1)); // Sixteenth Decim reference picture constructor EB_NEW( paReferenceObject->sixteenthDecimatedPicturePtr, EbPictureBufferDescCtor, (EB_PTR)(pictureBufferDescInitDataPtr + 2)); return EB_ErrorNone; } EB_ERRORTYPE EbPaReferenceObjectCreator( EB_PTR *objectDblPtr, EB_PTR objectInitDataPtr) { EbPaReferenceObject_t* obj; *objectDblPtr = NULL; EB_NEW(obj, EbPaReferenceObjectCtor, objectInitDataPtr); *objectDblPtr = obj; return EB_ErrorNone; }
3,944
2,061
<filename>backend/x11/backend.c #define _POSIX_C_SOURCE 200809L #include <assert.h> #include <fcntl.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <xf86drm.h> #include <wlr/config.h> #include <drm_fourcc.h> #include <wayland-server-core.h> #include <xcb/xcb.h> #include <xcb/dri3.h> #include <xcb/present.h> #include <xcb/render.h> #include <xcb/shm.h> #include <xcb/xcb_renderutil.h> #include <xcb/xfixes.h> #include <xcb/xinput.h> #include <wlr/backend/interface.h> #include <wlr/backend/x11.h> #include <wlr/interfaces/wlr_input_device.h> #include <wlr/interfaces/wlr_keyboard.h> #include <wlr/interfaces/wlr_pointer.h> #include <wlr/util/log.h> #include "backend/x11.h" #include "render/drm_format_set.h" #include "util/signal.h" // See dri2_format_for_depth in mesa const struct wlr_x11_format formats[] = { { .drm = DRM_FORMAT_XRGB8888, .depth = 24, .bpp = 32 }, { .drm = DRM_FORMAT_ARGB8888, .depth = 32, .bpp = 32 }, }; static const struct wlr_x11_format *x11_format_from_depth(uint8_t depth) { for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) { if (formats[i].depth == depth) { return &formats[i]; } } return NULL; } struct wlr_x11_output *get_x11_output_from_window_id( struct wlr_x11_backend *x11, xcb_window_t window) { struct wlr_x11_output *output; wl_list_for_each(output, &x11->outputs, link) { if (output->win == window) { return output; } } return NULL; } static void handle_x11_error(struct wlr_x11_backend *x11, xcb_value_error_t *ev); static void handle_x11_unknown_event(struct wlr_x11_backend *x11, xcb_generic_event_t *ev); static void handle_x11_event(struct wlr_x11_backend *x11, xcb_generic_event_t *event) { switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { case XCB_EXPOSE: { xcb_expose_event_t *ev = (xcb_expose_event_t *)event; struct wlr_x11_output *output = get_x11_output_from_window_id(x11, ev->window); if (output != NULL) { pixman_region32_union_rect( &output->exposed, &output->exposed, ev->x, ev->y, ev->width, ev->height); wlr_output_update_needs_frame(&output->wlr_output); } break; } case XCB_CONFIGURE_NOTIFY: { xcb_configure_notify_event_t *ev = (xcb_configure_notify_event_t *)event; struct wlr_x11_output *output = get_x11_output_from_window_id(x11, ev->window); if (output != NULL) { handle_x11_configure_notify(output, ev); } break; } case XCB_CLIENT_MESSAGE: { xcb_client_message_event_t *ev = (xcb_client_message_event_t *)event; if (ev->data.data32[0] == x11->atoms.wm_delete_window) { struct wlr_x11_output *output = get_x11_output_from_window_id(x11, ev->window); if (output != NULL) { wlr_output_destroy(&output->wlr_output); } } else { wlr_log(WLR_DEBUG, "Unhandled client message %"PRIu32, ev->data.data32[0]); } break; } case XCB_GE_GENERIC: { xcb_ge_generic_event_t *ev = (xcb_ge_generic_event_t *)event; if (ev->extension == x11->xinput_opcode) { handle_x11_xinput_event(x11, ev); } else if (ev->extension == x11->present_opcode) { handle_x11_present_event(x11, ev); } else { handle_x11_unknown_event(x11, event); } break; } case 0: { xcb_value_error_t *ev = (xcb_value_error_t *)event; handle_x11_error(x11, ev); break; } case XCB_UNMAP_NOTIFY: case XCB_MAP_NOTIFY: break; default: handle_x11_unknown_event(x11, event); break; } } static int x11_event(int fd, uint32_t mask, void *data) { struct wlr_x11_backend *x11 = data; if ((mask & WL_EVENT_HANGUP) || (mask & WL_EVENT_ERROR)) { if (mask & WL_EVENT_ERROR) { wlr_log(WLR_ERROR, "Failed to read from X11 server"); } wl_display_terminate(x11->wl_display); return 0; } xcb_generic_event_t *e; while ((e = xcb_poll_for_event(x11->xcb))) { handle_x11_event(x11, e); free(e); } int ret = xcb_connection_has_error(x11->xcb); if (ret != 0) { wlr_log(WLR_ERROR, "X11 connection error (%d)", ret); wl_display_terminate(x11->wl_display); } return 0; } struct wlr_x11_backend *get_x11_backend_from_backend( struct wlr_backend *wlr_backend) { assert(wlr_backend_is_x11(wlr_backend)); return (struct wlr_x11_backend *)wlr_backend; } static bool backend_start(struct wlr_backend *backend) { struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); x11->started = true; wlr_log(WLR_INFO, "Starting X11 backend"); wlr_signal_emit_safe(&x11->backend.events.new_input, &x11->keyboard_dev); for (size_t i = 0; i < x11->requested_outputs; ++i) { wlr_x11_output_create(&x11->backend); } return true; } static void backend_destroy(struct wlr_backend *backend) { if (!backend) { return; } struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); struct wlr_x11_output *output, *tmp; wl_list_for_each_safe(output, tmp, &x11->outputs, link) { wlr_output_destroy(&output->wlr_output); } wlr_input_device_destroy(&x11->keyboard_dev); wlr_backend_finish(backend); if (x11->event_source) { wl_event_source_remove(x11->event_source); } wl_list_remove(&x11->display_destroy.link); wlr_drm_format_set_finish(&x11->primary_dri3_formats); wlr_drm_format_set_finish(&x11->primary_shm_formats); wlr_drm_format_set_finish(&x11->dri3_formats); wlr_drm_format_set_finish(&x11->shm_formats); #if HAS_XCB_ERRORS xcb_errors_context_free(x11->errors_context); #endif close(x11->drm_fd); xcb_disconnect(x11->xcb); free(x11); } static int backend_get_drm_fd(struct wlr_backend *backend) { struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); return x11->drm_fd; } static uint32_t get_buffer_caps(struct wlr_backend *backend) { struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); return (x11->have_dri3 ? WLR_BUFFER_CAP_DMABUF : 0) | (x11->have_shm ? WLR_BUFFER_CAP_SHM : 0); } static const struct wlr_backend_impl backend_impl = { .start = backend_start, .destroy = backend_destroy, .get_drm_fd = backend_get_drm_fd, .get_buffer_caps = get_buffer_caps, }; bool wlr_backend_is_x11(struct wlr_backend *backend) { return backend->impl == &backend_impl; } static void handle_display_destroy(struct wl_listener *listener, void *data) { struct wlr_x11_backend *x11 = wl_container_of(listener, x11, display_destroy); backend_destroy(&x11->backend); } static xcb_depth_t *get_depth(xcb_screen_t *screen, uint8_t depth) { xcb_depth_iterator_t iter = xcb_screen_allowed_depths_iterator(screen); while (iter.rem > 0) { if (iter.data->depth == depth) { return iter.data; } xcb_depth_next(&iter); } return NULL; } static xcb_visualid_t pick_visualid(xcb_depth_t *depth) { xcb_visualtype_t *visuals = xcb_depth_visuals(depth); for (int i = 0; i < xcb_depth_visuals_length(depth); i++) { if (visuals[i]._class == XCB_VISUAL_CLASS_TRUE_COLOR) { return visuals[i].visual_id; } } return 0; } static int query_dri3_drm_fd(struct wlr_x11_backend *x11) { xcb_dri3_open_cookie_t open_cookie = xcb_dri3_open(x11->xcb, x11->screen->root, 0); xcb_dri3_open_reply_t *open_reply = xcb_dri3_open_reply(x11->xcb, open_cookie, NULL); if (open_reply == NULL) { return -1; } int *open_fds = xcb_dri3_open_reply_fds(x11->xcb, open_reply); if (open_fds == NULL) { free(open_reply); return -1; } assert(open_reply->nfd == 1); int drm_fd = open_fds[0]; free(open_reply); int flags = fcntl(drm_fd, F_GETFD); if (flags < 0) { close(drm_fd); return -1; } if (fcntl(drm_fd, F_SETFD, flags | FD_CLOEXEC) < 0) { close(drm_fd); return -1; } if (drmGetNodeTypeFromFd(drm_fd) != DRM_NODE_RENDER) { char *render_name = drmGetRenderDeviceNameFromFd(drm_fd); if (render_name == NULL) { close(drm_fd); return -1; } close(drm_fd); drm_fd = open(render_name, O_RDWR | O_CLOEXEC); if (drm_fd < 0) { free(render_name); return -1; } free(render_name); } return drm_fd; } static bool query_dri3_modifiers(struct wlr_x11_backend *x11, const struct wlr_x11_format *format) { if (x11->dri3_major_version == 1 && x11->dri3_minor_version < 2) { return true; // GetSupportedModifiers requires DRI3 1.2 } // Query the root window's supported modifiers, because we only care about // screen_modifiers for now xcb_dri3_get_supported_modifiers_cookie_t modifiers_cookie = xcb_dri3_get_supported_modifiers(x11->xcb, x11->screen->root, format->depth, format->bpp); xcb_dri3_get_supported_modifiers_reply_t *modifiers_reply = xcb_dri3_get_supported_modifiers_reply(x11->xcb, modifiers_cookie, NULL); if (!modifiers_reply) { wlr_log(WLR_ERROR, "Failed to get DMA-BUF modifiers supported by " "the X11 server for the format 0x%"PRIX32, format->drm); return false; } // If modifiers aren't supported, DRI3 will return an empty list const uint64_t *modifiers = xcb_dri3_get_supported_modifiers_screen_modifiers(modifiers_reply); int modifiers_len = xcb_dri3_get_supported_modifiers_screen_modifiers_length(modifiers_reply); for (int i = 0; i < modifiers_len; i++) { wlr_drm_format_set_add(&x11->dri3_formats, format->drm, modifiers[i]); } free(modifiers_reply); return true; } static bool query_formats(struct wlr_x11_backend *x11) { xcb_depth_iterator_t iter = xcb_screen_allowed_depths_iterator(x11->screen); while (iter.rem > 0) { uint8_t depth = iter.data->depth; const struct wlr_x11_format *format = x11_format_from_depth(depth); if (format != NULL) { if (x11->have_shm) { wlr_drm_format_set_add(&x11->shm_formats, format->drm, DRM_FORMAT_MOD_INVALID); } if (x11->have_dri3) { wlr_drm_format_set_add(&x11->dri3_formats, format->drm, DRM_FORMAT_MOD_INVALID); if (!query_dri3_modifiers(x11, format)) { return false; } } } xcb_depth_next(&iter); } return true; } static void x11_get_argb32(struct wlr_x11_backend *x11) { xcb_render_query_pict_formats_cookie_t cookie = xcb_render_query_pict_formats(x11->xcb); xcb_render_query_pict_formats_reply_t *reply = xcb_render_query_pict_formats_reply(x11->xcb, cookie, NULL); if (!reply) { wlr_log(WLR_ERROR, "Did not get any reply from xcb_render_query_pict_formats"); return; } xcb_render_pictforminfo_t *format = xcb_render_util_find_standard_format(reply, XCB_PICT_STANDARD_ARGB_32); if (format == NULL) { wlr_log(WLR_DEBUG, "No ARGB_32 render format"); free(reply); return; } x11->argb32 = format->id; free(reply); } struct wlr_backend *wlr_x11_backend_create(struct wl_display *display, const char *x11_display) { wlr_log(WLR_INFO, "Creating X11 backend"); struct wlr_x11_backend *x11 = calloc(1, sizeof(*x11)); if (!x11) { return NULL; } wlr_backend_init(&x11->backend, &backend_impl); x11->wl_display = display; wl_list_init(&x11->outputs); x11->xcb = xcb_connect(x11_display, NULL); if (!x11->xcb || xcb_connection_has_error(x11->xcb)) { wlr_log(WLR_ERROR, "Failed to open xcb connection"); goto error_x11; } struct { const char *name; xcb_intern_atom_cookie_t cookie; xcb_atom_t *atom; } atom[] = { { .name = "WM_PROTOCOLS", .atom = &x11->atoms.wm_protocols }, { .name = "WM_DELETE_WINDOW", .atom = &x11->atoms.wm_delete_window }, { .name = "_NET_WM_NAME", .atom = &x11->atoms.net_wm_name }, { .name = "UTF8_STRING", .atom = &x11->atoms.utf8_string }, { .name = "_VARIABLE_REFRESH", .atom = &x11->atoms.variable_refresh }, }; for (size_t i = 0; i < sizeof(atom) / sizeof(atom[0]); ++i) { atom[i].cookie = xcb_intern_atom(x11->xcb, true, strlen(atom[i].name), atom[i].name); } for (size_t i = 0; i < sizeof(atom) / sizeof(atom[0]); ++i) { xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply( x11->xcb, atom[i].cookie, NULL); if (reply) { *atom[i].atom = reply->atom; free(reply); } else { *atom[i].atom = XCB_ATOM_NONE; } } const xcb_query_extension_reply_t *ext; // DRI3 extension ext = xcb_get_extension_data(x11->xcb, &xcb_dri3_id); if (ext && ext->present) { xcb_dri3_query_version_cookie_t dri3_cookie = xcb_dri3_query_version(x11->xcb, 1, 2); xcb_dri3_query_version_reply_t *dri3_reply = xcb_dri3_query_version_reply(x11->xcb, dri3_cookie, NULL); if (dri3_reply && dri3_reply->major_version >= 1) { x11->have_dri3 = true; x11->dri3_major_version = dri3_reply->major_version; x11->dri3_minor_version = dri3_reply->minor_version; } else { wlr_log(WLR_INFO, "X11 does not support required DRI3 version " "(has %"PRIu32".%"PRIu32", want 1.0)", dri3_reply->major_version, dri3_reply->minor_version); } free(dri3_reply); } else { wlr_log(WLR_INFO, "X11 does not support DRI3 extension"); } // SHM extension ext = xcb_get_extension_data(x11->xcb, &xcb_shm_id); if (ext && ext->present) { xcb_shm_query_version_cookie_t shm_cookie = xcb_shm_query_version(x11->xcb); xcb_shm_query_version_reply_t *shm_reply = xcb_shm_query_version_reply(x11->xcb, shm_cookie, NULL); if (shm_reply) { if (shm_reply->major_version >= 1 || shm_reply->minor_version >= 2) { if (shm_reply->shared_pixmaps) { x11->have_shm = true; } else { wlr_log(WLR_INFO, "X11 does not support shared pixmaps"); } } else { wlr_log(WLR_INFO, "X11 does not support required SHM version " "(has %"PRIu32".%"PRIu32", want 1.2)", shm_reply->major_version, shm_reply->minor_version); } } else { wlr_log(WLR_INFO, "X11 does not support required SHM version"); } free(shm_reply); } else { wlr_log(WLR_INFO, "X11 does not support SHM extension"); } // Present extension ext = xcb_get_extension_data(x11->xcb, &xcb_present_id); if (!ext || !ext->present) { wlr_log(WLR_ERROR, "X11 does not support Present extension"); goto error_display; } x11->present_opcode = ext->major_opcode; xcb_present_query_version_cookie_t present_cookie = xcb_present_query_version(x11->xcb, 1, 2); xcb_present_query_version_reply_t *present_reply = xcb_present_query_version_reply(x11->xcb, present_cookie, NULL); if (!present_reply || present_reply->major_version < 1) { wlr_log(WLR_ERROR, "X11 does not support required Present version " "(has %"PRIu32".%"PRIu32", want 1.0)", present_reply->major_version, present_reply->minor_version); free(present_reply); goto error_display; } free(present_reply); // Xfixes extension ext = xcb_get_extension_data(x11->xcb, &xcb_xfixes_id); if (!ext || !ext->present) { wlr_log(WLR_ERROR, "X11 does not support Xfixes extension"); goto error_display; } xcb_xfixes_query_version_cookie_t fixes_cookie = xcb_xfixes_query_version(x11->xcb, 4, 0); xcb_xfixes_query_version_reply_t *fixes_reply = xcb_xfixes_query_version_reply(x11->xcb, fixes_cookie, NULL); if (!fixes_reply || fixes_reply->major_version < 4) { wlr_log(WLR_ERROR, "X11 does not support required Xfixes version " "(has %"PRIu32".%"PRIu32", want 4.0)", fixes_reply->major_version, fixes_reply->minor_version); free(fixes_reply); goto error_display; } free(fixes_reply); // Xinput extension ext = xcb_get_extension_data(x11->xcb, &xcb_input_id); if (!ext || !ext->present) { wlr_log(WLR_ERROR, "X11 does not support Xinput extension"); goto error_display; } x11->xinput_opcode = ext->major_opcode; xcb_input_xi_query_version_cookie_t xi_cookie = xcb_input_xi_query_version(x11->xcb, 2, 0); xcb_input_xi_query_version_reply_t *xi_reply = xcb_input_xi_query_version_reply(x11->xcb, xi_cookie, NULL); if (!xi_reply || xi_reply->major_version < 2) { wlr_log(WLR_ERROR, "X11 does not support required Xinput version " "(has %"PRIu32".%"PRIu32", want 2.0)", xi_reply->major_version, xi_reply->minor_version); free(xi_reply); goto error_display; } free(xi_reply); int fd = xcb_get_file_descriptor(x11->xcb); struct wl_event_loop *ev = wl_display_get_event_loop(display); uint32_t events = WL_EVENT_READABLE | WL_EVENT_ERROR | WL_EVENT_HANGUP; x11->event_source = wl_event_loop_add_fd(ev, fd, events, x11_event, x11); if (!x11->event_source) { wlr_log(WLR_ERROR, "Could not create event source"); goto error_display; } wl_event_source_check(x11->event_source); x11->screen = xcb_setup_roots_iterator(xcb_get_setup(x11->xcb)).data; if (!x11->screen) { wlr_log(WLR_ERROR, "Failed to get X11 screen"); goto error_event; } x11->depth = get_depth(x11->screen, 32); if (!x11->depth) { wlr_log(WLR_ERROR, "Failed to get 32-bit depth for X11 screen"); goto error_event; } x11->visualid = pick_visualid(x11->depth); if (!x11->visualid) { wlr_log(WLR_ERROR, "Failed to pick X11 visual"); goto error_event; } x11->x11_format = x11_format_from_depth(x11->depth->depth); if (!x11->x11_format) { wlr_log(WLR_ERROR, "Unsupported depth %"PRIu8, x11->depth->depth); goto error_event; } x11->colormap = xcb_generate_id(x11->xcb); xcb_create_colormap(x11->xcb, XCB_COLORMAP_ALLOC_NONE, x11->colormap, x11->screen->root, x11->visualid); if (!query_formats(x11)) { wlr_log(WLR_ERROR, "Failed to query supported DRM formats"); return false; } x11->drm_fd = -1; if (x11->have_dri3) { // DRI3 may return a render node (Xwayland) or an authenticated primary // node (plain Glamor). x11->drm_fd = query_dri3_drm_fd(x11); if (x11->drm_fd < 0) { wlr_log(WLR_ERROR, "Failed to query DRI3 DRM FD"); goto error_event; } } // Windows can only display buffers with the depth they were created with // TODO: look into changing the window's depth at runtime const struct wlr_drm_format *dri3_format = wlr_drm_format_set_get(&x11->dri3_formats, x11->x11_format->drm); if (x11->have_dri3 && dri3_format != NULL) { wlr_drm_format_set_add(&x11->primary_dri3_formats, dri3_format->format, DRM_FORMAT_MOD_INVALID); for (size_t i = 0; i < dri3_format->len; i++) { wlr_drm_format_set_add(&x11->primary_dri3_formats, dri3_format->format, dri3_format->modifiers[i]); } } const struct wlr_drm_format *shm_format = wlr_drm_format_set_get(&x11->shm_formats, x11->x11_format->drm); if (x11->have_shm && shm_format != NULL) { wlr_drm_format_set_add(&x11->primary_shm_formats, shm_format->format, DRM_FORMAT_MOD_INVALID); } #if HAS_XCB_ERRORS if (xcb_errors_context_new(x11->xcb, &x11->errors_context) != 0) { wlr_log(WLR_ERROR, "Failed to create error context"); return false; } #endif wlr_input_device_init(&x11->keyboard_dev, WLR_INPUT_DEVICE_KEYBOARD, &input_device_impl, "X11 keyboard", 0, 0); wlr_keyboard_init(&x11->keyboard, &keyboard_impl); x11->keyboard_dev.keyboard = &x11->keyboard; x11->display_destroy.notify = handle_display_destroy; wl_display_add_destroy_listener(display, &x11->display_destroy); // Create an empty pixmap to be used as the cursor. The // default GC foreground is 0, and that is what it will be // filled with. xcb_pixmap_t blank = xcb_generate_id(x11->xcb); xcb_create_pixmap(x11->xcb, 1, blank, x11->screen->root, 1, 1); xcb_gcontext_t gc = xcb_generate_id(x11->xcb); xcb_create_gc(x11->xcb, gc, blank, 0, NULL); xcb_rectangle_t rect = { .x = 0, .y = 0, .width = 1, .height = 1 }; xcb_poly_fill_rectangle(x11->xcb, blank, gc, 1, &rect); x11->transparent_cursor = xcb_generate_id(x11->xcb); xcb_create_cursor(x11->xcb, x11->transparent_cursor, blank, blank, 0, 0, 0, 0, 0, 0, 0, 0); xcb_free_gc(x11->xcb, gc); xcb_free_pixmap(x11->xcb, blank); x11_get_argb32(x11); return &x11->backend; error_event: wl_event_source_remove(x11->event_source); error_display: xcb_disconnect(x11->xcb); error_x11: free(x11); return NULL; } static void handle_x11_error(struct wlr_x11_backend *x11, xcb_value_error_t *ev) { #if HAS_XCB_ERRORS const char *major_name = xcb_errors_get_name_for_major_code( x11->errors_context, ev->major_opcode); if (!major_name) { wlr_log(WLR_DEBUG, "X11 error happened, but could not get major name"); goto log_raw; } const char *minor_name = xcb_errors_get_name_for_minor_code( x11->errors_context, ev->major_opcode, ev->minor_opcode); const char *extension; const char *error_name = xcb_errors_get_name_for_error(x11->errors_context, ev->error_code, &extension); if (!error_name) { wlr_log(WLR_DEBUG, "X11 error happened, but could not get error name"); goto log_raw; } wlr_log(WLR_ERROR, "X11 error: op %s (%s), code %s (%s), " "sequence %"PRIu16", value %"PRIu32, major_name, minor_name ? minor_name : "no minor", error_name, extension ? extension : "no extension", ev->sequence, ev->bad_value); return; log_raw: #endif wlr_log(WLR_ERROR, "X11 error: op %"PRIu8":%"PRIu16", code %"PRIu8", " "sequence %"PRIu16", value %"PRIu32, ev->major_opcode, ev->minor_opcode, ev->error_code, ev->sequence, ev->bad_value); } static void handle_x11_unknown_event(struct wlr_x11_backend *x11, xcb_generic_event_t *ev) { #if HAS_XCB_ERRORS const char *extension; const char *event_name = xcb_errors_get_name_for_xcb_event( x11->errors_context, ev, &extension); if (!event_name) { wlr_log(WLR_DEBUG, "No name for unhandled event: %u", ev->response_type); return; } wlr_log(WLR_DEBUG, "Unhandled X11 event: %s (%u)", event_name, ev->response_type); #else wlr_log(WLR_DEBUG, "Unhandled X11 event: %u", ev->response_type); #endif }
9,380
1,003
<filename>mogu_picture/src/main/java/com/moxi/mogublog/picture/service/MinioService.java package com.moxi.mogublog.picture.service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; /** * 本地对象存储服务 Minio文件上传服务类 * * @author 陌溪 * @date 2020年10月19日11:12:14 */ public interface MinioService { /** * 多文件上传 * * @param multipartFileList * @return * @throws IOException */ List<String> batchUploadFile(List<MultipartFile> multipartFileList); /** * 文件上传 * * @param multipartFile * @return * @throws IOException */ String uploadFile(MultipartFile multipartFile); /** * 通过URL上传图片 * * @param url * @param systemConfig * @return */ String uploadPictureByUrl(String url); }
409
780
package com.codeborne.selenide.commands; import com.codeborne.selenide.Command; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.impl.WebElementSource; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public class GetSearchCriteria implements Command<String> { @Override @Nonnull @CheckReturnValue public String execute(SelenideElement proxy, WebElementSource locator, @Nullable Object[] args) { return locator.getSearchCriteria(); } }
196
1,363
/* * Copyright 2019 liaochong * * 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.github.liaochong.myexcel.core.parser; import com.github.liaochong.myexcel.core.constant.Constants; import com.github.liaochong.myexcel.core.style.FontStyle; import com.github.liaochong.myexcel.utils.StringUtil; import com.github.liaochong.myexcel.utils.StyleUtil; import com.github.liaochong.myexcel.utils.TdUtil; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * 单元格所有样式解析以及提供 * <p> * title样式仅支持title * <p> * cell样式规则,继承关系:globalCommonStyle(globalEvenStyle)-globalCellStyle, * 如存在相同样式,子样式覆盖父样式 * * @author liaochong * @version 1.0 */ public final class StyleParser { /** * 全局标题样式 */ private Map<String, String> globalTitleStyle = Collections.emptyMap(); /** * 全局单元格样式 */ private Map<String, String> globalCommonStyle = Collections.emptyMap(); /** * 全局奇数行单元格样式 */ private Map<String, String> globalEvenStyle = Collections.emptyMap(); /** * 全局单元格样式 */ private Map<String, String> globalCellStyle = Collections.emptyMap(); /** * 全局超链接样式 */ private Map<String, String> globalLinkStyle = Collections.emptyMap(); /** * 各个列样式 */ private Map<String, Map<String, String>> eachColumnStyle = new HashMap<>(); /** * 格式样式Map */ private Map<String, Map<String, String>> formatsStyleMap = new HashMap<>(); /** * 自定义宽度 */ private Map<Integer, Integer> customWidthMap; /** * 是否为偶数行 */ private boolean isOddRow = true; /** * 无样式 */ private boolean noStyle; public StyleParser(Map<Integer, Integer> customWidthMap) { this.customWidthMap = customWidthMap; } /** * 解析全局样式,{@link com.github.liaochong.myexcel.core.annotation.ExcelModel} * * @param styles 全局样式 */ public void parse(Set<String> styles) { if (noStyle) { return; } Map<String, String> styleMap = new HashMap<>(); styles.forEach(style -> { String[] splits = style.split(Constants.ARROW); if (splits.length == 1) { styleMap.putIfAbsent("cell", "cell->" + style); return; } boolean appoint = splits[0].contains("&"); if (appoint) { eachColumnStyle.put(splits[0], StyleUtil.parseStyle(splits[1])); } else { styleMap.putIfAbsent(splits[0], style); } }); globalTitleStyle = parseStyle(styleMap, "title"); globalCommonStyle = parseStyle(styleMap, "odd"); globalEvenStyle = parseStyle(styleMap, "even"); globalCellStyle = parseStyle(styleMap, "cell"); String linkStyle = styleMap.get("link"); if (linkStyle != null) { globalLinkStyle = StyleUtil.parseStyle(linkStyle.split(Constants.ARROW)[1]); } else { globalLinkStyle = new HashMap<>(); globalLinkStyle.put(FontStyle.FONT_COLOR, "blue"); globalLinkStyle.put(FontStyle.TEXT_DECORATION, FontStyle.UNDERLINE); } } private Map<String, String> parseStyle(Map<String, String> styleMap, String prefix) { String style = styleMap.get(prefix); return style == null ? Collections.emptyMap() : StyleUtil.parseStyle(style.split(Constants.ARROW)[1]); } public void setColumnStyle(Field field, int fieldIndex, String... columnStyles) { if (noStyle) { return; } setEachColumnStyle("title", fieldIndex, globalTitleStyle); setEachColumnStyle("even", fieldIndex, globalEvenStyle); setEachColumnStyle("odd", fieldIndex, globalCommonStyle); setEachColumnStyle("cell", fieldIndex, globalCellStyle); if (columnStyles == null) { return; } for (String columnStyle : columnStyles) { if (StringUtil.isBlank(columnStyle)) { throw new IllegalArgumentException("Illegal style,field:" + field.getName()); } String[] splits = columnStyle.split(Constants.ARROW); if (splits.length == 1) { // 发现未设置样式归属,则设置为全局样式,清除其他样式 setEachColumnStyle("cell", fieldIndex, StyleUtil.parseStyle(splits[0])); } else { setEachColumnStyle(splits[0], fieldIndex, StyleUtil.parseStyle(splits[1])); } } } private void setEachColumnStyle(String prefix, int fieldIndex, Map<String, String> styleMap) { if (styleMap == null || styleMap.isEmpty()) { return; } String stylePrefix = prefix + "&" + fieldIndex; Map<String, String> parentStyleMap = eachColumnStyle.get(stylePrefix); if (parentStyleMap == null || parentStyleMap.isEmpty()) { parentStyleMap = new HashMap<>(styleMap); eachColumnStyle.put(stylePrefix, parentStyleMap); } else { parentStyleMap.putAll(styleMap); } setWidth(fieldIndex, parentStyleMap); } public Map<String, String> getTitleStyle(String styleKey) { if (noStyle) { return Collections.emptyMap(); } return eachColumnStyle.getOrDefault(styleKey, globalTitleStyle); } public void toggle() { isOddRow = !isOddRow; } public Map<String, String> getCellStyle(int fieldIndex, ContentTypeEnum contentType, String format) { Map<String, String> style = Collections.emptyMap(); if (!noStyle) { style = eachColumnStyle.get((isOddRow ? "odd&" : "even&") + fieldIndex); Map<String, String> cellStyleMap = eachColumnStyle.get("cell&" + fieldIndex); if (cellStyleMap != null) { if (style == null || style.isEmpty()) { style = cellStyleMap; } else { style = new HashMap<>(style); style.putAll(cellStyleMap); } } if (style == null && !globalCellStyle.isEmpty()) { style = globalCellStyle; } if (style == null) { style = isOddRow ? globalCommonStyle : globalEvenStyle; } if (ContentTypeEnum.isLink(contentType)) { style = new HashMap<>(style); style.putAll(globalLinkStyle); } } if (format != null) { style = this.getFormatStyle(format, fieldIndex, style); } return style; } private Map<String, String> getFormatStyle(String format, int fieldIndex, Map<String, String> style) { Map<String, String> formatStyle = formatsStyleMap.get(format + "_" + fieldIndex + "_" + (isOddRow ? "odd&" : "even&")); if (formatStyle == null) { formatStyle = new HashMap<>(style); formatStyle.put("format", format); formatsStyleMap.put(format + "_" + fieldIndex, formatStyle); } return formatStyle; } private void setWidth(int fieldIndex, Map<String, String> styleMap) { String width = styleMap.get("width"); if (width != null) { customWidthMap.put(fieldIndex, TdUtil.getValue(width)); } } public void setCustomWidthMap(Map<Integer, Integer> customWidthMap) { this.customWidthMap = customWidthMap; } public void setNoStyle(boolean noStyle) { this.noStyle = noStyle; } }
3,715
684
/* 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.activiti.camel; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.activiti.engine.ActivitiException; import org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior; import org.activiti.engine.impl.pvm.PvmProcessDefinition; import org.activiti.engine.impl.pvm.delegate.ActivityBehavior; import org.activiti.engine.impl.pvm.delegate.ActivityExecution; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultExchange; @Deprecated public class CamelBehaviour extends BpmnActivityBehavior implements ActivityBehavior { private static final long serialVersionUID = 1L; private Collection<ContextProvider> contextProviders; public CamelBehaviour(Collection<ContextProvider> camelContext) { this.contextProviders = camelContext; } public void execute(ActivityExecution execution) throws Exception { ActivitiEndpoint ae = createEndpoint(execution); Exchange ex = createExchange(execution, ae); ae.process(ex); execution.setVariables(ExchangeUtils.prepareVariables(ex, ae)); performDefaultOutgoingBehavior(execution); } private ActivitiEndpoint createEndpoint(ActivityExecution execution) { String uri = "activiti://" + getProcessName(execution) + ":" + execution.getActivity().getId(); return getEndpoint(getContext(execution), uri); } private ActivitiEndpoint getEndpoint(CamelContext ctx, String key) { for (Endpoint e : ctx.getEndpoints()) { if (e.getEndpointKey().equals(key) && (e instanceof ActivitiEndpoint)) { return (ActivitiEndpoint) e; } } throw new ActivitiException("Activiti endpoint not defined for " + key); } private CamelContext getContext(ActivityExecution execution) { String processName = getProcessName(execution); String names = ""; for (ContextProvider provider : contextProviders) { CamelContext ctx = provider.getContext(processName); if (ctx != null) { return ctx; } } throw new ActivitiException("Could not find camel context for " + processName + " names are " + names); } private Exchange createExchange(ActivityExecution activityExecution, ActivitiEndpoint endpoint) { Exchange ex = new DefaultExchange(getContext(activityExecution)); Map<String, Object> variables = activityExecution.getVariables(); if (endpoint.isCopyVariablesToProperties()) { for (Map.Entry<String, Object> var : variables.entrySet()) { ex.setProperty(var.getKey(), var.getValue()); } } if (endpoint.isCopyVariablesToBodyAsMap()) { ex.getIn().setBody(new HashMap<String,Object>(variables)); } return ex; } private String getProcessName(ActivityExecution execution) { PvmProcessDefinition processDefinition = execution.getActivity().getProcessDefinition(); return processDefinition.getKey(); } }
1,102
1,296
<filename>bindings/wp8/MUserList.h /** * @file MUserList.h * @brief List of MUser objects * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #pragma once #include "MUser.h" #include "megaapi.h" namespace mega { using namespace Windows::Foundation; using Platform::String; public ref class MUserList sealed { friend ref class MegaSDK; friend class DelegateMListener; friend class DelegateMGlobalListener; public: virtual ~MUserList(); MUser^ get(int i); int size(); private: MUserList(MegaUserList *userList, bool cMemoryOwn); MegaUserList *userList; bool cMemoryOwn; }; }
366
2,101
<reponame>tirkarthi/raiden import atexit import signal from abc import ABC, abstractmethod from types import TracebackType from typing import Any, Callable, List, Optional, Set, Type import gevent import structlog from gevent import Greenlet, GreenletExit from gevent.event import AsyncResult from gevent.greenlet import SpawnedLink from gevent.lock import RLock from gevent.subprocess import Popen, TimeoutExpired log = structlog.get_logger(__name__) STATUS_CODE_FOR_SUCCESS = 0 class Nursery(ABC): @abstractmethod def exec_under_watch(self, process_args: List[str], **kwargs: Any) -> Optional[Popen]: pass @abstractmethod def spawn_under_watch(self, function: Callable, *args: Any, **kargs: Any) -> Greenlet: pass @abstractmethod def wait(self, timeout: Optional[float]) -> None: pass class Janitor: """Janitor to properly cleanup after spawned subprocesses and greenlets. The goal of the janitor is to: - Propagate errors, if any of the watched processes / greenlets fails. - Keep track of spawned subprocesses and greenlets and make sure that everything is cleanup once the Janitor is done. - If the janitor is exiting because the monitored block is done (i.e. the with block is done executing), then a "clean" shutdown is performed. - Otherwise an exception occurred and the greenlets are killed it. """ def __init__(self, stop_timeout: float = 20) -> None: self.stop_timeout = stop_timeout self._stop = AsyncResult() self._processes: Set[Popen] = set() self._exit_in_progress = False # Lock to protect changes to `_stop` and `_processes`. The `_stop` # synchronization is necessary to fix the race described below, # `_processes` synchronization is necessary to avoid iteration over a # changing container. # # Important: It is very important to register any executed subprocess, # otherwise no signal will be sent during shutdown and the subprocess # will become orphan. To properly register the subprocesses it is very # important to finish any pending call to `exec_under_watch` before # exiting the `Janitor`, and if the exit does run, `exec_under_watch` # must not start a new process. # # Note this only works if the greenlet that instantiated the Janitor # itself has a chance to run. self._processes_lock = RLock() def __enter__(self) -> Nursery: # Registers an atexit callback in case the __exit__ doesn't get a # chance to run. This happens when the Janitor is not used in the main # greenlet, and its greenlet is not the one that is dying. atexit.register(self._free_resources) # Hide the nursery to require the context manager to be used. This # leads to better behavior in the happy case since the exit handler is # used. janitor = self class ProcessNursery(Nursery): @staticmethod def exec_under_watch(process_args: List[str], **kwargs: Any) -> Optional[Popen]: msg = ( "The Janitor can not work with `shell=True`. When that flag " "is used a proxy shell process is used to start the real " "target process, the result is that the Janitor will monitor " "and kill the proxy shell instead of the target, once the " "shell is killed the real targets are kept around as " "orphans, which is exactly what the Janitor is trying to " "prevent from happening." ) assert not kwargs.get("shell", False), msg def subprocess_stopped(result: AsyncResult) -> None: if janitor._exit_in_progress: # During __exit__ we expect processes to stop, since # they are killed by the janitor. return with janitor._processes_lock: # Processes are expected to quit while the nursery is # active, remove them from the track list to clear memory janitor._processes.remove(process) # if the subprocess error'ed propagate the error. try: exit_code = result.get() if exit_code != STATUS_CODE_FOR_SUCCESS: log.error( "Process died! Bailing out.", args=process.args, exit_code=exit_code, ) exception = SystemExit(exit_code) janitor._stop.set_exception(exception) except Exception as exception: log.exception( "Process erroed! Propagating error.", args=process.args, ) janitor._stop.set_exception(exception) with janitor._processes_lock: if janitor._stop.ready(): return None process = Popen(process_args, **kwargs) janitor._processes.add(process) # `rawlink`s are executed from within the hub, the problem # is that locks can not be acquire at that point. # SpawnedLink creates a new greenlet to run the callback to # circumvent that. callback = SpawnedLink(subprocess_stopped) process.result.rawlink(callback) # Important: `stop` may be set after Popen started, but before # it returned. If that happens `GreenletExit` exception is # raised here. In order to have proper cleared, exceptions have # to be handled and the process installed. if janitor._stop.ready(): process.send_signal(signal.SIGINT) return process @staticmethod def spawn_under_watch(function: Callable, *args: Any, **kwargs: Any) -> Greenlet: greenlet = gevent.spawn(function, *args, **kwargs) # The callback provided to `AsyncResult.rawlink` is executed # inside the Hub thread, the callback is calling `throw` which # has to be called from the Hub, so here there is no need to # wrap the callback in a SpawnedLink. # # `throw` does not raise the exception if the greenlet has # finished, which is exactly the semantics needed here. def stop_greenlet_from_hub(result: AsyncResult) -> None: """Stop the greenlet if the nursery is stopped.""" try: result.get() except BaseException as e: greenlet.throw(e) else: greenlet.throw(GreenletExit()) def propagate_error(g: Greenlet) -> None: """If the greenlet fails, stop the nursery.""" janitor._stop.set_exception(g.exception) greenlet.link_exception(propagate_error) janitor._stop.rawlink(stop_greenlet_from_hub) return greenlet @staticmethod def wait(timeout: Optional[float]) -> None: janitor._stop.wait(timeout) return ProcessNursery() def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType], ) -> Optional[bool]: self._exit_in_progress = True with self._processes_lock: # Make sure to signal that we are exiting. if not self._stop.done(): self._stop.set() self._free_resources() # Behave nicely if context manager's __exit__ is executed. This # implements the expected behavior of a context manager, which will # clear the resources when exiting. atexit.unregister(self._free_resources) self._stop.get() return None def _free_resources(self) -> None: with self._processes_lock: for p in self._processes: p.send_signal(signal.SIGINT) try: for p in self._processes: exit_code = p.wait(timeout=self.stop_timeout) if exit_code != STATUS_CODE_FOR_SUCCESS: log.warning( "Process did not exit cleanly", exit_code=exit_code, communicate=p.communicate(), ) except TimeoutExpired: log.warning( "Process did not stop in time. Sending SIGKILL to all remaining processes!", command=p.args, ) for p in self._processes: p.send_signal(signal.SIGKILL)
4,488
852
#include "CalibFormats/SiStripObjects/interface/SiStripHashedDetId.h" #include "CalibTracker/Records/interface/SiStripHashedDetIdRcd.h" #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h" using namespace sistrip; /** @class SiStripHashedDetIdESModule @author R.Bainbridge @brief Builds hashed DetId map based on DetIds read from geometry database */ class SiStripHashedDetIdESModule : public edm::ESProducer { public: SiStripHashedDetIdESModule(const edm::ParameterSet&); ~SiStripHashedDetIdESModule() override; /** Builds hashed DetId map based on geometry. */ std::unique_ptr<SiStripHashedDetId> produce(const SiStripHashedDetIdRcd&); private: const edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord> geomToken_; }; // ----------------------------------------------------------------------------- // SiStripHashedDetIdESModule::SiStripHashedDetIdESModule(const edm::ParameterSet& pset) : geomToken_(setWhatProduced(this, &SiStripHashedDetIdESModule::produce).consumes()) { edm::LogVerbatim("HashedDetId") << "[SiStripHashedDetIdESSourceFromGeom::" << __func__ << "]" << " Constructing object..."; } // ----------------------------------------------------------------------------- // SiStripHashedDetIdESModule::~SiStripHashedDetIdESModule() { edm::LogVerbatim("HashedDetId") << "[SiStripHashedDetIdESSourceFromGeom::" << __func__ << "]" << " Destructing object..."; } // ----------------------------------------------------------------------------- // std::unique_ptr<SiStripHashedDetId> SiStripHashedDetIdESModule::produce(const SiStripHashedDetIdRcd& rcd) { edm::LogVerbatim("HashedDetId") << "[SiStripHashedDetIdFakeESSource::" << __func__ << "]" << " Building \"fake\" hashed DetId map from geometry"; const auto& geom = rcd.get(geomToken_); std::vector<uint32_t> dets; dets.reserve(16000); for (const auto& iter : geom.detUnits()) { const auto strip = dynamic_cast<StripGeomDetUnit const*>(iter); if (strip) { dets.push_back((strip->geographicalId()).rawId()); } } edm::LogVerbatim(mlDqmCommon_) << "[SiStripHashedDetIdESModule::" << __func__ << "]" << " Retrieved " << dets.size() << " sistrip DetIds from geometry!"; // Create hash map object auto hash = std::make_unique<SiStripHashedDetId>(dets); LogTrace(mlDqmCommon_) << "[SiStripHashedDetIdESModule::" << __func__ << "]" << " DetId hash map: " << std::endl << *hash; return hash; } DEFINE_FWK_EVENTSETUP_MODULE(SiStripHashedDetIdESModule);
1,136
323
#define ONDISCONNECTED 0 #define ONERROR 1 #define ONSUBMARKETDATA 2 #define ONUNSUBMARKETDATA 3 #define ONDEPTHMARKETDATA 4 #define ONSUBORDERBOOK 5 #define ONUNSUBORDERBOOK 6 #define ONORDERBOOK 7 #define ONSUBTICKBYTICK 8 #define ONUNSUBTICKBYTICK 9 #define ONTICKBYTICK 10 #define ONSUBSCRIBEALLMARKETDATA 11 #define ONUNSUBSCRIBEALLMARKETDATA 12 #define ONSUBSCRIBEALLORDERBOOK 13 #define ONUNSUBSCRIBEALLORDERBOOK 14 #define ONSUBSCRIBEALLTICKBYTICK 15 #define ONUNSUBSCRIBEALLTICKBYTICK 16 #define ONQUERYALLTICKERS 17 #define ONQUERYTICKERSPRICEINFO 18 #define ONSUBSCRIBEALLOPTIONMARKETDATA 19 #define ONUNSUBSCRIBEALLOPTIONMARKETDATA 20 #define ONSUBSCRIBEALLOPTIONORDERBOOK 21 #define ONUNSUBSCRIBEALLOPTIONORDERBOOK 22 #define ONSUBSCRIBEALLOPTIONTICKBYTICK 23 #define ONUNSUBSCRIBEALLOPTIONTICKBYTICK 24
336
3,294
//PlotPanel.cpp file using namespace System; using namespace System::Windows; using namespace System::Windows::Controls; using namespace System::Windows::Shapes; using namespace System::Windows::Media; using namespace System::Threading; namespace PlotPanel { public ref class app : System::Windows::Application { // <Snippet1> public: ref class PlotPanel : Panel { public: PlotPanel () {}; protected: // Override the default Measure method of Panel // <Snippet2> virtual Size MeasureOverride(Size availableSize) override { Size^ panelDesiredSize = gcnew Size(); // In our example, we just have one child. // Report that our panel requires just the size of its only child. for each (UIElement^ child in InternalChildren) { child->Measure(availableSize); panelDesiredSize = child->DesiredSize; } return *panelDesiredSize ; } //</Snippet2> protected: virtual System::Windows::Size ArrangeOverride (Size finalSize) override { for each (UIElement^ child in InternalChildren) { double x = 50; double y = 50; child->Arrange(Rect(Point(x, y), child->DesiredSize)); } return finalSize; }; }; //</Snippet1> private: PlotPanel^ plot1; Window^ mainWindow; Shapes::Rectangle^ rect1; protected: virtual void OnStartup (StartupEventArgs^ e) override { Application::OnStartup(e); CreateAndShowMainWindow(); }; private: void CreateAndShowMainWindow () { // Create the application's main window mainWindow = gcnew Window(); plot1 = gcnew PlotPanel(); plot1->Background = Brushes::White; rect1 = gcnew Shapes::Rectangle(); rect1->Fill = Brushes::CornflowerBlue; rect1->Width = 200; rect1->Height = 200; mainWindow->Content = plot1; plot1->Children->Add(rect1); mainWindow->Title = "Custom Panel Sample"; mainWindow->Show(); }; }; private ref class EntryClass { public: [System::STAThread()] static void Main () { PlotPanel::app^ app = gcnew PlotPanel::app(); app->Run(); }; }; } //Entry Point: [System::STAThreadAttribute()] void main () { return PlotPanel::EntryClass::Main(); }
1,134
1,163
<reponame>kintel/iree // Copyright 2019 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #ifndef IREE_COMPILER_DIALECT_VM_TARGET_BYTECODE_CONSTANTENCODER_H_ #define IREE_COMPILER_DIALECT_VM_TARGET_BYTECODE_CONSTANTENCODER_H_ #include "iree/compiler/Utils/FlatbufferUtils.h" #include "iree/schemas/bytecode_module_def_builder.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Location.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace VM { struct SerializedConstantRef { flatbuffers_uint8_vec_ref_t ref = 0; int64_t totalSize = 0; uint32_t crc32 = 0; }; // Serializes a constant attribute to the FlatBuffer as a binary blob. // Returns the size in bytes of the serialized value and the flatbuffers offset // to the uint8 vec containing the data. If |calculateCRC32| is provided then a // CRC32 of the data will be computed and returned as well. SerializedConstantRef serializeConstant(Location loc, ElementsAttr elementsAttr, size_t alignment, bool calculateCRC32, FlatbufferBuilder &fbb); } // namespace VM } // namespace IREE } // namespace iree_compiler } // namespace mlir #endif // IREE_COMPILER_DIALECT_VM_TARGET_BYTECODE_CONSTANTENCODER_H_
559
2,757
<filename>Vlv2TbltDevicePkg/MonoStatusCode/PlatformStatusCode.h /*++ Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License that accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: PlatformStatusCode.h Abstract: Contains Platform specific implementations required to use status codes. --*/ #ifndef _PLATFORM_STATUS_CODE_H_ #define _PLATFORM_STATUS_CODE_H_ #define CONFIG_PORT0 0x4E #define INDEX_PORT0 0x4E #define DATA_PORT0 0x4F #define PCI_IDX 0xCF8 #define PCI_DAT 0xCFC #include "MonoStatusCode.h" #ifndef _PEI_PORT_80_STATUS_CODE_H_ #define _PEI_PORT_80_STATUS_CODE_H_ // // Status code reporting function // EFI_STATUS Port80ReportStatusCode ( IN CONST EFI_PEI_SERVICES **PeiServices, IN EFI_STATUS_CODE_TYPE CodeType, IN EFI_STATUS_CODE_VALUE Value, IN UINT32 Instance, IN CONST EFI_GUID * CallerId, IN CONST EFI_STATUS_CODE_DATA * Data OPTIONAL ); #endif #ifndef _PEI_SERIAL_STATUS_CODE_LIB_H_ #define _PEI_SERIAL_STATUS_CODE_LIB_H_ #include <Guid/StatusCodeDataTypeId.h> #include <Guid/StatusCodeDataTypeDebug.h> #include <Library/ReportStatusCodeLib.h> #include <Library/PrintLib.h> #include <Library/BaseMemoryLib.h> // // Initialization function // VOID SerialInitializeStatusCode ( VOID ); // // Status code reporting function // EFI_STATUS SerialReportStatusCode ( IN CONST EFI_PEI_SERVICES **PeiServices, IN EFI_STATUS_CODE_TYPE CodeType, IN EFI_STATUS_CODE_VALUE Value, IN UINT32 Instance, IN CONST EFI_GUID * CallerId, IN CONST EFI_STATUS_CODE_DATA * Data OPTIONAL ); #endif extern EFI_PEI_PROGRESS_CODE_PPI mStatusCodePpi; extern EFI_PEI_PPI_DESCRIPTOR mPpiListStatusCode; #define EFI_SIGNATURE_16(A, B) ((A) | (B << 8)) #define EFI_SIGNATURE_32(A, B, C, D) (EFI_SIGNATURE_16 (A, B) | (EFI_SIGNATURE_16 (C, D) << 16)) #define STATUSCODE_PEIM_SIGNATURE EFI_SIGNATURE_32 ('p', 's', 't', 'c') typedef struct { UINT32 Signature; EFI_FFS_FILE_HEADER *FfsHeader; EFI_PEI_NOTIFY_DESCRIPTOR StatusCodeNotify; } STATUSCODE_CALLBACK_STATE_INFORMATION; #pragma pack(1) typedef struct { UINT16 Limit; UINT32 Base; } GDT_DSCRIPTOR; #pragma pack() #define STATUSCODE_PEIM_FROM_THIS(a) \ BASE_CR ( \ a, \ STATUSCODE_CALLBACK_STATE_INFORMATION, \ StatusCodeNotify \ ) VOID EFIAPI PlatformInitializeStatusCode ( IN EFI_FFS_FILE_HEADER *FfsHeader, IN CONST EFI_PEI_SERVICES **PeiServices ); // // Function declarations // /** Install Firmware Volume Hob's once there is main memory @param PeiServices General purpose services available to every PEIM. @param NotifyDescriptor Not Used @param Ppi Not Used @retval Status EFI_SUCCESS if the interface could be successfully installed **/ EFI_STATUS EFIAPI MemoryDiscoveredPpiNotifyCallback ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi ); #endif
1,895
778
// // Created by <NAME> on 11/18/21. // #ifndef TUPLEX_FILEUTILS_H #define TUPLEX_FILEUTILS_H #include <string> namespace tuplex { /*! * when performing unix wildcard matching, this finds the longest prefix where no matching character is used * @param s path * @param escapechar characters escaped with this char will be ignored for the prefix search * @return longest prefix */ inline std::string findLongestPrefix(const std::string &s, const char escapechar = '\\') { // list from http://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm // http://man7.org/linux/man-pages/man7/glob.7.html // basically need to search for following chars char reserved_chars[] = "*?[]"; auto num_reserved_chars = strlen(reserved_chars); char lastChar = 0; const char *ptr = s.c_str(); while (*ptr != '\0') { auto curChar = *ptr; // check if curChar is any of the reserved ones for (unsigned i = 0; i < num_reserved_chars; ++i) if (curChar == reserved_chars[i]) { // check if last char is escapechar if (lastChar != escapechar) goto done; } lastChar = *ptr; ptr++; } done: auto idx = ptr - s.c_str(); return s.substr(0, idx); } inline std::string eliminateSeparatorRuns(const std::string& path, size_t numStartCharsToIgnore = 0, const char separator='/') { char *temp_buf = new char[path.size() + 1]; memset(temp_buf, 0, path.size() + 1); memcpy(temp_buf, path.c_str(), numStartCharsToIgnore * sizeof(char)); auto ptr = temp_buf + numStartCharsToIgnore; for(int i = numStartCharsToIgnore; i < path.size(); ++i) { *ptr = path[i]; if(*ptr == separator) { // skip subsequent separators while(i + 1 < path.size() && path[i + 1] == separator) ++i; } ptr++; } std::string res(temp_buf); delete [] temp_buf; return res; } } #endif //TUPLEX_FILEUTILS_H
1,044
343
<reponame>nzeh/syzygy // Copyright 2013 Google 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. // // Template implementation of some PE/COFF utilities. #ifndef SYZYGY_PE_PE_UTILS_IMPL_H_ #define SYZYGY_PE_PE_UTILS_IMPL_H_ namespace pe { template <typename ImageFile> bool CopySectionInfoToBlockGraph(const ImageFile& image_file, block_graph::BlockGraph* block_graph) { // Iterate through the image sections, and create sections in the BlockGraph. size_t num_sections = image_file.file_header()->NumberOfSections; for (size_t i = 0; i < num_sections; ++i) { const IMAGE_SECTION_HEADER* header = image_file.section_header(i); std::string name = ImageFile::GetSectionName(*header); block_graph::BlockGraph::Section* section = block_graph->AddSection( name, header->Characteristics); DCHECK(section != NULL); // For now, we expect them to have been created with the same IDs as those // in the original image. if (section->id() != i) { LOG(ERROR) << "Unexpected section ID."; return false; } } return true; } } // namespace pe #endif // SYZYGY_PE_PE_UTILS_IMPL_H_
573
2,364
<gh_stars>1000+ /* * Copyright (c) 2011 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.google.common.truth; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.collect.Table; import java.math.BigDecimal; import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; /** * In a fluent assertion chain, an object with which you can do any of the following: * * <ul> * <li>Set an optional message with {@link #withMessage}. * <li>Specify the type of {@code Subject} to create with {@link #about(Subject.Factory)}. * <li>For the types of {@code Subject} built into Truth, directly specify the value under test * with {@link #that(Object)}. * </ul> * * <p>For more information about the methods in this class, see <a * href="https://truth.dev/faq#full-chain">this FAQ entry</a>. * * <h3>For people extending Truth</h3> * * <p>You won't extend this type. When you write a custom subject, see <a * href="https://truth.dev/extension">our doc on extensions</a>. */ public class StandardSubjectBuilder { /** * Returns a new instance that invokes the given {@code FailureStrategy} when a check fails. Most * users should not need this. If you think you do, see the documentation on {@link * FailureStrategy}. */ public static StandardSubjectBuilder forCustomFailureStrategy(FailureStrategy failureStrategy) { return new StandardSubjectBuilder(FailureMetadata.forFailureStrategy(failureStrategy)); } private final FailureMetadata metadataDoNotReferenceDirectly; StandardSubjectBuilder(FailureMetadata metadata) { this.metadataDoNotReferenceDirectly = checkNotNull(metadata); } @SuppressWarnings({"unchecked", "rawtypes"}) public final <ComparableT extends Comparable<?>> ComparableSubject<ComparableT> that( @Nullable ComparableT actual) { return new ComparableSubject(metadata(), actual) {}; } public final BigDecimalSubject that(@Nullable BigDecimal actual) { return new BigDecimalSubject(metadata(), actual); } public final Subject that(@Nullable Object actual) { return new Subject(metadata(), actual); } @GwtIncompatible("ClassSubject.java") public final ClassSubject that(@Nullable Class<?> actual) { return new ClassSubject(metadata(), actual); } public final ThrowableSubject that(@Nullable Throwable actual) { return new ThrowableSubject(metadata(), actual, "throwable"); } public final LongSubject that(@Nullable Long actual) { return new LongSubject(metadata(), actual); } public final DoubleSubject that(@Nullable Double actual) { return new DoubleSubject(metadata(), actual); } public final FloatSubject that(@Nullable Float actual) { return new FloatSubject(metadata(), actual); } public final IntegerSubject that(@Nullable Integer actual) { return new IntegerSubject(metadata(), actual); } public final BooleanSubject that(@Nullable Boolean actual) { return new BooleanSubject(metadata(), actual); } public final StringSubject that(@Nullable String actual) { return new StringSubject(metadata(), actual); } public final IterableSubject that(@Nullable Iterable<?> actual) { return new IterableSubject(metadata(), actual); } public final <T> ObjectArraySubject<T> that(@Nullable T @Nullable [] actual) { return new ObjectArraySubject<>(metadata(), actual, "array"); } public final PrimitiveBooleanArraySubject that(boolean @Nullable [] actual) { return new PrimitiveBooleanArraySubject(metadata(), actual, "array"); } public final PrimitiveShortArraySubject that(short @Nullable [] actual) { return new PrimitiveShortArraySubject(metadata(), actual, "array"); } public final PrimitiveIntArraySubject that(int @Nullable [] actual) { return new PrimitiveIntArraySubject(metadata(), actual, "array"); } public final PrimitiveLongArraySubject that(long @Nullable [] actual) { return new PrimitiveLongArraySubject(metadata(), actual, "array"); } public final PrimitiveCharArraySubject that(char @Nullable [] actual) { return new PrimitiveCharArraySubject(metadata(), actual, "array"); } public final PrimitiveByteArraySubject that(byte @Nullable [] actual) { return new PrimitiveByteArraySubject(metadata(), actual, "array"); } public final PrimitiveFloatArraySubject that(float @Nullable [] actual) { return new PrimitiveFloatArraySubject(metadata(), actual, "array"); } public final PrimitiveDoubleArraySubject that(double @Nullable [] actual) { return new PrimitiveDoubleArraySubject(metadata(), actual, "array"); } public final GuavaOptionalSubject that(@Nullable Optional<?> actual) { return new GuavaOptionalSubject(metadata(), actual, "optional"); } public final MapSubject that(@Nullable Map<?, ?> actual) { return new MapSubject(metadata(), actual); } public final MultimapSubject that(@Nullable Multimap<?, ?> actual) { return new MultimapSubject(metadata(), actual, "multimap"); } public final MultisetSubject that(@Nullable Multiset<?> actual) { return new MultisetSubject(metadata(), actual); } public final TableSubject that(@Nullable Table<?, ?, ?> actual) { return new TableSubject(metadata(), actual); } /** * Returns a new instance that will output the given message before the main failure message. If * this method is called multiple times, the messages will appear in the order that they were * specified. */ public final StandardSubjectBuilder withMessage(@Nullable String messageToPrepend) { return withMessage("%s", messageToPrepend); } /** * Returns a new instance that will output the given message before the main failure message. If * this method is called multiple times, the messages will appear in the order that they were * specified. * * <p><b>Note:</b> the arguments will be substituted into the format template using {@link * com.google.common.base.Strings#lenientFormat Strings.lenientFormat}. Note this only supports * the {@code %s} specifier. * * @throws IllegalArgumentException if the number of placeholders in the format string does not * equal the number of given arguments */ public final StandardSubjectBuilder withMessage(String format, @Nullable Object... args) { return new StandardSubjectBuilder(metadata().withMessage(format, args)); } /** * Given a factory for some {@code Subject} class, returns a builder whose {@code that(actual)} * method creates instances of that class. Created subjects use the previously set failure * strategy and any previously set failure message. */ public final <S extends Subject, A> SimpleSubjectBuilder<S, A> about( Subject.Factory<S, A> factory) { return new SimpleSubjectBuilder<>(metadata(), factory); } public final <CustomSubjectBuilderT extends CustomSubjectBuilder> CustomSubjectBuilderT about( CustomSubjectBuilder.Factory<CustomSubjectBuilderT> factory) { return factory.createSubjectBuilder(metadata()); } /** * Reports a failure. * * <p>To set a message, first call {@link #withMessage} (or, more commonly, use the shortcut * {@link Truth#assertWithMessage}). */ public final void fail() { metadata().fail(ImmutableList.<Fact>of()); } private FailureMetadata metadata() { checkStatePreconditions(); return metadataDoNotReferenceDirectly; } /** * Extension point invoked before every assertion. This allows {@link Expect} to check that it's * been set up properly as a {@code TestRule}. */ void checkStatePreconditions() {} }
2,399
1,099
<filename>live/src/main/java/com/example/live/mvp/main/MainActivity.java package com.example.live.mvp.main; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.alibaba.android.arouter.facade.annotation.Route; import com.example.commonlibrary.BaseActivity; import com.example.commonlibrary.BaseFragment; import com.example.commonlibrary.baseadapter.SuperRecyclerView; import com.example.commonlibrary.baseadapter.adapter.ViewPagerAdapter; import com.example.commonlibrary.baseadapter.listener.OnSimpleItemClickListener; import com.example.commonlibrary.baseadapter.manager.WrappedGridLayoutManager; import com.example.commonlibrary.customview.CustomPopWindow; import com.example.commonlibrary.customview.ToolBarOption; import com.example.commonlibrary.utils.ToastUtils; import com.example.live.LiveApplication; import com.example.live.R; import com.example.live.adapter.PopWindowAdapter; import com.example.live.bean.CategoryLiveBean; import com.example.live.dagger.main.DaggerMainActivityComponent; import com.example.live.dagger.main.MainActivityModules; import com.example.live.mvp.list.ListLiveFragment; import com.example.live.mvp.search.SearchLiveActivity; import com.example.live.mvp.recommend.RecommendLiveFragment; import com.example.live.util.LiveUtil; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; @Route(path = "/live/main") public class MainActivity extends BaseActivity<List<CategoryLiveBean>, MainPresenter> implements View.OnClickListener { private ViewPager display; private TabLayout tab; private ImageView list; @Inject ViewPagerAdapter viewPagerAdapter; private List<CategoryLiveBean> data = new ArrayList<>(); @Override protected boolean isNeedHeadLayout() { return true; } @Override protected boolean isNeedEmptyLayout() { return true; } @Override protected int getContentLayout() { return R.layout.activity_main_live; } @Override protected void initView() { display = (ViewPager) findViewById(R.id.vp_activity_main_display); tab = (TabLayout) findViewById(R.id.tl_activity_main_tab); list = (ImageView) findViewById(R.id.iv_activity_main_expend_list); list.setOnClickListener(this); } @Override protected void initData() { DaggerMainActivityComponent.builder().mainActivityModules(new MainActivityModules(this)) .mainComponent(LiveApplication.getMainComponent()).build().inject(this); display.post(new Runnable() { @Override public void run() { presenter.getAllCategories(); } }); ToolBarOption toolBarOption = new ToolBarOption(); toolBarOption.setTitle("全民直播"); toolBarOption.setBgColor(getResources().getColor(R.color.base_color_text_grey)); setToolBar(toolBarOption); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.live_menu_item, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.live_menu_item_search) { ToastUtils.showLongToast("启动搜索界面"); SearchLiveActivity.start(this); } return true; } @Override public void updateData(List<CategoryLiveBean> categoryLiveBeen) { data.clear(); data.addAll(categoryLiveBeen); if (data != null && data.size() > 0) { List<String> titleList = new ArrayList<>(); List<BaseFragment> fragmentList = new ArrayList<>(); titleList.add("推荐"); fragmentList.add(RecommendLiveFragment.newInstance()); for (CategoryLiveBean bean : data) { ListLiveFragment listLiveFragment = ListLiveFragment.newInstance(); Bundle bundle = new Bundle(); bundle.putString(LiveUtil.SLUG, bean.getSlug()); listLiveFragment.setArguments(bundle); fragmentList.add(listLiveFragment); titleList.add(bean.getName()); } tab.setupWithViewPager(display); viewPagerAdapter.setTitleAndFragments(titleList, fragmentList); display.setAdapter(viewPagerAdapter); display.setCurrentItem(0); } } @Override public void hideLoading() { if (data != null && data.size() > 0) { super.hideLoading(); } else { showEmptyView(); } } private CustomPopWindow customPopWindow; private PopWindowAdapter popWindowAdapter; @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.iv_activity_main_expend_list) { if (customPopWindow == null) { customPopWindow = new CustomPopWindow.Builder().parentView(v).contentView(getContentView()).activity(this) .build(); } if (!customPopWindow.isShowing()) { customPopWindow.showAsDropDown(v); } else { customPopWindow.dismiss(); } } } private View getContentView() { View contentView = getLayoutInflater().inflate(R.layout.view_activity_main_pop_window, null); SuperRecyclerView display = (SuperRecyclerView) contentView.findViewById(R.id.srcv_view_activity_main_pop_window_display); display.setLayoutManager(new WrappedGridLayoutManager(this, 5)); popWindowAdapter = new PopWindowAdapter(); display.setAdapter(popWindowAdapter); List<CategoryLiveBean> list = new ArrayList<>(); CategoryLiveBean categoryLiveBean = new CategoryLiveBean(); categoryLiveBean.setIcon_image(""); categoryLiveBean.setName("推荐"); list.add(categoryLiveBean); list.addAll(data); popWindowAdapter.addData(list); popWindowAdapter.setOnItemClickListener(new OnSimpleItemClickListener() { @Override public void onItemClick(int position, View view) { customPopWindow.dismiss(); MainActivity.this.display.setCurrentItem(position); } }); return contentView; } }
2,707
1,605
/* * 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.pdfbox.pdmodel.interactive.measurement; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; /** * This class represents a rectlinear measure dictionary. * */ public class PDRectlinearMeasureDictionary extends PDMeasureDictionary { /** * The subtype of the rectlinear measure dictionary. */ public static final String SUBTYPE = "RL"; /** * Constructor. */ public PDRectlinearMeasureDictionary() { this.setSubtype(SUBTYPE); } /** * Constructor. * * @param dictionary the corresponding dictionary */ public PDRectlinearMeasureDictionary(COSDictionary dictionary) { super(dictionary); } /** * This will return the scale ration. * * @return the scale ratio. */ public String getScaleRatio() { return this.getCOSObject().getString(COSName.R); } /** * This will set the scale ration. * * @param scaleRatio the scale ratio. */ public void setScaleRatio(String scaleRatio) { this.getCOSObject().setString(COSName.R, scaleRatio); } /** * This will return the changes along the x-axis. * * @return changes along the x-axis */ public PDNumberFormatDictionary[] getChangeXs() { COSArray x = getCOSObject().getCOSArray(COSName.X); if (x != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[x.size()]; for (int i = 0; i < x.size(); i++) { COSDictionary dic = (COSDictionary) x.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the changes along the x-axis. * * @param changeXs changes along the x-axis */ public void setChangeXs(PDNumberFormatDictionary[] changeXs) { COSArray array = new COSArray(); for (PDNumberFormatDictionary changeX : changeXs) { array.add(changeX); } this.getCOSObject().setItem(COSName.X, array); } /** * This will return the changes along the y-axis. * * @return changes along the y-axis */ public PDNumberFormatDictionary[] getChangeYs() { COSArray y = getCOSObject().getCOSArray(COSName.Y); if (y != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[y.size()]; for (int i = 0; i < y.size(); i++) { COSDictionary dic = (COSDictionary) y.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the changes along the y-axis. * * @param changeYs changes along the y-axis */ public void setChangeYs(PDNumberFormatDictionary[] changeYs) { COSArray array = new COSArray(); for (PDNumberFormatDictionary changeY : changeYs) { array.add(changeY); } this.getCOSObject().setItem(COSName.Y, array); } /** * This will return the distances. * * @return distances */ public PDNumberFormatDictionary[] getDistances() { COSArray d = getCOSObject().getCOSArray(COSName.D); if (d != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[d.size()]; for (int i = 0; i < d.size(); i++) { COSDictionary dic = (COSDictionary) d.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the distances. * * @param distances distances */ public void setDistances(PDNumberFormatDictionary[] distances) { COSArray array = new COSArray(); for (PDNumberFormatDictionary distance : distances) { array.add(distance); } this.getCOSObject().setItem(COSName.D, array); } /** * This will return the areas. * * @return areas */ public PDNumberFormatDictionary[] getAreas() { COSArray a = getCOSObject().getCOSArray(COSName.A); if (a != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[a.size()]; for (int i = 0; i < a.size(); i++) { COSDictionary dic = (COSDictionary) a.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the areas. * * @param areas areas */ public void setAreas(PDNumberFormatDictionary[] areas) { COSArray array = new COSArray(); for (PDNumberFormatDictionary area : areas) { array.add(area); } this.getCOSObject().setItem(COSName.A, array); } /** * This will return the angles. * * @return angles */ public PDNumberFormatDictionary[] getAngles() { COSArray t = getCOSObject().getCOSArray(COSName.T); if (t != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[t.size()]; for (int i = 0; i < t.size(); i++) { COSDictionary dic = (COSDictionary) t.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the angles. * * @param angles angles */ public void setAngles(PDNumberFormatDictionary[] angles) { COSArray array = new COSArray(); for (PDNumberFormatDictionary angle : angles) { array.add(angle); } this.getCOSObject().setItem(COSName.T, array); } /** * This will return the sloaps of a line. * * @return the sloaps of a line */ public PDNumberFormatDictionary[] getLineSloaps() { COSArray s = getCOSObject().getCOSArray(COSName.S); if (s != null) { PDNumberFormatDictionary[] retval = new PDNumberFormatDictionary[s.size()]; for (int i = 0; i < s.size(); i++) { COSDictionary dic = (COSDictionary) s.get(i); retval[i] = new PDNumberFormatDictionary(dic); } return retval; } return null; } /** * This will set the sloaps of a line. * * @param lineSloaps the sloaps of a line */ public void setLineSloaps(PDNumberFormatDictionary[] lineSloaps) { COSArray array = new COSArray(); for (PDNumberFormatDictionary lineSloap : lineSloaps) { array.add(lineSloap); } this.getCOSObject().setItem(COSName.S, array); } /** * This will return the origin of the coordinate system. * * @return the origin */ public float[] getCoordSystemOrigin() { COSArray o = getCOSObject().getCOSArray(COSName.O); return o != null ? o.toFloatArray() : null; } /** * This will set the origin of the coordinate system. * * @param coordSystemOrigin the origin */ public void setCoordSystemOrigin(float[] coordSystemOrigin) { COSArray array = new COSArray(); array.setFloatArray(coordSystemOrigin); this.getCOSObject().setItem(COSName.O, array); } /** * This will return the CYX factor. * * @return CYX factor */ public float getCYX() { return this.getCOSObject().getFloat(COSName.CYX); } /** * This will set the CYX factor. * * @param cyx CYX factor */ public void setCYX(float cyx) { this.getCOSObject().setFloat(COSName.CYX, cyx); } }
4,144
389
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.internal.gosu.annotations; import gw.lang.reflect.IType; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import gw.lang.annotation.Annotations; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Collections; import java.lang.annotation.Annotation; public class AnnotationMap { private Map<String, List> _annotationsByFeatureName = new HashMap<String, List>(); private List _currentAnnotationList; private Annotations.Builder _currentJavaAnnotationBuilder; private IJavaType _currentJavaType; public AnnotationMap startAnnotationInfoForFeature( String featureId ) { _currentAnnotationList = new ArrayList(); _annotationsByFeatureName.put( featureId, _currentAnnotationList ); return this; } public AnnotationMap startJavaAnnotation( IType type ) { _currentJavaType = (IJavaType)type; Class annotationClass = _currentJavaType.getBackingClass(); _currentJavaAnnotationBuilder = Annotations.builder( annotationClass ); return this; } public AnnotationMap withArg( String name, Object arg ) { _currentJavaAnnotationBuilder.withElement( name, arg ); return this; } public AnnotationMap finishJavaAnnotation() { Annotation annotation = _currentJavaAnnotationBuilder.create(); _currentAnnotationList.add( annotation ); return this; } public AnnotationMap addGosuAnnotation( Object annotation ) { _currentAnnotationList.add( annotation ); return this; } public Map<String, List> getAnnotations() { return Collections.unmodifiableMap( _annotationsByFeatureName ); } }
551
776
<filename>src/stubgenerator/server/cppserverstubgenerator.h /************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file serverstubgenerator.h * @date 01.05.2013 * @author <NAME> <<EMAIL>> * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SERVERSTUBGENERATOR_H #define JSONRPC_CPP_SERVERSTUBGENERATOR_H #include "../codegenerator.h" #include "../stubgenerator.h" namespace jsonrpc { class CPPServerStubGenerator : public StubGenerator { public: CPPServerStubGenerator(const std::string &stubname, std::vector<Procedure> &procedures, std::ostream &outputstream); CPPServerStubGenerator(const std::string &stubname, std::vector<Procedure> &procedures, const std::string &filename); virtual void generateStub(); void generateBindings(); void generateProcedureDefinitions(); void generateAbstractDefinitions(); std::string generateBindingParameterlist(const Procedure &proc); void generateParameterMapping(const Procedure &proc); }; } // namespace jsonrpc #endif // JSONRPC_CPP_SERVERSTUBGENERATOR_H
375
6,098
package water.rapids.ast.prims.string; import water.Iced; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.parser.BufferedString; import water.rapids.Val; import water.rapids.ast.AstBuiltin; import water.rapids.vals.ValFrame; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Searches for matches to argument "regex" within each element * of a string column. * * Params: * - regex regular expression * - ignore_case if ignore_case == 1, matching is case insensitive * - invert if invert == 1, identifies elements that do not match the regex * - output_logical if output_logical == 1, result will be a logical vector, otherwise returns matching positions */ public class AstGrep extends AstBuiltin<AstGrep> { @Override public String[] args() { return new String[]{"ary", "regex", "ignore_case", "invert", "output_logical"}; } @Override public int nargs() { return 1 + 5; } // (grep x regex ignore_case invert output_logical) @Override public String str() { return "grep"; } @Override protected Val exec(Val[] args) { Frame fr = args[1].getFrame(); String regex = args[2].getStr(); boolean ignoreCase = args[3].getNum() == 1; boolean invert = args[4].getNum() == 1; boolean outputLogical = args[5].getNum() == 1; GrepHelper grepHelper = new GrepHelper(regex, ignoreCase, invert, outputLogical); if ((fr.numCols() != 1) || ! (fr.anyVec().isCategorical() || fr.anyVec().isString())) throw new IllegalArgumentException("can only grep on a single categorical/string column."); Vec v = fr.anyVec(); assert v != null; Frame result; if (v.isCategorical()) { int[] filtered = grepDomain(grepHelper, v); Arrays.sort(filtered); result = new GrepCatTask(grepHelper, filtered).doAll(Vec.T_NUM, v).outputFrame(); } else { result = new GrepStrTask(grepHelper).doAll(Vec.T_NUM, v).outputFrame(); } return new ValFrame(result); } private static int[] grepDomain(GrepHelper grepHelper, Vec v) { Pattern p = grepHelper.compilePattern(); String[] domain = v.domain(); int cnt = 0; int[] filtered = new int[domain.length]; for (int i = 0; i < domain.length; i++) { if (p.matcher(domain[i]).find()) filtered[cnt++] = i; } int[] result = new int[cnt]; System.arraycopy(filtered, 0, result, 0, cnt); return result; } private static class GrepCatTask extends MRTask<GrepCatTask> { private final int[] _matchingCats; private final GrepHelper _gh; GrepCatTask(GrepHelper gh, int[] matchingCats) { _matchingCats = matchingCats; _gh = gh; } @Override public void map(Chunk c, NewChunk n) { OutputWriter w = OutputWriter.makeWriter(_gh, n, c.start()); int rows = c._len; for (int r = 0; r < rows; r++) { if (c.isNA(r)) { w.addNA(r); } else { int cat = (int) c.at8(r); int pos = Arrays.binarySearch(_matchingCats, cat); w.addRow(r, pos >= 0); } } } } private static class GrepStrTask extends MRTask<GrepStrTask> { private final GrepHelper _gh; GrepStrTask(GrepHelper gh) { _gh = gh; } @Override public void map(Chunk c, NewChunk n) { OutputWriter w = OutputWriter.makeWriter(_gh, n, c.start()); Pattern p = _gh.compilePattern(); Matcher m = p.matcher(""); BufferedString bs = new BufferedString(); int rows = c._len; for (int r = 0; r < rows; r++) { if (c.isNA(r)) { w.addNA(r); } else { m.reset(c.atStr(bs, r).toString()); w.addRow(r, m.find()); } } } } private static class GrepHelper extends Iced<GrepHelper> { private String _regex; private boolean _ignoreCase; private boolean _invert; private boolean _outputLogical; public GrepHelper() {} GrepHelper(String regex, boolean ignoreCase, boolean invert, boolean outputLogical) { _regex = regex; _ignoreCase = ignoreCase; _invert = invert; _outputLogical = outputLogical; } Pattern compilePattern() { int flags = _ignoreCase ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE : 0; return Pattern.compile(_regex, flags); } } private static abstract class OutputWriter { static final double MATCH = 1; static final double NO_MATCH = 0; NewChunk _nc; long _start; boolean _invert; OutputWriter(NewChunk nc, long start, boolean invert) { _nc = nc; _start = start; _invert = invert; } abstract void addNA(int row); abstract void addRow(int row, boolean matched); static OutputWriter makeWriter(GrepHelper gh, NewChunk nc, long start) { return gh._outputLogical ? new IndicatorWriter(nc, start, gh._invert) : new PositionWriter(nc, start, gh._invert); } } private static class IndicatorWriter extends OutputWriter { IndicatorWriter(NewChunk nc, long start, boolean invert) { super(nc, start, invert); } @Override void addNA(int row) { _nc.addNum(_invert ? MATCH : NO_MATCH); } @Override void addRow(int row, boolean matched) { _nc.addNum(matched != _invert ? MATCH : NO_MATCH); } } private static class PositionWriter extends OutputWriter { PositionWriter(NewChunk nc, long start, boolean invert) { super(nc, start, invert); } @Override void addNA(int row) { if (_invert) _nc.addNum(_start + row); } @Override void addRow(int row, boolean matched) { if (matched != _invert) _nc.addNum(_start + row); } } }
2,311
1,500
<gh_stars>1000+ package xtdb.calcite; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexNode; import com.google.common.collect.ImmutableList; import clojure.lang.Keyword; import clojure.lang.IFn; import java.util.List; import java.util.Map; public class XtdbProject extends Project implements XtdbRel { private final IFn projectFn; private final List<? extends RexNode> projects; public XtdbProject(RelOptCluster cluster, RelTraitSet traitSet, RelNode input, List<? extends RexNode> projects, RelDataType rowType) { super(cluster, traitSet, ImmutableList.of(), input, projects, rowType); assert getConvention() == XtdbRel.CONVENTION; this.projects = projects; this.projectFn = XtdbUtils.resolveWithErrorLogging("xtdb.calcite/enrich-project"); } @Override public Project copy(RelTraitSet traitSet, RelNode input, List<RexNode> projects, RelDataType rowType) { return new XtdbProject(input.getCluster(), traitSet, input, projects, rowType); } @SuppressWarnings("unchecked") @Override public void implement(Implementor implementor) { implementor.visitChild(0, getInput()); implementor.schema = (Map<Keyword, Object>) projectFn.invoke(implementor.schema, getNamedProjects()); } @Override public RelOptTable getTable() { return getInput().getTable(); } }
639
316
package pv.com.pvcloudgo.model.bean; import java.io.Serializable; /** * Created by stefan on 17/1/4. */ public class Account implements Serializable { String whoclassName; String id; String whoId; String whoName; String withdrawalsPwd; float totalPrice; float frozenPrice; float availablePrice; String isQueren; String addressId; String addressTreeIds; public String getWhoclassName() { return whoclassName; } public String getId() { return id; } public String getWhoId() { return whoId; } public String getWhoName() { return whoName; } public String getWithdrawalsPwd() { return withdrawalsPwd; } public float getTotalPrice() { return totalPrice; } public float getFrozenPrice() { return frozenPrice; } public float getAvailablePrice() { return availablePrice; } public String getIsQueren() { return isQueren; } public String getAddressId() { return addressId; } public String getAddressTreeIds() { return addressTreeIds; } }
470
2,338
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++14 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++2a %s // Verify that using an initializer list for a non-aggregate looks for // constructors.. struct NonAggr1 { // expected-note 2 {{candidate constructor}} NonAggr1(int, int) { } // expected-note {{candidate constructor}} int m; }; struct Base { }; struct NonAggr2 : public Base { // expected-note 0-3 {{candidate constructor}} int m; }; class NonAggr3 { // expected-note 3 {{candidate constructor}} int m; }; struct NonAggr4 { // expected-note 3 {{candidate constructor}} int m; virtual void f(); }; NonAggr1 na1 = { 17 }; // expected-error{{no matching constructor for initialization of 'NonAggr1'}} NonAggr2 na2 = { 17 }; NonAggr3 na3 = { 17 }; // expected-error{{no matching constructor for initialization of 'NonAggr3'}} NonAggr4 na4 = { 17 }; // expected-error{{no matching constructor for initialization of 'NonAggr4'}} #if __cplusplus <= 201402L // expected-error@-4{{no matching constructor for initialization of 'NonAggr2'}} #else // expected-error@-6{{requires explicit braces}} NonAggr2 na2b = { {}, 17 }; // ok #endif // PR5817 typedef int type[][2]; const type foo = {0}; // Vector initialization. typedef short __v4hi __attribute__ ((__vector_size__ (8))); __v4hi v1 = { (void *)1, 2, 3 }; // expected-error {{cannot initialize a vector element of type 'short' with an rvalue of type 'void *'}} // Array initialization. int a[] = { (void *)1 }; // expected-error {{cannot initialize an array element of type 'int' with an rvalue of type 'void *'}} // Struct initialization. struct S { int a; } s = { (void *)1 }; // expected-error {{cannot initialize a member subobject of type 'int' with an rvalue of type 'void *'}} // Check that we're copy-initializing the structs. struct A { A(); A(int); ~A(); A(const A&) = delete; // expected-note 0-2{{'A' has been explicitly marked deleted here}} }; struct B { A a; }; struct C { const A& a; }; void f() { A as1[1] = { }; A as2[1] = { 1 }; #if __cplusplus <= 201402L // expected-error@-2 {{copying array element of type 'A' invokes deleted constructor}} #endif B b1 = { }; B b2 = { 1 }; #if __cplusplus <= 201402L // expected-error@-2 {{copying member subobject of type 'A' invokes deleted constructor}} #endif C c1 = { 1 }; } class Agg { public: int i, j; }; class AggAgg { public: Agg agg1; Agg agg2; }; AggAgg aggagg = { 1, 2, 3, 4 }; namespace diff_cpp14_dcl_init_aggr_example { struct derived; struct base { friend struct derived; private: base(); }; struct derived : base {}; derived d1{}; #if __cplusplus > 201402L // expected-error@-2 {{private}} // expected-note@-7 {{here}} #endif derived d2; } namespace ProtectedBaseCtor { // FIXME: It's unclear whether f() and g() should be valid in C++1z. What is // the object expression in a constructor call -- the base class subobject or // the complete object? struct A { protected: A(); }; struct B : public A { friend B f(); friend B g(); friend B h(); }; B f() { return {}; } #if __cplusplus > 201402L // expected-error@-2 {{protected default constructor}} // expected-note@-12 {{here}} #endif B g() { return {{}}; } #if __cplusplus <= 201402L // expected-error@-2 {{no matching constructor}} // expected-note@-15 3{{candidate}} #else // expected-error@-5 {{protected default constructor}} // expected-note@-21 {{here}} #endif B h() { return {A{}}; } #if __cplusplus <= 201402L // expected-error@-2 {{no matching constructor}} // expected-note@-24 3{{candidate}} #endif // expected-error@-5 {{protected constructor}} // expected-note@-30 {{here}} } namespace IdiomaticStdArrayInitDoesNotWarn { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wmissing-braces" template<typename T, int N> struct StdArray { T contents[N]; }; StdArray<int, 3> x = {1, 2, 3}; template<typename T, int N> struct ArrayAndSomethingElse { T contents[N]; int something_else; }; ArrayAndSomethingElse<int, 3> y = {1, 2, 3}; // expected-warning {{suggest braces}} #if __cplusplus >= 201703L template<typename T, int N> struct ArrayAndBaseClass : StdArray<int, 3> { T contents[N]; }; ArrayAndBaseClass<int, 3> z = {1, 2, 3}; // expected-warning {{suggest braces}} // This pattern is used for tagged aggregates and must not warn template<typename T, int N> struct JustABaseClass : StdArray<T, N> {}; JustABaseClass<int, 3> w = {1, 2, 3}; // but this should be also ok JustABaseClass<int, 3> v = {{1, 2, 3}}; template <typename T, int N> struct OnionBaseClass : JustABaseClass<T, N> {}; OnionBaseClass<int, 3> u = {1, 2, 3}; OnionBaseClass<int, 3> t = {{{1, 2, 3}}}; struct EmptyBase {}; template <typename T, int N> struct AggregateAndEmpty : StdArray<T, N>, EmptyBase {}; AggregateAndEmpty<int, 3> p = {1, 2, 3}; // expected-warning {{suggest braces}} #endif #pragma clang diagnostic pop } namespace HugeArraysUseArrayFiller { // All we're checking here is that initialization completes in a reasonable // amount of time. struct A { int n; int arr[1000 * 1000 * 1000]; } a = {1, {2}}; } namespace ElementDestructor { // The destructor for each element of class type is potentially invoked // (15.4 [class.dtor]) from the context where the aggregate initialization // occurs. Produce a diagnostic if an element's destructor isn't accessible. class X { int f; ~X(); }; // expected-note {{implicitly declared private here}} struct Y { X x; }; void test0() { auto *y = new Y {}; // expected-error {{temporary of type 'ElementDestructor::X' has private destructor}} } struct S0 { int f; ~S0() = delete; }; // expected-note 3 {{'~S0' has been explicitly marked deleted here}} struct S1 { S0 s0; int f; }; S1 test1() { auto *t = new S1 { .f = 1 }; // expected-error {{attempt to use a deleted function}} return {2}; // expected-error {{attempt to use a deleted function}} } // Check if the type of an array element has a destructor. struct S2 { S0 a[4]; }; void test2() { auto *t = new S2 {1,2,3,4}; // expected-error {{attempt to use a deleted function}} } #if __cplusplus >= 201703L namespace BaseDestructor { struct S0 { int f; ~S0() = delete; }; // expected-note {{'~S0' has been explicitly marked deleted here}} // Check destructor of base class. struct S3 : S0 {}; void test3() { S3 s3 = {1}; // expected-error {{attempt to use a deleted function}} } } #endif // A's destructor doesn't have to be accessible from the context of C's // initialization. struct A { friend struct B; private: ~A(); }; struct B { B(); A a; }; struct C { B b; }; C c = { B() }; }
2,416
3,084
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: util.cpp Abstract: This module contains the internal helper function definitions for the SpbTestTool app. Environment: user-mode Revision History: --*/ #include "internal.h" _Success_(return) bool PopStringParameter( _Inout_ list<string> *Parameters, _Out_ string *Value, _Out_opt_ bool *Present ) { if (Parameters->empty()) { if (Present != nullptr) { *Present = false; *Value = string(""); return true; } else { printf("Missing required parameter\n"); return false; } } if (Present != nullptr) { *Present = true; } *Value = Parameters->front(); Parameters->pop_front(); return true; } _Success_(return) bool ParseNumber( _In_ const string &String, _In_ ULONG Radix, _Out_ ULONG *Value, _In_opt_ bounds Bounds ) { PSTR end; #pragma prefast(suppress:__WARNING_MISSING_ZERO_TERMINATION2 ,"zero-termination is checked below") *Value = strtoul(String.c_str(), &end, Radix); // // Make sure the entire string parsed. // if (*end != '\0') { printf("Value %s is not a number\n", String.c_str()); return false; } // // See if we should do a bounds check. // if ((Bounds.first != 0) || (Bounds.second != 0)) { if ((*Value < Bounds.first) || (*Value > Bounds.second)) { printf("Value %s is out of bounds\n", String.c_str()); return false; } } return true; } _Success_(return) bool PopNumberParameter( _Inout_ list<string> *Parameters, _In_ ULONG Radix, _Out_ ULONG *Value, _In_opt_ bounds Bounds, _Out_opt_ bool *Present ) { string s; bool found = PopStringParameter(Parameters, &s, Present); if ((Present != nullptr) && (*Present == false)) { *Value = Bounds.first; return true; } else if (found == false) { return false; } return ParseNumber(s, Radix, Value, Bounds); } _Success_(return) bool PopBufferParameter( _Inout_ list<string> *Parameters, _Out_ pair<ULONG, PBYTE> *Value ) { ULONG length = 0; PBYTE buffer = nullptr; // // Check for an explict length // if (Parameters->front() != "{") { if (PopNumberParameter(Parameters, 10, &length) == false) { printf("Length expected\n"); return false; } // // Consume any leading { // if ((Parameters->empty() == false) && (Parameters->front() == "{")) { Parameters->pop_front(); } } else { string tmp; if (PopStringParameter(Parameters, &tmp) == false) { return false; } else if (tmp != "{") { printf("output buffer must start with {\n"); return false; } // // Count values until the trailing } - assume one byte per value // list<string>::iterator i; for(i = Parameters->begin(); ((i != Parameters->end()) && (*i != "}")); i++) { length += 1; } if (*i != "}") { printf("output buffer must end with }\n"); return false; } } if (length != 0) { ULONG b = 0; bool bufferEnd = false; // // Allocate the buffer. // buffer = new BYTE[length]; for(b = 0; b < length; b += 1) { ULONG value = 0; if (bufferEnd == false) { string nextElement; PopStringParameter(Parameters, &nextElement); if (nextElement == "}") { value = 0; bufferEnd = true; } else if (ParseNumber(nextElement, 16, &value, bounds(0, 0xff)) == false) { printf("invalid byte value %s\n", nextElement.c_str()); delete [] buffer; return false; } } buffer[b] = (BYTE) value; } if (bufferEnd == false) { string end; if (PopStringParameter(Parameters, &end) == false) { printf("unclosed buffer\n"); delete [] buffer; return false; } else if (end != "}") { printf("buffer has too many initializers\n"); delete [] buffer; return false; } } } Value->first = length; Value->second = buffer; return true; }
2,919
20,995
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/heap/free-list.h" #include "src/base/macros.h" #include "src/common/globals.h" #include "src/heap/free-list-inl.h" #include "src/heap/heap.h" #include "src/heap/memory-chunk-inl.h" #include "src/objects/free-space-inl.h" namespace v8 { namespace internal { // ----------------------------------------------------------------------------- // Free lists for old object spaces implementation void FreeListCategory::Reset(FreeList* owner) { if (is_linked(owner) && !top().is_null()) { owner->DecreaseAvailableBytes(available_); } set_top(FreeSpace()); set_prev(nullptr); set_next(nullptr); available_ = 0; } FreeSpace FreeListCategory::PickNodeFromList(size_t minimum_size, size_t* node_size) { FreeSpace node = top(); DCHECK(!node.is_null()); DCHECK(Page::FromHeapObject(node)->CanAllocate()); if (static_cast<size_t>(node.Size()) < minimum_size) { *node_size = 0; return FreeSpace(); } set_top(node.next()); *node_size = node.Size(); UpdateCountersAfterAllocation(*node_size); return node; } FreeSpace FreeListCategory::SearchForNodeInList(size_t minimum_size, size_t* node_size) { FreeSpace prev_non_evac_node; for (FreeSpace cur_node = top(); !cur_node.is_null(); cur_node = cur_node.next()) { DCHECK(Page::FromHeapObject(cur_node)->CanAllocate()); size_t size = cur_node.size(kRelaxedLoad); if (size >= minimum_size) { DCHECK_GE(available_, size); UpdateCountersAfterAllocation(size); if (cur_node == top()) { set_top(cur_node.next()); } if (!prev_non_evac_node.is_null()) { MemoryChunk* chunk = MemoryChunk::FromHeapObject(prev_non_evac_node); if (chunk->owner_identity() == CODE_SPACE) { chunk->heap()->UnprotectAndRegisterMemoryChunk( chunk, UnprotectMemoryOrigin::kMaybeOffMainThread); } prev_non_evac_node.set_next(cur_node.next()); } *node_size = size; return cur_node; } prev_non_evac_node = cur_node; } return FreeSpace(); } void FreeListCategory::Free(Address start, size_t size_in_bytes, FreeMode mode, FreeList* owner) { FreeSpace free_space = FreeSpace::cast(HeapObject::FromAddress(start)); free_space.set_next(top()); set_top(free_space); available_ += size_in_bytes; if (mode == kLinkCategory) { if (is_linked(owner)) { owner->IncreaseAvailableBytes(size_in_bytes); } else { owner->AddCategory(this); } } } void FreeListCategory::RepairFreeList(Heap* heap) { Map free_space_map = ReadOnlyRoots(heap).free_space_map(); FreeSpace n = top(); while (!n.is_null()) { ObjectSlot map_slot = n.map_slot(); if (map_slot.contains_map_value(kNullAddress)) { map_slot.store_map(free_space_map); } else { DCHECK(map_slot.contains_map_value(free_space_map.ptr())); } n = n.next(); } } void FreeListCategory::Relink(FreeList* owner) { DCHECK(!is_linked(owner)); owner->AddCategory(this); } // ------------------------------------------------ // Generic FreeList methods (alloc/free related) FreeList* FreeList::CreateFreeList() { return new FreeListManyCachedOrigin(); } FreeSpace FreeList::TryFindNodeIn(FreeListCategoryType type, size_t minimum_size, size_t* node_size) { FreeListCategory* category = categories_[type]; if (category == nullptr) return FreeSpace(); FreeSpace node = category->PickNodeFromList(minimum_size, node_size); if (!node.is_null()) { DecreaseAvailableBytes(*node_size); DCHECK(IsVeryLong() || Available() == SumFreeLists()); } if (category->is_empty()) { RemoveCategory(category); } return node; } FreeSpace FreeList::SearchForNodeInList(FreeListCategoryType type, size_t minimum_size, size_t* node_size) { FreeListCategoryIterator it(this, type); FreeSpace node; while (it.HasNext()) { FreeListCategory* current = it.Next(); node = current->SearchForNodeInList(minimum_size, node_size); if (!node.is_null()) { DecreaseAvailableBytes(*node_size); DCHECK(IsVeryLong() || Available() == SumFreeLists()); if (current->is_empty()) { RemoveCategory(current); } return node; } } return node; } size_t FreeList::Free(Address start, size_t size_in_bytes, FreeMode mode) { Page* page = Page::FromAddress(start); page->DecreaseAllocatedBytes(size_in_bytes); // Blocks have to be a minimum size to hold free list items. if (size_in_bytes < min_block_size_) { page->add_wasted_memory(size_in_bytes); wasted_bytes_ += size_in_bytes; return size_in_bytes; } // Insert other blocks at the head of a free list of the appropriate // magnitude. FreeListCategoryType type = SelectFreeListCategoryType(size_in_bytes); page->free_list_category(type)->Free(start, size_in_bytes, mode, this); DCHECK_EQ(page->AvailableInFreeList(), page->AvailableInFreeListFromAllocatedBytes()); return 0; } // ------------------------------------------------ // FreeListMany implementation constexpr unsigned int FreeListMany::categories_min[kNumberOfCategories]; FreeListMany::FreeListMany() { // Initializing base (FreeList) fields number_of_categories_ = kNumberOfCategories; last_category_ = number_of_categories_ - 1; min_block_size_ = kMinBlockSize; categories_ = new FreeListCategory*[number_of_categories_](); Reset(); } FreeListMany::~FreeListMany() { delete[] categories_; } size_t FreeListMany::GuaranteedAllocatable(size_t maximum_freed) { if (maximum_freed < categories_min[0]) { return 0; } for (int cat = kFirstCategory + 1; cat <= last_category_; cat++) { if (maximum_freed < categories_min[cat]) { return categories_min[cat - 1]; } } return maximum_freed; } Page* FreeListMany::GetPageForSize(size_t size_in_bytes) { FreeListCategoryType minimum_category = SelectFreeListCategoryType(size_in_bytes); Page* page = nullptr; for (int cat = minimum_category + 1; !page && cat <= last_category_; cat++) { page = GetPageForCategoryType(cat); } if (!page) { // Might return a page in which |size_in_bytes| will not fit. page = GetPageForCategoryType(minimum_category); } return page; } FreeSpace FreeListMany::Allocate(size_t size_in_bytes, size_t* node_size, AllocationOrigin origin) { DCHECK_GE(kMaxBlockSize, size_in_bytes); FreeSpace node; FreeListCategoryType type = SelectFreeListCategoryType(size_in_bytes); for (int i = type; i < last_category_ && node.is_null(); i++) { node = TryFindNodeIn(static_cast<FreeListCategoryType>(i), size_in_bytes, node_size); } if (node.is_null()) { // Searching each element of the last category. node = SearchForNodeInList(last_category_, size_in_bytes, node_size); } if (!node.is_null()) { Page::FromHeapObject(node)->IncreaseAllocatedBytes(*node_size); } DCHECK(IsVeryLong() || Available() == SumFreeLists()); return node; } // ------------------------------------------------ // FreeListManyCached implementation FreeListManyCached::FreeListManyCached() { ResetCache(); } void FreeListManyCached::Reset() { ResetCache(); FreeListMany::Reset(); } bool FreeListManyCached::AddCategory(FreeListCategory* category) { bool was_added = FreeList::AddCategory(category); // Updating cache if (was_added) { UpdateCacheAfterAddition(category->type_); } #ifdef DEBUG CheckCacheIntegrity(); #endif return was_added; } void FreeListManyCached::RemoveCategory(FreeListCategory* category) { FreeList::RemoveCategory(category); // Updating cache int type = category->type_; if (categories_[type] == nullptr) { UpdateCacheAfterRemoval(type); } #ifdef DEBUG CheckCacheIntegrity(); #endif } size_t FreeListManyCached::Free(Address start, size_t size_in_bytes, FreeMode mode) { Page* page = Page::FromAddress(start); page->DecreaseAllocatedBytes(size_in_bytes); // Blocks have to be a minimum size to hold free list items. if (size_in_bytes < min_block_size_) { page->add_wasted_memory(size_in_bytes); wasted_bytes_ += size_in_bytes; return size_in_bytes; } // Insert other blocks at the head of a free list of the appropriate // magnitude. FreeListCategoryType type = SelectFreeListCategoryType(size_in_bytes); page->free_list_category(type)->Free(start, size_in_bytes, mode, this); // Updating cache if (mode == kLinkCategory) { UpdateCacheAfterAddition(type); #ifdef DEBUG CheckCacheIntegrity(); #endif } DCHECK_EQ(page->AvailableInFreeList(), page->AvailableInFreeListFromAllocatedBytes()); return 0; } FreeSpace FreeListManyCached::Allocate(size_t size_in_bytes, size_t* node_size, AllocationOrigin origin) { USE(origin); DCHECK_GE(kMaxBlockSize, size_in_bytes); FreeSpace node; FreeListCategoryType type = SelectFreeListCategoryType(size_in_bytes); type = next_nonempty_category[type]; for (; type < last_category_; type = next_nonempty_category[type + 1]) { node = TryFindNodeIn(type, size_in_bytes, node_size); if (!node.is_null()) break; } if (node.is_null()) { // Searching each element of the last category. type = last_category_; node = SearchForNodeInList(type, size_in_bytes, node_size); } // Updating cache if (!node.is_null() && categories_[type] == nullptr) { UpdateCacheAfterRemoval(type); } #ifdef DEBUG CheckCacheIntegrity(); #endif if (!node.is_null()) { Page::FromHeapObject(node)->IncreaseAllocatedBytes(*node_size); } DCHECK(IsVeryLong() || Available() == SumFreeLists()); return node; } // ------------------------------------------------ // FreeListManyCachedFastPath implementation FreeSpace FreeListManyCachedFastPath::Allocate(size_t size_in_bytes, size_t* node_size, AllocationOrigin origin) { USE(origin); DCHECK_GE(kMaxBlockSize, size_in_bytes); FreeSpace node; // Fast path part 1: searching the last categories FreeListCategoryType first_category = SelectFastAllocationFreeListCategoryType(size_in_bytes); FreeListCategoryType type = first_category; for (type = next_nonempty_category[type]; type <= last_category_; type = next_nonempty_category[type + 1]) { node = TryFindNodeIn(type, size_in_bytes, node_size); if (!node.is_null()) break; } // Fast path part 2: searching the medium categories for tiny objects if (node.is_null()) { if (size_in_bytes <= kTinyObjectMaxSize) { for (type = next_nonempty_category[kFastPathFallBackTiny]; type < kFastPathFirstCategory; type = next_nonempty_category[type + 1]) { node = TryFindNodeIn(type, size_in_bytes, node_size); if (!node.is_null()) break; } } } // Searching the last category if (node.is_null()) { // Searching each element of the last category. type = last_category_; node = SearchForNodeInList(type, size_in_bytes, node_size); } // Finally, search the most precise category if (node.is_null()) { type = SelectFreeListCategoryType(size_in_bytes); for (type = next_nonempty_category[type]; type < first_category; type = next_nonempty_category[type + 1]) { node = TryFindNodeIn(type, size_in_bytes, node_size); if (!node.is_null()) break; } } // Updating cache if (!node.is_null() && categories_[type] == nullptr) { UpdateCacheAfterRemoval(type); } #ifdef DEBUG CheckCacheIntegrity(); #endif if (!node.is_null()) { Page::FromHeapObject(node)->IncreaseAllocatedBytes(*node_size); } DCHECK(IsVeryLong() || Available() == SumFreeLists()); return node; } // ------------------------------------------------ // FreeListManyCachedOrigin implementation FreeSpace FreeListManyCachedOrigin::Allocate(size_t size_in_bytes, size_t* node_size, AllocationOrigin origin) { if (origin == AllocationOrigin::kGC) { return FreeListManyCached::Allocate(size_in_bytes, node_size, origin); } else { return FreeListManyCachedFastPath::Allocate(size_in_bytes, node_size, origin); } } // ------------------------------------------------ // Generic FreeList methods (non alloc/free related) void FreeList::Reset() { ForAllFreeListCategories( [this](FreeListCategory* category) { category->Reset(this); }); for (int i = kFirstCategory; i < number_of_categories_; i++) { categories_[i] = nullptr; } wasted_bytes_ = 0; available_ = 0; } size_t FreeList::EvictFreeListItems(Page* page) { size_t sum = 0; page->ForAllFreeListCategories([this, &sum](FreeListCategory* category) { sum += category->available(); RemoveCategory(category); category->Reset(this); }); return sum; } void FreeList::RepairLists(Heap* heap) { ForAllFreeListCategories( [heap](FreeListCategory* category) { category->RepairFreeList(heap); }); } bool FreeList::AddCategory(FreeListCategory* category) { FreeListCategoryType type = category->type_; DCHECK_LT(type, number_of_categories_); FreeListCategory* top = categories_[type]; if (category->is_empty()) return false; DCHECK_NE(top, category); // Common double-linked list insertion. if (top != nullptr) { top->set_prev(category); } category->set_next(top); categories_[type] = category; IncreaseAvailableBytes(category->available()); return true; } void FreeList::RemoveCategory(FreeListCategory* category) { FreeListCategoryType type = category->type_; DCHECK_LT(type, number_of_categories_); FreeListCategory* top = categories_[type]; if (category->is_linked(this)) { DecreaseAvailableBytes(category->available()); } // Common double-linked list removal. if (top == category) { categories_[type] = category->next(); } if (category->prev() != nullptr) { category->prev()->set_next(category->next()); } if (category->next() != nullptr) { category->next()->set_prev(category->prev()); } category->set_next(nullptr); category->set_prev(nullptr); } void FreeList::PrintCategories(FreeListCategoryType type) { FreeListCategoryIterator it(this, type); PrintF("FreeList[%p, top=%p, %d] ", static_cast<void*>(this), static_cast<void*>(categories_[type]), type); while (it.HasNext()) { FreeListCategory* current = it.Next(); PrintF("%p -> ", static_cast<void*>(current)); } PrintF("null\n"); } size_t FreeListCategory::SumFreeList() { size_t sum = 0; FreeSpace cur = top(); while (!cur.is_null()) { // We can't use "cur->map()" here because both cur's map and the // root can be null during bootstrapping. DCHECK( cur.map_slot().contains_map_value(Page::FromHeapObject(cur) ->heap() ->isolate() ->root(RootIndex::kFreeSpaceMap) .ptr())); sum += cur.size(kRelaxedLoad); cur = cur.next(); } return sum; } int FreeListCategory::FreeListLength() { int length = 0; FreeSpace cur = top(); while (!cur.is_null()) { length++; cur = cur.next(); } return length; } #ifdef DEBUG bool FreeList::IsVeryLong() { int len = 0; for (int i = kFirstCategory; i < number_of_categories_; i++) { FreeListCategoryIterator it(this, static_cast<FreeListCategoryType>(i)); while (it.HasNext()) { len += it.Next()->FreeListLength(); if (len >= FreeListCategory::kVeryLongFreeList) return true; } } return false; } // This can take a very long time because it is linear in the number of entries // on the free list, so it should not be called if FreeListLength returns // kVeryLongFreeList. size_t FreeList::SumFreeLists() { size_t sum = 0; ForAllFreeListCategories( [&sum](FreeListCategory* category) { sum += category->SumFreeList(); }); return sum; } #endif } // namespace internal } // namespace v8
6,375
679
<reponame>Grosskopf/openoffice /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_comphelper.hxx" #include <comphelper/weakeventlistener.hxx> #include <osl/diagnose.h> //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //===================================================================== //= OWeakListenerAdapter //===================================================================== //--------------------------------------------------------------------- OWeakListenerAdapterBase::~OWeakListenerAdapterBase() { } //===================================================================== //= OWeakEventListenerAdapter //===================================================================== //--------------------------------------------------------------------- OWeakEventListenerAdapter::OWeakEventListenerAdapter( Reference< XWeak > _rxListener, Reference< XComponent > _rxBroadcaster ) :OWeakEventListenerAdapter_Base( _rxListener, _rxBroadcaster ) { // add ourself as listener to the broadcaster OSL_ENSURE( _rxBroadcaster.is(), "OWeakEventListenerAdapter::OWeakEventListenerAdapter: invalid broadcaster!" ); if ( _rxBroadcaster.is() ) { osl_incrementInterlockedCount( &m_refCount ); { _rxBroadcaster->addEventListener( this ); } osl_decrementInterlockedCount( &m_refCount ); OSL_ENSURE( m_refCount > 0, "OWeakEventListenerAdapter::OWeakEventListenerAdapter: oops - not to be used with implementations which hold their listeners weak!" ); // the one and only reason for this adapter class (A) is to add as listener to a component (C) which // holds its listeners hard, and forward all calls then to another listener (L) which is // held weak by A. // Now if C holds listeners weak, then we do not need A, we can add L directly to C. } OSL_ENSURE( getListener().is(), "OWeakEventListenerAdapter::OWeakEventListenerAdapter: invalid listener (does not support the XEventListener interface)!" ); } //--------------------------------------------------------------------- void SAL_CALL OWeakEventListenerAdapter::disposing( ) { Reference< XComponent > xBroadcaster( getBroadcaster( ), UNO_QUERY ); OSL_ENSURE( xBroadcaster.is(), "OWeakEventListenerAdapter::disposing: broadcaster is invalid in the meantime! How this?" ); if ( xBroadcaster.is() ) { xBroadcaster->removeEventListener( this ); } resetListener(); } //......................................................................... } // namespace comphelper //.........................................................................
922
5,788
<filename>shardingsphere-test/shardingsphere-integration-test/shardingsphere-integration-test-fixture/src/test/java/org/apache/shardingsphere/test/integration/env/database/embedded/type/MySQLEmbeddedDatabase.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.test.integration.env.database.embedded.type; import com.google.common.base.Enums; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.sun.jna.Platform; import com.wix.mysql.EmbeddedMysql; import com.wix.mysql.config.Charset; import com.wix.mysql.config.DownloadConfig; import com.wix.mysql.config.MysqldConfig; import com.wix.mysql.distribution.Version; import org.apache.shardingsphere.infra.database.type.DatabaseType; import org.apache.shardingsphere.infra.database.type.DatabaseTypeRegistry; import org.apache.shardingsphere.test.integration.env.database.embedded.EmbeddedDatabase; import org.apache.shardingsphere.test.integration.env.database.embedded.EmbeddedDatabaseDistributionProperties; import java.io.File; import java.util.Arrays; import java.util.stream.Collectors; /** * Embedded database for MySQL. */ public final class MySQLEmbeddedDatabase implements EmbeddedDatabase { private volatile EmbeddedMysql embeddedMySQL; @Override public void start(final EmbeddedDatabaseDistributionProperties embeddedDatabaseProps, final int port) { DatabaseType databaseType = DatabaseTypeRegistry.getActualDatabaseType(getType()); DownloadConfig downloadConfig = DownloadConfig.aDownloadConfig().withBaseUrl(embeddedDatabaseProps.getURL(databaseType)).build(); MysqldConfig.Builder mysqldConfigBuilder = MysqldConfig.aMysqldConfig(detectVersion(embeddedDatabaseProps.getVersion(databaseType))) .withCharset(Charset.UTF8MB4) .withTempDir(new File(downloadConfig.getCacheDir(), "runtime").getPath()) .withPort(port) .withUser("test", "test") .withServerVariable("bind-address", "0.0.0.0") .withServerVariable("innodb_flush_log_at_trx_commit", 2); if (!Platform.isWindows()) { mysqldConfigBuilder = mysqldConfigBuilder.withServerVariable("innodb_flush_method", "O_DIRECT"); } embeddedMySQL = EmbeddedMysql.anEmbeddedMysql(mysqldConfigBuilder.build(), downloadConfig).start(); } private Version detectVersion(final String distributionVersion) { Version version; if (Strings.isNullOrEmpty(distributionVersion) && Platform.isMac()) { String osName = System.getProperty("os.name"); String osVersion = System.getProperty("os.version"); if (osVersion.startsWith("10.6")) { version = Version.v5_5_40; } else if (osVersion.startsWith("10.9")) { version = Version.v5_6_24; } else if (osVersion.startsWith("10.10")) { version = Version.v5_7_10; } else if (osVersion.startsWith("10.11")) { version = Version.v5_7_16; } else if (osVersion.startsWith("10.12")) { version = Version.v5_7_19; } else if (osVersion.startsWith("10.13")) { version = Version.v8_0_11; } else if (osVersion.startsWith("10.14") || osVersion.startsWith("10.15")) { version = Version.v5_7_27; } else { throw new UnsupportedOperationException(String.format("%s-%s is not supported", osName, osVersion)); } } else if (Strings.isNullOrEmpty(distributionVersion) && com.sun.jna.Platform.isLinux()) { version = Version.v5_7_latest; } else if (Strings.isNullOrEmpty(distributionVersion) && com.sun.jna.Platform.isWindows()) { version = Version.v5_7_latest; } else { version = Enums.getIfPresent(Version.class, distributionVersion).orNull(); Preconditions.checkArgument(null != version, String.format("The current setup version %s is not supported, only the following versions [%s] are currently supported", distributionVersion, Arrays.stream(Version.values()).map(v -> String.join(".", v.getMajorVersion(), v.getMinorVersion() + "")).collect(Collectors.joining(", ")))); } return version; } @Override public void stop() { if (null != embeddedMySQL) { embeddedMySQL.stop(); embeddedMySQL = null; } } @Override public String getType() { return "MySQL"; } }
2,071
2,577
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.impl; 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.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl; import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl; import org.camunda.bpm.engine.impl.pvm.runtime.CompensationBehavior; import org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl; import org.camunda.bpm.engine.impl.util.EnsureUtil; import org.camunda.bpm.engine.runtime.ActivityInstance; /** * Maps an activity (plain activities + their containing flow scopes) to the scope executions * that are executing them. For every instance of a scope, there is one such execution. * * @author <NAME> */ public class ActivityExecutionTreeMapping { protected Map<ScopeImpl, Set<ExecutionEntity>> activityExecutionMapping; protected CommandContext commandContext; protected String processInstanceId; protected ProcessDefinitionImpl processDefinition; public ActivityExecutionTreeMapping(CommandContext commandContext, String processInstanceId) { this.activityExecutionMapping = new HashMap<ScopeImpl, Set<ExecutionEntity>>(); this.commandContext = commandContext; this.processInstanceId = processInstanceId; initialize(); } protected void submitExecution(ExecutionEntity execution, ScopeImpl scope) { getExecutions(scope).add(execution); } public Set<ExecutionEntity> getExecutions(ScopeImpl activity) { Set<ExecutionEntity> executionsForActivity = activityExecutionMapping.get(activity); if (executionsForActivity == null) { executionsForActivity = new HashSet<ExecutionEntity>(); activityExecutionMapping.put(activity, executionsForActivity); } return executionsForActivity; } public ExecutionEntity getExecution(ActivityInstance activityInstance) { ScopeImpl scope = null; if (activityInstance.getId().equals(activityInstance.getProcessInstanceId())) { scope = processDefinition; } else { scope = processDefinition.findActivity(activityInstance.getActivityId()); } return intersect( getExecutions(scope), activityInstance.getExecutionIds()); } protected ExecutionEntity intersect(Set<ExecutionEntity> executions, String[] executionIds) { Set<String> executionIdSet = new HashSet<String>(); for (String executionId : executionIds) { executionIdSet.add(executionId); } for (ExecutionEntity execution : executions) { if (executionIdSet.contains(execution.getId())) { return execution; } } throw new ProcessEngineException("Could not determine execution"); } protected void initialize() { ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId); this.processDefinition = processInstance.getProcessDefinition(); List<ExecutionEntity> executions = fetchExecutionsForProcessInstance(processInstance); executions.add(processInstance); List<ExecutionEntity> leaves = findLeaves(executions); assignExecutionsToActivities(leaves); } protected void assignExecutionsToActivities(List<ExecutionEntity> leaves) { for (ExecutionEntity leaf : leaves) { ScopeImpl activity = leaf.getActivity(); if (activity != null) { if (leaf.getActivityInstanceId() != null) { EnsureUtil.ensureNotNull("activity", activity); submitExecution(leaf, activity); } mergeScopeExecutions(leaf); } else if (leaf.isProcessInstanceExecution()) { submitExecution(leaf, leaf.getProcessDefinition()); } } } protected void mergeScopeExecutions(ExecutionEntity leaf) { Map<ScopeImpl, PvmExecutionImpl> mapping = leaf.createActivityExecutionMapping(); for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) { ScopeImpl scope = mappingEntry.getKey(); ExecutionEntity scopeExecution = (ExecutionEntity) mappingEntry.getValue(); submitExecution(scopeExecution, scope); } } protected List<ExecutionEntity> fetchExecutionsForProcessInstance(ExecutionEntity execution) { List<ExecutionEntity> executions = new ArrayList<ExecutionEntity>(); executions.addAll(execution.getExecutions()); for (ExecutionEntity child : execution.getExecutions()) { executions.addAll(fetchExecutionsForProcessInstance(child)); } return executions; } protected List<ExecutionEntity> findLeaves(List<ExecutionEntity> executions) { List<ExecutionEntity> leaves = new ArrayList<ExecutionEntity>(); for (ExecutionEntity execution : executions) { if (isLeaf(execution)) { leaves.add(execution); } } return leaves; } /** * event-scope executions are not considered in this mapping and must be ignored */ protected boolean isLeaf(ExecutionEntity execution) { if (CompensationBehavior.isCompensationThrowing(execution)) { return true; } else { return !execution.isEventScope() && execution.getNonEventScopeExecutions().isEmpty(); } } }
1,885
2,146
<gh_stars>1000+ #include <capnp/message.h> int main() { ::capnp::MallocMessageBuilder message; return 0; }
48
2,338
typedef struct { int anon_field_b; } StructB; namespace Namespace { template <typename T> struct AlsoInNamespace { T field; }; extern template struct AlsoInNamespace<int>; } // namespace Namespace
65
1,059
/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once /* * Tilck text mode color constants */ enum vga_color { /* regular (darker) colors */ COLOR_BLACK = 0, COLOR_BLUE = 1, COLOR_GREEN = 2, COLOR_CYAN = 3, COLOR_RED = 4, COLOR_MAGENTA = 5, COLOR_YELLOW = 6, /* on VGA this is kind-of brown */ COLOR_WHITE = 7, /* light gray */ /* brighter colors */ COLOR_BRIGHT_BLACK = 8, /* dark gray */ COLOR_BRIGHT_BLUE = 9, COLOR_BRIGHT_GREEN = 10, COLOR_BRIGHT_CYAN = 11, COLOR_BRIGHT_RED = 12, COLOR_BRIGHT_MAGENTA = 13, COLOR_BRIGHT_YELLOW = 14, COLOR_BRIGHT_WHITE = 15, }; #define make_color(fg, bg) ((u8)(((fg) | (bg) << 4))) #define get_color_fg(color) ((color) & 0xF) #define get_color_bg(color) (((color) >> 4) & 0xF) #define DEFAULT_FG_COLOR COLOR_WHITE #define DEFAULT_BG_COLOR COLOR_BLACK #define DEFAULT_COLOR16 (make_color(DEFAULT_FG_COLOR, DEFAULT_BG_COLOR)) /* * Entry defs (color + char): the hardware format (VGA textmode) is used also * by the hw-independent subsystems "term" and "fb_console", for convenience. */ #define make_vgaentry(c, color) ((u16)(((u16)c) | ((u16)color << 8))) #define vgaentry_get_fg(e) LO_BITS((e) >> 8, 4, u8) #define vgaentry_get_bg(e) LO_BITS((e) >> 12, 4, u8) #define vgaentry_get_char(e) LO_BITS((e), 8, u8) #define vgaentry_get_color(e) SHR_BITS((e), 8, u8)
732
1,338
<gh_stars>1000+ /* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #ifndef OBSERVABLE_H #define OBSERVABLE_H #include <List.h> class Observer; class Observable { public: Observable(); virtual ~Observable(); bool AddObserver(Observer* observer); bool RemoveObserver(Observer* observer); int32 CountObservers() const; Observer* ObserverAtFast(int32 index) const; void Notify() const; void SuspendNotifications(bool suspend); bool HasPendingNotifications() const { return fPendingNotifications; } private: BList fObservers; int32 fSuspended; mutable bool fPendingNotifications; }; class AutoNotificationSuspender { public: AutoNotificationSuspender(Observable* object) : fObject(object) { fObject->SuspendNotifications(true); } virtual ~AutoNotificationSuspender() { fObject->SuspendNotifications(false); } private: Observable* fObject; }; #endif // OBSERVABLE_H
498
4,772
package example.service; import example.repo.Customer1107Repository; import org.springframework.stereotype.Service; @Service public class Customer1107Service { public Customer1107Service(Customer1107Repository repo) {} }
64
340
<gh_stars>100-1000 def print_formatted(number): align = len(bin(number)[2:]) for num in range(1, number + 1): n_dec = str(num) n_oct = oct(num)[2:] n_hex = hex(num)[2:].upper() n_bin = bin(num)[2:] print(n_dec.rjust(align), n_oct.rjust(align), n_hex.rjust(align), n_bin.rjust(align))
166
713
package org.infinispan.configuration.parsing; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Namespace. An annotation which allows specifying the namespace recognized by an implementation of * a {@link ConfigurationParser}. If you need to specify multiple namespaces, use the * {@link Namespaces} annotation. * * @author <NAME> * @since 6.0 */ @Retention(RetentionPolicy.RUNTIME) @Repeatable(Namespaces.class) public @interface Namespace { /** * The URI of the namespace. Defaults to the empty string. */ String uri() default ""; /** * The root element of this namespace. */ String root(); /** * The first version of the schema where this is supported. Defaults to 7.0. Only considered if {@link #uri()} ends * with a wildcard */ String since() default "7.0"; /** * The last version of the schema where this is supported. Defaults to the current release. Only considered if {@link #uri()} ends * with a wildcard */ String until() default ""; }
342
763
package org.batfish.representation.vyos; import org.batfish.common.Warnings; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.routing_policy.expr.BooleanExpr; import org.batfish.datamodel.routing_policy.expr.BooleanExprs; import org.batfish.datamodel.routing_policy.expr.DestinationNetwork; import org.batfish.datamodel.routing_policy.expr.MatchPrefixSet; import org.batfish.datamodel.routing_policy.expr.NamedPrefixSet; /** * A route-map condition requiring the candidate route be for a network allowed by a specified * prefix-list. */ public class RouteMapMatchPrefixList implements RouteMapMatch { private final String _prefixList; private final int _statementLine; public RouteMapMatchPrefixList(String prefixList, int statementLine) { _prefixList = prefixList; _statementLine = statementLine; } public String getPrefixList() { return _prefixList; } @Override public BooleanExpr toBooleanExpr(VyosConfiguration vc, Configuration c, Warnings w) { PrefixList pl = vc.getPrefixLists().get(_prefixList); if (pl != null) { return new MatchPrefixSet(DestinationNetwork.instance(), new NamedPrefixSet(_prefixList)); } else { vc.undefined( VyosStructureType.PREFIX_LIST, _prefixList, VyosStructureUsage.ROUTE_MAP_MATCH_PREFIX_LIST, _statementLine); // TODO: see if vyos treats as true, false, or disallows return BooleanExprs.TRUE; } } }
534
364
<reponame>spring-operator/reactive-streams-commons package rsc.publisher; import org.junit.Test; import rsc.test.TestSubscriber; public class PublisherCountTest { @Test(expected = NullPointerException.class) public void sourceNull() { new PublisherCount<>(null); } public void normal() { TestSubscriber<Long> ts = new TestSubscriber<>(); new PublisherCount<>(new PublisherRange(1, 10)).subscribe(ts); ts.assertValue(10L) .assertComplete() .assertNoError(); } public void normalBackpressured() { TestSubscriber<Long> ts = new TestSubscriber<>(0); new PublisherCount<>(new PublisherRange(1, 10)).subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); ts.request(2); ts.assertValue(10L) .assertComplete() .assertNoError(); } }
387
3,442
<filename>src/net/java/sip/communicator/impl/gui/main/chat/conference/ConferenceChatContact.java /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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.java.sip.communicator.impl.gui.main.chat.conference; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.main.chat.*; import net.java.sip.communicator.service.protocol.*; /** * The <tt>ConferenceChatContact</tt> represents a <tt>ChatContact</tt> in a * conference chat. * * @author <NAME> * @author <NAME> */ public class ConferenceChatContact extends ChatContact<ChatRoomMember> { /** * Creates an instance of <tt>ChatContact</tt> by passing to it the * <tt>ChatRoomMember</tt> for which it is created. * * @param chatRoomMember the <tt>ChatRoomMember</tt> for which this * <tt>ChatContact</tt> is created. */ public ConferenceChatContact(ChatRoomMember chatRoomMember) { super(chatRoomMember); } /** * Implements ChatContact#getAvatarBytes(). Delegates to chatRoomMember. */ @Override public byte[] getAvatarBytes() { return descriptor.getAvatar(); } /** * Returns the contact name. * * @return the contact name */ @Override public String getName() { String name = descriptor.getName(); if (name == null || name.length() < 1) name = GuiActivator.getResources() .getI18NString("service.gui.UNKNOWN"); return name; } public ChatRoomMemberRole getRole() { return descriptor.getRole(); } /** * Implements ChatContact#getUID(). Delegates to * ChatRoomMember#getContactAddress() because it's supposed to be unique. */ @Override public String getUID() { return descriptor.getContactAddress(); } }
872
1,251
package cn.dblearn.blog.portal.book.controller; import cn.dblearn.blog.common.Result; import cn.dblearn.blog.common.constants.RedisCacheNames; import cn.dblearn.blog.common.util.PageUtils; import cn.dblearn.blog.entity.book.BookNote; import cn.dblearn.blog.portal.common.annotation.LogLike; import cn.dblearn.blog.portal.common.annotation.LogView; import cn.dblearn.blog.portal.book.service.BookNoteService; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.Map; /** * BookNoteNoteAdminController * * @author bobbi * @date 2018/11/20 20:25 * @email <EMAIL> * @description */ @RestController("bookNotePortalController") @CacheConfig(cacheNames = {RedisCacheNames.BOOKNOTE}) public class BookNoteController { @Resource private BookNoteService bookNoteService; @GetMapping("/bookNote/{bookNoteId}") @LogView(type = "bookNote") public Result getBookNote(@PathVariable Integer bookNoteId){ BookNote bookNote = bookNoteService.getById(bookNoteId); return Result.ok().put("bookNote",bookNote); } @GetMapping("/bookNotes") @Cacheable public Result list(@RequestParam Map<String, Object> params){ PageUtils page = bookNoteService.queryPageCondition(params); return Result.ok().put("page",page); } @PutMapping("/bookNote/like/{id}") @LogLike(type = "bookNote") public Result likeBookNote(@PathVariable Integer id) { return Result.ok(); } }
582
14,668
<filename>weblayer/shell/app/resource.h // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBLAYER_SHELL_APP_RESOURCE_H_ #define WEBLAYER_SHELL_APP_RESOURCE_H_ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by shell.rc // #define IDR_MAINFRAME 128 #define IDM_EXIT 105 #define IDM_CLOSE_WINDOW 106 #define IDM_NEW_WINDOW 107 #define IDC_WEBLAYERSHELL 109 #define IDD_ALERT 130 #define IDD_CONFIRM 131 #define IDD_PROMPT 132 #define IDC_NAV_BACK 1001 #define IDC_NAV_FORWARD 1002 #define IDC_NAV_RELOAD 1003 #define IDC_NAV_STOP 1004 #define IDC_PROMPTEDIT 1005 #define IDC_DIALOGTEXT 1006 #ifndef IDC_STATIC #define IDC_STATIC -1 #endif // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 130 #define _APS_NEXT_RESOURCE_VALUE 129 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 117 #endif #endif #endif // WEBLAYER_SHELL_APP_RESOURCE_H_
447
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.lib.lexer; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.api.lexer.Language; import org.netbeans.api.lexer.LanguagePath; import org.netbeans.api.lexer.PartType; import org.netbeans.api.lexer.TokenId; import org.netbeans.lib.editor.util.CharSequenceUtilities; import org.netbeans.spi.lexer.Lexer; import org.netbeans.spi.lexer.LexerInput; import org.netbeans.lib.lexer.token.AbstractToken; import org.netbeans.lib.lexer.token.CustomTextToken; import org.netbeans.lib.lexer.token.DefaultToken; import org.netbeans.lib.lexer.token.PropertyToken; import org.netbeans.spi.lexer.LanguageHierarchy; import org.netbeans.spi.lexer.LexerRestartInfo; import org.netbeans.spi.lexer.TokenFactory; import org.netbeans.spi.lexer.TokenPropertyProvider; /** * Implementation of the functionality related to lexer input. * * @author <NAME> * @version 1.00 */ public abstract class LexerInputOperation<T extends TokenId> { // -J-Dorg.netbeans.lib.lexer.LexerInputOperation.level=FINE static final Logger LOG = Logger.getLogger(LexerInputOperation.class.getName()); // -J-Dorg.netbeans.spi.lexer.LexerInput.level=FINE static final Logger LexerInputLOG = Logger.getLogger(LexerInput.class.getName()); protected final TokenList<T> tokenList; /** * Current reading index which usually corresponds to real offset. * <br/> * It should be set to its initial value in the constructor by descendants. */ protected int readOffset; /** * A value that designates a start of a token being currently recognized. */ protected int tokenStartOffset; /** * Maximum index from which the char was fetched for current * (or previous) tokens recognition. * <br> * The index is updated lazily - only when EOF is reached * and when backup() is called. */ private int lookaheadOffset; /** * Token length computed by assignTokenLength(). */ protected int tokenLength; protected Lexer<T> lexer; protected final LanguageOperation<T> languageOperation; /** * How many flyweight tokens were created in a row. */ private int flyTokenSequenceLength; protected final WrapTokenIdCache<T> wrapTokenIdCache; public LexerInputOperation(TokenList<T> tokenList, int tokenIndex, Object lexerRestartState) { this.tokenList = tokenList; LanguagePath languagePath = tokenList.languagePath(); Language<T> language = tokenList.language(); this.languageOperation = LexerUtilsConstants.languageOperation(language); // Determine flyTokenSequenceLength setting while (--tokenIndex >= 0 && tokenList.tokenOrEmbedding(tokenIndex).token().isFlyweight()) { flyTokenSequenceLength++; } LanguageHierarchy<T> languageHierarchy = LexerApiPackageAccessor.get().languageHierarchy( LexerUtilsConstants.<T>innerLanguage(languagePath)); TokenFactory<T> tokenFactory = LexerSpiPackageAccessor.get().createTokenFactory(this); LexerInput lexerInput = LexerSpiPackageAccessor.get().createLexerInput(this); LexerRestartInfo<T> info = LexerSpiPackageAccessor.get().createLexerRestartInfo( lexerInput, tokenFactory, lexerRestartState, languagePath, tokenList.inputAttributes()); lexer = LexerSpiPackageAccessor.get().createLexer(languageHierarchy, info); wrapTokenIdCache = tokenList.tokenHierarchyOperation().getWrapTokenIdCache(language); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.INFO, "LexerInputOperation created for " + tokenList.tokenHierarchyOperation().inputSource(), new Exception()); // NOI18N } } /** * Read a character or return LexerInput.EOF. * * @param offset offset among characters that were read from this lexer input operation (zero * offset is first character read from this lexer input operation). * @return character at the given offset or LexerInput.EOF. */ public abstract int read(int offset); /** * Read a character that was already requested by {@link #read(int)} in the past. * * @param offset offset among characters that were read from this lexer input operation (zero * offset is first character read from this lexer input operation). * @return character at the given offset. */ public abstract char readExisting(int offset); /** * Fill appropriate data like token list and offset into a non-flyweight token. * <br/> * This method should also move over the token's characters by increasing * starting offset of the token and possibly other related variables. * * @param token non-null non-flyweight token. */ protected abstract void fillTokenData(AbstractToken<T> token); public final int read() { int c = read(readOffset++); if (c == LexerInput.EOF) { lookaheadOffset = readOffset; // count EOF char into lookahead readOffset--; // readIndex must not include EOF } return c; } public final int readLength() { return readOffset - tokenStartOffset; } public final char readExistingAtIndex(int index) { return readExisting(tokenStartOffset + index); } public final void backup(int count) { if (lookaheadOffset < readOffset) { lookaheadOffset = readOffset; } readOffset -= count; } /** * Get last recognized token's lookahead. * The method should only be used after fetching of the token. * * @return extra characters need for token's recognition >= 0. */ public final int lookahead() { return Math.max(lookaheadOffset, readOffset) - tokenStartOffset; } public AbstractToken<T> nextToken() { if (lexer == null) { return null; } while (true) { AbstractToken<T> token = (AbstractToken<T>)lexer.nextToken(); if (token == null) { checkLexerInputFinished(); return null; } // if (LOG.isLoggable(Level.FINE)) { // LOG.fine("NEXT-TOKEN: off=" + tokenStartOffset + ", len=" + tokenLength // NOI18N // + ", " + token.dumpInfo() + '\n'); // } // Check if token id of the new token belongs to the language Language<T> language = languageOperation.language(); // Check that the id belongs to the language if (!isSkipToken(token) && !language.tokenIds().contains(token.id())) { String msgPrefix = "Invalid TokenId=" + token.id() + " returned from lexer=" + lexer + " for language=" + language + ":\n"; if (token.id().ordinal() > language.maxOrdinal()) { throw new IllegalStateException(msgPrefix + "Language.maxOrdinal()=" + language.maxOrdinal() + " < " + token.id().ordinal()); } else { // Ordinal ok but different id with that ordinal contained in language throw new IllegalStateException(msgPrefix + "Language contains no or different tokenId with ordinal=" + token.id().ordinal() + ": " + language.tokenId(token.id().ordinal())); } } // Skip token's chars tokenStartOffset += tokenLength; if (!isSkipToken(token)) return token; } // Continue to fetch non-skip token } /** * Used by token list updater after nextToken() to determine start offset of a token * to be recognized next. Overriden for join token lists since join tokens * may span multiple ETLs. * * @return start offset of a next token that would be recognized. */ public int lastTokenEndOffset() { return tokenStartOffset; } public AbstractToken<T> getFlyweightToken(T id, String text) { if (text.length() > readLength()) { throw new IllegalArgumentException("getFlyweightToken(): Creating token " + // NOI18N " for unread characters: text=\"" + // NOI18N CharSequenceUtilities.debugText(text) + "\"; text.length()=" + // NOI18N text.length() + " > readLength()=" + readLength()); // NOI18N } // Compare each recognized char with the corresponding char in text if (LOG.isLoggable(Level.FINE)) { for (int i = 0; i < text.length(); i++) { if (text.charAt(i) != readExistingAtIndex(i)) { throw new IllegalArgumentException("Flyweight text in " + // NOI18N "TokenFactory.getFlyweightToken(" + id + ", \"" + // NOI18N CharSequenceUtilities.debugText(text) + "\") " + // NOI18N "differs from recognized text: '" + // NOI18N CharSequenceUtilities.debugChar(readExisting(i)) + "' != '" + CharSequenceUtilities.debugChar(text.charAt(i)) + // NOI18N "' at index=" + i // NOI18N ); } } } logTokenContent("getFlyweightToken", id, text.length()); assignTokenLength(text.length()); AbstractToken<T> token; if ((token = checkSkipToken(id)) == null) { if (isFlyTokenAllowed()) { token = languageOperation.getFlyweightToken(wrapTokenIdCache.plainWid(id), text); flyTokenSequenceLength++; } else { // Create regular token token = createDefaultTokenInstance(id); fillTokenData(token); flyTokenSequenceLength = 0; } } return token; } private AbstractToken<T> checkSkipToken(T id) { if (isSkipTokenId(id)) { // Prevent fly token occurrence after skip token to have a valid offset flyTokenSequenceLength = LexerUtilsConstants.MAX_FLY_SEQUENCE_LENGTH; return skipToken(); } return null; } private void checkTokenIdNonNull(T id) { if (id == null) { throw new IllegalArgumentException("Token id must not be null. Fix lexer " + lexer); // NOI18N } } public AbstractToken<T> createToken(T id, int length) { checkTokenIdNonNull(id); logTokenContent("createToken", id, length); assignTokenLength(length); AbstractToken<T> token; if ((token = checkSkipToken(id)) == null) { token = createDefaultTokenInstance(id); fillTokenData(token); flyTokenSequenceLength = 0; } return token; } private void logTokenContent(String opName, T id, int length) { if (LexerInputLOG.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(100); sb.append("TokenFactory.").append(opName).append("("); sb.append(id).append(", ").append(length); sb.append("): \""); for (int i = 0; i < length; i++) { CharSequenceUtilities.debugChar(sb, readExistingAtIndex(i)); } sb.append("\", st=").append(lexer.state()).append('\n'); LexerInputLOG.fine(sb.toString()); } } protected AbstractToken<T> createDefaultTokenInstance(T id) { return new DefaultToken<T>(wrapTokenIdCache.plainWid(id), tokenLength); } public AbstractToken<T> createToken(T id, int length, PartType partType) { if (partType == null) throw new IllegalArgumentException("partType must be non-null"); if (partType == PartType.COMPLETE) return createToken(id, length); checkTokenIdNonNull(id); return createPropertyToken(id, length, null, partType); } public AbstractToken<T> createPropertyToken(T id, int length, TokenPropertyProvider<T> propertyProvider, PartType partType) { if (partType == null) partType = PartType.COMPLETE; logTokenContent("createPropertyToken", id, length); assignTokenLength(length); AbstractToken<T> token; if ((token = checkSkipToken(id)) == null) { token = createPropertyTokenInstance(id, propertyProvider, partType); fillTokenData(token); flyTokenSequenceLength = 0; } return token; } protected AbstractToken<T> createPropertyTokenInstance(T id, TokenPropertyProvider<T> propertyProvider, PartType partType) { return new PropertyToken<T>(wrapTokenIdCache.plainWid(id), tokenLength, propertyProvider, partType); } public AbstractToken<T> createCustomTextToken(T id, int length, CharSequence customText) { logTokenContent("createCustomTextToken", id, length); assignTokenLength(length); AbstractToken<T> token; if ((token = checkSkipToken(id)) == null) { token = createCustomTextTokenInstance(id, customText); fillTokenData(token); flyTokenSequenceLength = 0; } return token; } protected AbstractToken<T> createCustomTextTokenInstance(T id, CharSequence customText) { return new CustomTextToken<T>(wrapTokenIdCache.plainWid(id), customText, tokenLength); } public boolean isSkipTokenId(T id) { Set<T> skipTokenIds = tokenList.skipTokenIds(); return (skipTokenIds != null && skipTokenIds.contains(id)); } protected final int tokenLength() { return tokenLength; } public void assignTokenLength(int tokenLength) { if (tokenLength > readLength()) { throw new IndexOutOfBoundsException("tokenLength=" + tokenLength // NOI18N + " > " + readLength() + ". " + lexer.getClass() + // NOI18N " implementation must be fixed to create all tokens with a proper token length value."); // NOI18N } if (tokenLength <= 0) { throw new IndexOutOfBoundsException("tokenLength=" + tokenLength + " <= 0. " + lexer.getClass() + // NOI18N " implementation must be fixed to create all tokens with a proper token length value."); // NOI18N } this.tokenLength = tokenLength; } public final Object lexerState() { return lexer.state(); } protected boolean isFlyTokenAllowed() { return (flyTokenSequenceLength < LexerUtilsConstants.MAX_FLY_SEQUENCE_LENGTH); } public final boolean isSkipToken(AbstractToken<T> token) { return (token == LexerUtilsConstants.SKIP_TOKEN); } @SuppressWarnings("unchecked") public final AbstractToken<T> skipToken() { return (AbstractToken<T>)LexerUtilsConstants.SKIP_TOKEN; } /** * Release the underlying lexer. This method can be called multiple times. */ public final void release() { if (lexer != null) { lexer.release(); lexer = null; } } /** * Check that there are no more characters to be read from the given * lexer input operation. */ private void checkLexerInputFinished() { if (read() != LexerInput.EOF || readLength() > 0) { StringBuilder sb = new StringBuilder(100); int readLen = readLength(); sb.append("Lexer ").append(lexer); // NOI18N sb.append("\n returned null token but lexerInput.readLength()="); // NOI18N sb.append(readLen); sb.append("\n lexer-state: ").append(lexer.state()); sb.append("\n ").append(this); // NOI18N sb.append("\n Chars: \""); for (int i = 0; i < readLen; i++) { sb.append(CharSequenceUtilities.debugChar(readExistingAtIndex(i))); } sb.append("\" - these characters need to be tokenized."); // NOI18N sb.append("\nFix the lexer to not return null token in this state."); // NOI18N throw new IllegalStateException(sb.toString()); } } @Override public String toString() { return "tokenStartOffset=" + tokenStartOffset + ", readOffset=" + readOffset + // NOI18N ", lookaheadOffset=" + lookaheadOffset; } }
7,151
777
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/paint/RootInlineBoxPainter.h" #include "core/layout/api/LineLayoutAPIShim.h" #include "core/layout/line/EllipsisBox.h" #include "core/layout/line/RootInlineBox.h" #include "core/paint/PaintInfo.h" namespace blink { void RootInlineBoxPainter::paintEllipsisBox(const PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom) const { if (m_rootInlineBox.hasEllipsisBox() && m_rootInlineBox.getLineLayoutItem().style()->visibility() == EVisibility::kVisible && paintInfo.phase == PaintPhaseForeground) m_rootInlineBox.ellipsisBox()->paint(paintInfo, paintOffset, lineTop, lineBottom); } void RootInlineBoxPainter::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom) { m_rootInlineBox.InlineFlowBox::paint(paintInfo, paintOffset, lineTop, lineBottom); paintEllipsisBox(paintInfo, paintOffset, lineTop, lineBottom); } } // namespace blink
698
8,451
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2020 QuestDB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package io.questdb.std.datetime; import io.questdb.std.LongList; import io.questdb.std.ObjList; import io.questdb.std.Unsafe; import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransitionRule; import java.time.zone.ZoneRules; public abstract class AbstractTimeZoneRules implements TimeZoneRules { public static final long SAVING_INSTANT_TRANSITION = Unsafe.getFieldOffset(ZoneRules.class, "savingsInstantTransitions"); public static final long STANDARD_OFFSETS = Unsafe.getFieldOffset(ZoneRules.class, "standardOffsets"); public static final long LAST_RULES = Unsafe.getFieldOffset(ZoneRules.class, "lastRules"); public static final long WALL_OFFSETS = Unsafe.getFieldOffset(ZoneRules.class, "wallOffsets"); private final long cutoffTransition; private final LongList historicTransitions = new LongList(); private final ObjList<TransitionRule> rules; private final int ruleCount; private final int[] wallOffsets; private final long firstWall; private final long lastWall; private final long standardOffset; private final long multiplier; public AbstractTimeZoneRules(ZoneRules rules, long multiplier) { this.multiplier = multiplier; final long[] savingsInstantTransition = (long[]) Unsafe.getUnsafe().getObject(rules, SAVING_INSTANT_TRANSITION); if (savingsInstantTransition.length == 0) { ZoneOffset[] standardOffsets = (ZoneOffset[]) Unsafe.getUnsafe().getObject(rules, STANDARD_OFFSETS); standardOffset = standardOffsets[0].getTotalSeconds() * multiplier; } else { standardOffset = Long.MIN_VALUE; for (int i = 0, n = savingsInstantTransition.length; i < n; i++) { historicTransitions.add(savingsInstantTransition[i] * multiplier); } } cutoffTransition = historicTransitions.getLast(); ZoneOffsetTransitionRule[] lastRules = (ZoneOffsetTransitionRule[]) Unsafe.getUnsafe().getObject(rules, LAST_RULES); this.rules = new ObjList<>(lastRules.length); for (int i = 0, n = lastRules.length; i < n; i++) { ZoneOffsetTransitionRule zr = lastRules[i]; TransitionRule tr = new TransitionRule(); tr.offsetBefore = zr.getOffsetBefore().getTotalSeconds(); tr.offsetAfter = zr.getOffsetAfter().getTotalSeconds(); tr.standardOffset = zr.getStandardOffset().getTotalSeconds(); tr.dow = zr.getDayOfWeek() == null ? -1 : zr.getDayOfWeek().getValue(); tr.dom = zr.getDayOfMonthIndicator(); tr.month = zr.getMonth().getValue(); tr.midnightEOD = zr.isMidnightEndOfDay(); tr.hour = zr.getLocalTime().getHour(); tr.minute = zr.getLocalTime().getMinute(); tr.second = zr.getLocalTime().getSecond(); switch (zr.getTimeDefinition()) { case UTC: tr.timeDef = TransitionRule.UTC; break; case STANDARD: tr.timeDef = TransitionRule.STANDARD; break; default: tr.timeDef = TransitionRule.WALL; break; } this.rules.add(tr); } this.ruleCount = lastRules.length; ZoneOffset[] wallOffsets = (ZoneOffset[]) Unsafe.getUnsafe().getObject(rules, WALL_OFFSETS); this.wallOffsets = new int[wallOffsets.length]; for (int i = 0, n = wallOffsets.length; i < n; i++) { this.wallOffsets[i] = wallOffsets[i].getTotalSeconds(); } this.firstWall = this.wallOffsets[0] * multiplier; this.lastWall = this.wallOffsets[wallOffsets.length - 1] * multiplier; } @Override public long getOffset(long utcEpoch, int year, boolean leap) { if (standardOffset != Long.MIN_VALUE) { return standardOffset; } if (ruleCount > 0 && utcEpoch > cutoffTransition) { return offsetFromRules(utcEpoch, year, leap); } if (utcEpoch > cutoffTransition) { return lastWall; } return offsetFromHistory(utcEpoch); } @Override public long getOffset(long utcEpoch) { final int y = getYear(utcEpoch); return getOffset(utcEpoch, y, isLeapYear(y)); } @Override public long getNextDST(long utcEpoch, int year, boolean leap) { if (standardOffset != Long.MIN_VALUE) { // when we have standard offset the next DST does not exist // since we are trying to avoid unnecessary offset lookup the max long // should ensure all timestamps stay below next DST return Long.MAX_VALUE; } if (ruleCount > 0 && utcEpoch >= cutoffTransition) { return dstFromRules(utcEpoch, year, leap); } if (utcEpoch < cutoffTransition) { return dstFromHistory(utcEpoch); } return Long.MAX_VALUE; } @Override public long getNextDST(long utcEpoch) { final int y = getYear(utcEpoch); return getNextDST(utcEpoch, y, isLeapYear(y)); } abstract protected long addDays(long epoch, int days); private long dstFromHistory(long epoch) { int index = historicTransitions.binarySearch(epoch); if (index == -1) { return Long.MAX_VALUE; } if (index < 0) { index = -index - 2; } return historicTransitions.getQuick(index + 1); } private long dstFromRules(long epoch, int year, boolean leap) { for (int i = 0; i < ruleCount; i++) { long date = getDSTFromRule(year, leap, i); if (epoch < date) { return date; } } if (ruleCount > 0) { return getDSTFromRule(year + 1, isLeapYear(year + 1), 0); } return Long.MAX_VALUE; } private long getDSTFromRule(int year, boolean leap, int i) { int offsetBefore; TransitionRule zr = rules.getQuick(i); offsetBefore = zr.offsetBefore; int dom = zr.dom; int month = zr.month; int dow = zr.dow; long date; if (dom < 0) { date = toEpoch( year, leap, month, getDaysPerMonth(month, leap) + 1 + dom, zr.hour, zr.minute ) + zr.second * multiplier; if (dow > -1) { date = previousOrSameDayOfWeek(date, dow); } } else { assert month > 0; date = toEpoch(year, leap, month, dom, zr.hour, zr.minute) + zr.second * multiplier; if (dow > -1) { date = nextOrSameDayOfWeek(date, dow); } } if (zr.midnightEOD) { date = addDays(date, 1); } switch (zr.timeDef) { case TransitionRule.UTC: date += (offsetBefore - ZoneOffset.UTC.getTotalSeconds()) * multiplier; break; case TransitionRule.STANDARD: date += (offsetBefore - zr.standardOffset) * multiplier; break; default: // WALL break; } // go back to epoch epoch date -= offsetBefore * multiplier; return date; } abstract protected int getDaysPerMonth(int month, boolean leapYear); abstract protected int getYear(long epoch); abstract protected boolean isLeapYear(int year); abstract protected long nextOrSameDayOfWeek(long epoch, int dow); private long offsetFromHistory(long epoch) { int index = historicTransitions.binarySearch(epoch); if (index == -1) { return firstWall; } if (index < 0) { index = -index - 2; } return wallOffsets[index + 1] * multiplier; } private long offsetFromRules(long epoch, int year, boolean leap) { int offsetBefore; int offsetAfter = 0; for (int i = 0; i < ruleCount; i++) { TransitionRule zr = rules.getQuick(i); offsetBefore = zr.offsetBefore; offsetAfter = zr.offsetAfter; int dom = zr.dom; int month = zr.month; int dow = zr.dow; long date; if (dom < 0) { date = toEpoch( year, leap, month, getDaysPerMonth(month, leap) + 1 + dom, zr.hour, zr.minute ) + zr.second * multiplier; if (dow > -1) { date = previousOrSameDayOfWeek(date, dow); } } else { assert month > 0; date = toEpoch(year, leap, month, dom, zr.hour, zr.minute) + zr.second * multiplier; if (dow > -1) { date = nextOrSameDayOfWeek(date, dow); } } if (zr.midnightEOD) { date = addDays(date, 1); } switch (zr.timeDef) { case TransitionRule.UTC: date += (offsetBefore - ZoneOffset.UTC.getTotalSeconds()) * multiplier; break; case TransitionRule.STANDARD: date += (offsetBefore - zr.standardOffset) * multiplier; break; default: // WALL break; } // go back to epoch epoch date -= offsetBefore * multiplier; if (epoch < date) { return offsetBefore * multiplier; } } return offsetAfter * multiplier; } abstract protected long previousOrSameDayOfWeek(long epoch, int dow); abstract protected long toEpoch(int year, boolean leapYear, int month, int day, int hour, int min); }
5,115
897
/* Program to calculate b^n%m . This program also known as Recursive Modular Exponentiation */ #include<iostream> #include <cmath> using namespace std; int power(int b,int n,int m) { if(n==0) return 1; else if(n%2==0) return power(b,n/2,m)*power(b,n/2,m)%m; else return power(b,n/2,m)*power(b,n/2,m)%m*b%m; } int main() { int b,n,m; cout<<"Enter base \n"; cin>>b; cout<<"Enter Exponent \n"; cin>>n; cout<<"Enter Value to take modulus\n"; cin>>m; cout<<"\nAnswer of b ^ n % m : "<<power(b,n,m); } /* Input:- 2 6 6 Ouput:- 4 */ /* Time Complexity - O(n) Space Complexity - O(n) */
300
1,240
<gh_stars>1000+ package com.eventyay.organizer.robo.ui; import androidx.fragment.app.Fragment; import com.eventyay.organizer.common.ContextManager; import com.eventyay.organizer.core.attendee.list.AttendeesFragment; import com.eventyay.organizer.core.auth.login.LoginFragment; import com.eventyay.organizer.core.auth.reset.ResetPasswordFragment; import com.eventyay.organizer.core.auth.signup.SignUpFragment; import com.eventyay.organizer.core.event.dashboard.EventDashboardFragment; import com.eventyay.organizer.core.event.list.EventListFragment; import com.eventyay.organizer.core.settings.SettingsFragment; import com.eventyay.organizer.core.ticket.create.CreateTicketFragment; import com.eventyay.organizer.core.ticket.list.TicketsFragment; import com.eventyay.organizer.data.event.Event; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.robolectric.ParameterizedRobolectricTestRunner; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; @Ignore @SuppressWarnings({"PMD.JUnit4TestShouldUseAfterAnnotation", "PMD.JUnit4TestShouldUseBeforeAnnotation"}) public class FragmentInstanceTest<T extends Fragment> extends BaseParameterTest { private final Class<T> testFragmentClass; private final long id; public FragmentInstanceTest(Class<T> testFragmentClass, long id) { this.testFragmentClass = testFragmentClass; this.id = id; if (testFragmentClass == CreateTicketFragment.class) { setUpMockEvent(); } } private void setUpMockEvent() { Event event = new Event(); event.timezone = "UTC"; event.endsAt = "2018-12-14T23:59:59.123456+00:00"; ContextManager.setSelectedEvent(event); } @BeforeClass public static void setUp() { // UtilModel.blockNetwork(); } @AfterClass public static void tearDown() { // UtilModel.releaseNetwork(); ContextManager.setSelectedEvent(null); } @ParameterizedRobolectricTestRunner.Parameters(name = "InstantiateFragment = {0}") public static Collection<Object[]> data() { // TODO: Re-enable once Roboelectric is fixed return Arrays.asList(new Object[][]{ {EventDashboardFragment.class, 1}, {EventListFragment.class, -1}, //{AttendeeCheckInFragment.class, 1}, {SettingsFragment.class, -1}, {CreateTicketFragment.class, -1}, //{TicketDetailFragment.class, 1}, {TicketsFragment.class, 1}, {AttendeesFragment.class, 1}, {LoginFragment.class, -1}, {SignUpFragment.class, -1}, {ResetPasswordFragment.class, -1} }); } private Fragment getFragment() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (id == -1) { return (Fragment) testFragmentClass.getDeclaredMethod("newInstance").invoke(null); } else { return (Fragment) testFragmentClass.getDeclaredMethod("newInstance", long.class).invoke(null, id); } } private static void testFragmentCreation(Fragment fragment) { // SupportFragmentController.of(fragment).create().start().pause().stop().destroy(); } @Test public void shouldInstantiate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { testFragmentCreation(getFragment()); } }
1,360
377
from wappalyzer import Wappalyzer from builtwith import builtwith from run_tools import run_tool import json import sys import subprocess import commands from mongo_connection import mongo_client import time import signal import logging def technologyScan(ip,domain,type): # config database client = mongo_client() db = client.config cursor = db.external.find() #type = sys.argv[3] # checking for selfServe of org scan and setting the paramter if(type == "selfServe"): logFile = cursor[0]['SELF_SERVE_PATH_LOGFILE'] database = cursor[0]['SELF_SERVE_DATABASE'] else: logFile = cursor[0]['PATH_LOGFILE'] database = cursor[0]['DATABASE'] TIMEOUT = int(cursor[0]['TIMEOUT_TECH']) db = client[database] # log file logging.basicConfig(filename = logFile,format='%(levelname)s:%(message)s',level=logging.DEBUG) # timeout def signal_handler(signum,frame): raise Exception("Timed Out!") signal.signal(signal.SIGALRM, signal_handler) #ip = sys.argv[1] #domain = sys.argv[2] w = Wappalyzer() serv = db.services if domain != "null": host = domain # host is the parameter to be passed else: host = ip if domain == "null": domain = "" # checking whether to scan through 80 or 443 if serv.find({"ip":ip,"443":{"$exists":True}}).count() > 0: prefix = "https://" elif serv.find({"ip":ip,"80":{"$exists":True}}).count() > 0: prefix = "http://" component = {} # every 3rd party tools is scanning 6 times, if it finds the technology than it stops # wappalyzer count = 6 while (count): if count <= 3: host = ip # host is changed to ip after 3 scan count -= 1 logging.info("Wappalyzer working on "+host) signal.alarm(TIMEOUT) try: # calling wappalyzer wapp = w.analyze(prefix+host) except Exception as e: logging.error("Issues with wappalyzer: "+str(e)) signal.alarm(0) continue signal.alarm(0) logging.info(wapp) if len(wapp) == 0: # checking for output logging.info("No output.") if count != 0: logging.info("Sleeping for 10 seconds.") time.sleep(10) continue for key in wapp: component[key.lower()] = wapp[key][unicode('version')] break # builtwith if domain != "": host = domain else: host = ip count = 6 while(count): if count <= 3: host = ip count -= 1 logging.info("Builtwith working on "+host) signal.alarm(TIMEOUT) try: # builtwith working bw = builtwith(prefix+host) except Exception as e: logging.error("Issues with builtwith: "+str(e)) signal.alarm(0) continue signal.alarm(0) logging.info(bw) if len(bw) == 0: logging.info("No output.") if count != 0: logging.info("Sleeping for 10 seconds.") time.sleep(10) continue for keys in bw: # checking for output for key in bw[keys]: if key not in component.keys(): component[key.lower()] = "" break # phantalyzer if domain != "": host = domain else: host = ip count = 6 while (count): if count <= 3: host = ip count -= 1 logging.info("Phantalyzer working on "+host) signal.alarm(TIMEOUT) try: phanta = run_tool(name="phantomjs",prefix=prefix,domain=host) except Exception as e: logging.error("Issue with phantalyzer: "+str(e)) signal.alarm(0) try: phanta = phanta[1] phanta = phanta.strip() logging.info(phanta) if phanta == "": logging.info("No output.") if count != 0: logging.info("Sleeping for 10 seconds.") time.sleep(10) continue phanta = phanta.split("\n") phanta[0] = phanta[0].strip() phanta = phanta[0].split(":")[1] if phanta == "" or phanta.strip() == '160': logging.info("No output.") if count != 0: logging.info("Sleeping for 10 seconds.") time.sleep(10) continue phanta = phanta.split("|") for te in phanta: te = te.strip() if te not in component.keys() and te != "": component[te.lower()] = "" break except Exception as e: logging.error("Issue with phantalyzer: "+str(e)) # wappalyzer extension if domain != "": host = domain else: host = ip count = 6 while(count): if count <= 3: host = ip count -= 1 logging.info("Wappalyzer extension working on "+host) signal.alarm(TIMEOUT) try: cmd = "phantomjs src/drivers/phantomjs/driver.js "+prefix+host phantjs = run_tool(cmd=cmd) except Exception as e: logging.error("Issue with phantomjs code: "+str(e)) signal.alarm(0) try: logging.info(phantjs[1].strip()) if phantjs[1].strip() == "": logging.info("No output.") if count != 0: logging.info("Sleeping for 20 seconds.") time.sleep(2) continue phantjs = json.loads(phantjs[1]) phantjs = phantjs['applications'] if len(phantjs) == 0: logging.info("No output.") if count != 0: logging.info("Sleeping for 20 seconds.") time.sleep(20) continue for i in range(len(phantjs)): if (phantjs[i][unicode('name')]).lower() not in component.keys(): component[(phantjs[i][unicode('name')]).lower()] = phantjs[i][unicode('version')] elif component[(phantjs[i][unicode('name')]).lower()] == "": component[(phantjs[i][unicode('name')]).lower()] = phantjs[i][unicode('version')] break except Exception as e: logging.error("Phantomjs code not working. Issues: "+str(e)) # finding cves try: for key in component: temp = {} temp['version'] = component[key] allCve = [] if component[key] == "": temp['cves'] = allCve temp['false_positive'] = "0" component[key] = temp continue cmd = "python3 Tools/cve-search-master/bin/search.py -p "+str(key).lower().replace(" js",".js").replace(" ","_").replace("apache","apache:http_server")+":"+str(component[key])+" -o json" cves = run_tool(cmd=cmd) cves = cves[1] size = len(cves.split("\n")) if size == 1 and cves == "": temp['cves'] = allCve temp['false_positive'] = "0" component[key] = temp continue for j in range(size): cve = {} tt = json.loads(cves.split("\n")[j]) cve['id'] = tt['id'] cve['cvss'] = tt['cvss'] allCve.append(cve) temp['cves'] = allCve temp['false_positive'] = "0" component[key] = temp except Exception as e: logging.error("Issues with finding cves. Issues: "+str(e)) technologies = db.technologies checking = technologies.find_one({"ip":ip}) if technologies.find({"ip":ip}).count() > 0: technologies.remove({"ip":ip}) technology = {"ip":ip,"domain":domain} technologies.insert_one(technology) for key in component: try: for ch in checking: if key.replace("."," ") == ch.encode('ascii','ignore') and component[key]['version'] == checking[ch]['version'].encode('ascii','ignore'): component[key]['false_positive'] = checking[ch]['false_positive'] except Exception as e: print "Issues with updating false positive: "+str(e) technologies.update({"ip":ip},{"$set":{str(key.replace("."," ")):component[key]}}) print key+" with version "+str(component[key]) if __name__== "__main__": technologyScan(sys.argv[1],sys.argv[2],sys.argv[3])
2,957
741
<reponame>sumity90/Applozic-Android-SDK<filename>mobicomkitui/src/main/java/com/applozic/mobicomkit/uiwidgets/ActivityLifecycleHandler.java package com.applozic.mobicomkit.uiwidgets; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.os.Build; import android.os.Bundle; /** * Created by sunil on 27/11/15. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class ActivityLifecycleHandler implements Application.ActivityLifecycleCallbacks { private static int resumed; private static int paused; private static int started; private static int stopped; public static boolean isApplicationVisible() { return started > stopped; } public static boolean isApplicationInForeground() { return resumed > paused; } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { ++started; } @Override public void onActivityResumed(Activity activity) { ++resumed; } @Override public void onActivityPaused(Activity activity) { ++paused; } @Override public void onActivityStopped(Activity activity) { ++stopped; } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }
519
663
<reponame>mchelen-gov/integrations-core { "name": "[Avi Vantage] Virtual service {{virtualservice_name.name}} has a high number of errors", "type": "query alert", "query": "avg(last_5m):avg:avi_vantage.l7_client.pct_response_errors{*} by {virtualservice_name,host} > 70", "message": "{{#is_alert}}\nVirtual service {{virtualservice_name.name}} is experiencing a very high number of errors.\n{{/is_alert}} \n\n{{#is_recovery}}\nError rate of virtual service {{virtualservice_name.name}} is back to a lower level.\n{{/is_recovery}} ", "tags": [ "integration:avi_vantage" ], "options": { "notify_audit": false, "locked": false, "timeout_h": 0, "new_host_delay": 300, "require_full_window": true, "notify_no_data": false, "renotify_interval": "0", "escalation_message": "", "no_data_timeframe": null, "include_tags": true, "thresholds": { "critical": 70 } }, "priority": null, "recommended_monitor_metadata": { "description": "Notify your team when one of Avi Virtual Service is experiencing a high percentage of errors." } }
408
348
{"nom":"Lanteuil","circ":"2ème circonscription","dpt":"Corrèze","inscrits":428,"abs":201,"votants":227,"blancs":28,"nuls":13,"exp":186,"res":[{"nuance":"LR","nom":"<NAME>","voix":112},{"nuance":"REM","nom":"<NAME>","voix":74}]}
91
9,541
namespace simdjson { namespace SIMDJSON_IMPLEMENTATION { /** * A fast, simple, DOM-like interface that parses JSON as you use it. * * Designed for maximum speed and a lower memory profile. */ namespace ondemand { /** Represents the depth of a JSON value (number of nested arrays/objects). */ using depth_t = int32_t; } // namespace ondemand } // namespace SIMDJSON_IMPLEMENTATION } // namespace simdjson #include "simdjson/generic/ondemand/json_type.h" #include "simdjson/generic/ondemand/token_position.h" #include "simdjson/generic/ondemand/logger.h" #include "simdjson/generic/ondemand/raw_json_string.h" #include "simdjson/generic/ondemand/token_iterator.h" #include "simdjson/generic/ondemand/json_iterator.h" #include "simdjson/generic/ondemand/value_iterator.h" #include "simdjson/generic/ondemand/array_iterator.h" #include "simdjson/generic/ondemand/object_iterator.h" #include "simdjson/generic/ondemand/array.h" #include "simdjson/generic/ondemand/document.h" #include "simdjson/generic/ondemand/value.h" #include "simdjson/generic/ondemand/field.h" #include "simdjson/generic/ondemand/object.h" #include "simdjson/generic/ondemand/parser.h" #include "simdjson/generic/ondemand/document_stream.h" #include "simdjson/generic/ondemand/serialization.h"
449
1,367
<gh_stars>1000+ package android.view; import java.util.List; public class InputEventCompatProcessor { public List<InputEvent> processInputEventForCompatibility(InputEvent e) { return null; } }
65
427
// RUN: %clang_cc1 -triple i686-pc-win32 -disable-llvm-passes -emit-llvm -o - -O1 %s | FileCheck %s // // Test that TBAA works in the Microsoft C++ ABI. We used to error out while // attempting to mangle RTTI. struct StructA { int a; }; struct StructB : virtual StructA { StructB(); }; StructB::StructB() { a = 42; // CHECK: store i32 42, i32* {{.*}}, !tbaa [[TAG_A_i32:!.*]] } // CHECK: [[TYPE_INT:!.*]] = !{!"int", [[TYPE_CHAR:!.*]], i64 0} // CHECK: [[TYPE_CHAR]] = !{!"omnipotent char", ! // CHECK: [[TAG_A_i32]] = !{[[TYPE_A:!.*]], [[TYPE_INT]], i64 0} // CHECK: [[TYPE_A]] = !{!"?AUStructA@@", [[TYPE_INT]], i64 0}
278
1,031
package additive_animations.fragments; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.interpolator.view.animation.LinearOutSlowInInterpolator; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import at.wirecube.additiveanimations.additive_animator.AdditiveAnimator; import at.wirecube.additiveanimations.additiveanimationsdemo.R; import at.wirecube.additiveanimations.helper.FloatProperty; import at.wirecube.additiveanimations.helper.evaluators.ColorEvaluator; public class CustomAnimationsWithoutSubclassDemoFragment extends Fragment { ViewGroup rootView; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = (ViewGroup) inflater.inflate(R.layout.fragment_text_view_color_demo, container, false); final TextView animatedView = (TextView) rootView.findViewById(R.id.animated_text_view); Button button = (Button) rootView.findViewById(R.id.change_color_button); button.setOnClickListener(new View.OnClickListener() { int currentColor = 0; final int colors[] = new int[] { getResources().getColor(R.color.niceBlue), getResources().getColor(R.color.niceGreen), getResources().getColor(R.color.nicePink), getResources().getColor(R.color.niceOrange) }; @Override public void onClick(View v) { AdditiveAnimator.animate(animatedView).setInterpolator(new LinearOutSlowInInterpolator()) .property(colors[currentColor++ % 4], new ColorEvaluator(), new FloatProperty<View>("TextColorAnimationTag") { @Override public Float get(View object) { return Float.valueOf(animatedView.getCurrentTextColor()); } @Override public void set(View object, Float value) { animatedView.setTextColor(value.intValue()); } }).start(); } }); return rootView; } }
995
1,799
<filename>lite/utils/env.h // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <cstdlib> #include <cstring> #include <iostream> #include <string> // The environment variables for the subgraph settings, use "SUBGRAPH_" as // prefix. // Specify the path of configuration file for the subgraph segmentation, an // example is shown as below: // op_type:in_var_name_0,in_var_name1:out_var_name_0,out_var_name1 // op_type::out_var_name_0 // op_type:in_var_name_0 // op_type #define SUBGRAPH_CUSTOM_PARTITION_CONFIG_FILE \ "SUBGRAPH_CUSTOM_PARTITION_CONFIG_FILE" // The original weight/local/unused variables in the subblock of the subgraph op // will be saved only if 'SUBGRAPH_ONLINE_MODE' is set to true(default) during // the analysis phase, it ensure the ops in the subblock can be converted to the // target device model online during the execution phase. #define SUBGRAPH_ONLINE_MODE "SUBGRAPH_ONLINE_MODE" // The environment variables for the quant model settings, use "QUANT_" as // prefix. // Apply the constraints for the quantized ops(such as concat) that the inputs // and outputs must have the same scale. Use the environment variable to specify // how to caculate the new scale, includes the following methods: // 0(default): The mean of the input and output scales. // 1: The maximum of the input and output scales. // 2: The minimum of the input and output scales. #define QUANT_INPUT_OUTPUT_SCALE_RESTRICT_METHOD \ "QUANT_INPUT_OUTPUT_SCALE_RESTRICT_METHOD" namespace paddle { namespace lite { static std::string GetStringFromEnv(const std::string& str, const std::string& def = "") { char* variable = std::getenv(str.c_str()); if (!variable) { return def; } return std::string(variable); } static bool GetBoolFromEnv(const std::string& str, bool def = false) { char* variable = std::getenv(str.c_str()); if (!variable) { return def; } if (strcmp(variable, "false") == 0 || strcmp(variable, "0") == 0) { return false; } else { return true; } } static int GetIntFromEnv(const std::string& str, int def = 0) { char* variable = std::getenv(str.c_str()); if (!variable) { return def; } return atoi(variable); } static double GetDoubleFromEnv(const std::string& str, double def = 0.0) { char* variable = std::getenv(str.c_str()); if (!variable) { return def; } return atof(variable); } static uint64_t GetUInt64FromEnv(const std::string& str, uint64_t def = 0ul) { char* variable = std::getenv(str.c_str()); if (!variable) { return def; } return static_cast<uint64_t>(atol(variable)); } } // namespace lite } // namespace paddle
1,084
763
<reponame>zabrewer/batfish<filename>projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/collections/FileLines.java package org.batfish.datamodel.collections; import static com.google.common.base.MoreObjects.firstNonNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSortedSet; import java.util.Objects; import java.util.SortedSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public class FileLines { private static final String PROP_FILENAME = "filename"; private static final String PROP_LINES = "lines"; @Nonnull private final String _filename; @Nonnull private SortedSet<Integer> _lines; @JsonCreator public FileLines( @JsonProperty(PROP_FILENAME) String filename, @Nullable @JsonProperty(PROP_LINES) SortedSet<Integer> lines) { _filename = filename; _lines = firstNonNull(lines, ImmutableSortedSet.of()); } @JsonProperty(PROP_FILENAME) public String getFilename() { return _filename; } @JsonProperty(PROP_LINES) public SortedSet<Integer> getLines() { return _lines; } @Override public String toString() { return _filename + ":" + _lines; } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } else if (!(other instanceof FileLines)) { return false; } FileLines o = (FileLines) other; return _filename.equals(o._filename) && _lines.equals(o._lines); } @Override public int hashCode() { return Objects.hash(_filename, _lines); } }
612
2,486
import unittest from slack_sdk.oauth.installation_store import InstallationStore from slack_sdk.oauth.installation_store.async_installation_store import ( AsyncInstallationStore, ) class TestInterface(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_sync(self): store = InstallationStore() self.assertIsNotNone(store) def test_async(self): store = AsyncInstallationStore() self.assertIsNotNone(store)
194
12,824
<reponame>stefan-jurco/scala package test; import java.lang.invoke.*; public final class Bootstrap { private Bootstrap() { } public static CallSite bootstrap(MethodHandles.Lookup lookup, String invokedName, MethodType invokedType, Object... args) throws Throwable { int arity = (int) args[0]; MethodHandle MH = (MethodHandle) args[1]; String[] strings = new String[arity]; for (int i = 0; i < arity; i++) { strings[i] = (String) args[2 + i]; } Reflection handleAndStrings = new Reflection(MH, strings); MethodHandle foo = MethodHandles.lookup().findVirtual(Reflection.class, "foo", MethodType.methodType(String.class, String.class)); return new java.lang.invoke.ConstantCallSite(foo.bindTo(handleAndStrings)); } static class Reflection { private final MethodHandle handle; private final String[] scalaParamNames; public Reflection(MethodHandle handle, String[] scalaParamNames) { this.handle = handle; this.scalaParamNames = scalaParamNames; } public String foo(String f) { return toString() + ", " + f; } @java.lang.Override public java.lang.String toString() { return "HandleAndStrings{" + "handle=" + handle + ", scalaParamNames=" + java.util.Arrays.toString(scalaParamNames) + '}'; } } }
689
3,371
{ "name": "list-detection", "description": "Detects unordered and ordered lists in the text from paragraphs, using bullet points and numberings as indications. This module is a work in progress." }
51
3,181
// Copyright © 2013-2014 <NAME> <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package net.orfjackal.retrolambda.interfaces; import org.objectweb.asm.*; import static org.objectweb.asm.Opcodes.*; public class FixInvokeStaticOnInterfaceMethod extends ClassVisitor { public FixInvokeStaticOnInterfaceMethod(ClassVisitor next) { super(ASM5, next); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MyMethodVisitor(super.visitMethod(access, name, desc, signature, exceptions)); } private static class MyMethodVisitor extends MethodVisitor { public MyMethodVisitor(MethodVisitor next) { super(Opcodes.ASM5, next); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (opcode == INVOKESTATIC && itf) { // pre-Java8 bytecode is not allowed to do invokestatic calls on interface method references itf = false; } super.visitMethodInsn(opcode, owner, name, desc, itf); } } }
486
10,225
<reponame>mweber03/quarkus package io.quarkus.test.kubernetes.client; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.function.Consumer; import io.fabric8.openshift.client.server.mock.OpenShiftServer; import io.quarkus.test.common.QuarkusTestResource; /** * Use on your test resource to get a mock {@link OpenShiftServer} spawn up, and injectable with {@link OpenShiftTestServer}. * This annotation is only active when used on a test class, and only for this test class. */ @QuarkusTestResource(value = OpenShiftServerTestResource.class, restrictToAnnotatedClass = true) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface WithOpenShiftTestServer { /** * Start it with HTTPS */ boolean https() default false; /** * Start it in CRUD mode */ boolean crud() default true; /** * Setup class to call after the mock server is created, for custom setup. */ Class<? extends Consumer<OpenShiftServer>> setup() default NO_SETUP.class; class NO_SETUP implements Consumer<OpenShiftServer> { @Override public void accept(OpenShiftServer t) { } } }
430
330
<filename>pybamm/input/parameters/lead_acid/positive_electrodes/lead_dioxide_Sulzer2019/lead_dioxide_ocp_Bode1977.py # # Open-circuit voltage in the positive (lead-dioxide) electrode # from pybamm import log10 def lead_dioxide_ocp_Bode1977(m): """ Dimensional open-circuit voltage in the positive (lead-dioxide) electrode [V], from [1]_, as a function of the molar mass m [mol.kg-1]. References ---------- .. [1] <NAME>. Lead-acid batteries. <NAME> and Sons, Inc., New York, NY, 1977. """ U = ( 1.628 + 0.074 * log10(m) + 0.033 * log10(m) ** 2 + 0.043 * log10(m) ** 3 + 0.022 * log10(m) ** 4 ) return U
302
316
<reponame>MrMarvin/cloudkeeper from resotolib.args import ArgumentParser from resotoworker.__main__ import add_args from resotoworker.collect import add_args as collect_add_args from resotoworker.cleanup import add_args as cleanup_add_args from resotoworker.resotocore import add_args as resotocore_add_args from resotolib.core import add_args as core_add_args def test_args(): arg_parser = ArgumentParser( description="resoto worker", env_args_prefix="RESOTOWORKER_", ) add_args(arg_parser) collect_add_args(arg_parser) cleanup_add_args(arg_parser) resotocore_add_args(arg_parser) core_add_args(arg_parser) arg_parser.parse_args() assert ArgumentParser.args.resotocore_uri == "http://localhost:8900"
286
330
/* * Tencent is pleased to support the open source community by making ScriptX available. * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ScriptX/ScriptX.h> #include <iostream> namespace script::test { class IOAgent : public script::InspectorAgent { public: void sendMessageToDebugger(const std::string_view& utf8) override { std::cout << utf8 << std::endl; std::cerr << "<< " << utf8 << std::endl; } void sendMessageToEngine_(const std::string_view& utf8) { std::cerr << ">> " << utf8 << std::endl; sendMessageToEngine(utf8); } ~IOAgent() override = default; ; }; } // namespace script::test // running steps // websocketd --port=8080 --devconsole InspectorTest // open chrome for: devtools://devtools/bundled/js_app.html?ws=localhost:8080 int main() { std::cerr << "Inspector run" << std::endl; // using namespace script; using script::EngineScope; using script::InspectorAgent; using script::Number; using script::ScriptEngine; using script::ScriptEngineImpl; using script::ScriptInspector; ScriptEngine* engine = new ScriptEngineImpl(); auto agent = new script::test::IOAgent(); auto ins = ScriptInspector::create(engine, std::unique_ptr<InspectorAgent>(agent), {"young", false}); bool wait = true; { EngineScope engineScope(engine); const char* src = R"( function fibo(x) { if (x <=1) return 1; return fibo(x-1) + fibo(x-2); } )"; const char* url = "Test.js"; engine->eval(src, url); } std::thread t([&]() { while (true) { EngineScope engineScope(engine); auto fibo = engine->get("fibo").asFunction(); fibo.call({}, Number::newNumber(10)); engine->messageQueue()->loopQueue(script::utils::MessageQueue::LoopType::kLoopOnce); } }); // // while (wait) { // wait = wait; // } const std::string_view line = R"( {"id":1,"method":"Profiler.enable"} {"id":2,"method":"Runtime.enable"} {"id":3,"method":"Debugger.enable","params":{"maxScriptsCacheSize":10000000}} {"id":4,"method":"Debugger.setPauseOnExceptions","params":{"state":"none"}} {"id":5,"method":"Debugger.setAsyncCallStackDepth","params":{"maxDepth":32}} {"id":6,"method":"Runtime.getIsolateId"} {"id":7,"method":"Debugger.setBlackboxPatterns","params":{"patterns":[]}} {"id":8,"method":"Runtime.runIfWaitingForDebugger"} )"; std::string s; while (true) { std::getline(std::cin, s); if (!s.empty()) { agent->sendMessageToEngine_(s); } s.clear(); } agent->sendMessageToEngine_(R"({"id":1,"method":"Profiler.enable"})"); agent->sendMessageToEngine_(R"({"id":2,"method":"Runtime.enable"})"); agent->sendMessageToEngine_( R"({"id":3,"method":"Debugger.enable","params":{"maxScriptsCacheSize":10000000}})"); agent->sendMessageToEngine_( R"({"id":4,"method":"Debugger.setPauseOnExceptions","params":{"state":"none"}})"); agent->sendMessageToEngine_( R"({"id":5,"method":"Debugger.setAsyncCallStackDepth","params":{"maxDepth":32}})"); agent->sendMessageToEngine_(R"({"id":6,"method":"Runtime.getIsolateId"})"); agent->sendMessageToEngine_( R"({"id":7,"method":"Debugger.setBlackboxPatterns","params":{"patterns":[]}})"); agent->sendMessageToEngine_(R"({"id":8,"method":"Runtime.runIfWaitingForDebugger"})"); t.join(); }
1,400
2,350
<reponame>lesterw1/RoaringBitmap<filename>RoaringBitmap/src/main/java/org/roaringbitmap/buffer/BufferFastAggregation.java /* * (c) the authors Licensed under the Apache License, Version 2.0. */ package org.roaringbitmap.buffer; import java.nio.CharBuffer; import java.nio.LongBuffer; import java.util.*; /** * Fast algorithms to aggregate many bitmaps. * * @author <NAME> */ public final class BufferFastAggregation { /** * Compute the AND aggregate. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap and(ImmutableRoaringBitmap... bitmaps) { if (bitmaps.length > 2) { return workShyAnd(new long[1024], bitmaps); } return naive_and(bitmaps); } /** * Compute the AND aggregate. * * @param aggregationBuffer a memory buffer for use in the aggregation. * Will be cleared after use. * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap and(long[] aggregationBuffer, ImmutableRoaringBitmap... bitmaps) { if (bitmaps.length > 2) { if(aggregationBuffer.length < 1024) { throw new IllegalArgumentException("buffer should have at least 1024 elements."); } try { return workShyAnd(aggregationBuffer, bitmaps); } finally { Arrays.fill(aggregationBuffer, 0L); } } return naive_and(bitmaps); } /** * Compute the AND aggregate. * * In practice, calls {#link workShyAnd} * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap and(Iterator<? extends ImmutableRoaringBitmap> bitmaps) { return and(new long[1024], bitmaps); } /** * Compute the AND aggregate. * * In practice, calls {#link workShyAnd} * * @param aggregationBuffer a buffer for use in aggregations * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap and(long[] aggregationBuffer, Iterator<? extends ImmutableRoaringBitmap> bitmaps) { if (bitmaps.hasNext()) { try { return workShyAnd(aggregationBuffer, bitmaps); } finally { Arrays.fill(aggregationBuffer, 0L); } } return new MutableRoaringBitmap(); } /** * Compute the AND aggregate. * * In practice, calls {#link naive_and} * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap and(MutableRoaringBitmap... bitmaps) { return and(convertToImmutable(bitmaps)); } /** * Convenience method converting one type of iterator into another, to avoid unnecessary warnings. * * @param i input bitmaps * @return an iterator over the provided iterator, with a different type */ public static Iterator<ImmutableRoaringBitmap> convertToImmutable( final Iterator<MutableRoaringBitmap> i) { return new Iterator<ImmutableRoaringBitmap>() { @Override public boolean hasNext() { return i.hasNext(); } @Override public ImmutableRoaringBitmap next() { return i.next(); } @Override public void remove() { } }; } private static ImmutableRoaringBitmap[] convertToImmutable(MutableRoaringBitmap[] array) { ImmutableRoaringBitmap[] answer = new ImmutableRoaringBitmap[array.length]; System.arraycopy(array, 0, answer, 0, answer.length); return answer; } /** * Minimizes memory usage while computing the or aggregate on a moderate number of bitmaps. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #or(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap horizontal_or(ImmutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); if (bitmaps.length == 0) { return answer; } PriorityQueue<MappeableContainerPointer> pq = new PriorityQueue<>(bitmaps.length); for (int k = 0; k < bitmaps.length; ++k) { MappeableContainerPointer x = bitmaps[k].highLowContainer.getContainerPointer(); if (x.getContainer() != null) { pq.add(x); } } while (!pq.isEmpty()) { MappeableContainerPointer x1 = pq.poll(); if (pq.isEmpty() || (pq.peek().key() != x1.key())) { answer.getMappeableRoaringArray().append(x1.key(), x1.getContainer().clone()); x1.advance(); if (x1.getContainer() != null) { pq.add(x1); } continue; } MappeableContainerPointer x2 = pq.poll(); MappeableContainer newc = x1.getContainer().lazyOR(x2.getContainer()); while (!pq.isEmpty() && (pq.peek().key() == x1.key())) { MappeableContainerPointer x = pq.poll(); newc = newc.lazyIOR(x.getContainer()); x.advance(); if (x.getContainer() != null) { pq.add(x); } else if (pq.isEmpty()) { break; } } newc = newc.repairAfterLazy(); answer.getMappeableRoaringArray().append(x1.key(), newc); x1.advance(); if (x1.getContainer() != null) { pq.add(x1); } x2.advance(); if (x2.getContainer() != null) { pq.add(x2); } } return answer; } /** * Calls naive_or. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ @Deprecated public static MutableRoaringBitmap horizontal_or(@SuppressWarnings("rawtypes") Iterator bitmaps) { return naive_or(bitmaps); } /** * Minimizes memory usage while computing the or aggregate on a moderate number of bitmaps. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #or(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap horizontal_or(MutableRoaringBitmap... bitmaps) { return horizontal_or(convertToImmutable(bitmaps)); } /** * Minimizes memory usage while computing the xor aggregate on a moderate number of bitmaps. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #xor(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap horizontal_xor(ImmutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); if (bitmaps.length == 0) { return answer; } PriorityQueue<MappeableContainerPointer> pq = new PriorityQueue<>(bitmaps.length); for (int k = 0; k < bitmaps.length; ++k) { MappeableContainerPointer x = bitmaps[k].highLowContainer.getContainerPointer(); if (x.getContainer() != null) { pq.add(x); } } while (!pq.isEmpty()) { MappeableContainerPointer x1 = pq.poll(); if (pq.isEmpty() || (pq.peek().key() != x1.key())) { answer.getMappeableRoaringArray().append(x1.key(), x1.getContainer().clone()); x1.advance(); if (x1.getContainer() != null) { pq.add(x1); } continue; } MappeableContainerPointer x2 = pq.poll(); MappeableContainer newc = x1.getContainer().xor(x2.getContainer()); while (!pq.isEmpty() && (pq.peek().key() == x1.key())) { MappeableContainerPointer x = pq.poll(); newc = newc.ixor(x.getContainer()); x.advance(); if (x.getContainer() != null) { pq.add(x); } else if (pq.isEmpty()) { break; } } answer.getMappeableRoaringArray().append(x1.key(), newc); x1.advance(); if (x1.getContainer() != null) { pq.add(x1); } x2.advance(); if (x2.getContainer() != null) { pq.add(x2); } } return answer; } /** * Minimizes memory usage while computing the xor aggregate on a moderate number of bitmaps. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #xor(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap horizontal_xor(MutableRoaringBitmap... bitmaps) { return horizontal_xor(convertToImmutable(bitmaps)); } /** * Compute overall AND between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_and(ImmutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer; if (bitmaps.length > 0) { answer = (bitmaps[0]).toMutableRoaringBitmap(); for (int k = 1; k < bitmaps.length; ++k) { answer = ImmutableRoaringBitmap.and(answer, bitmaps[k]); } } else { answer = new MutableRoaringBitmap(); } return answer; } /** * Compute overall AND between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap naive_and(@SuppressWarnings("rawtypes") Iterator bitmaps) { if (!bitmaps.hasNext()) { return new MutableRoaringBitmap(); } MutableRoaringBitmap answer = ((ImmutableRoaringBitmap) bitmaps.next()).toMutableRoaringBitmap(); while (bitmaps.hasNext()) { answer.and((ImmutableRoaringBitmap) bitmaps.next()); } return answer; } /** * Compute overall AND between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_and(MutableRoaringBitmap... bitmaps) { if (bitmaps.length == 0) { return new MutableRoaringBitmap(); } MutableRoaringBitmap answer = bitmaps[0].clone(); for (int k = 1; k < bitmaps.length; ++k) { answer.and(bitmaps[k]); } return answer; } /** * Computes the intersection by first intersecting the keys, avoids * materialising containers. * * @param aggregationBuffer a buffer for use in aggregations. * @param bitmaps the inputs * @return the intersection of the bitmaps */ static MutableRoaringBitmap workShyAnd(long[] aggregationBuffer, ImmutableRoaringBitmap... bitmaps) { long[] words = aggregationBuffer; ImmutableRoaringBitmap first = bitmaps[0]; for (int i = 0; i < first.highLowContainer.size(); ++i) { char key = first.highLowContainer.getKeyAtIndex(i); words[key >>> 6] |= 1L << key; } int numContainers = first.highLowContainer.size(); for (int i = 1; i < bitmaps.length && numContainers > 0; ++i) { final char[] keys; if (bitmaps[i].highLowContainer instanceof MutableRoaringArray) { keys = ((MutableRoaringArray) bitmaps[i].highLowContainer).keys; } else { keys = new char[bitmaps[i].highLowContainer.size()]; for (int j = 0; j < keys.length; ++j) { keys[j] = bitmaps[i].highLowContainer.getKeyAtIndex(j); } } numContainers = BufferUtil.intersectArrayIntoBitmap(words, CharBuffer.wrap(keys), bitmaps[i].highLowContainer.size()); } if (numContainers == 0) { return new MutableRoaringBitmap(); } char[] keys = new char[numContainers]; int base = 0; int pos = 0; for (long word : words) { while (word != 0L) { keys[pos++] = (char)(base + Long.numberOfTrailingZeros(word)); word &= (word - 1); } base += 64; } MappeableContainer[][] containers = new MappeableContainer[numContainers][bitmaps.length]; for (int i = 0; i < bitmaps.length; ++i) { ImmutableRoaringBitmap bitmap = bitmaps[i]; int position = 0; for (int j = 0; j < bitmap.highLowContainer.size(); ++j) { char key = bitmap.highLowContainer.getKeyAtIndex(j); if ((words[key >>> 6] & (1L << key)) != 0) { containers[position++][i] = bitmap.highLowContainer.getContainerAtIndex(j); } } } MutableRoaringArray array = new MutableRoaringArray(keys, new MappeableContainer[numContainers], 0); for (int i = 0; i < numContainers; ++i) { MappeableContainer[] slice = containers[i]; Arrays.fill(words, -1L); MappeableContainer tmp = new MappeableBitmapContainer(LongBuffer.wrap(words), -1); for (MappeableContainer container : slice) { MappeableContainer and = tmp.iand(container); if (and != tmp) { tmp = and; } } tmp = tmp.repairAfterLazy(); if (!tmp.isEmpty()) { array.append(keys[i], tmp instanceof MappeableBitmapContainer ? tmp.clone() : tmp); } } return new MutableRoaringBitmap(array); } /** * Computes the intersection by first intersecting the keys, avoids * materialising containers. * * @param aggregationBuffer a buffer for use in aggregations. * @param bitmaps the inputs * @return the intersection of the bitmaps */ static MutableRoaringBitmap workShyAnd(long[] aggregationBuffer, Iterator<? extends ImmutableRoaringBitmap> bitmaps) { long[] words = aggregationBuffer; List<ImmutableRoaringBitmap> collected = new ArrayList<>(); ImmutableRoaringBitmap first = bitmaps.next(); collected.add(first); for (int i = 0; i < first.highLowContainer.size(); ++i) { char key = first.highLowContainer.getKeyAtIndex(i); words[key >>> 6] |= 1L << key; } int bitmapCount = 1; int numContainers = first.highLowContainer.size(); while (numContainers > 0 && bitmaps.hasNext()) { final char[] keys; ImmutableRoaringBitmap bitmap = bitmaps.next(); collected.add(bitmap); ++bitmapCount; if (bitmap.highLowContainer instanceof MutableRoaringArray) { keys = ((MutableRoaringArray) bitmap.highLowContainer).keys; } else { keys = new char[bitmap.highLowContainer.size()]; for (int j = 0; j < keys.length; ++j) { keys[j] = bitmap.highLowContainer.getKeyAtIndex(j); } } numContainers = BufferUtil.intersectArrayIntoBitmap(words, CharBuffer.wrap(keys), bitmap.highLowContainer.size()); } if (numContainers == 0) { return new MutableRoaringBitmap(); } char[] keys = new char[numContainers]; int base = 0; int pos = 0; for (long word : words) { while (word != 0L) { keys[pos++] = (char)(base + Long.numberOfTrailingZeros(word)); word &= (word - 1); } base += 64; } MappeableContainer[][] containers = new MappeableContainer[numContainers][bitmapCount]; for (int i = 0; i < bitmapCount; ++i) { ImmutableRoaringBitmap bitmap = collected.get(i); int position = 0; for (int j = 0; j < bitmap.highLowContainer.size(); ++j) { char key = bitmap.highLowContainer.getKeyAtIndex(j); if ((words[key >>> 6] & (1L << key)) != 0) { containers[position++][i] = bitmap.highLowContainer.getContainerAtIndex(j); } } } MutableRoaringArray array = new MutableRoaringArray(keys, new MappeableContainer[numContainers], 0); for (int i = 0; i < numContainers; ++i) { MappeableContainer[] slice = containers[i]; Arrays.fill(words, -1L); MappeableContainer tmp = new MappeableBitmapContainer(LongBuffer.wrap(words), -1); for (MappeableContainer container : slice) { MappeableContainer and = tmp.iand(container); if (and != tmp) { tmp = and; } } tmp = tmp.repairAfterLazy(); if (!tmp.isEmpty()) { array.append(keys[i], tmp instanceof MappeableBitmapContainer ? tmp.clone() : tmp); } } return new MutableRoaringBitmap(array); } /** * Computes the intersection by first intersecting the keys, avoids * materialising containers, limits memory usage. You must provide a long[] array * of length at least 1024, initialized with zeroes. We do not check whether the array * is initialized with zeros: it is the caller's responsability. * You should expect this function to be slower than workShyAnd and the reduction * in memory usage might be small. * * @param buffer should be a 1024-long array * @param bitmaps the inputs * @return the intersection of the bitmaps */ public static MutableRoaringBitmap workAndMemoryShyAnd(long[] buffer, ImmutableRoaringBitmap... bitmaps) { if(buffer.length < 1024) { throw new IllegalArgumentException("buffer should have at least 1024 elements."); } long[] words = buffer; ImmutableRoaringBitmap first = bitmaps[0]; for (int i = 0; i < first.highLowContainer.size(); ++i) { char key = first.highLowContainer.getKeyAtIndex(i); words[key >>> 6] |= 1L << key; } int numContainers = first.highLowContainer.size(); for (int i = 1; i < bitmaps.length && numContainers > 0; ++i) { final char[] keys; if (bitmaps[i].highLowContainer instanceof MutableRoaringArray) { keys = ((MutableRoaringArray) bitmaps[i].highLowContainer).keys; } else { keys = new char[bitmaps[i].highLowContainer.size()]; for (int j = 0; j < keys.length; ++j) { keys[j] = bitmaps[i].highLowContainer.getKeyAtIndex(j); } } numContainers = BufferUtil.intersectArrayIntoBitmap(words, CharBuffer.wrap(keys), bitmaps[i].highLowContainer.size()); } if (numContainers == 0) { return new MutableRoaringBitmap(); } char[] keys = new char[numContainers]; int base = 0; int pos = 0; for (long word : words) { while (word != 0L) { keys[pos++] = (char)(base + Long.numberOfTrailingZeros(word)); word &= (word - 1); } base += 64; } MutableRoaringArray array = new MutableRoaringArray(keys, new MappeableContainer[numContainers], 0); for (int i = 0; i < numContainers; ++i) { char MatchingKey = keys[i]; Arrays.fill(words, -1L); MappeableContainer tmp = new MappeableBitmapContainer(LongBuffer.wrap(words), -1); for(ImmutableRoaringBitmap bitmap: bitmaps) { int idx = bitmap.highLowContainer.getIndex(MatchingKey); if(idx < 0) { continue; } MappeableContainer container = bitmap.highLowContainer.getContainerAtIndex(idx); MappeableContainer and = tmp.iand(container); if (and != tmp) { tmp = and; } } tmp = tmp.repairAfterLazy(); if (!tmp.isEmpty()) { array.append(keys[i], tmp instanceof MappeableBitmapContainer ? tmp.clone() : tmp); } } return new MutableRoaringBitmap(array); } /** * Compute overall OR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_or(ImmutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); for (int k = 0; k < bitmaps.length; ++k) { answer.naivelazyor(bitmaps[k]); } answer.repairAfterLazy(); return answer; } /** * Compute overall OR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap naive_or(@SuppressWarnings("rawtypes") Iterator bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); while (bitmaps.hasNext()) { answer.naivelazyor((ImmutableRoaringBitmap) bitmaps.next()); } answer.repairAfterLazy(); return answer; } /** * Compute overall OR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_or(MutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); for (int k = 0; k < bitmaps.length; ++k) { answer.lazyor(bitmaps[k]); } answer.repairAfterLazy(); return answer; } /** * Compute overall XOR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_xor(ImmutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); for (int k = 0; k < bitmaps.length; ++k) { answer.xor(bitmaps[k]); } return answer; } /** * Compute overall XOR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap naive_xor(@SuppressWarnings("rawtypes") Iterator bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); while (bitmaps.hasNext()) { answer.xor((ImmutableRoaringBitmap) bitmaps.next()); } return answer; } /** * Compute overall XOR between bitmaps two-by-two. * * This function runs in linear time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap naive_xor(MutableRoaringBitmap... bitmaps) { MutableRoaringBitmap answer = new MutableRoaringBitmap(); for (int k = 0; k < bitmaps.length; ++k) { answer.xor(bitmaps[k]); } return answer; } /** * Compute overall OR between bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap or(ImmutableRoaringBitmap... bitmaps) { return naive_or(bitmaps); } /** * Compute overall OR between bitmaps. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap or(@SuppressWarnings("rawtypes") Iterator bitmaps) { return naive_or(bitmaps); } /** * Compute overall OR between bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap or(MutableRoaringBitmap... bitmaps) { return naive_or(bitmaps); } /** * Uses a priority queue to compute the or aggregate. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #horizontal_or(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap priorityqueue_or(ImmutableRoaringBitmap... bitmaps) { if (bitmaps.length == 0) { return new MutableRoaringBitmap(); } else if (bitmaps.length == 1) { return bitmaps[0].toMutableRoaringBitmap(); } // we buffer the call to getLongSizeInBytes(), hence the code complexity final ImmutableRoaringBitmap[] buffer = Arrays.copyOf(bitmaps, bitmaps.length); final int[] sizes = new int[buffer.length]; final boolean[] istmp = new boolean[buffer.length]; for (int k = 0; k < sizes.length; ++k) { sizes[k] = buffer[k].serializedSizeInBytes(); } PriorityQueue<Integer> pq = new PriorityQueue<>(128, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return sizes[a] - sizes[b]; } }); for (int k = 0; k < sizes.length; ++k) { pq.add(k); } while (pq.size() > 1) { Integer x1 = pq.poll(); Integer x2 = pq.poll(); if (istmp[x1] && istmp[x2]) { buffer[x1] = MutableRoaringBitmap.lazyorfromlazyinputs((MutableRoaringBitmap) buffer[x1], (MutableRoaringBitmap) buffer[x2]); sizes[x1] = buffer[x1].serializedSizeInBytes(); pq.add(x1); } else if (istmp[x2]) { ((MutableRoaringBitmap) buffer[x2]).lazyor(buffer[x1]); sizes[x2] = buffer[x2].serializedSizeInBytes(); pq.add(x2); } else if (istmp[x1]) { ((MutableRoaringBitmap) buffer[x1]).lazyor(buffer[x2]); sizes[x1] = buffer[x1].serializedSizeInBytes(); pq.add(x1); } else { buffer[x1] = ImmutableRoaringBitmap.lazyor(buffer[x1], buffer[x2]); sizes[x1] = buffer[x1].serializedSizeInBytes(); istmp[x1] = true; pq.add(x1); } } MutableRoaringBitmap answer = (MutableRoaringBitmap) buffer[pq.poll()]; answer.repairAfterLazy(); return answer; } /** * Uses a priority queue to compute the or aggregate. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #horizontal_or(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap priorityqueue_or( @SuppressWarnings("rawtypes") Iterator bitmaps) { if (!bitmaps.hasNext()) { return new MutableRoaringBitmap(); } // we buffer the call to getLongSizeInBytes(), hence the code complexity ArrayList<ImmutableRoaringBitmap> buffer = new ArrayList<>(); while (bitmaps.hasNext()) { buffer.add((ImmutableRoaringBitmap) bitmaps.next()); } final long[] sizes = new long[buffer.size()]; final boolean[] istmp = new boolean[buffer.size()]; for (int k = 0; k < sizes.length; ++k) { sizes[k] = buffer.get(k).getLongSizeInBytes(); } PriorityQueue<Integer> pq = new PriorityQueue<>(128, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return (int)(sizes[a] - sizes[b]); } }); for (int k = 0; k < sizes.length; ++k) { pq.add(k); } if (pq.size() == 1) { return buffer.get(pq.poll()).toMutableRoaringBitmap(); } while (pq.size() > 1) { Integer x1 = pq.poll(); Integer x2 = pq.poll(); if (istmp[x1] && istmp[x2]) { buffer.set(x1, MutableRoaringBitmap.lazyorfromlazyinputs( (MutableRoaringBitmap) buffer.get(x1), (MutableRoaringBitmap) buffer.get(x2))); sizes[x1] = buffer.get(x1).getLongSizeInBytes(); pq.add(x1); } else if (istmp[x2]) { ((MutableRoaringBitmap) buffer.get(x2)).lazyor(buffer.get(x1)); sizes[x2] = buffer.get(x2).getLongSizeInBytes(); pq.add(x2); } else if (istmp[x1]) { ((MutableRoaringBitmap) buffer.get(x1)).lazyor(buffer.get(x2)); sizes[x1] = buffer.get(x1).getLongSizeInBytes(); pq.add(x1); } else { buffer.set(x1, ImmutableRoaringBitmap.lazyor(buffer.get(x1), buffer.get(x2))); sizes[x1] = buffer.get(x1).getLongSizeInBytes(); istmp[x1] = true; pq.add(x1); } } MutableRoaringBitmap answer = (MutableRoaringBitmap) buffer.get(pq.poll()); answer.repairAfterLazy(); return answer; } /** * Uses a priority queue to compute the xor aggregate. * * This function runs in linearithmic (O(n log n)) time with respect to the number of bitmaps. * * @param bitmaps input bitmaps * @return aggregated bitmap * @see #horizontal_xor(ImmutableRoaringBitmap...) */ public static MutableRoaringBitmap priorityqueue_xor(ImmutableRoaringBitmap... bitmaps) { // code could be faster, see priorityqueue_or if (bitmaps.length < 2) { throw new IllegalArgumentException("Expecting at least 2 bitmaps"); } final PriorityQueue<ImmutableRoaringBitmap> pq = new PriorityQueue<>(bitmaps.length, new Comparator<ImmutableRoaringBitmap>() { @Override public int compare(ImmutableRoaringBitmap a, ImmutableRoaringBitmap b) { return (int)(a.getLongSizeInBytes() - b.getLongSizeInBytes()); } }); Collections.addAll(pq, bitmaps); while (pq.size() > 1) { final ImmutableRoaringBitmap x1 = pq.poll(); final ImmutableRoaringBitmap x2 = pq.poll(); pq.add(ImmutableRoaringBitmap.xor(x1, x2)); } return (MutableRoaringBitmap) pq.poll(); } /** * Compute overall XOR between bitmaps. * * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap xor(ImmutableRoaringBitmap... bitmaps) { return naive_xor(bitmaps); } /** * Compute overall XOR between bitmaps. * * @param bitmaps input bitmaps (ImmutableRoaringBitmap or MutableRoaringBitmap) * @return aggregated bitmap */ public static MutableRoaringBitmap xor(@SuppressWarnings("rawtypes") Iterator bitmaps) { return naive_xor(bitmaps); } /** * Compute overall XOR between bitmaps. * * * @param bitmaps input bitmaps * @return aggregated bitmap */ public static MutableRoaringBitmap xor(MutableRoaringBitmap... bitmaps) { return naive_xor(bitmaps); } /** * Private constructor to prevent instantiation of utility class */ private BufferFastAggregation() { } }
12,058