max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
14,668 |
<reponame>zealoussnow/chromium
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
#include <vector>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace internal {
MapFieldBase::~MapFieldBase() {
if (repeated_field_ != NULL && arena_ == NULL) delete repeated_field_;
}
const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const {
ConstAccess();
SyncRepeatedFieldWithMap();
return *reinterpret_cast<RepeatedPtrFieldBase*>(repeated_field_);
}
RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() {
MutableAccess();
SyncRepeatedFieldWithMap();
SetRepeatedDirty();
return reinterpret_cast<RepeatedPtrFieldBase*>(repeated_field_);
}
size_t MapFieldBase::SpaceUsedExcludingSelfLong() const {
ConstAccess();
mutex_.Lock();
size_t size = SpaceUsedExcludingSelfNoLock();
mutex_.Unlock();
ConstAccess();
return size;
}
size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const {
if (repeated_field_ != NULL) {
return repeated_field_->SpaceUsedExcludingSelfLong();
} else {
return 0;
}
}
bool MapFieldBase::IsMapValid() const {
ConstAccess();
// "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get
// executed before state_ is checked.
int state = state_.load(std::memory_order_acquire);
return state != STATE_MODIFIED_REPEATED;
}
bool MapFieldBase::IsRepeatedFieldValid() const {
ConstAccess();
int state = state_.load(std::memory_order_acquire);
return state != STATE_MODIFIED_MAP;
}
void MapFieldBase::SetMapDirty() {
MutableAccess();
// These are called by (non-const) mutator functions. So by our API it's the
// callers responsibility to have these calls properly ordered.
state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed);
}
void MapFieldBase::SetRepeatedDirty() {
MutableAccess();
// These are called by (non-const) mutator functions. So by our API it's the
// callers responsibility to have these calls properly ordered.
state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed);
}
void MapFieldBase::SyncRepeatedFieldWithMap() const {
ConstAccess();
// acquire here matches with release below to ensure that we can only see a
// value of CLEAN after all previous changes have been synced.
switch (state_.load(std::memory_order_acquire)) {
case STATE_MODIFIED_MAP:
mutex_.Lock();
// Double check state, because another thread may have seen the same
// state and done the synchronization before the current thread.
if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) {
SyncRepeatedFieldWithMapNoLock();
state_.store(CLEAN, std::memory_order_release);
}
mutex_.Unlock();
ConstAccess();
break;
case CLEAN:
mutex_.Lock();
// Double check state
if (state_.load(std::memory_order_relaxed) == CLEAN) {
if (repeated_field_ == nullptr) {
if (arena_ == nullptr) {
repeated_field_ = new RepeatedPtrField<Message>();
} else {
repeated_field_ =
Arena::CreateMessage<RepeatedPtrField<Message> >(arena_);
}
}
state_.store(CLEAN, std::memory_order_release);
}
mutex_.Unlock();
ConstAccess();
break;
default:
break;
}
}
void MapFieldBase::SyncRepeatedFieldWithMapNoLock() const {
if (repeated_field_ == NULL) {
repeated_field_ = Arena::CreateMessage<RepeatedPtrField<Message> >(arena_);
}
}
void MapFieldBase::SyncMapWithRepeatedField() const {
ConstAccess();
// acquire here matches with release below to ensure that we can only see a
// value of CLEAN after all previous changes have been synced.
if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_REPEATED) {
mutex_.Lock();
// Double check state, because another thread may have seen the same state
// and done the synchronization before the current thread.
if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_REPEATED) {
SyncMapWithRepeatedFieldNoLock();
state_.store(CLEAN, std::memory_order_release);
}
mutex_.Unlock();
ConstAccess();
}
}
// ------------------DynamicMapField------------------
DynamicMapField::DynamicMapField(const Message* default_entry)
: default_entry_(default_entry) {}
DynamicMapField::DynamicMapField(const Message* default_entry, Arena* arena)
: TypeDefinedMapFieldBase<MapKey, MapValueRef>(arena),
map_(arena),
default_entry_(default_entry) {}
DynamicMapField::~DynamicMapField() {
// DynamicMapField owns map values. Need to delete them before clearing
// the map.
for (Map<MapKey, MapValueRef>::iterator iter = map_.begin();
iter != map_.end(); ++iter) {
iter->second.DeleteData();
}
map_.clear();
}
int DynamicMapField::size() const { return GetMap().size(); }
void DynamicMapField::Clear() {
Map<MapKey, MapValueRef>* map = &const_cast<DynamicMapField*>(this)->map_;
if (MapFieldBase::arena_ == nullptr) {
for (Map<MapKey, MapValueRef>::iterator iter = map->begin();
iter != map->end(); ++iter) {
iter->second.DeleteData();
}
}
map->clear();
if (MapFieldBase::repeated_field_ != nullptr) {
MapFieldBase::repeated_field_->Clear();
}
// Data in map and repeated field are both empty, but we can't set status
// CLEAN which will invalidate previous reference to map.
MapFieldBase::SetMapDirty();
}
bool DynamicMapField::ContainsMapKey(const MapKey& map_key) const {
const Map<MapKey, MapValueRef>& map = GetMap();
Map<MapKey, MapValueRef>::const_iterator iter = map.find(map_key);
return iter != map.end();
}
void DynamicMapField::AllocateMapValue(MapValueRef* map_val) {
const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
map_val->SetType(val_des->cpp_type());
// Allocate memory for the MapValueRef, and initialize to
// default value.
switch (val_des->cpp_type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
TYPE* value = Arena::Create<TYPE>(MapFieldBase::arena_); \
map_val->SetValue(value); \
break; \
}
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
HANDLE_TYPE(UINT64, uint64);
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
HANDLE_TYPE(STRING, std::string);
HANDLE_TYPE(ENUM, int32);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message =
default_entry_->GetReflection()->GetMessage(*default_entry_, val_des);
Message* value = message.New(MapFieldBase::arena_);
map_val->SetValue(value);
break;
}
}
}
bool DynamicMapField::InsertOrLookupMapValue(const MapKey& map_key,
MapValueRef* val) {
// Always use mutable map because users may change the map value by
// MapValueRef.
Map<MapKey, MapValueRef>* map = MutableMap();
Map<MapKey, MapValueRef>::iterator iter = map->find(map_key);
if (iter == map->end()) {
MapValueRef& map_val = map_[map_key];
AllocateMapValue(&map_val);
val->CopyFrom(map_val);
return true;
}
// map_key is already in the map. Make sure (*map)[map_key] is not called.
// [] may reorder the map and iterators.
val->CopyFrom(iter->second);
return false;
}
bool DynamicMapField::LookupMapValue(const MapKey& map_key,
MapValueConstRef* val) const {
const Map<MapKey, MapValueRef>& map = GetMap();
Map<MapKey, MapValueRef>::const_iterator iter = map.find(map_key);
if (iter == map.end()) {
return false;
}
// map_key is already in the map. Make sure (*map)[map_key] is not called.
// [] may reorder the map and iterators.
val->CopyFrom(iter->second);
return true;
}
bool DynamicMapField::DeleteMapValue(const MapKey& map_key) {
MapFieldBase::SyncMapWithRepeatedField();
Map<MapKey, MapValueRef>::iterator iter = map_.find(map_key);
if (iter == map_.end()) {
return false;
}
// Set map dirty only if the delete is successful.
MapFieldBase::SetMapDirty();
if (MapFieldBase::arena_ == nullptr) {
iter->second.DeleteData();
}
map_.erase(iter);
return true;
}
const Map<MapKey, MapValueRef>& DynamicMapField::GetMap() const {
MapFieldBase::SyncMapWithRepeatedField();
return map_;
}
Map<MapKey, MapValueRef>* DynamicMapField::MutableMap() {
MapFieldBase::SyncMapWithRepeatedField();
MapFieldBase::SetMapDirty();
return &map_;
}
void DynamicMapField::SetMapIteratorValue(MapIterator* map_iter) const {
Map<MapKey, MapValueRef>::const_iterator iter =
TypeDefinedMapFieldBase<MapKey, MapValueRef>::InternalGetIterator(
map_iter);
if (iter == map_.end()) return;
map_iter->key_.CopyFrom(iter->first);
map_iter->value_.CopyFrom(iter->second);
}
void DynamicMapField::MergeFrom(const MapFieldBase& other) {
GOOGLE_DCHECK(IsMapValid() && other.IsMapValid());
Map<MapKey, MapValueRef>* map = MutableMap();
const DynamicMapField& other_field =
reinterpret_cast<const DynamicMapField&>(other);
for (Map<MapKey, MapValueRef>::const_iterator other_it =
other_field.map_.begin();
other_it != other_field.map_.end(); ++other_it) {
Map<MapKey, MapValueRef>::iterator iter = map->find(other_it->first);
MapValueRef* map_val;
if (iter == map->end()) {
map_val = &map_[other_it->first];
AllocateMapValue(map_val);
} else {
map_val = &iter->second;
}
// Copy map value
const FieldDescriptor* field_descriptor =
default_entry_->GetDescriptor()->map_value();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: {
map_val->SetInt32Value(other_it->second.GetInt32Value());
break;
}
case FieldDescriptor::CPPTYPE_INT64: {
map_val->SetInt64Value(other_it->second.GetInt64Value());
break;
}
case FieldDescriptor::CPPTYPE_UINT32: {
map_val->SetUInt32Value(other_it->second.GetUInt32Value());
break;
}
case FieldDescriptor::CPPTYPE_UINT64: {
map_val->SetUInt64Value(other_it->second.GetUInt64Value());
break;
}
case FieldDescriptor::CPPTYPE_FLOAT: {
map_val->SetFloatValue(other_it->second.GetFloatValue());
break;
}
case FieldDescriptor::CPPTYPE_DOUBLE: {
map_val->SetDoubleValue(other_it->second.GetDoubleValue());
break;
}
case FieldDescriptor::CPPTYPE_BOOL: {
map_val->SetBoolValue(other_it->second.GetBoolValue());
break;
}
case FieldDescriptor::CPPTYPE_STRING: {
map_val->SetStringValue(other_it->second.GetStringValue());
break;
}
case FieldDescriptor::CPPTYPE_ENUM: {
map_val->SetEnumValue(other_it->second.GetEnumValue());
break;
}
case FieldDescriptor::CPPTYPE_MESSAGE: {
map_val->MutableMessageValue()->CopyFrom(
other_it->second.GetMessageValue());
break;
}
}
}
}
void DynamicMapField::Swap(MapFieldBase* other) {
DynamicMapField* other_field = down_cast<DynamicMapField*>(other);
std::swap(this->MapFieldBase::repeated_field_, other_field->repeated_field_);
map_.swap(other_field->map_);
// a relaxed swap of the atomic
auto other_state = other_field->state_.load(std::memory_order_relaxed);
auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed);
other_field->state_.store(this_state, std::memory_order_relaxed);
this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed);
}
void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const {
const Reflection* reflection = default_entry_->GetReflection();
const FieldDescriptor* key_des = default_entry_->GetDescriptor()->map_key();
const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
if (MapFieldBase::repeated_field_ == NULL) {
if (MapFieldBase::arena_ == NULL) {
MapFieldBase::repeated_field_ = new RepeatedPtrField<Message>();
} else {
MapFieldBase::repeated_field_ =
Arena::CreateMessage<RepeatedPtrField<Message> >(
MapFieldBase::arena_);
}
}
MapFieldBase::repeated_field_->Clear();
for (Map<MapKey, MapValueRef>::const_iterator it = map_.begin();
it != map_.end(); ++it) {
Message* new_entry = default_entry_->New(MapFieldBase::arena_);
MapFieldBase::repeated_field_->AddAllocated(new_entry);
const MapKey& map_key = it->first;
switch (key_des->cpp_type()) {
case FieldDescriptor::CPPTYPE_STRING:
reflection->SetString(new_entry, key_des, map_key.GetStringValue());
break;
case FieldDescriptor::CPPTYPE_INT64:
reflection->SetInt64(new_entry, key_des, map_key.GetInt64Value());
break;
case FieldDescriptor::CPPTYPE_INT32:
reflection->SetInt32(new_entry, key_des, map_key.GetInt32Value());
break;
case FieldDescriptor::CPPTYPE_UINT64:
reflection->SetUInt64(new_entry, key_des, map_key.GetUInt64Value());
break;
case FieldDescriptor::CPPTYPE_UINT32:
reflection->SetUInt32(new_entry, key_des, map_key.GetUInt32Value());
break;
case FieldDescriptor::CPPTYPE_BOOL:
reflection->SetBool(new_entry, key_des, map_key.GetBoolValue());
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_FLOAT:
case FieldDescriptor::CPPTYPE_ENUM:
case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Can't get here.";
break;
}
const MapValueRef& map_val = it->second;
switch (val_des->cpp_type()) {
case FieldDescriptor::CPPTYPE_STRING:
reflection->SetString(new_entry, val_des, map_val.GetStringValue());
break;
case FieldDescriptor::CPPTYPE_INT64:
reflection->SetInt64(new_entry, val_des, map_val.GetInt64Value());
break;
case FieldDescriptor::CPPTYPE_INT32:
reflection->SetInt32(new_entry, val_des, map_val.GetInt32Value());
break;
case FieldDescriptor::CPPTYPE_UINT64:
reflection->SetUInt64(new_entry, val_des, map_val.GetUInt64Value());
break;
case FieldDescriptor::CPPTYPE_UINT32:
reflection->SetUInt32(new_entry, val_des, map_val.GetUInt32Value());
break;
case FieldDescriptor::CPPTYPE_BOOL:
reflection->SetBool(new_entry, val_des, map_val.GetBoolValue());
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
reflection->SetDouble(new_entry, val_des, map_val.GetDoubleValue());
break;
case FieldDescriptor::CPPTYPE_FLOAT:
reflection->SetFloat(new_entry, val_des, map_val.GetFloatValue());
break;
case FieldDescriptor::CPPTYPE_ENUM:
reflection->SetEnumValue(new_entry, val_des, map_val.GetEnumValue());
break;
case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message = map_val.GetMessageValue();
reflection->MutableMessage(new_entry, val_des)->CopyFrom(message);
break;
}
}
}
}
void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
Map<MapKey, MapValueRef>* map = &const_cast<DynamicMapField*>(this)->map_;
const Reflection* reflection = default_entry_->GetReflection();
const FieldDescriptor* key_des = default_entry_->GetDescriptor()->map_key();
const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
// DynamicMapField owns map values. Need to delete them before clearing
// the map.
if (MapFieldBase::arena_ == nullptr) {
for (Map<MapKey, MapValueRef>::iterator iter = map->begin();
iter != map->end(); ++iter) {
iter->second.DeleteData();
}
}
map->clear();
for (RepeatedPtrField<Message>::iterator it =
MapFieldBase::repeated_field_->begin();
it != MapFieldBase::repeated_field_->end(); ++it) {
// MapKey type will be set later.
MapKey map_key;
switch (key_des->cpp_type()) {
case FieldDescriptor::CPPTYPE_STRING:
map_key.SetStringValue(reflection->GetString(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_INT64:
map_key.SetInt64Value(reflection->GetInt64(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_INT32:
map_key.SetInt32Value(reflection->GetInt32(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_UINT64:
map_key.SetUInt64Value(reflection->GetUInt64(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_UINT32:
map_key.SetUInt32Value(reflection->GetUInt32(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_BOOL:
map_key.SetBoolValue(reflection->GetBool(*it, key_des));
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_FLOAT:
case FieldDescriptor::CPPTYPE_ENUM:
case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Can't get here.";
break;
}
if (MapFieldBase::arena_ == nullptr) {
// Remove existing map value with same key.
Map<MapKey, MapValueRef>::iterator iter = map->find(map_key);
if (iter != map->end()) {
iter->second.DeleteData();
}
}
MapValueRef& map_val = (*map)[map_key];
map_val.SetType(val_des->cpp_type());
switch (val_des->cpp_type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE, METHOD) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
TYPE* value = Arena::Create<TYPE>(MapFieldBase::arena_); \
*value = reflection->Get##METHOD(*it, val_des); \
map_val.SetValue(value); \
break; \
}
HANDLE_TYPE(INT32, int32, Int32);
HANDLE_TYPE(INT64, int64, Int64);
HANDLE_TYPE(UINT32, uint32, UInt32);
HANDLE_TYPE(UINT64, uint64, UInt64);
HANDLE_TYPE(DOUBLE, double, Double);
HANDLE_TYPE(FLOAT, float, Float);
HANDLE_TYPE(BOOL, bool, Bool);
HANDLE_TYPE(STRING, std::string, String);
HANDLE_TYPE(ENUM, int32, EnumValue);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message = reflection->GetMessage(*it, val_des);
Message* value = message.New(MapFieldBase::arena_);
value->CopyFrom(message);
map_val.SetValue(value);
break;
}
}
}
}
size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
size_t size = 0;
if (MapFieldBase::repeated_field_ != NULL) {
size += MapFieldBase::repeated_field_->SpaceUsedExcludingSelfLong();
}
size += sizeof(map_);
size_t map_size = map_.size();
if (map_size) {
Map<MapKey, MapValueRef>::const_iterator it = map_.begin();
size += sizeof(it->first) * map_size;
size += sizeof(it->second) * map_size;
// If key is string, add the allocated space.
if (it->first.type() == FieldDescriptor::CPPTYPE_STRING) {
size += sizeof(std::string) * map_size;
}
// Add the allocated space in MapValueRef.
switch (it->second.type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
size += sizeof(TYPE) * map_size; \
break; \
}
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
HANDLE_TYPE(UINT64, uint64);
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
HANDLE_TYPE(STRING, std::string);
HANDLE_TYPE(ENUM, int32);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE: {
while (it != map_.end()) {
const Message& message = it->second.GetMessageValue();
size += message.GetReflection()->SpaceUsedLong(message);
++it;
}
break;
}
}
}
return size;
}
} // namespace internal
} // namespace protobuf
} // namespace google
| 8,766 |
537 |
<reponame>shouxieai/tensorRT_Pro
import os
import cv2
import numpy as np
import pytrt as tp
# change current workspace
os.chdir("../workspace/")
def compile_detector_model(width, height):
width = tp.upbound(width)
height = tp.upbound(height)
index_of_reshape_layer = 0
def hook_reshape(name, shape):
# print(name)
# layerset = [
# "Reshape_100", "Reshape_104", "Reshape_108",
# "Reshape_113", "Reshape_117", "Reshape_121",
# "Reshape_126", "Reshape_130", "Reshape_134"
# ]
nonlocal index_of_reshape_layer
strides = [8, 16, 32, 8, 16, 32, 8, 16, 32]
index = index_of_reshape_layer
index_of_reshape_layer += 1
stride = strides[index]
return [-1, height * width // stride // stride * 2, shape[2]]
engine_file = f"retinaface.{width}x{height}.fp32.trtmodel"
if not os.path.exists(engine_file):
tp.set_compile_hook_reshape_layer(hook_reshape)
tp.compile_onnx_to_file(
5, tp.onnx_hub("mb_retinaface"), engine_file,
inputs_dims=np.array([
[1, 3, height, width]
], dtype=np.int32)
)
return engine_file
def compile_feature_model():
engine_file = "arcface_iresnet50.FP32.trtmodel"
if not os.path.exists(engine_file):
tp.compile_onnx_to_file(5, tp.onnx_hub("arcface_iresnet50"), engine_file)
return engine_file
def extract_feature_one(detector_model, feature_model, image, save_debug_name=None):
faces = detector_model.commit(image).get()
if len(faces) == 0:
print("Can not detect any face")
return None
max_face = max(faces, key=lambda item: item.width * item.height)
crop_image, face = detector_model.crop_face_and_landmark(image, max_face)
feature = feature_model.commit(crop_image, face.landmark).get()
if save_debug_name is not None:
left, top, right, bottom = map(int, [face.left, face.top, face.right, face.bottom])
cv2.rectangle(crop_image, (left, top), (right, bottom), (255, 0, 255), 5)
for x, y in face.landmark.astype(int):
cv2.circle(crop_image, (x, y), 3, (0, 255, 0), -1, 16)
print(f"Save debug image to {save_debug_name}")
cv2.imwrite(save_debug_name, crop_image)
return feature
def cosine_distance(a, b):
return float(a @ b.T)
detect_file = compile_detector_model(640, 640)
arcface_file = compile_feature_model()
detector_model = tp.Retinaface(detect_file, nms_threshold=0.4)
feature_model = tp.Arcface(arcface_file)
image_a = cv2.imread("face/library/2ys2.jpg")
image_b = cv2.imread("face/library/2ys3.jpg")
image_c = cv2.imread("face/library/male.jpg")
feature_a = extract_feature_one(detector_model, feature_model, image_a, "image_a.jpg")
feature_b = extract_feature_one(detector_model, feature_model, image_b, "image_b.jpg")
feature_c = extract_feature_one(detector_model, feature_model, image_c, "image_c.jpg")
print("a == b", cosine_distance(feature_a, feature_b))
print("a != c", cosine_distance(feature_a, feature_c))
print("b != c", cosine_distance(feature_b, feature_c))
| 1,444 |
384 |
/**
* 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.tez.runtime.library.cartesianproduct;
import com.google.common.annotations.VisibleForTesting;
import org.apache.tez.common.Preconditions;
import com.google.protobuf.ByteString;
import org.apache.tez.dag.api.EdgeManagerPluginContext;
import org.apache.tez.dag.api.EdgeManagerPluginOnDemand;
import javax.annotation.Nullable;
import static org.apache.tez.runtime.library.cartesianproduct.CartesianProductUserPayload.*;
/**
* This EM wrap a real edge manager implementation object. It choose whether it's partitioned or
* fair implementation according to the config. All method invocations are actually
* redirected to real implementation.
*/
public class CartesianProductEdgeManager extends EdgeManagerPluginOnDemand {
private CartesianProductEdgeManagerReal edgeManagerReal;
public CartesianProductEdgeManager(EdgeManagerPluginContext context) {
super(context);
}
@Override
public void initialize() throws Exception {
Preconditions.checkArgument(getContext().getUserPayload() != null);
CartesianProductConfigProto config = CartesianProductConfigProto.parseFrom(
ByteString.copyFrom(getContext().getUserPayload().getPayload()));
// no need to check config because config comes from VM and is already checked by VM
edgeManagerReal = config.getIsPartitioned()
? new CartesianProductEdgeManagerPartitioned(getContext())
: new FairCartesianProductEdgeManager(getContext());
edgeManagerReal.initialize(config);
}
@VisibleForTesting
protected CartesianProductEdgeManagerReal getEdgeManagerReal() {
return this.edgeManagerReal;
}
@Override
public void prepareForRouting() throws Exception {
edgeManagerReal.prepareForRouting();
}
@Override
public int routeInputErrorEventToSource(int destTaskId, int failedInputId) throws Exception {
return edgeManagerReal.routeInputErrorEventToSource(destTaskId, failedInputId);
}
@Nullable
@Override
public EventRouteMetadata routeDataMovementEventToDestination(int srcTaskId,
int srcOutputId,
int destTaskId)
throws Exception {
return edgeManagerReal.routeDataMovementEventToDestination(srcTaskId, srcOutputId, destTaskId);
}
@Nullable
@Override
public CompositeEventRouteMetadata routeCompositeDataMovementEventToDestination(int srcTaskId,
int destTaskId)
throws Exception {
return edgeManagerReal.routeCompositeDataMovementEventToDestination(srcTaskId, destTaskId);
}
@Nullable
@Override
public EventRouteMetadata routeInputSourceTaskFailedEventToDestination(int srcTaskId,
int destTaskId)
throws Exception {
return edgeManagerReal.routeInputSourceTaskFailedEventToDestination(srcTaskId, destTaskId);
}
@Override
public int getNumDestinationTaskPhysicalInputs(int destTaskId) {
return edgeManagerReal.getNumDestinationTaskPhysicalInputs(destTaskId);
}
@Override
public int getNumSourceTaskPhysicalOutputs(int srcTaskId) {
return edgeManagerReal.getNumSourceTaskPhysicalOutputs(srcTaskId);
}
@Override
public int getNumDestinationConsumerTasks(int sourceTaskIndex) {
return edgeManagerReal.getNumDestinationConsumerTasks(sourceTaskIndex);
}
}
| 1,393 |
852 |
#ifndef CalibCalorimetry_EcalLaserAnalyzer_EcalABAnalyzer_h
#define CalibCalorimetry_EcalLaserAnalyzer_EcalABAnalyzer_h
// $Id: EcalABAnalyzer.h
#include <memory>
#include <vector>
#include <map>
#include <FWCore/Framework/interface/one/EDAnalyzer.h>
#include <DataFormats/EcalDigi/interface/EcalDigiCollections.h>
#include <DataFormats/EcalRawData/interface/EcalRawDataCollections.h>
#include <Geometry/EcalMapping/interface/EcalElectronicsMapping.h>
#include <Geometry/EcalMapping/interface/EcalMappingRcd.h>
class TShapeAnalysis;
class TAPDPulse;
class TMom;
// Define geometrical constants
// NOT the same for "EB" and "EE"
//
// "EB" "EE"
//
// 0 0
// 1 2 1 2
// 3 4
// 5 6
// 7 8
//
//
// "EB" geometry
#define NCRYSEB 1700 // Number of crystals per EB supermodule
// "EE" geometry
#define NCRYSEE 830 // Number of crystals per EE supermodule
class EcalABAnalyzer : public edm::one::EDAnalyzer<> {
public:
explicit EcalABAnalyzer(const edm::ParameterSet &iConfig);
~EcalABAnalyzer() override;
void analyze(const edm::Event &e, const edm::EventSetup &c) override;
void beginJob() override;
void endJob() override;
enum VarCol { iBlue, iRed, nColor };
private:
int iEvent;
const std::string eventHeaderCollection_;
const std::string eventHeaderProducer_;
const std::string digiCollection_;
const std::string digiProducer_;
const edm::EDGetTokenT<EcalRawDataCollection> rawDataToken_;
edm::EDGetTokenT<EBDigiCollection> ebDigiToken_;
edm::EDGetTokenT<EEDigiCollection> eeDigiToken_;
const edm::ESGetToken<EcalElectronicsMapping, EcalMappingRcd> mappingToken_;
// Framework parameters
const unsigned int _nsamples;
unsigned int _presample;
const unsigned int _firstsample;
const unsigned int _lastsample;
const unsigned int _timingcutlow;
const unsigned int _timingcuthigh;
const unsigned int _timingquallow;
const unsigned int _timingqualhigh;
const double _ratiomincutlow;
const double _ratiomincuthigh;
const double _ratiomaxcutlow;
const double _presamplecut;
const unsigned int _niter;
const double _alpha;
const double _beta;
const unsigned int _nevtmax;
const double _noise;
const double _chi2cut;
const std::string _ecalPart;
const int _fedid;
const double _qualpercent;
const int _debug;
TAPDPulse *APDPulse;
TMom *Delta01;
TMom *Delta12;
const std::string resdir_;
// Output file names
std::string alphafile;
std::string alphainitfile;
TShapeAnalysis *shapana;
unsigned int nevtAB[NCRYSEB];
// Define geometrical constants
// Default values correspond to "EB" geometry (1700 crystals)
unsigned int nCrys;
bool doesABTreeExist;
bool _fitab;
// Identify run type
int runType;
int runNum;
int fedID;
int dccID;
int side;
int lightside;
int iZ;
// Temporary root files and trees
std::vector<int> colors;
std::map<int, int> channelMapEE;
std::vector<int> dccMEM;
std::vector<int> modules;
// Declaration of leaves types for temporary trees
int phi, eta;
int event;
int color;
double adc[10];
int adcG[10];
int channelIteratorEE;
int iEta[NCRYSEB], iPhi[NCRYSEB];
int iTowerID[NCRYSEB], iChannelID[NCRYSEB], idccID[NCRYSEB], iside[NCRYSEB];
// Quality Checks variables and flags
int nEvtBadGain[NCRYSEB];
int nEvtBadTiming[NCRYSEB];
int nEvtTot[NCRYSEB];
bool wasGainOK[NCRYSEB];
bool wasTimingOK[NCRYSEB];
bool isGainOK;
bool isTimingOK;
};
#endif
| 1,306 |
2,542 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Reliability;
using namespace Transport;
using namespace std;
INITIALIZE_SIZE_ESTIMATION(ServiceReplicaSet)
GlobalWString InvalidPrimaryTrace = make_global<wstring>(L"Primary=[-invalid-], ");
GlobalWString SecondariesTrace = make_global<wstring>(L"Secondaries");
GlobalWString ReplicasTrace = make_global<wstring>(L"Replicas");
ServiceReplicaSet::ServiceReplicaSet()
: isStateful_(false),
isPrimaryLocationValid_(false),
primaryLocation_(),
replicaLocations_(),
lookupVersion_(0)
{
}
ServiceReplicaSet::ServiceReplicaSet(
bool isStateful,
bool isPrimaryLocationValid,
std::wstring && primaryLocation,
std::vector<std::wstring> && replicaLocations,
int64 lookupVersion)
: isStateful_(isStateful),
isPrimaryLocationValid_(isPrimaryLocationValid),
primaryLocation_(move(primaryLocation)),
replicaLocations_(move(replicaLocations)),
lookupVersion_(lookupVersion)
{
}
ServiceReplicaSet::ServiceReplicaSet(ServiceReplicaSet const & other)
: isStateful_(other.isStateful_),
isPrimaryLocationValid_(other.isPrimaryLocationValid_),
primaryLocation_(other.primaryLocation_),
replicaLocations_(other.replicaLocations_),
lookupVersion_(other.lookupVersion_)
{
}
ServiceReplicaSet & ServiceReplicaSet::operator=(ServiceReplicaSet const & other)
{
if (this != &other)
{
isStateful_ = other.isStateful_;
isPrimaryLocationValid_ = other.isPrimaryLocationValid_;
primaryLocation_ = other.primaryLocation_;
replicaLocations_ = other.replicaLocations_;
lookupVersion_ = other.lookupVersion_;
}
return *this;
}
ServiceReplicaSet::ServiceReplicaSet(ServiceReplicaSet && other)
: isStateful_(std::move(other.isStateful_)),
isPrimaryLocationValid_(std::move(other.isPrimaryLocationValid_)),
primaryLocation_(std::move(other.primaryLocation_)),
replicaLocations_(std::move(other.replicaLocations_)),
lookupVersion_(std::move(other.lookupVersion_))
{
}
ServiceReplicaSet & ServiceReplicaSet::operator=(ServiceReplicaSet && other)
{
if (this != &other)
{
isStateful_ = std::move(other.isStateful_);
isPrimaryLocationValid_ = std::move(other.isPrimaryLocationValid_);
primaryLocation_ = std::move(other.primaryLocation_);
replicaLocations_ = std::move(other.replicaLocations_);
lookupVersion_ = std::move(other.lookupVersion_);
}
return *this;
}
bool ServiceReplicaSet::IsEmpty() const
{
if (IsStateful)
{
return !IsPrimaryLocationValid && SecondaryLocations.size() == 0;
}
else
{
return ReplicaLocations.size() == 0;
}
}
bool ServiceReplicaSet::operator == (ServiceReplicaSet const & other) const
{
bool equals = true;
equals = isStateful_ == other.isStateful_;
if (!equals) { return equals; }
equals = isPrimaryLocationValid_ == other.isPrimaryLocationValid_;
if (!equals) { return equals; }
equals = primaryLocation_ == other.primaryLocation_;
if (!equals) { return equals; }
equals = replicaLocations_.size() == other.replicaLocations_.size();
if (!equals) { return equals; }
for (auto ix=0; ix<replicaLocations_.size(); ++ix)
{
equals = replicaLocations_[ix] == other.replicaLocations_[ix];
if (!equals) { return equals; }
}
equals = lookupVersion_ == other.lookupVersion_;
return equals;
}
bool ServiceReplicaSet::operator != (ServiceReplicaSet const & other) const
{
return !(*this == other);
}
void ServiceReplicaSet::WriteTo(__in Common::TextWriter & w, Common::FormatOptions const &) const
{
if (isStateful_)
{
if (isPrimaryLocationValid_)
{
w.WriteLine("Primary: {0}", primaryLocation_);
}
w.WriteLine("Secondaries:");
for (std::wstring const& secondaryLocation : replicaLocations_)
{
w.WriteLine(" {0}", secondaryLocation);
}
}
else
{
w.WriteLine("Replicas:");
for (std::wstring const& replicaLocation : replicaLocations_)
{
w.WriteLine(" {0}", replicaLocation);
}
}
w.WriteLine("Version: {0}", lookupVersion_);
}
string ServiceReplicaSet::AddField(Common::TraceEvent &traceEvent, string const& name)
{
traceEvent.AddField<wstring>(name + ".primary");
traceEvent.AddField<wstring>(name + ".replicaType");
traceEvent.AddField<wstring>(name + ".replicas");
traceEvent.AddField<int64>(name + ".version");
return "{0}{1}=[{2}], Version={3}";
}
void ServiceReplicaSet::FillEventData(TraceEventContext &context) const
{
if (isStateful_)
{
if (isPrimaryLocationValid_)
{
context.WriteCopy(wformatString("Primary=[{0}], ", primaryLocation_));
}
else
{
context.Write<wstring>(*InvalidPrimaryTrace);
}
context.Write<wstring>(*SecondariesTrace);
}
else
{
context.Write<wstring>(L"");
context.Write<wstring>(*ReplicasTrace);
}
wstring replicas;
StringWriter writer(replicas);
bool isFirst = true;
for (auto it = replicaLocations_.begin(); it != replicaLocations_.end(); ++it)
{
if (!isFirst)
{
writer << L", ";
}
else
{
isFirst = false;
}
writer << L"'" << *it << L"'";
}
context.WriteCopy<wstring>(replicas);
context.Write<int64>(lookupVersion_);
}
| 2,254 |
1,327 |
/*******************************************************************************
* Copyright 2019-2022 Intel Corporation
* Copyright 2020-2022 FUJITSU LIMITED
*
* 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 <assert.h>
#include "common/c_types_map.hpp"
#include "common/dnnl_thread.hpp"
#include "common/math_utils.hpp"
#include "common/memory_tracking.hpp"
#include "common/nstl.hpp"
#include "common/type_helpers.hpp"
#include "common/utils.hpp"
#include "cpu/aarch64/jit_generator.hpp"
#include "cpu/aarch64/injectors/jit_uni_eltwise_injector.hpp"
#include "cpu/aarch64/jit_uni_softmax.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
namespace aarch64 {
using namespace Xbyak_aarch64;
template <cpu_isa_t isa>
struct jit_softmax_base_t : public jit_generator {
struct call_params_t {
// keep all sizes at 8 bytes -- jit code expects this
const void *src, *dst, *diff_dst; // src dubs as diff_src
const void *interim; // scratch memory for intermediate storage
const void *oscale; // oscale defined for all data type cases
size_t process_n_elems;
};
DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_softmax_t)
// cpu specific part
using TReg = typename cpu_isa_traits<isa>::TReg;
using TRegS = typename cpu_isa_traits<isa>::TRegS;
const int vlen = cpu_isa_traits<isa>::vlen;
const softmax_pd_t *pd_;
const memory_desc_wrapper src_d_, dst_d_, diff_dst_d_;
virtual void operator()(const call_params_t *p) = 0;
std::unique_ptr<jit_uni_eltwise_injector_f32<isa>> exp_injector_;
std::unique_ptr<jit_uni_eltwise_injector_f32<isa>> log_injector_;
XReg reg_param = abi_param1;
XReg reg_exp_injector_table = x1;
XReg reg_log_injector_table = x3;
XReg reg_src = x8;
XReg reg_diff_src = reg_src;
XReg reg_dst = x9;
XReg reg_diff_dst = x14;
XReg reg_src_spat_offt = x10;
XReg reg_process_n_elems = x11;
XReg reg_reverse_n_elems = x12;
XReg reg_tmp = x13;
XReg reg_dst_spat_offt = x16;
XReg reg_diff_dst_spat_offt = reg_log_injector_table;
XReg reg_interim = reg_diff_dst;
XReg reg_interim_spat_offt = abi_not_param1;
XReg reg_output_scale = x6;
const PReg p_shuff0 = p11;
const PReg p_shuff1 = p5;
const PReg injector_mask = p1;
const PReg injector_tmp = p6;
TReg vtmp = TReg(27);
TReg tail_vmask = TReg(0);
TReg vneg_flt_max = TReg(28);
TReg vone = TReg(29);
TReg vsum = TReg(30);
TReg vmax = TReg(31);
TReg vsbr = vsum; // must be not equal to vmax
TReg vzero = TReg(21);
TReg vsaturation_ubound = vneg_flt_max;
TReg v_tmp0 = TReg(23);
bool is_softmax_ = pd_->is_softmax();
bool is_logsoftmax_ = pd_->is_logsoftmax();
bool axis_is_blocked_;
bool need_scratchpad_;
size_t simd_w_ = 0;
size_t unroll_regs_ = 4;
size_t axis_simd_full_;
size_t axis_simd_tail_;
size_t n_loops_;
size_t loop_tail_;
size_t process_n_elems_;
size_t src_axis_stride_;
size_t interim_axis_stride_;
size_t dst_axis_stride_;
size_t diff_dst_axis_stride_;
void compute_predefined_variables() {
axis_simd_full_ = pd_->axis_size() / simd_w_;
axis_simd_tail_ = pd_->axis_size() % simd_w_;
n_loops_ = axis_simd_full_ / unroll_regs_;
loop_tail_ = axis_simd_full_ - n_loops_ * unroll_regs_;
process_n_elems_ = compute_process_n_elems(dst_d_);
src_axis_stride_ = compute_axis_stride(src_d_);
interim_axis_stride_ = simd_w_ * sizeof(float);
dst_axis_stride_ = compute_axis_stride(dst_d_);
if (!pd_->is_fwd())
diff_dst_axis_stride_ = compute_axis_stride(diff_dst_d_);
axis_is_blocked_ = pd_->axis_size(true) != pd_->axis_size();
}
size_t compute_process_n_elems(const memory_desc_wrapper &mdw) {
const auto &bd = mdw.blocking_desc();
if (bd.inner_nblks) return bd.strides[pd_->axis()];
return simd_w_;
}
size_t compute_axis_stride(const memory_desc_wrapper &mdw) {
return compute_process_n_elems(mdw) * mdw.data_type_size();
}
void load_common_params() {
fmov(vone.s, 1.0);
mov(W_TMP_0, float2int(-FLT_MAX));
dup(vneg_flt_max.s, W_TMP_0);
#define PARAM_OFF(x) offsetof(call_params_t, x)
#define PARAM_LOAD(reg, var) \
add_imm(X_DEFAULT_ADDR, reg_param, PARAM_OFF(var), X_TMP_0); \
ldr(reg, ptr(X_DEFAULT_ADDR));
/* Address offset must be less than 256. */
PARAM_LOAD(reg_process_n_elems, process_n_elems);
PARAM_LOAD(reg_dst, dst);
if (pd_->is_fwd()) {
PARAM_LOAD(reg_src, src);
} else {
PARAM_LOAD(reg_diff_src, src);
PARAM_LOAD(reg_diff_dst, diff_dst);
}
if (need_scratchpad_) { PARAM_LOAD(reg_interim, interim); }
PARAM_LOAD(reg_output_scale, oscale);
#undef PARAM_OFF
#undef PARAM_LOAD
}
void uni_fmax(const ZReg &dst, const ZReg &src, const ZReg &src2,
const PReg &mask = PReg(DUMMY_IDX)) {
const uint32_t idxDst = dst.getIdx();
const uint32_t idxSrc = src.getIdx();
const uint32_t idxSrc2 = src2.getIdx();
uint32_t pattern = 0;
PReg mask_reg(DUMMY_IDX);
pattern += (idxDst == idxSrc) ? (1 << 2) : 0;
pattern += (idxDst == idxSrc2) ? (1 << 1) : 0;
pattern += (idxSrc == idxSrc2) ? 1 : 0;
if (mask.getIdx() == DUMMY_IDX)
mask_reg = P_ALL_ONE;
else
mask_reg = mask;
switch (pattern) {
case 0x4: /* dst = src && dst != src2 && src != src2
This is the most popular case. */
fmax(dst.s, mask_reg / T_m, src2.s);
break;
default: assert(!"Unreachable!"); break;
}
}
XReg xreg_addr(const XReg &base, const XReg &off = XReg(DUMMY_IDX),
const int disp = 0) {
XReg x_addr = base;
uint32_t offIdx = off.getIdx();
if (offIdx <= SP_IDX) {
add(X_DEFAULT_ADDR, base, off);
x_addr = X_DEFAULT_ADDR;
}
if (disp) {
add_imm(X_DEFAULT_ADDR, x_addr, disp, X_TMP_0);
x_addr = X_DEFAULT_ADDR;
}
return x_addr;
}
XReg diff_src_ptr(size_t offt = 0) {
return xreg_addr(reg_diff_src, reg_src_spat_offt, offt);
}
XReg src_ptr(size_t offt = 0) {
return xreg_addr(reg_src, reg_src_spat_offt, offt);
}
XReg interim_ptr(size_t offt = 0) {
return xreg_addr(reg_interim, reg_interim_spat_offt, offt);
}
XReg dst_ptr(size_t offt = 0) {
return xreg_addr(reg_dst, reg_dst_spat_offt, offt);
}
XReg diff_dst_ptr(size_t offt = 0) {
return xreg_addr(reg_diff_dst, reg_diff_dst_spat_offt, offt);
}
enum class op_t : unsigned { max, sum };
void perform_op(TReg v, TReg vtmp, op_t op) {
if (op == op_t::max)
uni_fmax(v, v, vtmp);
else if (op == op_t::sum)
fadd(v.s, v.s, vtmp.s);
}
template <typename body_t>
void axis_loop(body_t body) {
Label main_loop, tail_loop, tail_axis;
// reverse_spat_offt to dispatch between labels
mov(reg_reverse_n_elems, reg_process_n_elems);
mov_imm(reg_src_spat_offt, 0); // src/diff_src addr
mov_imm(reg_dst_spat_offt, 0); // dst addr
if (need_scratchpad_) mov_imm(reg_interim_spat_offt, 0); // scratch addr
if (!pd_->is_fwd()) mov_imm(reg_diff_dst_spat_offt, 0); // d_dst addr
L(main_loop);
{
if (n_loops_) {
cmp(reg_reverse_n_elems, unroll_regs_ * process_n_elems_);
b(LT, tail_loop);
body(unroll_regs_, false);
sub_imm(reg_reverse_n_elems, reg_reverse_n_elems,
unroll_regs_ * process_n_elems_, X_TMP_0);
add_imm(reg_src_spat_offt, reg_src_spat_offt,
unroll_regs_ * src_axis_stride_, X_TMP_0);
add_imm(reg_dst_spat_offt, reg_dst_spat_offt,
unroll_regs_ * dst_axis_stride_, X_TMP_0);
if (need_scratchpad_)
add_imm(reg_interim_spat_offt, reg_interim_spat_offt,
unroll_regs_ * interim_axis_stride_, X_TMP_0);
if (!pd_->is_fwd())
add_imm(reg_diff_dst_spat_offt, reg_diff_dst_spat_offt,
unroll_regs_ * diff_dst_axis_stride_, X_TMP_0);
b(main_loop);
}
}
L(tail_loop);
{
if (loop_tail_) {
body(loop_tail_, false);
add_imm(reg_src_spat_offt, reg_src_spat_offt,
loop_tail_ * src_axis_stride_, X_TMP_0);
add_imm(reg_dst_spat_offt, reg_dst_spat_offt,
loop_tail_ * dst_axis_stride_, X_TMP_0);
if (need_scratchpad_)
add_imm(reg_interim_spat_offt, reg_interim_spat_offt,
loop_tail_ * interim_axis_stride_, X_TMP_0);
if (!pd_->is_fwd())
add_imm(reg_diff_dst_spat_offt, reg_diff_dst_spat_offt,
loop_tail_ * diff_dst_axis_stride_, X_TMP_0);
}
}
L(tail_axis);
{
if (axis_simd_tail_) { body(1, true); }
}
}
virtual void prepare_tail_mask() = 0;
virtual void get_horizontal_op(const TReg &v, const TReg &vtmp, op_t op)
= 0;
virtual void accumulate_vmax() = 0;
virtual void accumulate_vsum() = 0;
virtual void compute_dst() = 0;
virtual void initialization_hook() {}
virtual void accumulate_vsbr() {}
virtual void compute_diff_src() {}
void forward() {
accumulate_vmax();
accumulate_vsum();
compute_dst();
}
void backward() {
accumulate_vsbr();
compute_diff_src();
}
void prepare_mask() {
if (isa == sve_512) {
sub_imm(X_TRANSLATOR_STACK, X_TRANSLATOR_STACK, 64 * 2, X_TMP_0);
str(p_shuff0, ptr(X_TRANSLATOR_STACK, 0, MUL_VL));
str(p_shuff1, ptr(X_TRANSLATOR_STACK, 1, MUL_VL));
not_(P_TMP_1.b, P_ALL_ONE, P_ALL_ONE.b);
trn1(p_shuff0.d, P_ALL_ONE.d, P_TMP_1.d);
trn1(p_shuff0.d, p_shuff0.d, p_shuff0.d);
trn1(p_shuff1.s, P_ALL_ONE.s, P_TMP_1.s);
}
}
void restore_mask() {
assert(isa == sve_512);
ldr(p_shuff0, ptr(X_TRANSLATOR_STACK, 0, MUL_VL));
ldr(p_shuff1, ptr(X_TRANSLATOR_STACK, 1, MUL_VL));
add_imm(X_TRANSLATOR_STACK, X_TRANSLATOR_STACK, 64 * 2, X_TMP_0);
}
// either this stub or duplication at each jit_binary_t ctor due to methods
// that are participated are not defined at the moment of base ctor
// initialization.
void generate() override {
if (pd_->is_fwd() || is_logsoftmax_)
exp_injector_.reset(new jit_uni_eltwise_injector_f32<isa>(this,
alg_kind::eltwise_exp, 0.0f, 0.0f, 1.0f, true,
reg_exp_injector_table, injector_mask, injector_tmp,
P_ALL_ONE));
if (pd_->is_fwd() && is_logsoftmax_) {
log_injector_.reset(new jit_uni_eltwise_injector_f32<isa>(this,
alg_kind::eltwise_log, 0.0f, 0.0f, 1.0f, true,
reg_log_injector_table, injector_mask, injector_tmp,
P_ALL_ONE));
}
compute_predefined_variables();
preamble();
initialization_hook();
prepare_mask();
if (exp_injector_) exp_injector_->load_table_addr();
if (log_injector_) log_injector_->load_table_addr();
if (axis_simd_tail_) prepare_tail_mask();
load_common_params();
if (pd_->is_fwd())
forward();
else
backward();
restore_mask();
postamble();
if (exp_injector_) exp_injector_->prepare_table();
if (log_injector_) log_injector_->prepare_table();
}
jit_softmax_base_t(const softmax_pd_t *pd)
: jit_generator(nullptr, MAX_CODE_SIZE, true)
, pd_(pd)
, src_d_(pd_->is_fwd() ? pd_->src_md() : pd_->diff_src_md())
, dst_d_(pd_->dst_md())
, diff_dst_d_(pd_->diff_dst_md()) {
simd_w_ = vlen / sizeof(float); // bf16 works on ymms
need_scratchpad_ = utils::one_of(
dst_d_.data_type(), data_type::u8, data_type::s8);
}
};
template <cpu_isa_t isa>
struct jit_softmax_t;
template <>
struct jit_softmax_t<sve_512> : public jit_softmax_base_t<sve_512> {
PReg tail_opmask = p2;
void store(const XReg &addr, const ZReg &vmm, data_type_t dt,
bool tail = false) {
PReg opmask = P_ALL_ONE;
bool tail_mask_valid = false;
auto effective_addr = addr;
TReg src_vmm = vmm;
if (tail) {
if (dt == data_type::f32) {
if (axis_is_blocked_) {
src_vmm = vzero;
eor(vzero.d, vzero.d, vzero.d);
mov(src_vmm.s, tail_opmask / T_m, vmm.s);
effective_addr = addr;
} else {
effective_addr = addr;
tail_mask_valid = true;
}
} else { // int8 store instructions assume mask on register
tail_mask_valid = true;
}
}
if (tail_mask_valid) opmask = tail_opmask;
switch (dt) {
case data_type::f32:
st1w(src_vmm.s, opmask, ptr(effective_addr));
break;
case data_type::u8:
eor(vzero.d, vzero.d, vzero.d); // since vzero might be spoiled
saturate_f32(vmm, vzero, vsaturation_ubound, data_type::u8,
P_ALL_ONE);
frinti(vmm.s, P_ALL_ONE / T_m, vmm.s);
fcvtzu(vmm.s, P_ALL_ONE / T_m, vmm.s);
smin(vmm.s, 127);
st1b(vmm.s, opmask, ptr(effective_addr));
// Need to restore data back to fp32 since we apply exp after
// storing and data should be fp32.
if (is_logsoftmax_) scvtf(vmm.s, opmask / T_m, vmm.s);
break;
case data_type::s8:
saturate_f32(vmm, vzero, vsaturation_ubound, data_type::s8,
P_ALL_ONE);
frinti(vmm.s, opmask / T_m, vmm.s);
fcvtzs(vmm.s, opmask / T_m, vmm.s);
smin(vmm.s, 127);
smax(vmm.s, -128);
st1b(vmm.s, opmask, ptr(effective_addr));
// Need to restore data back to fp32 since we apply exp after
// storing and data should be fp32.
if (is_logsoftmax_) scvtf(vmm.s, opmask / T_m, vmm.s);
break;
default: assert(!"unsupported"); break;
}
};
void load(const TReg &vmm, const XReg &addr, data_type_t dt,
bool tail = false) {
PReg tmp_mask = P_ALL_ONE;
ZRegS effective_vmm = vmm.s;
if (tail) tmp_mask = tail_opmask;
switch (dt) {
case data_type::f32:
ld1w(effective_vmm, tmp_mask, ptr(addr));
break;
case data_type::u8:
ld1b(effective_vmm, tmp_mask / T_z, ptr(addr));
scvtf(effective_vmm, P_ALL_ONE / T_m, effective_vmm);
break;
case data_type::s8:
ld1sb(effective_vmm, tmp_mask / T_z, ptr(addr));
scvtf(effective_vmm, P_ALL_ONE / T_m, effective_vmm);
break;
default: assert(!"unsupported"); break;
}
};
void prepare_tail_mask() override {
const int sw_tail = axis_simd_tail_;
PRegS p = tail_opmask.s;
switch (sw_tail) {
case 16: ptrue(p, VL16); break;
case 8: ptrue(p, VL8); break;
case 7: ptrue(p, VL7); break;
case 6: ptrue(p, VL6); break;
case 5: ptrue(p, VL5); break;
case 4: ptrue(p, VL4); break;
case 3: ptrue(p, VL3); break;
case 2: ptrue(p, VL2); break;
case 1: ptrue(p, VL1); break;
default:
index(vtmp.s, 1, 1);
cmple(p, P_ALL_ONE / T_z, vtmp.s, sw_tail);
break;
}
}
void get_horizontal_op(const ZReg &v, const ZReg &vtmp, op_t op) override {
mov(vtmp.d, v.d);
ext(vtmp.b, v.b, 32);
perform_op(v, vtmp, op);
mov(vtmp.s, P_ALL_ONE, v.s);
mov(v_tmp0.s, P_ALL_ONE, v.s);
ext(v_tmp0.b, v.b, 48);
ext(vtmp.b, v.b, 16);
mov(vtmp.d, p_shuff0 / T_m, v_tmp0.d);
perform_op(v, vtmp, op);
uzp2(v_tmp0.d, v.d, v.d);
trn1(vtmp.d, v_tmp0.d, v.d);
perform_op(v, vtmp, op);
trn1(vtmp.s, v.s, v.s);
trn2(v_tmp0.s, v.s, v.s);
mov(vtmp.s, p_shuff1 / T_m, v_tmp0.s);
perform_op(v, vtmp, op);
}
void accumulate_vmax() override {
// flush to -FLT_MAX before accumulation
mov(vmax.d, vneg_flt_max.d);
axis_loop([&](int unroll, bool tail = false) {
for (int i = 0; i < unroll; i++) {
TReg vreg_tmp_src = TReg(i + 1);
load(vreg_tmp_src, src_ptr(src_axis_stride_ * i),
src_d_.data_type(), tail);
if (tail) {
uni_fmax(vmax, vmax, vreg_tmp_src, tail_opmask);
} else {
uni_fmax(vmax, vmax, vreg_tmp_src);
}
}
});
get_horizontal_op(vmax, vtmp = vsum, op_t::max);
}
void accumulate_vsum() override {
// Initialize saturation vector register
if (utils::one_of(dst_d_.data_type(), data_type::u8, data_type::s8)) {
init_saturate_f32(vzero, vsaturation_ubound, reg_tmp,
data_type::f32, dst_d_.data_type());
}
eor(vsum.d, vsum.d, vsum.d); // flush to zero before accumulation
axis_loop([&](int unroll, bool tail = false) {
for (int i = 0; i < unroll; i++) {
TReg vreg_tmp_src = TReg(i + 1);
load(vreg_tmp_src, src_ptr(src_axis_stride_ * i),
src_d_.data_type(), tail);
fsub(vreg_tmp_src.s, vreg_tmp_src.s, vmax.s);
if (is_logsoftmax_) { // store before applying exp
if (need_scratchpad_) {
store(interim_ptr(interim_axis_stride_ * i),
vreg_tmp_src, data_type::f32, tail);
} else {
store(dst_ptr(dst_axis_stride_ * i), vreg_tmp_src,
dst_d_.data_type(), tail);
}
}
exp_injector_->compute_vector(vreg_tmp_src.getIdx());
if (tail)
fadd(vsum.s, tail_opmask / T_m, vreg_tmp_src.s);
else
fadd(vsum.s, vsum.s, vreg_tmp_src.s);
if (is_softmax_) { // store after applying exp
if (need_scratchpad_) {
store(interim_ptr(interim_axis_stride_ * i),
vreg_tmp_src, data_type::f32, tail);
} else {
store(dst_ptr(dst_axis_stride_ * i), vreg_tmp_src,
dst_d_.data_type(), tail);
}
}
}
});
get_horizontal_op(vsum, vtmp = vmax, op_t::sum);
if (is_softmax_) {
mov(v_tmp0.d, vsum.d);
mov(vsum.d, P_ALL_ONE, vone.d);
fdiv(vsum.s, P_ALL_ONE / T_m, v_tmp0.s);
}
if (is_logsoftmax_) log_injector_->compute_vector(vsum.getIdx());
}
void compute_dst() override {
axis_loop([&](int unroll, bool tail = false) {
for (int i = 0; i < unroll; i++) {
ZReg vreg_tmp_src = ZReg(i + 1);
if (need_scratchpad_) {
load(vreg_tmp_src, interim_ptr(interim_axis_stride_ * i),
data_type::f32, tail);
} else {
load(vreg_tmp_src, dst_ptr(dst_axis_stride_ * i),
dst_d_.data_type(), tail);
}
if (is_softmax_) {
fmul(vreg_tmp_src.s, vreg_tmp_src.s, vsum.s);
}
if (is_logsoftmax_) {
fsub(vreg_tmp_src.s, vreg_tmp_src.s, vsum.s);
}
TReg vscale = vmax;
ldr(vscale, ptr(reg_output_scale));
fmul(vreg_tmp_src.s, vreg_tmp_src.s, vscale.s);
store(dst_ptr(dst_axis_stride_ * i), vreg_tmp_src,
dst_d_.data_type(), tail);
}
});
}
void accumulate_vsbr() override {
eor(vsbr.d, vsbr.d, vsbr.d); // flush to zero before accumulation
axis_loop([&](int unroll, bool tail = false) {
for (int i = 0; i < unroll; i++) {
ZReg vreg_tmp_dst = ZReg(i * 2 + 1);
ZReg vreg_tmp_diff_dst = ZReg(i * 2 + 2);
load(vreg_tmp_diff_dst, diff_dst_ptr(diff_dst_axis_stride_ * i),
diff_dst_d_.data_type(), tail);
if (is_softmax_) {
load(vreg_tmp_dst, dst_ptr(dst_axis_stride_ * i),
dst_d_.data_type(), tail);
fmul(vreg_tmp_diff_dst.s, vreg_tmp_diff_dst.s,
vreg_tmp_dst.s);
}
fadd(vsbr.s, vsbr.s, vreg_tmp_diff_dst.s);
}
});
get_horizontal_op(vsbr, vtmp = vmax, op_t::sum);
}
void compute_diff_src() override {
axis_loop([&](int unroll, bool tail = false) {
for (int i = 0; i < unroll; i++) {
ZReg vreg_tmp_dst = ZReg(i * 2 + 1);
ZReg vreg_tmp_diff_dst = ZReg(i * 2 + 2);
load(vreg_tmp_dst, dst_ptr(dst_axis_stride_ * i),
dst_d_.data_type(), tail);
load(vreg_tmp_diff_dst, diff_dst_ptr(diff_dst_axis_stride_ * i),
diff_dst_d_.data_type(), tail);
if (is_softmax_) {
fsub(vreg_tmp_diff_dst.s, vreg_tmp_diff_dst.s, vsbr.s);
fmul(vreg_tmp_diff_dst.s, vreg_tmp_dst.s,
vreg_tmp_diff_dst.s);
}
if (is_logsoftmax_) {
exp_injector_->compute_vector(vreg_tmp_dst.getIdx());
fmls(vreg_tmp_diff_dst.s, P_ALL_ONE / T_m, vreg_tmp_dst.s,
vsbr.s);
}
store(diff_src_ptr(src_axis_stride_ * i), vreg_tmp_diff_dst,
src_d_.data_type(), tail);
}
});
}
void initialization_hook() override {}
jit_softmax_t(const softmax_pd_t *pd) : jit_softmax_base_t(pd) {}
void operator()(const call_params_t *p) override {
return jit_generator::operator()(p);
}
}; // namespace aarch64
template <cpu_isa_t isa>
jit_uni_softmax_fwd_t<isa>::jit_uni_softmax_fwd_t(const pd_t *apd)
: primitive_t(apd)
, softmax_driver_(new softmax_impl::driver_t<isa>(pd())) {}
template <cpu_isa_t isa>
jit_uni_softmax_fwd_t<isa>::~jit_uni_softmax_fwd_t() {
delete softmax_driver_;
}
template <cpu_isa_t isa>
status_t jit_uni_softmax_fwd_t<isa>::init(engine_t *engine) {
return softmax_driver_->create_kernel();
}
template <cpu_isa_t isa>
status_t jit_uni_softmax_fwd_t<isa>::execute(const exec_ctx_t &ctx) const {
const auto src = CTX_IN_MEM(const char *, DNNL_ARG_SRC);
auto dst = CTX_OUT_MEM(char *, DNNL_ARG_DST);
auto scratchpad_ptr = ctx.get_scratchpad_grantor().template get<char>(
memory_tracking::names::key_softmax_interim_store);
const float *oscales = pd()->attr()->output_scales_.scales_;
const memory_desc_wrapper src_d(pd()->src_md());
const memory_desc_wrapper dst_d(pd()->dst_md());
const auto src_data_type_size = src_d.data_type_size();
const auto dst_data_type_size = dst_d.data_type_size();
const auto &bd = src_d.blocking_desc();
const auto axis = pd()->axis();
const auto axis_size_padded = pd()->axis_size(true);
const auto inner_stride
= bd.inner_nblks ? bd.inner_blks[bd.inner_nblks - 1] : (dim_t)1;
const auto inner_size = bd.strides[axis] / inner_stride;
const auto process_n_elems = pd()->axis_size() * inner_size;
const auto outer_stride = axis_size_padded * inner_size;
const auto outer_size = src_d.nelems(true) / outer_stride;
const int nthr = pd()->nthr_;
parallel_nd_ext(nthr, outer_size, inner_size,
[&](int ithr, int, dim_t ou, dim_t in) {
dim_t offset = (ou * outer_stride + in * inner_stride);
const char *src_ptr = src + offset * src_data_type_size;
char *dst_ptr = dst + offset * dst_data_type_size;
char *interim_ptr = scratchpad_ptr
+ ithr * axis_size_padded * sizeof(float);
const auto *oscale_ptr = oscales;
softmax_driver_->exec(src_ptr, dst_ptr, interim_ptr, oscale_ptr,
process_n_elems);
});
return status::success;
}
template <cpu_isa_t isa>
jit_uni_softmax_bwd_t<isa>::jit_uni_softmax_bwd_t(const pd_t *apd)
: primitive_t(apd)
, softmax_driver_(new softmax_impl::driver_t<isa>(pd())) {}
template <cpu_isa_t isa>
jit_uni_softmax_bwd_t<isa>::~jit_uni_softmax_bwd_t() {
delete softmax_driver_;
}
template <cpu_isa_t isa>
status_t jit_uni_softmax_bwd_t<isa>::init(engine_t *engine) {
return softmax_driver_->create_kernel();
}
template <cpu_isa_t isa>
status_t jit_uni_softmax_bwd_t<isa>::execute(const exec_ctx_t &ctx) const {
auto dst = CTX_IN_MEM(const char *, DNNL_ARG_DST);
auto diff_dst = CTX_IN_MEM(const char *, DNNL_ARG_DIFF_DST);
auto diff_src = CTX_OUT_MEM(char *, DNNL_ARG_DIFF_SRC);
const memory_desc_wrapper dst_d(pd()->dst_md());
const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md());
const memory_desc_wrapper diff_src_d(pd()->diff_src_md());
const auto dst_data_type_size = dst_d.data_type_size();
const auto diff_dst_data_type_size = diff_dst_d.data_type_size();
const auto diff_src_data_type_size = diff_src_d.data_type_size();
const auto &bd = dst_d.blocking_desc();
const auto axis = pd()->axis();
const auto inner_stride
= bd.inner_nblks ? bd.inner_blks[bd.inner_nblks - 1] : (dim_t)1;
const auto inner_size = bd.strides[axis] / inner_stride;
const auto process_n_elems = pd()->axis_size() * inner_size;
const auto outer_stride = pd()->axis_size(true) * inner_size;
const auto outer_size = dst_d.nelems(true) / outer_stride;
parallel_nd(outer_size, inner_size, [&](dim_t ou, dim_t in) {
dim_t offset = (ou * outer_stride + in * inner_stride);
char *diff_src_ptr = diff_src + offset * diff_src_data_type_size;
const char *dst_ptr = dst + offset * dst_data_type_size;
const char *diff_dst_ptr = diff_dst + offset * diff_dst_data_type_size;
softmax_driver_->exec(
diff_src_ptr, dst_ptr, diff_dst_ptr, process_n_elems);
});
return status::success;
}
namespace softmax_impl {
template <cpu_isa_t isa>
struct driver_t : public c_compatible {
driver_t(const softmax_pd_t *pd) : pd_(pd), ker_(pd_) {}
void exec(const void *src, void *dst, void *interim, const void *oscale,
const dim_t process_n_elems) {
typename jit_softmax_t<isa>::call_params_t p;
p.process_n_elems = process_n_elems;
p.src = src;
p.dst = dst;
p.interim = interim;
p.oscale = oscale;
ker_(&p);
}
void exec(void *diff_src, const void *dst, const void *diff_dst,
const dim_t process_n_elems) {
typename jit_softmax_t<isa>::call_params_t p;
p.process_n_elems = process_n_elems;
p.src = diff_src;
p.dst = dst;
p.diff_dst = diff_dst;
ker_(&p);
}
status_t create_kernel() { return ker_.create_kernel(); }
private:
const softmax_pd_t *pd_;
jit_softmax_t<isa> ker_;
};
} // namespace softmax_impl
/* struct instantiation */
template struct jit_uni_softmax_fwd_t<sve_512>;
template struct jit_uni_softmax_bwd_t<sve_512>;
} // namespace aarch64
} // namespace cpu
} // namespace impl
} // namespace dnnl
| 15,992 |
369 |
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include "IPCRingBufferResults.h"
#include "IPCRingBufferSharedObjects.h"
#include "SharedMemory.h"
#include "SharedMemoryObjectWithMutex.h"
#include <osvr/Common/IPCRingBuffer.h>
#include <osvr/Util/ImagingReportTypesC.h>
#include <osvr/Util/Log.h>
#include <osvr/Util/Logger.h>
// Library/third-party includes
#include <boost/version.hpp>
// Standard includes
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace osvr {
namespace common {
/// Grab a logger for IPCRingBuffer verbosity and errors.
static util::log::Logger &getIPCRingBufferLogger() {
static util::log::LoggerPtr logger =
util::log::make_logger("IPCRingBuffer");
return *logger;
}
/// @brief the ABI level: this must be bumped if the layout of any
/// shared-memory objects (Bookkeeping, ElementData) changes, if Boost
/// Interprocess changes affect the utilized ABI, or if other changes occur
/// that would interfere with communication.
static IPCRingBuffer::abi_level_type SHM_SOURCE_ABI_LEVEL = 0;
#ifdef _WIN32
#if (BOOST_VERSION < 105400)
#error \
"Boost Interprocess pre-1.54 on Win32 is ABI-incompatible with newer Boost due to changed bootstamp function."
#endif
#else // !_WIN32
// No obvious ABI breaks through 1.58 seem to apply to us on non-Windows
// platforms
#endif
static_assert(std::is_same<IPCRingBuffer::BackendType,
ipc::SharedMemoryBackendType>::value,
"The typedefs IPCRingBuffer::BackendType and "
"ipc::SharedMemoryBackendType must remain in sync!");
static_assert(
std::is_same<IPCRingBuffer::value_type, OSVR_ImageBufferElement>::value,
"The ring buffer's individual byte type must match the image buffer "
"element type.");
namespace bip = boost::interprocess;
namespace {
typedef OSVR_ImageBufferElement BufferType;
template <typename T, typename ManagedMemory>
using ipc_deleter_type =
typename ManagedMemory::template deleter<T>::type;
typedef IPCRingBuffer::sequence_type sequence_type;
/// @brief Destroys the "unique_instance" of a given type in a managed
/// memory segment. If there isn't an instance, this is a no-op.
template <typename T, typename ManagedMemory>
inline void destroy_unique_instance(ManagedMemory &shm) {
auto result = shm.template find<T>(bip::unique_instance);
if (result.first) {
shm.template destroy<T>(bip::unique_instance);
}
}
} // namespace
namespace {
static size_t computeRequiredSpace(IPCRingBuffer::Options const &opts) {
size_t alignedEntrySize = opts.getEntrySize() + opts.getAlignment();
size_t dataSize = alignedEntrySize * (opts.getEntries() + 1);
// Give 33% overhead on the raw bookkeeping data
static const size_t BOOKKEEPING_SIZE =
(sizeof(detail::Bookkeeping) +
(sizeof(detail::ElementData) * opts.getEntries())) *
4 / 3;
return dataSize + BOOKKEEPING_SIZE;
}
class SharedMemorySegmentHolder {
public:
SharedMemorySegmentHolder() : m_bookkeeping(nullptr) {}
virtual ~SharedMemorySegmentHolder(){};
detail::Bookkeeping *getBookkeeping() { return m_bookkeeping; }
virtual uint64_t getSize() const = 0;
virtual uint64_t getFreeMemory() const = 0;
protected:
detail::Bookkeeping *m_bookkeeping;
};
template <typename ManagedMemory>
class SegmentHolderBase : public SharedMemorySegmentHolder {
public:
typedef ManagedMemory managed_memory_type;
virtual uint64_t getSize() const { return m_shm->get_size(); }
virtual uint64_t getFreeMemory() const {
return m_shm->get_free_memory();
}
protected:
unique_ptr<managed_memory_type> m_shm;
};
template <typename ManagedMemory>
class ServerSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ServerSharedMemorySegmentHolder(IPCRingBuffer::Options const &opts)
: m_name(opts.getName()) {
getIPCRingBufferLogger().debug() << "Creating segment, name "
<< opts.getName() << ", size "
<< computeRequiredSpace(opts);
try {
removeSharedMemory();
/// @todo Some shared memory types (specifically, Windows),
/// don't have a remove, so we should re-open.
Base::m_shm.reset(new ManagedMemory(
bip::create_only, opts.getName().c_str(),
computeRequiredSpace(opts)));
} catch (bip::interprocess_exception &e) {
getIPCRingBufferLogger().error()
<< "Failed to create shared memory segment "
<< opts.getName() << " with exception: " << e.what();
return;
}
// detail::Bookkeeping::destroy(*Base::m_shm);
Base::m_bookkeeping =
detail::Bookkeeping::construct(*Base::m_shm, opts);
}
virtual ~ServerSharedMemorySegmentHolder() {
detail::Bookkeeping::destroy(*Base::m_shm);
removeSharedMemory();
}
void removeSharedMemory() {
ipc::device_type<ManagedMemory>::remove(m_name.c_str());
}
private:
std::string m_name;
};
template <typename ManagedMemory>
class ClientSharedMemorySegmentHolder
: public SegmentHolderBase<ManagedMemory> {
public:
typedef SegmentHolderBase<ManagedMemory> Base;
ClientSharedMemorySegmentHolder(
IPCRingBuffer::Options const &opts) {
getIPCRingBufferLogger().debug() << "Finding segment, name "
<< opts.getName();
try {
Base::m_shm.reset(new ManagedMemory(
bip::open_only, opts.getName().c_str()));
} catch (bip::interprocess_exception &e) {
getIPCRingBufferLogger().error()
<< "Failed to open shared memory segment "
<< opts.getName() << " with exception: " << e.what();
return;
}
Base::m_bookkeeping = detail::Bookkeeping::find(*Base::m_shm);
}
virtual ~ClientSharedMemorySegmentHolder() {}
private:
};
/// @brief Factory function for constructing a memory segment holder.
template <typename ManagedMemory>
inline unique_ptr<SharedMemorySegmentHolder>
constructMemorySegment(IPCRingBuffer::Options const &opts,
bool doCreate) {
unique_ptr<SharedMemorySegmentHolder> ret;
if (doCreate) {
ret.reset(
new ServerSharedMemorySegmentHolder<ManagedMemory>(opts));
} else {
ret.reset(
new ClientSharedMemorySegmentHolder<ManagedMemory>(opts));
}
if (nullptr == ret->getBookkeeping()) {
ret.reset();
} else {
getIPCRingBufferLogger().debug()
<< "size: " << ret->getSize()
<< ", free: " << ret->getFreeMemory();
}
return ret;
}
} // namespace
IPCRingBuffer::BufferWriteProxy::BufferWriteProxy(
detail::IPCPutResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::BufferReadProxy::BufferReadProxy(
detail::IPCGetResultPtr &&data, IPCRingBufferPtr &&shm)
: m_buf(nullptr), m_seq(0), m_data(std::move(data)) {
if (nullptr != m_data) {
m_buf = m_data->buffer;
m_seq = m_data->seq;
m_data->shm = std::move(shm);
}
}
IPCRingBuffer::smart_pointer_type
IPCRingBuffer::BufferReadProxy::getBufferSmartPointer() const {
return smart_pointer_type(m_data, m_buf);
}
IPCRingBuffer::Options::Options()
: m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name)
: m_name(ipc::make_name_safe(name)),
m_shmBackend(ipc::DEFAULT_MANAGED_SHM_ID) {}
IPCRingBuffer::Options::Options(std::string const &name,
BackendType backend)
: m_name(ipc::make_name_safe(name)), m_shmBackend(backend) {}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setName(std::string const &name) {
m_name = ipc::make_name_safe(name);
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setAlignment(alignment_type alignment) {
/// @todo ensure power of 2
m_alignment = alignment;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntries(entry_count_type entries) {
m_entries = entries;
return *this;
}
IPCRingBuffer::Options &
IPCRingBuffer::Options::setEntrySize(entry_size_type entrySize) {
m_entrySize = entrySize;
return *this;
}
class IPCRingBuffer::Impl {
public:
Impl(unique_ptr<SharedMemorySegmentHolder> &&segment,
Options const &opts)
: m_seg(std::move(segment)), m_bookkeeping(nullptr), m_opts(opts) {
m_bookkeeping = m_seg->getBookkeeping();
m_opts.setEntries(m_bookkeeping->getCapacity());
m_opts.setEntrySize(m_bookkeeping->getBufferLength());
}
detail::IPCPutResultPtr put() {
return m_bookkeeping->produceElement();
}
detail::IPCGetResultPtr get(sequence_type num) {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->getBySequenceNumber(num, boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{buf, std::move(readerLock),
num, nullptr});
}
return ret;
}
detail::IPCGetResultPtr getLatest() {
detail::IPCGetResultPtr ret;
auto boundsLock = m_bookkeeping->getSharableLock();
auto elt = m_bookkeeping->back(boundsLock);
if (nullptr != elt) {
auto readerLock = elt->getSharableLock();
auto buf = elt->getBuf(readerLock);
/// The nullptr will be filled in by the main object.
ret.reset(new detail::IPCGetResult{
buf, std::move(readerLock),
m_bookkeeping->backSequenceNumber(boundsLock), nullptr});
}
return ret;
}
Options const &getOpts() const { return m_opts; }
private:
unique_ptr<SharedMemorySegmentHolder> m_seg;
detail::Bookkeeping *m_bookkeeping;
Options m_opts;
};
IPCRingBufferPtr IPCRingBuffer::m_constructorHelper(Options const &opts,
bool doCreate) {
IPCRingBufferPtr ret;
unique_ptr<SharedMemorySegmentHolder> segment;
switch (opts.getBackend()) {
case ipc::BASIC_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::basic_managed_shm>(opts, doCreate);
break;
#ifdef OSVR_HAVE_WINDOWS_SHM
case ipc::WINDOWS_MANAGED_SHM_ID:
segment = constructMemorySegment<ipc::windows_managed_shm>(
opts, doCreate);
break;
#endif
#ifdef OSVR_HAVE_XSI_SHM
case ipc::SYSV_MANAGED_SHM_ID:
segment =
constructMemorySegment<ipc::sysv_managed_shm>(opts, doCreate);
break;
#endif
default:
getIPCRingBufferLogger().error()
<< "Unsupported/unrecognized shared memory backend: "
<< int(opts.getBackend());
break;
}
if (!segment) {
return ret;
}
unique_ptr<Impl> impl(new Impl(std::move(segment), opts));
ret.reset(new IPCRingBuffer(std::move(impl)));
return ret;
}
IPCRingBuffer::abi_level_type IPCRingBuffer::getABILevel() {
return SHM_SOURCE_ABI_LEVEL;
}
IPCRingBufferPtr IPCRingBuffer::create(Options const &opts) {
return m_constructorHelper(opts, true);
}
IPCRingBufferPtr IPCRingBuffer::find(Options const &opts) {
return m_constructorHelper(opts, false);
}
IPCRingBuffer::IPCRingBuffer(unique_ptr<Impl> &&impl)
: m_impl(std::move(impl)) {}
IPCRingBuffer::~IPCRingBuffer() {}
IPCRingBuffer::BackendType IPCRingBuffer::getBackend() const {
return m_impl->getOpts().getBackend();
}
std::string const &IPCRingBuffer::getName() const {
return m_impl->getOpts().getName();
}
uint32_t IPCRingBuffer::getEntrySize() const {
return m_impl->getOpts().getEntrySize();
}
uint16_t IPCRingBuffer::getEntries() const {
return m_impl->getOpts().getEntries();
}
IPCRingBuffer::BufferWriteProxy IPCRingBuffer::put() {
return BufferWriteProxy(m_impl->put(), shared_from_this());
}
IPCRingBuffer::sequence_type IPCRingBuffer::put(pointer_to_const_type data,
size_t len) {
auto proxy = put();
std::memcpy(proxy.get(), data, len);
return proxy.getSequenceNumber();
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::get(sequence_type num) {
return BufferReadProxy(m_impl->get(num), shared_from_this());
}
IPCRingBuffer::BufferReadProxy IPCRingBuffer::getLatest() {
return BufferReadProxy(m_impl->getLatest(), shared_from_this());
}
} // namespace common
} // namespace osvr
| 7,382 |
460 |
<filename>paoding-rose-web/src/main/java/net/paoding/rose/web/paramresolver/ServletRequestDataBinder.java
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.paoding.rose.web.paramresolver;
import java.util.Date;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import net.paoding.rose.web.paramresolver.ResolverFactoryImpl.DateEditor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyValue;
import org.springframework.validation.AbstractPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.util.WebUtils;
/**
* Special {@link org.springframework.validation.DataBinder} to perform
* data binding from servlet request parameters to JavaBeans, including
* support for multipart files.
*
* <p>
* See the DataBinder/WebDataBinder superclasses for customization options,
* which include specifying allowed/required fields, and registering custom
* property editors.
*
* <p>
* Used by Spring Web MVC's BaseCommandController and
* MultiActionController. Note that BaseCommandController and its
* subclasses allow for easy customization of the binder instances that
* they use through overriding <code>initBinder</code>.
*
* <p>
* Can also be used for manual data binding in custom web controllers: for
* example, in a plain Controller implementation or in a
* MultiActionController handler method. Simply instantiate a
* ServletRequestDataBinder for each binding process, and invoke
* <code>bind</code> with the current ServletRequest as argument:
*
* <pre class="code"> MyBean myBean = new MyBean(); // apply binder to
* custom target object ServletRequestDataBinder binder = new
* ServletRequestDataBinder(myBean); // register custom editors, if desired
* binder.registerCustomEditor(...); // trigger actual binding of request
* parameters binder.bind(request); // optionally evaluate binding errors
* Errors errors = binder.getErrors(); ...</pre>
*
* @author <NAME>
* @author <NAME>
* @see #bind(javax.servlet.ServletRequest)
* @see #registerCustomEditor
* @see #setAllowedFields
* @see #setRequiredFields
* @see #setFieldMarkerPrefix
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
*/
public class ServletRequestDataBinder extends WebDataBinder {
private String prefix;
/**
* Create a new ServletRequestDataBinder instance, with default object
* name.
*
* @param target the target object to bind onto (or <code>null</code>
* if the binder is just used to convert a plain parameter
* value)
* @see #DEFAULT_OBJECT_NAME
*/
public ServletRequestDataBinder(Object target) {
super(target);
}
/**
* Create a new ServletRequestDataBinder instance.
*
* @param target the target object to bind onto (or <code>null</code>
* if the binder is just used to convert a plain parameter
* value)
* @param objectName the name of the target object
*/
public ServletRequestDataBinder(Object target, String objectName) {
super(target, objectName);
prefix = objectName + '.';
}
/**
* Return the internal BindingResult held by this DataBinder, as
* AbstractPropertyBindingResult.
*/
@Override
protected AbstractPropertyBindingResult getInternalBindingResult() {
AbstractPropertyBindingResult bindingResult = super.getInternalBindingResult();
// by rose
PropertyEditorRegistry registry = bindingResult.getPropertyEditorRegistry();
registry.registerCustomEditor(Date.class, new DateEditor(Date.class));
registry.registerCustomEditor(java.sql.Date.class, new DateEditor(java.sql.Date.class));
registry.registerCustomEditor(java.sql.Time.class, new DateEditor(java.sql.Time.class));
registry.registerCustomEditor(java.sql.Timestamp.class, new DateEditor(
java.sql.Timestamp.class));
return bindingResult;
}
/**
* Bind the parameters of the given request to this binder's target,
* also binding multipart files in case of a multipart request.
* <p>
* This call can create field errors, representing basic binding errors
* like a required field (code "required"), or type mismatch between
* value and bean property (code "typeMismatch").
* <p>
* Multipart files are bound via their parameter name, just like normal
* HTTP parameters: i.e. "uploadedFile" to an "uploadedFile" bean
* property, invoking a "setUploadedFile" setter method.
* <p>
* The type of the target property for a multipart file can be
* MultipartFile, byte[], or String. The latter two receive the
* contents of the uploaded file; all metadata like original file name,
* content type, etc are lost in those cases.
*
* @param request request with parameters to bind (can be multipart)
* @see org.springframework.web.multipart.MultipartHttpServletRequest
* @see org.springframework.web.multipart.MultipartFile
* @see #bindMultipartFiles
* @see #bind(org.springframework.beans.PropertyValues)
*/
public void bind(ServletRequest request) {
MutablePropertyValues mpvs = new MutablePropertyValues(WebUtils.getParametersStartingWith(
request, prefix));
MultipartRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartRequest.class);
if (multipartRequest != null) {
bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
}
addBindValues(mpvs, request);
doBind(mpvs);
}
/**
* Extension point that subclasses can use to add extra bind values for a
* request. Invoked before {@link #doBind(MutablePropertyValues)}.
* The default implementation is empty.
* @param mpvs the property values that will be used for data binding
* @param request the current request
*/
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
}
@Override
protected void doBind(MutablePropertyValues mpvs) {
// book.author.name的设置要自动使book.author设置一个author进去
PropertyValue[] pvArray = mpvs.getPropertyValues();
MutablePropertyValues newMpvs = null;
for (int i = 0; i < pvArray.length; i++) {
PropertyValue pv = pvArray[i];
String propertyName = pv.getName();
int dot = propertyName.indexOf('.');
while (dot != -1) {
String field = propertyName.substring(0, dot);
if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
if (newMpvs == null) {
newMpvs = new MutablePropertyValues();
}
newMpvs.addPropertyValue(field, BeanUtils.instantiateClass(fieldType));
}
dot = propertyName.indexOf('.', dot + 1);
}
}
if (newMpvs == null) {
super.doBind(mpvs);
} else {
newMpvs.addPropertyValues(mpvs);
super.doBind(newMpvs);
}
}
/**
* Treats errors as fatal.
* <p>
* Use this method only if it's an error if the input isn't valid. This
* might be appropriate if all input is from dropdowns, for example.
*
* @throws ServletRequestBindingException subclass of ServletException
* on any binding problem
*/
public void closeNoCatch() throws ServletRequestBindingException {
if (getBindingResult().hasErrors()) {
throw new ServletRequestBindingException("Errors binding onto object '"
+ getBindingResult().getObjectName() + "'", new BindException(
getBindingResult()));
}
}
}
| 3,351 |
634 |
/****************************************************************
* 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.james.repository.file;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
/**
* A special ObjectInputStream to handle highly transient classes hosted by
* Avalon components that are juggling many classloaders.
*/
public class ClassLoaderObjectInputStream extends ObjectInputStream {
private final ClassLoader classLoader;
public ClassLoaderObjectInputStream(ClassLoader classLoader, InputStream inputStream) throws IOException {
super(inputStream);
this.classLoader = classLoader;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException {
final Class<?> clazz = Class.forName(objectStreamClass.getName(), false, classLoader);
if (null != clazz) {
return clazz; // the classloader knows of the class
} else {
// classloader knows not of class, let the super classloader do it
return super.resolveClass(objectStreamClass);
}
}
}
| 790 |
937 |
package cyclops.futurestream.react.lazy.futures;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import cyclops.futurestream.LazyReact;
import org.junit.Test;
public class AccessTest {
@Test
public void get0(){
assertThat(LazyReact.sequentialBuilder().of(1).actOnFutures().get(0)._1(),equalTo(1));
}
@Test
public void getMultple(){
assertThat(LazyReact.sequentialBuilder().of(1,2,3,4,5).actOnFutures().get(2)._1(),equalTo(3));
}
@Test
public void elementAt0(){
assertTrue(LazyReact.sequentialBuilder().of(1).actOnFutures().elementAt(0).isPresent());
}
@Test
public void elementAtMultple(){
assertThat(LazyReact.sequentialBuilder().of(1,2,3,4,5).actOnFutures().elementAt(2).get(),equalTo(3));
}
@Test
public void elementAt1(){
assertFalse(LazyReact.sequentialBuilder().of(1).actOnFutures().elementAt(1).isPresent());
}
@Test
public void elementAtEmpty(){
assertFalse(LazyReact.sequentialBuilder().of().actOnFutures().elementAt(0).isPresent());
}
}
| 422 |
335 |
<gh_stars>100-1000
{
"word": "Insertion",
"definitions": [
"The action of inserting something.",
"The placing of a spacecraft or satellite into an orbit or trajectory.",
"The addition of extra DNA or RNA into a section of genetic material.",
"An amendment or addition inserted in a text.",
"Each appearance of an advertisement in a newspaper or periodical.",
"An ornamental section of cloth or needlework inserted into a garment.",
"The place or manner of attachment of an organ.",
"The place or manner of attachment of a muscle to the part which it moves."
],
"parts-of-speech": "Noun"
}
| 218 |
7,464 |
<reponame>mz1999/vjtools
package com.vip.vjtools.vjkit.collection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertFalse;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.vip.vjtools.vjkit.number.RandomUtil;
public class ArrayUtilTest {
@Test
public void shuffle() {
String[] arrays = new String[] { "d", "a", "c", "b", "e", "i", "g" };
String[] arraysClone = Arrays.copyOf(arrays, arrays.length);
Arrays.sort(arrays);
assertThat(arrays).containsExactly("a", "b", "c", "d", "e", "g", "i");
ArrayUtil.shuffle(arrays);
assertFalse("should not be equal to origin array", Arrays.equals(arrays, arraysClone));
// System.out.println(Arrays.toString(arrays));
Arrays.sort(arrays);
ArrayUtil.shuffle(arrays, RandomUtil.secureRandom());
assertFalse("should not be equal to origin array", Arrays.equals(arrays, arraysClone));
}
@Test
public void asList() {
List<String> list = ArrayUtil.asList("d", "a", "c", "b", "e", "i", "g");
assertThat(list).hasSize(7).containsExactly("d", "a", "c", "b", "e", "i", "g");
try {
list.add("a");
fail("should fail before");
} catch (Throwable t) {
assertThat(t).isInstanceOf(UnsupportedOperationException.class);
}
List<Integer> list3 = ArrayUtil.intAsList(1, 2, 3);
assertThat(list3).hasSize(3).containsExactly(1, 2, 3);
List<Long> list4 = ArrayUtil.longAsList(1L, 2L, 3L);
assertThat(list4).hasSize(3).containsExactly(1L, 2L, 3L);
List<Double> list5 = ArrayUtil.doubleAsList(1.1d, 2.2d, 3.3d);
assertThat(list5).hasSize(3).containsExactly(1.1d, 2.2d, 3.3d);
}
@Test
public void contact() {
String[] array = new String[] { "d", "a", "c" };
assertThat(ArrayUtil.concat("z", array)).containsExactly("z", "d", "a", "c");
assertThat(ArrayUtil.concat(array, "z")).containsExactly("d", "a", "c", "z");
}
}
| 792 |
631 |
<reponame>bluebird88/HIS
package com.neu.his.cloud.zuul.mapper;
import com.neu.his.cloud.zuul.model.SmsPermission;
import com.neu.his.cloud.zuul.model.SmsRolePermissionRelation;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @ClassName: SmsRolePermissionDao
* @description: TODO
* @author Zain
* @date 2019/5/30 14:22
*/
@Mapper
public interface SmsRolePermissionDao {
/**
* 根据角色获取权限
* <p>author:赵煜
*/
List<SmsPermission> getPermissionList(@Param("roleId") Long roleId);
/**
* 批量插入角色和权限关系
* <p>author:赵煜
*/
int insertList(@Param("list") List<SmsRolePermissionRelation> list);
}
| 346 |
1,063 |
# -*- coding: utf-8 -*-
from yacs.config import CfgNode
from .dim_processors_impl.identity import Identity
from .dim_processors_impl.l2_normalize import L2Normalize
from .dim_processors_impl.part_pca import PartPCA
from .dim_processors_impl.part_svd import PartSVD
from .dim_processors_impl.pca import PCA
from .dim_processors_impl.svd import SVD
from .dim_processors_impl.rmac_pca import RMACPCA
from .dim_processors_base import DimProcessorBase
__all__ = [
'DimProcessorBase',
'Identity', 'L2Normalize', 'PartPCA', 'PartSVD', 'PCA', 'SVD', 'RMACPCA',
]
| 217 |
1,179 |
<gh_stars>1000+
// SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2019, Broadcom
*/
#include <drivers/bcm_sotp.h>
#include <io.h>
#include <kernel/misc.h>
#include <kernel/pseudo_ta.h>
#define SOTP_SERVICE_UUID \
{0x6272636D, 0x2018, 0x1101, \
{0x42, 0x43, 0x4D, 0x5F, 0x53, 0x4F, 0x54, 0x50} }
enum pta_bcm_sotp_cmd {
PTA_BCM_SOTP_CMD_READ = 0,
PTA_BCM_SOTP_CMD_WRITE,
};
#define SOTP_TA_NAME "pta_bcm_sotp.ta"
static TEE_Result pta_sotp_read(uint32_t param_types,
TEE_Param params[TEE_NUM_PARAMS])
{
uint64_t sotp_row_value = 0;
uint32_t val = 0;
uint32_t exp_param_types = TEE_PARAM_TYPES(TEE_PARAM_TYPE_VALUE_INPUT,
TEE_PARAM_TYPE_VALUE_OUTPUT,
TEE_PARAM_TYPE_NONE,
TEE_PARAM_TYPE_NONE);
if (exp_param_types != param_types) {
EMSG("Invalid Param types");
return TEE_ERROR_BAD_PARAMETERS;
}
val = params[0].value.a;
bcm_iproc_sotp_mem_read(val, 1, &sotp_row_value);
reg_pair_from_64(sotp_row_value, ¶ms[1].value.a,
¶ms[1].value.b);
return TEE_SUCCESS;
}
static TEE_Result pta_sotp_write(uint32_t param_types __unused,
TEE_Param params[TEE_NUM_PARAMS] __unused)
{
/* Nothing as of now */
return TEE_ERROR_NOT_IMPLEMENTED;
}
static TEE_Result invoke_command(void *session_context __unused,
uint32_t cmd_id,
uint32_t param_types,
TEE_Param params[TEE_NUM_PARAMS])
{
TEE_Result res = TEE_SUCCESS;
DMSG("command entry point[%d] for \"%s\"", cmd_id, SOTP_TA_NAME);
switch (cmd_id) {
case PTA_BCM_SOTP_CMD_READ:
res = pta_sotp_read(param_types, params);
break;
case PTA_BCM_SOTP_CMD_WRITE:
res = pta_sotp_write(param_types, params);
break;
default:
EMSG("cmd %d Not supported %s", cmd_id, SOTP_TA_NAME);
res = TEE_ERROR_NOT_SUPPORTED;
break;
}
return res;
}
pseudo_ta_register(.uuid = SOTP_SERVICE_UUID,
.name = SOTP_TA_NAME,
.flags = PTA_DEFAULT_FLAGS,
.invoke_command_entry_point = invoke_command);
| 969 |
473 |
#include "libpov.h"
// \x00<> =/&\x01\x00\x48<cml><cml><\x01\xc0\x47\x43AAAAAAAAYYYY></\x01\xc0\x47\x43AAAAAAAAYYYY><XXXX></XXXX></cml></cml>\x07\x01\x00\x00\x00\x00\x05\x04\x04\x84\x00\x01\x06\x02\x00\x00\x00
unsigned char *cgc_memchr(unsigned char *buf, int c, cgc_size_t n)
{
cgc_size_t i;
for (i = 0; i < n; i++)
if (buf[i] == c)
return &buf[i];
return 0;
}
int main(int cgc_argc, char *cgc_argv[])
{
unsigned char chars[6];
unsigned char buf[128];
unsigned char tmp[16];
unsigned int i, size, addr = 0x4347C001, desc = 0;
cgc_size_t bytes;
type2_vals t2;
cgc_type2_negotiate(&t2);
next_addr:
do
{
try_again:
cgc_random(chars, sizeof(chars), &bytes);
for (i = 0; i < sizeof(chars); i++)
{
if (chars[i] == 0)
goto try_again;
if (cgc_memchr((void*)&addr, chars[i], 4) != 0)
goto try_again;
if (cgc_memchr((void*)"cml", chars[i], 3) != 0)
goto try_again;
if (cgc_memchr(&chars[i + 1], chars[i], sizeof(chars) - i - 1) != 0)
goto try_again;
}
} while (0);
i = 0;
buf[i++] = 0x00;
buf[i++] = chars[0];
buf[i++] = chars[1];
buf[i++] = chars[2];
buf[i++] = chars[3];
buf[i++] = chars[4];
buf[i++] = chars[5];
cgc_transmit_all(STDOUT, buf, i);
cgc_random(tmp, 16, &bytes);
for (i = 0; i < 16; i++)
{
while (cgc_memchr(chars, tmp[i], 6) != 0 || tmp[i] == 0)
tmp[i]++;
}
i = 0;
buf[i++] = 0x01;
buf[i++] = 0x00;
buf[i++] = 0x48;
buf[i++] = chars[0];
buf[i++] = 'c';
buf[i++] = 'm';
buf[i++] = 'l';
buf[i++] = chars[1];
buf[i++] = chars[0];
buf[i++] = 'c';
buf[i++] = 'm';
buf[i++] = 'l';
buf[i++] = chars[1];
buf[i++] = chars[0];
*(unsigned int *)&buf[i] = addr;
i += 4;
cgc_memcpy(&buf[i], tmp, 12);
i += 12;
buf[i++] = chars[1];
buf[i++] = chars[0];
buf[i++] = chars[4];
*(unsigned int *)&buf[i] = addr;
i += 4;
cgc_memcpy(&buf[i], tmp, 12);
i += 12;
buf[i++] = chars[1];
buf[i++] = chars[0];
cgc_memcpy(&buf[i], tmp+12, 4);
i += 4;
buf[i++] = chars[1];
buf[i++] = chars[0];
buf[i++] = chars[4];
cgc_memcpy(&buf[i], tmp+12, 4);
i += 4;
buf[i++] = chars[1];
buf[i++] = chars[0];
buf[i++] = chars[4];
buf[i++] = 'c';
buf[i++] = 'm';
buf[i++] = 'l';
buf[i++] = chars[1];
buf[i++] = chars[0];
buf[i++] = chars[4];
buf[i++] = 'c';
buf[i++] = 'm';
buf[i++] = 'l';
buf[i++] = chars[1];
cgc_transmit_all(STDOUT, buf, i);
desc++;
cgc_memcpy(buf, "\x07\x01\x00\x00\x00\x00\x05\x04\x04\x84\x00\x01", 12);
*(unsigned int *)&buf[1] = desc;
cgc_transmit_all(STDOUT, buf, 12);
desc++;
cgc_memcpy(buf, "\x06\x02\x00\x00\x00", 5);
*(unsigned int *)&buf[1] = desc;
cgc_transmit_all(STDOUT, buf, 5);
cgc_length_read(STDIN, buf, 12);
if (buf[11] == 0x00)
{
cgc_length_read(STDIN, buf, 2);
size = buf[0] * 256 + buf[1];
}
else
{
size = 0;
}
if (size < 4)
{
if (size)
cgc_length_read(STDIN, buf, size);
if (addr < 0x4347C011)
{
addr += 4;
goto next_addr;
}
}
else
{
cgc_length_read(STDIN, buf, 4);
}
cgc_type2_submit(buf, 4);
return 0;
}
| 2,020 |
1,484 |
from anchore_engine.db import Image
from anchore_engine.services.policy_engine.engine.loaders import ImageLoader
def get_image():
img = Image()
img.user_id = "unit_test"
img.id = "da28a15dbf563fbc5a486f622b44970ee1bf10f48013bab640f403b06b278543"
return img
class TestLoadingJavaCPEs:
ANALYSIS_DATA = {
"package_list": {
"pkgs.java": {
"base": {
"/usr/lib/jvm/java-1.8-openjdk/jre/lib/ext/zipfs.jar": '{"cpes": ["cpe:2.3:a:zipfs:zipfs:1.8.0_212:*:*:*:*:java:*:*","cpe:2.3:a:zipfs:zipfs:1.8.0_212:*:*:*:*:maven:*:*","cpe:2.3:a:*:zipfs:1.8.0_212:*:*:*:*:java:*:*","cpe:2.3:a:*:zipfs:1.8.0_212:*:*:*:*:maven:*:*","cpe:2.3:a:zipfs:zipfs:1.8.0_212:*:*:*:*:*:*:*","cpe:2.3:a:*:zipfs:1.8.0_212:*:*:*:*:*:*:*"],"implementation-version": "1.8.0_212","location": "/usr/lib/jvm/java-1.8-openjdk/jre/lib/ext/zipfs.jar","maven-version": "N/A","origin": "Oracle Corporation","name": "zipfs","specification-version": "1.8","type": "java-jar"}'
}
}
}
}
def test_extract_java_syft_cpes_returns_cpes(self):
cpes = ImageLoader(self.ANALYSIS_DATA).extract_syft_cpes(
{},
self.ANALYSIS_DATA["package_list"]["pkgs.java"]["base"],
get_image(),
"java",
)
assert cpes is not None
def test_fuzzy_java_cpes_returns_cpes(self):
fuzzy_cpes = ImageLoader(self.ANALYSIS_DATA).get_fuzzy_java_cpes(
self.ANALYSIS_DATA, {}, get_image()
)
assert fuzzy_cpes is not None
class TestLoadingPythonCPEs:
ANALYSIS_DATA = {
"package_list": {
"pkgs.python": {
"base": {
"/usr/local/lib/python3.9/site-packages/wheel": '{"cpes":["cpe:2.3:a:*:wheel:0.36.1:*:*:*:*:*:*:*","cpe:2.3:a:*:wheel:0.36.1:*:*:*:*:python:*:*","cpe:2.3:a:wheel:wheel:0.36.1:*:*:*:*:*:*:*","cpe:2.3:a:wheel:wheel:0.36.1:*:*:*:*:python:*:*","cpe:2.3:a:python-wheel:wheel:0.36.1:*:*:*:*:*:*:*","cpe:2.3:a:python-wheel:wheel:0.36.1:*:*:*:*:python:*:*"],"license":"MIT","licenses":["MIT"],"location":"/usr/local/lib/python3.9/site-packages","origin":"<NAME> <<EMAIL>>","name":"wheel","type":"PYTHON","version":"0.36.1"}'
}
}
}
}
def test_extract_python_syft_cpes_returns_cpes(self):
cpes = ImageLoader(self.ANALYSIS_DATA).extract_syft_cpes(
{},
self.ANALYSIS_DATA["package_list"]["pkgs.python"]["base"],
get_image(),
"python",
)
assert cpes is not None
def test_fuzzy_python_cpes_returns_cpes(self):
fuzzy_cpes = ImageLoader(self.ANALYSIS_DATA).get_fuzzy_python_cpes(
self.ANALYSIS_DATA, {}, get_image()
)
assert fuzzy_cpes is not None
class TestLoadingGemsCPEs:
ANALYSIS_DATA = {
"package_list": {
"pkgs.gems": {
"base": {
"/usr/lib/ruby/gems/2.7.0/specifications/default/zlib-1.1.0.gemspec": '{"cpes":["cpe:2.3:a:*:zlib:1.1.0:*:*:*:*:*:*:*"],"license":"BSD-2-Clause","licenses":["BSD-2-Clause"],"location":"/usr/lib/ruby/gems/2.7.0/specifications/default/zlib-1.1.0.gemspec","origin":"<NAME>,UENO Katsuhiro","name":"zlib","type":"GEM","versions":["1.1.0"]}'
}
}
}
}
def test_extract_gems_syft_cpes_returns_cpes(self):
cpes = ImageLoader(self.ANALYSIS_DATA).extract_syft_cpes(
{},
self.ANALYSIS_DATA["package_list"]["pkgs.gems"]["base"],
get_image(),
"gem",
)
assert cpes is not None
def test_fuzzy_gem_cpes_returns_cpes(self):
fuzzy_cpes = ImageLoader(self.ANALYSIS_DATA).get_fuzzy_gem_cpes(
self.ANALYSIS_DATA, {}, get_image()
)
assert fuzzy_cpes is not None
class TestLoadingNpmsCPEs:
ANALYSIS_DATA = {
"package_list": {
"pkgs.npms": {
"base": {
"/usr/lib/node_modules/npm/node_modules/yargs-parser/package.jsonl": '{"cpes":["cpe:2.3:a:*:yargs-parser:9.0.2:*:*:*:*:*:*:*"],"license":"ISC","licenses":["ISC"],"location":"/usr/lib/node_modules/npm/node_modules/yargs-parser/package.json","origin":"<NAME> <<EMAIL>>","name":"yargs-parser","type":"NPM","versions":["9.0.2"]}'
}
}
}
}
def test_extract_npms_syft_cpes_returns_cpes(self):
cpes = ImageLoader(self.ANALYSIS_DATA).extract_syft_cpes(
{},
self.ANALYSIS_DATA["package_list"]["pkgs.npms"]["base"],
get_image(),
"npm",
)
assert cpes is not None
def test_fuzzy_npm_cpes_returns_cpes(self):
fuzzy_cpes = ImageLoader(self.ANALYSIS_DATA).get_fuzzy_npm_cpes(
self.ANALYSIS_DATA, {}, get_image()
)
assert fuzzy_cpes is not None
| 2,603 |
1,210 |
<gh_stars>1000+
#include <cstdio>
#include <cstdlib>
#define LOWBIT(x) ((x) & (-(x)))
#define COMPOSITE 0
#define PRIME 1
typedef long long ll;
using namespace std;
ll qpow(ll x, int y, int p)
{
if (y == 0) return 1;
ll h = qpow(x * x % p, y >> 1, p);
if ((y & 1) == 0) return h;
else return h * x % p;
}
bool witness(int a, int n)
{
int t = LOWBIT(n - 1);
int u = n / t;
ll x = qpow(a, u, n);
for (int i = 1; i < t; i <<= 1)
{
ll r = x * x % (ll)n;
if (r == 1 && x != 1 && x != n - 1) return true;
x = r;
}
if (x != 1) return true;
return false;
}
bool Miller_Rabin(int n, int s)
{
if (n == 2) return PRIME;
if ((n & 1) == 0) return COMPOSITE;
while (s--)
{
if (witness(rand() % (n - 2) + 2, n) == true) return COMPOSITE;
}
return PRIME;
}
int main()
{
int n;
while (true)
{
scanf("%d", &n);
printf("%s\n", Miller_Rabin(n, 10) == COMPOSITE ? "COMPOSITE" : "PRIME");
}
return 0;
}
| 452 |
892 |
<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-6672-h2cg-jp6j",
"modified": "2022-05-17T00:01:26Z",
"published": "2022-05-17T00:01:26Z",
"aliases": [
"CVE-2022-1062"
],
"details": "The th23 Social WordPress plugin through 1.2.0 does not sanitise and escape some of its settings, which could allow high privilege users such as admin to perform Cross-Site Scripting attacks even when the unfiltered_html capability is disallowed",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-1062"
},
{
"type": "WEB",
"url": "https://wpscan.com/vulnerability/e770ba87-95d2-40c9-89cc-5d7390e9cbb0"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": null,
"github_reviewed": false
}
}
| 387 |
1,372 |
<gh_stars>1000+
# Copyright 2017 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
## py2/py3 compat
from __future__ import print_function
import pyerrors
def div(a, b):
try:
r = pyerrors.Div(a, b)
print("pyerrors.Div(%d, %d) = %d"% (a, b, r))
except Exception as e:
print(e)
def new_mystring(s):
try:
ms = pyerrors.NewMyString(s)
print('pyerrors.NewMyString("%s") = "%s"'% (s, ms.String()))
except Exception as e:
print(e)
div(5,0) # error
div(5,2)
new_mystring("") # error
new_mystring("hello")
print("OK")
| 297 |
319 |
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.demos.sandbox;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import java.io.IOException;
import java.net.MalformedURLException;
import org.openimaj.image.FImage;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.RGBColour;
import org.openimaj.image.processing.threshold.OtsuThreshold;
import org.openimaj.video.VideoDisplay;
import org.openimaj.video.VideoDisplayListener;
import org.openimaj.video.capture.VideoCapture;
public class QRTester {
public static void main(String[] args) throws MalformedURLException, IOException {
// MBFImage cimg = ImageUtilities.readMBF(new
// URL("http://cdn.socialnomics.net/wp-content/uploads/2011/03/QR-code-girl1.jpg"));
// // MBFImage cimg = ImageUtilities.readMBF(new
// URL("http://thinkd2c.files.wordpress.com/2011/05/qrcode_wwd.png"));
// findMarkers(cimg);
// DisplayUtilities.display(cimg);
final VideoDisplay<MBFImage> display = VideoDisplay.createVideoDisplay(new VideoCapture(640, 480));
display.addVideoListener(new VideoDisplayListener<MBFImage>() {
@Override
public void beforeUpdate(MBFImage frame) {
findMarkers(frame);
}
@Override
public void afterUpdate(VideoDisplay<MBFImage> display) {
// TODO Auto-generated method stub
}
});
}
static void findMarkers(MBFImage cimg) {
FImage image = cimg.flatten();
image = image.processInplace(new OtsuThreshold());
// image = image.threshold(0.2f);
for (int y = 0; y < image.height; y += 2) {
final TIntArrayList centres = processLineH(image, y);
for (final int x : centres.toArray()) {
cimg.drawLine(x, y - 10, x, y + 10, RGBColour.RED);
cimg.drawLine(x - 10, y, x + 10, y, RGBColour.RED);
}
}
// cimg.internalAssign(new MBFImage(image,image,image));
}
static TIntArrayList processLineH(FImage image, int y) {
final TIntArrayList counts = new TIntArrayList();
int start = 0;
while (start < image.width) {
if (image.pixels[y][start] == 0)
break;
start++;
}
for (int i = start; i < image.width; i++) {
int count = 0;
final float state = image.pixels[y][i];
for (; i < image.width; i++) {
if (image.pixels[y][i] != state) {
i--; // step back because the outer loop increments
break;
}
count++;
}
counts.add(count);
}
return findPossibleH(counts, start);
}
static TIntArrayList findPossibleH(TIntArrayList counts, final int start) {
final TIntArrayList centers = new TIntArrayList();
// assume first count is black. Only need check patterns starting with
// black...
for (int i = 0, co = start; i < counts.size() - 5; i += 2) {
final TIntList pattern = counts.subList(i, i + 5);
if (isValid(pattern)) {
int sum = 0;
for (final int j : pattern.toArray())
sum += j;
centers.add(co + (sum / 2));
}
co += counts.get(i) + counts.get(i + 1);
}
return centers;
}
private static boolean isValid(TIntList pattern) {
// 1 1 3 1 1
// B W B W B
final float[] apat = { 1, 1, 3, 1, 1 };
final float[] fpat = { pattern.get(0), pattern.get(1), pattern.get(2), pattern.get(3), pattern.get(4) };
// System.out.print(Arrays.toString(fpat) + "\t\t");
final float ratio = 4 / (fpat[0] + fpat[1] + fpat[3] + fpat[4]);
for (int i = 0; i < 5; i++)
fpat[i] *= ratio;
float error = 0;
for (int i = 0; i < 5; i++) {
final float diff = apat[i] - fpat[i];
error += diff * diff;
}
// System.out.println(error);
// System.out.println(Arrays.toString(fpat) + "\t\t" + error);
if (error < 0.5)
return true;
return false;
}
}
| 1,903 |
854 |
<reponame>timxor/leetcode-journal<gh_stars>100-1000
__________________________________________________________________________________________________
0ms
class Solution {
public boolean isValid(String s) {
char stack[] = new char[s.length()];
int top = -1;
char current;
for(int i = 0; i < s.length(); i++)
{
current = s.charAt(i);
if(current =='(' || current =='[' || current == '{'){
stack[++top] = current;
}
else
{
if(top == -1)
return false;
else if(current == ')' && stack[top] != '(')
return false;
else if(current == ']' && stack[top] != '[')
return false;
else if(current == '}' && stack[top] != '{')
return false;
else
top--;
}
}
if(top == -1)
return true;
return false;
}
}
__________________________________________________________________________________________________
1ms
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}
__________________________________________________________________________________________________
2ms
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else {
if(stack.empty()) {
return false;
}
Character val = stack.pop();
// System.out.println(val);
if(!((val == '(' && s.charAt(i) == ')') || (val == '[' && s.charAt(i) == ']') || (val == '{' && s.charAt(i) == '}'))) {
return false;
}
}
}
if(stack.empty()) {
return true;
} else {
return false;
}
}
}
__________________________________________________________________________________________________
34152 kb
class Solution {
public boolean isValid(String s) {
if (s.isEmpty())
return true;
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack<Character> stack = new Stack<>();
if (s.length() % 2 != 0)
return false;
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
// close
if (stack.isEmpty())
return false;
Character c = stack.pop();
if (map.get(s.charAt(i)) != c) {
return false;
}
}
if(map.containsValue(s.charAt(i))){
//open
stack.add(s.charAt(i));
continue;
}
}
if(!stack.isEmpty())
return false;
return true;
}
}
__________________________________________________________________________________________________
34236 kb
class Solution {
public boolean isValid(String s) {
Map<String, String> CoupleString = new HashMap<String, String>();
CoupleString.put(")","(");
CoupleString.put("}","{");
CoupleString.put("]","[");
Stack<String> aCharStringStack = new Stack<String>();
aCharStringStack.empty();
for(int i =0;i<s.length();i++){
String aCharStr = s.substring(i,i+1);
if(!aCharStringStack.isEmpty()){
String aCharOfStack = aCharStringStack.pop();
if(!aCharOfStack.equals(CoupleString.get(aCharStr))){
aCharStringStack.push(aCharOfStack);
aCharStringStack.push(aCharStr);
}
}else {
aCharStringStack.push(aCharStr);
}
}
return aCharStringStack.empty();
}
}
__________________________________________________________________________________________________
| 1,919 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-36gv-vcm7-9gf5",
"modified": "2022-05-02T03:31:42Z",
"published": "2022-05-02T03:31:42Z",
"aliases": [
"CVE-2009-2116"
],
"details": "Directory traversal vulnerability in admin.php in SkyBlueCanvas 1.1 r237 allows remote authenticated administrators to list directory contents via a .. (dot dot) in the dir parameter.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-2116"
},
{
"type": "WEB",
"url": "http://forum.intern0t.net/intern0t-advisories/1120-intern0t-skybluecanvas-1-1-r237-multiple-vulnerabilities.html"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/35478"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/504302/100/0/threaded"
}
],
"database_specific": {
"cwe_ids": [
"CWE-22"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 475 |
545 |
#include <string>
#include <iostream>
#include <fstream>
bool containAscenderOrDescender(const std::string &s) {
// Upper case letters do not included.
const std::string ascenders_and_descenders{"<KEY>"};
return s.find_first_of(ascenders_and_descenders) != std::string::npos;
}
int main() {
std::string filename;
std::cin >> filename;
std::ifstream in(filename);
if (in.is_open()) {
std::string longestWord, word;
while (in >> word)
if (!containAscenderOrDescender(word) && word.size() > longestWord.size())
longestWord = word;
if (longestWord.empty())
std::cout << "There is no word contains neither ascenders nor descenders "
"in file \"" << filename << "\"." << std::endl;
else
std::cout << "The longest word that contains neither ascenders nor "
"descenders in file \"" << filename
<< "\" is \"" << longestWord << "\"." << std::endl;
} else {
std::cerr << "Can not open file: " << filename << std::endl;
}
return 0;
}
| 405 |
626 |
package org.jsmart.zerocode.jupiter.demo;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.text.StrSubstitutor;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class CalculatorTest {
Calculator calculator = new Calculator();
@Test
@DisplayName("1 + 1 = 2")
void addsTwoNumbers() {
assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
}
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"1, 2, 3",
"11, 22, 33"
})
void add(int first, int second, int expectedResult) {
Calculator calculator = new Calculator();
assertEquals(expectedResult, calculator.add(first, second),
() -> first + " + " + second + " should equal " + expectedResult);
}
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"1, 2, 3",
"11, 22, 33",
"Hello World, How, Hello World How"
})
void conCat(Object first, Object second, Object expectedResult) {
Calculator calculator = new Calculator();
System.out.println(first + "+" + second + "=" + expectedResult);
}
@ParameterizedTest(name = "run #{index} with [{arguments}]")
@ValueSource(strings = {"Hello", "JUnit"})
void withValueSource(String word) {
assertNotNull(word);
}
@Test
void testParamResolver() {
String WelcomeMessage="Hello ${firstName} ${lastName}!";
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("firstName", "Peter");
valuesMap.put("lastName", "Osi");
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String message = sub.replace(WelcomeMessage);
assertEquals("Hello <NAME>!", message);
}
}
| 850 |
1,780 |
package io.seata.samples.sca.customer.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Created by yu.hb on 2019-10-30
*/
@FeignClient(value = "sca-provider")
public interface ProviderFeignService {
@GetMapping("/feign/echo")
String feignEcho(@RequestParam("name") String name);
}
| 151 |
45,293 |
<reponame>Mu-L/kotlin
public abstract interface KtInterface /* KtInterface*/ {
public abstract void defaultFun();// defaultFun()
public abstract void withoutBody();// withoutBody()
class DefaultImpls ...
}
| 62 |
828 |
# -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
def r2_c(y_true, y_pred):
from tensorflow.keras import backend as K
import tensorflow as tf
y_true = tf.convert_to_tensor(y_true, dtype='float32')
y_pred = tf.convert_to_tensor(y_pred, dtype='float32')
SS_res = K.sum(K.square(y_true - y_pred))
SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
score = (1 - SS_res / (SS_tot + K.epsilon()))
return score
| 210 |
396 |
<gh_stars>100-1000
"""
version info
"""
# @modified 20170109 - Feature #1854: Ionosphere learn
# Added learn
# __version_info__ = ('1', '1', '0')
# @modified 20210614 - Branch #1444: thunder
# __version_info__ = ('2', '1', '0')
# __version_info__ = ('2', '1', '0')
# @modified 20211109 - Bug #4308: matrixprofile - fN on big drops
# __version_info__ = ('2', '1', '0-4264')
# __branch__ = 'SNAB'
# __version_tag__ = 'cloudburst'
# __version_info__ = ('2', '1', '0-4309')
# __branch__ = 'SNAB'
# __version_tag__ = 'trigger_history_override'
__version_info__ = ('2', '1', '0-4328')
__branch__ = 'SNAB'
__version_tag__ = 'BATCH_METRICS_CUSTOM_FULL_DURATIONS'
__version__ = '.'.join(__version_info__)
# @modified 20190117 - release #2748: v1.2.11
# Changed version naming in terms release names from vx.y.z instead of of using
# vx.y.z-__version_tag__ e.g. now v1.2.11 instead of v1.2.11-stable
# __absolute_version__ = 'Skyline (%s v%s-%s)' % (__branch__, __version__, __version_tag__)
__absolute_version__ = 'Skyline (%s v%s %s)' % (__branch__, __version__, __version_tag__)
# __version__ = '0.5.0'
# __absolute_version__ = Skyline (crucible v0.5.0-beta)
| 469 |
1,276 |
#include <cstdint>
#include "common.h"
namespace soa_size_t {
struct Point {
float x[N];
float y[N];
float z[N];
};
Point ps;
void compute() {
for (std::size_t i = 0; i < N; i++) {
ps.x[i] = ps.x[i] + ps.y[i] + ps.z[i];
}
}
}
| 139 |
9,717 |
<reponame>collinwright/nixpkgs
{
"name": "matrix-recorder",
"version": "0.0.6",
"description": "A recorder that can record Matrix rooms you are a member of (including E2E-encrypted rooms).",
"author": "Hello Matrix <<EMAIL>>",
"main": "matrix-recorder.js",
"scripts": {
"start": "node matrix-recorder.js"
},
"repository": {
"type": "git",
"url": "https://gitlab.com/argit/matrix-recorder.git"
},
"dependencies": {
"marked": "^0.6.2",
"matrix-js-sdk": "^0.7.13",
"mime-types": "^2.1.14",
"mustache": "^2.3.0",
"node-fetch": "^1.6.3",
"node-localstorage": "^1.3.0",
"sqlite3": "^4.0.7",
"olm": "https://packages.matrix.org/npm/olm/olm-2.3.0.tgz"
},
"license": "MIT",
"optionalDependencies": {
}
}
| 358 |
343 |
import re
import requests
import json
import os
import pdfkit
from bs4 import BeautifulSoup
from urllib.parse import quote
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>{title}</h1>
<p>{text}</p>
</body>
</html>
"""
htmls = []
num = 0
def get_data(url):
global htmls, num
headers = {
'Authorization': '<PASSWORD>',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
rsp = requests.get(url, headers=headers)
with open('test.json', 'w', encoding='utf-8') as f: # 将返回数据写入 test.json 方便查看
f.write(json.dumps(rsp.json(), indent=2, ensure_ascii=False))
with open('test.json', encoding='utf-8') as f:
for topic in json.loads(f.read()).get('resp_data').get('topics'):
content = topic.get('question', topic.get('talk', topic.get('task', topic.get('solution'))))
# print(content)
text = content.get('text', '')
text = re.sub(r'<[^>]*>', '', text).strip()
text = text.replace('\n', '<br>')
title = str(num) + text[:9]
num += 1
if content.get('images'):
soup = BeautifulSoup(html_template, 'html.parser')
for img in content.get('images'):
url = img.get('large').get('url')
img_tag = soup.new_tag('img', src=url)
soup.body.append(img_tag)
html_img = str(soup)
html = html_img.format(title=title, text=text)
else:
html = html_template.format(title=title, text=text)
if topic.get('question'):
answer = topic.get('answer').get('text', "")
soup = BeautifulSoup(html, 'html.parser')
answer_tag = soup.new_tag('p')
answer_tag.string = answer
soup.body.append(answer_tag)
html_answer = str(soup)
html = html_answer.format(title=title, text=text)
htmls.append(html)
next_page = rsp.json().get('resp_data').get('topics')
if next_page:
create_time = next_page[-1].get('create_time')
if create_time[20:23] == "000":
end_time = create_time[:20]+"999"+create_time[23:]
else :
res = int(create_time[20:23])-1
end_time = create_time[:20]+str(res).zfill(3)+create_time[23:] # zfill 函数补足结果前面的零,始终为3位数
end_time = quote(end_time)
if len(end_time) == 33:
end_time = end_time[:24] + '0' + end_time[24:]
next_url = start_url + '&end_time=' + end_time
print(next_url)
get_data(next_url)
return htmls
def make_pdf(htmls):
html_files = []
for index, html in enumerate(htmls):
file = str(index) + ".html"
html_files.append(file)
with open(file, "w", encoding="utf-8") as f:
f.write(html)
options = {
"user-style-sheet": "test.css",
"page-size": "Letter",
"margin-top": "0.75in",
"margin-right": "0.75in",
"margin-bottom": "0.75in",
"margin-left": "0.75in",
"encoding": "UTF-8",
"custom-header": [("Accept-Encoding", "gzip")],
"cookie": [
("cookie-name1", "cookie-value1"), ("cookie-name2", "cookie-value2")
],
"outline-depth": 10,
}
try:
pdfkit.from_file(html_files, "电子书.pdf", options=options)
except Exception as e:
pass
for file in html_files:
os.remove(file)
print("已制作电子书在当前目录!")
if __name__ == '__main__':
start_url = 'https://api.zsxq.com/v1.10/groups/8424258282/topics?scope=digests&count=20'
make_pdf(get_data(start_url))
| 2,009 |
3,444 |
/**
* Copyright (c) 2018, biezhi 王爵nice (<EMAIL>)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hellokaton.blade.validator;
import lombok.AllArgsConstructor;
import java.util.function.Predicate;
@AllArgsConstructor
public class SimpleValidation<T> implements Validation<T> {
private Predicate<T> predicate;
private String onErrorMessage;
public static <T> SimpleValidation<T> from(Predicate<T> predicate, String onErrorMessage) {
return new SimpleValidation<>(predicate, onErrorMessage);
}
@Override
public ValidationResult test(T param) {
return predicate.test(param) ? ValidationResult.ok() : ValidationResult.fail(onErrorMessage);
}
}
| 378 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Siorac-de-Ribérac","circ":"3ème circonscription","dpt":"Dordogne","inscrits":213,"abs":72,"votants":141,"blancs":10,"nuls":13,"exp":118,"res":[{"nuance":"SOC","nom":"<NAME>","voix":65},{"nuance":"MDM","nom":"<NAME>","voix":53}]}
| 118 |
4,054 |
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.ca.restapi.mock;
import com.yahoo.component.AbstractComponent;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import java.util.HashMap;
import java.util.Map;
/**
* @author mpolden
*/
public class SecretStoreMock extends AbstractComponent implements SecretStore {
private final Map<String, String> secrets = new HashMap<>();
public SecretStoreMock setSecret(String key, String value) {
secrets.put(key, value);
return this;
}
@Override
public String getSecret(String key) {
if (!secrets.containsKey(key)) throw new RuntimeException("No such key '" + key + "'");
return secrets.get(key);
}
@Override
public String getSecret(String key, int version) {
if (!secrets.containsKey(key)) throw new RuntimeException("No such key '" + key + "'");
return secrets.get(key);
}
}
| 343 |
372 |
<gh_stars>100-1000
import requests
import logging
from zipfile import ZipFile
import subprocess
import shlex
from pathlib import Path
import json
from time import sleep
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
message = ''
code = ''
retries = 10
SUCCESS = "SUCCESS"
FAILED = "FAILED"
def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=''):
responseUrl = event['ResponseURL']
print(responseUrl)
responseBody = {}
responseBody['Status'] = responseStatus
responseBody['Reason'] = reason if reason else 'See the details in CloudWatch Log Stream: ' + context.log_stream_name
responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name
responseBody['StackId'] = event['StackId']
responseBody['RequestId'] = event['RequestId']
responseBody['LogicalResourceId'] = event['LogicalResourceId']
responseBody['NoEcho'] = noEcho
responseBody['Data'] = responseData
json_responseBody = json.dumps(responseBody)
print("Response body:\n" + json_responseBody)
headers = {
'content-type': '',
'content-length': str(len(json_responseBody))
}
try:
response = requests.put(responseUrl,
data=json_responseBody,
headers=headers)
print("Status code: " + response.reason)
except Exception as e:
print("send(..) failed executing requests.put(..): " + str(e))
def run_command(command):
code = 0
try:
logger.debug("executing command: %s" % command)
output = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT).decode("utf-8")
logging.debug(output)
except subprocess.CalledProcessError as exc:
code = exc.returncode
output = exc.output.decode("utf-8")
logger.error("Command failed [exit %s]: %s" % (exc.returncode, exc.output.decode("utf-8")))
return code, output
with ZipFile("./awscli-exe-linux-x86_64.zip") as zip:
zip.extractall('/tmp/cli-install/')
run_command('chmod +x /tmp/cli-install/aws/dist/aws')
run_command('chmod +x /tmp/cli-install/aws/install')
c, r = run_command('/tmp/cli-install/aws/install -b /tmp/bin -i /tmp/aws-cli')
if c != 0:
raise Exception(f"Failed to install cli. Code: {c} Message: {r}")
def execute_cli(properties):
code, response = run_command(f"/tmp/bin/aws {properties['AwsCliCommand']} --output json")
if code != 0 and ('NotFound' in response or 'does not exist' in response):
return None
if code != 0:
raise Exception(response)
return json.loads(response)
def handler(event, context):
logger.debug(event)
status = SUCCESS
pid = 'None'
resp = {}
reason = ''
try:
if event['RequestType'] != 'Delete':
while not Path("/tmp/bin/aws").is_file():
print("waiting for cli install to complete")
sleep(10)
resp = execute_cli(event['ResourceProperties'])
if 'IdField' in event['ResourceProperties'] and isinstance(resp, dict):
pid = resp[event['ResourceProperties']['IdField']]
else:
pid = str(resp)
except Exception:
logging.error('Unhandled exception', exc_info=True)
reason = (str(e))
status = FAILED
finally:
send(event, context, status, resp, pid, reason=reason)
| 1,369 |
1,442 |
#ifndef KANDINSKY_COLOR_H
#define KANDINSKY_COLOR_H
#include <stdint.h>
class KDColor {
public:
constexpr KDColor() : m_value(0) {}
// FIXME: This should not be needed, and is probably wasting CPU cycles
static constexpr KDColor RGB16(uint16_t rgb) {
return KDColor(rgb);
}
static constexpr KDColor RGB24(uint32_t rgb) {
return KDColor(((rgb&0xF80000)>>8)|((rgb&0x00FC00)>>5)|((rgb&0x0000F8)>>3));
}
static constexpr KDColor RGB888(uint8_t r, uint8_t g, uint8_t b) {
return KDColor((r>>3)<<11 | (g>>2) << 5 | (b>>3));
}
uint8_t red() const {
uint8_t r5 = (m_value>>11)&0x1F;
return r5 << 3;
}
uint8_t green() const {
uint8_t g6 = (m_value>>5)&0x3F;
return g6 << 2;
}
uint8_t blue() const {
uint8_t b5 = m_value&0x1F;
return b5 << 3;
}
static KDColor blend(KDColor first, KDColor second, uint8_t alpha);
operator uint16_t() const { return m_value; }
private:
constexpr KDColor(uint16_t value) : m_value(value) {}
uint16_t m_value;
};
constexpr KDColor KDColorBlack = KDColor::RGB24(0x000000);
constexpr KDColor KDColorWhite = KDColor::RGB24(0xFFFFFF);
constexpr KDColor KDColorRed = KDColor::RGB24(0xFF0000);
constexpr KDColor KDColorGreen = KDColor::RGB24(0x00FF00);
constexpr KDColor KDColorBlue = KDColor::RGB24(0x0000FF);
constexpr KDColor KDColorYellow = KDColor::RGB24(0xFFFF00);
constexpr KDColor KDColorOrange = KDColor::RGB24(0xFF9900);
constexpr KDColor KDColorPurple = KDColor::RGB24(0xFF00DD);
#endif
| 615 |
5,102 |
package com.nepxion.discovery.plugin.strategy.sentinel.monitor.constant;
/**
* <p>Title: Nepxion Discovery</p>
* <p>Description: Nepxion Discovery</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
* @author <NAME>
* @author <NAME>
* @version 1.0
*/
public class SentinelStrategyMonitorConstant {
public static final String SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_RULE_OUTPUT_ENABLED = "spring.application.strategy.tracer.sentinel.rule.output.enabled";
public static final String SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_ARGS_OUTPUT_ENABLED = "spring.application.strategy.tracer.sentinel.args.output.enabled";
public static final String TRACER_NAME = "SENTINEL-TRACER";
public static final String SPAN_NAME = "SENTINEL";
public static final String ORIGIN = "origin";
public static final String ASYNC = "async";
public static final String RESOURCE_NAME = "resource.name";
public static final String RESOURCE_SHOW_NAME = "resource.showname";
public static final String RESOURCE_TYPE = "resource.type";
public static final String ENTRY_TYPE = "entry.type";
public static final String RULE_LIMIT_APP = "rule.limit.app";
public static final String RULE = "rule";
public static final String CAUSE = "cause";
public static final String BLOCK_EXCEPTION = "block.exception";
public static final String COUNT = "count";
public static final String ARGS = "args";
}
| 490 |
32,544 |
package com.baeldung.hibernate.audit;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(e -> e.getAuthentication())
.map(Authentication::getName);
}
}
| 187 |
5,937 |
<filename>src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/HwLinearGradientBrush.h
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
//
// Description:
// Contains CHwLinearGradientBrush declaration
//
MtExtern(CHwLinearGradientBrush);
//+----------------------------------------------------------------------------
//
// Class: CHwLinearGradientBrush
//
// Synopsis: This class implements the primary color source interface for a
// linear gradient brush
//
// This class uses a linear gradient color source. It is also a
// cacheable resource and a poolable brush. The caching is done on
// the brush level so that we may cache multiple realizations if
// needed.
//
class CHwLinearGradientBrush : public CHwCacheablePoolBrush
{
public:
DECLARE_METERHEAP_ALLOC(ProcessHeap, Mt(CHwLinearGradientBrush));
CHwLinearGradientBrush(
__in_ecount(1) IMILPoolManager *pManager,
__in_ecount(1) CD3DDeviceLevel1 *pDevice
);
~CHwLinearGradientBrush();
// IMILCacheableResource methods
override bool IsValid() const;
// CHwCacheablePoolBrush methods
override virtual HRESULT SetBrushAndContext(
__inout_ecount(1) CMILBrush *pBrush,
__in_ecount(1) const CHwBrushContext &hwBrushContext
);
// IHwPrimaryColorSource methods
override virtual HRESULT SendOperations(
__inout_ecount(1) CHwPipelineBuilder *pBuilder
);
// CHwLinearGradientBrush methods
HRESULT GetHwTexturedColorSource(
__deref_out_ecount(1) CHwTexturedColorSource ** const ppColorSource
);
protected:
HRESULT SetBrushAndContextInternal(
__inout_ecount(1) CMILBrush *pBrush,
__in_ecount(1) const CHwBrushContext &hwBrushContext
);
private:
UINT m_uCachedUniquenessToken; // uniqueness token for cached linear
// gradient brush
protected:
// Linear Gradient Color Source
CHwLinearGradientColorSource *m_pLinGradSource;
};
| 862 |
482 |
<reponame>m7onov/pgjdbc-ng
package com.impossibl.jdbc.spy;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Arrays;
import java.util.Properties;
import java.util.logging.Logger;
public class SpyDriver implements Driver {
private static SpyDriver registered;
static {
try {
registered = new SpyDriver();
DriverManager.registerDriver(registered);
}
catch (SQLException e) {
}
}
private String getTargetDriverUrl(String url) {
return "jdbc" + url.substring(8);
}
private Driver getTargetDriver(String url) throws SQLException {
return DriverManager.getDriver(getTargetDriverUrl(url));
}
@Override
public Connection connect(String url, Properties info) throws SQLException {
if (!url.startsWith("jdbc:spy")) return null;
Driver driver = getTargetDriver(url);
String spyFactoryClassName =
info.getProperty("spy.factory", System.getProperty("spy.factory", TracerFactory.class.getName()));
info.remove("spy.factory");
ListenerFactory spyFactory;
try {
Class<?> spyFactoryClass = Class.forName(spyFactoryClassName);
spyFactory = (ListenerFactory) spyFactoryClass.getConstructor().newInstance();
}
catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new SQLException("SPY: Unable to instantiate Spy ListenerFactory: " + spyFactoryClassName, e);
}
ConnectionListener connectionListener = spyFactory.newConnectionListener(info);
Connection connection = driver.connect(getTargetDriverUrl(url), info);
return new ConnectionRelay(connection, connectionListener);
}
@Override
public boolean acceptsURL(String url) throws SQLException {
return url.startsWith("jdbc:spy") && getTargetDriver(url).acceptsURL(getTargetDriverUrl(url));
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
DriverPropertyInfo[] propertyInfos = getTargetDriver(url).getPropertyInfo(url, info);
propertyInfos = Arrays.copyOf(propertyInfos, propertyInfos.length + 1);
propertyInfos[propertyInfos.length - 1] = new DriverPropertyInfo("spy.trace.url", info.getProperty("spy.trace.url"));
return propertyInfos;
}
@Override
public int getMajorVersion() {
return 1;
}
@Override
public int getMinorVersion() {
return 0;
}
@Override
public boolean jdbcCompliant() {
return false;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
}
| 905 |
1,916 |
/* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKcommon *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2010-12 Stanford University and the Authors. *
* Authors: <NAME> *
* Contributors: *
* *
* 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 "SimTKcommon.h"
#include "SimTKcommon/Testing.h"
#include "SimTKcommon/internal/Xml.h"
#include <iostream>
#include <string>
#include <cstdio>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::printf;
using namespace SimTK;
// This example is from Wikipedia's XML entry.
const char* xmlPainting =
"<?xml version='1.0' encoding='UTF-8'?>\n"
"<!-- a top-level comment -->\n"
"<!-- a multiline\n comment\n third line -->\n"
" \n" // line should be ignored
"but something like this is top level text and will need to get \n"
"moved into a new '_Root' element\n"
"<painting artist='Raphael' artist='metoo'>\n"
" <img src=\"madonna.jpg\" alt='<NAME>, by Raphael'/>\n"
" <!-- What follows is a so-called 'caption' -->\n"
" <caption>This is Raphael's \"Foligno\" Madonna, painted in\n"
" <date>1511</date>-<date>1512</date>.\n"
" <![CDATA[some non-Unicode text]]>\n"
" < !SOMETHING but this tag is unknown> \n"
" </caption>\n"
" This part is just plain old text.\n"
" As is this \"quoted\" thing.\n"
"</painting>\n"
"<!whazzis unknown junk>\n"
"<!-- final comment -->";
const char* xmlPlainTextFile =
"That is, the first line should be a declaration, most commonly exactly the\n"
"characters shown above, without the \"standalone\" attribute which will\n"
"default to \"yes\" anyway. If we don't see a declaration when reading an XML\n"
"document, we'll assume we read the one above. Then the document should contain\n"
"exactly one top-level (root) element representing the type of document &\n"
"document-level attributes.\n";
const char* xmlUnclosedComment =
"<?xml version='1.0' encoding='UTF-8'?>\n"
" <!-- What follows is a so-called 'caption' ->\n" // UNCLOSED!
"<!whazzis unknown junk>";
const char* xmlJustAComment =
"<!-- this is the entire contents -->\n";
const char* xmlEmpty = " \n \n \t "; // white space only
static void showElement(Xml::Element elt, const String& indent="") {
cout << indent << "ELEMENT WITH TAG '" << elt.getElementTag() << "':\n";
// Show attributes
Xml::attribute_iterator ap = elt.attribute_begin();
for (; ap != elt.attribute_end(); ++ap)
cout << indent << " ATTR '" << ap->getName() << "'='"
<< ap->getValue() << "'\n";
// Show all contents
Xml::node_iterator p = elt.node_begin();
for (; p != elt.node_end(); ++p) {
cout << indent << p->getNodeTypeAsString() << endl;
if (p->getNodeType() == Xml::ElementNode)
showElement(Xml::Element::getAs(*p), indent + " ");
}
cout << indent << "END OF ELEMENT.\n";
}
void testXmlFromString() {
Xml::Document fromString;
fromString.readFromString(xmlJustAComment);
cout << "Just a comment: '" << fromString << "'\n";
fromString.readFromString(xmlPlainTextFile);
cout << "Plain text file: '" << fromString << "'\n";
// Note that the "condense white space" setting is global, not
// document-specific.
Xml::Document preserveWhite;
Xml::Document::setXmlCondenseWhiteSpace(false);
SimTK_TEST(!Xml::Document::isXmlWhiteSpaceCondensed());
preserveWhite.readFromString(xmlPlainTextFile);
cout << "Plain text file with white space preserved (raw): "
<< preserveWhite.getRootElement().getValue() << "\n";
cout << "... (formatted with condense=false): "
<< preserveWhite << "\n";
Xml::Document::setXmlCondenseWhiteSpace(true);
cout << "... (formatted with condense=true): "
<< preserveWhite << "\n";
SimTK_TEST_MUST_THROW(fromString.readFromString(xmlEmpty));
SimTK_TEST_MUST_THROW(fromString.readFromString(xmlUnclosedComment));
fromString.readFromString(String(xmlPainting));
cout << "Painting: '" << fromString << "'\n";
cout << "Doc type is: " << fromString.getRootTag() << endl;
cout << " version: " << fromString.getXmlVersion() << endl;
cout << " encoding: " << fromString.getXmlEncoding() << endl;
cout << " standalone: "
<< String(fromString.getXmlIsStandalone() ? "yes" : "no") << endl;
cout << "All nodes in doc:\n";
Xml::node_iterator np = fromString.node_begin();
for (; np != fromString.node_end(); ++np)
cout << " " << np->getNodeTypeAsString() << endl;
Xml::Element root = fromString.getRootElement();
cout << "hasNode()=" << root.hasNode() << endl;
cout << "hasNode(Comment)=" << root.hasNode(Xml::CommentNode) << endl;
cout << "hasNode(Unknown)=" << root.hasNode(Xml::UnknownNode) << endl;
showElement(root);
Xml::node_iterator p = root.node_begin(Xml::NoJunkNodes);
for (; p != root.node_end(); ++p)
cout << p->getNodeTypeAsString() << endl;
cout << "Caption elements:\n";
Xml::element_iterator ep(root.element_begin("caption"));
for (; ep != root.element_end(); ++ep)
cout << ep->getNodeTypeAsString() << ": <" << ep->getElementTag()
<< ">" << endl;
cout << "All elements:\n";
Array_<Xml::Element> all = root.getAllElements();
for (unsigned i=0; i < all.size(); ++i)
cout << "<" << all[i].getElementTag() << ">" << endl;
Array_<Xml::Node> allNodes(root.node_begin(Xml::NoJunkNodes),
root.node_end());
for (unsigned i=0; i < allNodes.size(); ++i)
cout << "Node " << allNodes[i].getNodeTypeAsString() << endl;
String prettyString, compactString;
fromString.writeToString(prettyString);
cout << "String pretty: " << prettyString.size()
<< "\n'" << prettyString << "'\n";
fromString.writeToString(compactString, true); // compact
cout << "String compact: " << compactString.size()
<< "\n'" << compactString << "'\n";
SimTK_TEST(compactString.size() < prettyString.size());
cout << "painting.allNode=" << root.getRequiredElement("painting")
.getAllNodes() << endl;
cout << "painting.img.allAttr=" <<
root.getRequiredElement("painting").getRequiredElement("img")
.getAllAttributes() << endl;
//fromString.writeToFile("TestXml.xml");
//Xml ex("TestXml.xml");
//cout << "Document tag: " << ex.getDocumentTag() << endl;
//for (Xml::nodu;e_iterator xp=ex.node_begin(); xp != ex.node_end(); ++xp)
// cout << "Node type: " << xp->getNodeTypeAsString() << endl;
//PolygonalMesh mesh;
//mesh.loadVtpFile("arm_r_humerus.vtp");
//cout << "num vertices=" << mesh.getNumVertices() << " faces="
// << mesh.getNumFaces() << endl;
}
void testXmlFromScratch() {
Xml::Document scratch;
scratch.setRootTag("MyDoc");
cout << scratch;
Xml::Comment c("This is a comment.");
Xml::Unknown u("!GODONLY knows what this is!!");
Xml::Text t("This is some\ntext on two lines with trailing blanks ");
Xml::Element e("elementTag");
// We're never going to use this one so its heap space will
// leak if we don't explicitly call clearOrphan().
Xml::Element neverMind("neverMind");
cout << "initially e='" << e.getValue() << "'" << endl;
e.updValue() += "AVALUE:";
cout << "then e='" << e.getValue() << "'" << endl;
e.setAttributeValue("attr1", String(Vec2(9,-9)));
cout << "attr1 is " << e.getRequiredAttributeValueAs<Vec2>("attr1") << endl;
cout << "isOrphan? " << String(c.isOrphan()) << ":" << c;
cout << "isOrphan? " << String(u.isOrphan()) << ":" << u;
cout << "isOrphan? " << String(t.isOrphan()) << ":" << t;
cout << "isOrphan? " << String(e.isOrphan()) << ":" << e;
e.setValue("this is the only value");
e.updValue() += " (but then I added this)";
cout << "e value=" << e.getValue() << endl;
cout << "e = " << e << endl;
e.setValue("9 10 -3.2e-4");
cout << "e value=" << e.getValueAs< Array_<float> >() << endl;
cout << "e = " << e << endl;
scratch.insertTopLevelNodeAfter(scratch.node_begin(), c);
cout << "isOrphan? " << String(c.isOrphan()) << ":" << c;
cout << scratch;
scratch.insertTopLevelNodeBefore(scratch.node_begin(Xml::ElementNode), u);
cout << "isOrphan? " << String(u.isOrphan()) << ":" << u;
cout << scratch;
scratch.insertTopLevelNodeBefore(scratch.node_begin(),
Xml::Comment("This should be at the top of the file, except declaration."));
cout << scratch;
Xml::Document scratch2;
scratch2 = scratch; // deep copy
scratch.eraseTopLevelNode(scratch.node_begin());
cout << "First node gone (scratch)?\n" << scratch;
cout << "First node still there (scratch2)?\n" << scratch2;
Xml::Element e2("anotherElt", Vec3(.1,.2,.3));
cout << e2;
e.insertNodeAfter(e.element_end(), e2);
cout << "now owns anotherElt:\n" << e;
Xml::Element root = scratch.getRootElement();
root.insertNodeAfter(root.node_begin(), e);
cout << scratch;
scratch.setIndentString("..");
cout << scratch;
Xml::Element ecopy = e.clone();
ecopy.setElementTag("elementTagCopy");
cout << "COPY of e: " << ecopy;
//scratch.writeToFile("scratch.xml");
e.eraseNode(e.element_begin("anotherElt"));
cout << "in-place removal of anotherElt from e: " << scratch;
cout << "COPY of e: " << ecopy;
root.insertNodeAfter(root.element_begin("elementTag"), ecopy);
cout << "After copy insert, scratch=" << scratch;
Xml::Node extract = root.removeNode(root.element_begin("elementTagCopy"));
cout << "Extracted copy: " << extract << endl;
cout << "Now scratch=" << scratch << endl;
cout << "Duplicate scratch=" << Xml::Document(scratch) << endl;
neverMind.clearOrphan();
}
#define SHOWIT(something) \
cout << String(#something) << String("'") << something << String("'\n")
void testStringConvert() {
SimTK_TEST(convertStringTo<int>(" 239\n ")==239);
SimTK_TEST(convertStringTo<String>(" lunch box\n") == " lunch box\n");
SimTK_TEST(convertStringTo<std::string>(" lunch box\n") == " lunch box\n");
SimTK_TEST(convertStringTo<int>("1234")==1234);
SimTK_TEST(convertStringTo<unsigned>("01234")==1234);
SimTK_TEST(convertStringTo<float>("1234.5")==1234.5);
SimTK_TEST_MUST_THROW(convertStringTo<char*>(" lunch box\n"));
SimTK_TEST_MUST_THROW(convertStringTo<int>(" 234 j"));
SimTK_TEST_MUST_THROW(convertStringTo<int>("345.5"));
SimTK_TEST(convertStringTo< std::complex<double> >("(-4,22)")
==std::complex<double>(-4,22));
SimTK_TEST(convertStringTo< Vec3 >("1 2 3") == Vec3(1,2,3));
SimTK_TEST(convertStringTo< Vec3 >("1, 2 , 3") == Vec3(1,2,3));
SimTK_TEST(convertStringTo< Vec3 >("[ -3 , 5, 6 ] ")== Vec3(-3,5,6));
SimTK_TEST(convertStringTo< Vec3 >("( -3 5 -6 ) ")== Vec3(-3,5,-6));
SimTK_TEST(convertStringTo< Vec3 >(" ~ [ -3 , 5, 6 ] ")== Vec3(-3,5,6));
SimTK_TEST(convertStringTo< Vec3 >("~( -3 5 -6 ) ")== Vec3(-3,5,-6));
SimTK_TEST_MUST_THROW(convertStringTo< Vec3 >("( -3 5 -6 ] "));
SimTK_TEST_MUST_THROW(convertStringTo< Vec3 >(" -3 5 -6 ] "));
SimTK_TEST_MUST_THROW(convertStringTo< Vec3 >(" ~ -3 5 -6 "));
typedef Vec<2,std::complex<float> > fCVec2;
SimTK_TEST(convertStringTo<fCVec2>("[(1,2) (3,4)]")
== fCVec2(std::complex<float>(1,2), std::complex<float>(3,4)));
Array_<int> a = convertStringTo< Array_<int> >("1 2 3 4");
Array_<float> af(2);
SimTK_TEST_MUST_THROW( // because ArrayView_ is fixed size (2)
String(" -.25, .5, 29.2e4 ").convertTo<ArrayView_<float> >(af));
// But this should work because an Array_ can be resized.
String(" -.25, .5, 29.2e4 ").convertTo<Array_<float> >(af);
SimTK_TEST(af[0]==-.25 && af[1]==.5 && af[2]==292000);
}
int main() {
cout << "Path of this executable: '" << Pathname::getThisExecutablePath() << "'\n";
cout << "Executable directory: '" << Pathname::getThisExecutableDirectory() << "'\n";
cout << "Current working directory: '" << Pathname::getCurrentWorkingDirectory() << "'\n";
SimTK_START_TEST("TestXml");
SimTK_SUBTEST(testStringConvert);
SimTK_SUBTEST(testXmlFromString);
SimTK_SUBTEST(testXmlFromScratch);
SimTK_END_TEST();
}
| 5,746 |
995 |
// Copyright (c) 2018-2019
// <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// The authors gratefully acknowledge the support of
// Fraunhofer and Google in producing this work
// which started as a Google Summer of Code project.
//
/// \file tensor.hpp Definition for the tensor template class
#ifndef BOOST_UBLAS_TENSOR_IMPL_HPP
#define BOOST_UBLAS_TENSOR_IMPL_HPP
#include <boost/config.hpp>
#include <initializer_list>
#include "algorithms.hpp"
#include "expression.hpp"
#include "expression_evaluation.hpp"
#include "extents.hpp"
#include "strides.hpp"
#include "index.hpp"
namespace boost { namespace numeric { namespace ublas {
template<class T, class F, class A>
class tensor;
template<class T, class F, class A>
class matrix;
template<class T, class A>
class vector;
///** \brief Base class for Tensor container models
// *
// * it does not model the Tensor concept but all derived types should.
// * The class defines a common base type and some common interface for all
// * statically derived Tensor classes
// * We implement the casts to the statically derived type.
// */
//template<class C>
//class tensor_container:
// public detail::tensor_expression<C>
//{
//public:
// static const unsigned complexity = 0;
// typedef C container_type;
// typedef tensor_tag type_category;
// BOOST_UBLAS_INLINE
// const container_type &operator () () const {
// return *static_cast<const container_type *> (this);
// }
// BOOST_UBLAS_INLINE
// container_type &operator () () {
// return *static_cast<container_type *> (this);
// }
//};
/** @brief A dense tensor of values of type \c T.
*
* For a \f$n\f$-dimensional tensor \f$v\f$ and \f$0\leq i < n\f$ every element \f$v_i\f$ is mapped
* to the \f$i\f$-th element of the container. A storage type \c A can be specified which defaults to \c unbounded_array.
* Elements are constructed by \c A, which need not initialise their value.
*
* @tparam T type of the objects stored in the tensor (like int, double, complex,...)
* @tparam A The type of the storage array of the tensor. Default is \c unbounded_array<T>. \c <bounded_array<T> and \c std::vector<T> can also be used
*/
template<class T, class F = first_order, class A = std::vector<T,std::allocator<T>> >
class tensor:
public detail::tensor_expression<tensor<T, F, A>,tensor<T, F, A>>
{
static_assert( std::is_same<F,first_order>::value ||
std::is_same<F,last_order >::value, "boost::numeric::tensor template class only supports first- or last-order storage formats.");
using self_type = tensor<T, F, A>;
public:
template<class derived_type>
using tensor_expression_type = detail::tensor_expression<self_type,derived_type>;
template<class derived_type>
using matrix_expression_type = matrix_expression<derived_type>;
template<class derived_type>
using vector_expression_type = vector_expression<derived_type>;
using super_type = tensor_expression_type<self_type>;
// static_assert(std::is_same_v<tensor_expression_type<self_type>, detail::tensor_expression<tensor<T,F,A>,tensor<T,F,A>>>, "tensor_expression_type<self_type>");
using array_type = A;
using layout_type = F;
using size_type = typename array_type::size_type;
using difference_type = typename array_type::difference_type;
using value_type = typename array_type::value_type;
using reference = typename array_type::reference;
using const_reference = typename array_type::const_reference;
using pointer = typename array_type::pointer;
using const_pointer = typename array_type::const_pointer;
using iterator = typename array_type::iterator;
using const_iterator = typename array_type::const_iterator;
using reverse_iterator = typename array_type::reverse_iterator;
using const_reverse_iterator = typename array_type::const_reverse_iterator;
using tensor_temporary_type = self_type;
using storage_category = dense_tag;
using strides_type = basic_strides<std::size_t,layout_type>;
using extents_type = shape;
using matrix_type = matrix<value_type,layout_type,array_type>;
using vector_type = vector<value_type,array_type>;
/** @brief Constructs a tensor.
*
* @note the tensor is empty.
* @note the tensor needs to reshaped for further use.
*
*/
BOOST_UBLAS_INLINE
constexpr tensor ()
: tensor_expression_type<self_type>() // container_type
, extents_()
, strides_()
, data_()
{
}
/** @brief Constructs a tensor with an initializer list
*
* By default, its elements are initialized to 0.
*
* @code tensor<float> A{4,2,3}; @endcode
*
* @param l initializer list for setting the dimension extents of the tensor
*/
explicit BOOST_UBLAS_INLINE
tensor (std::initializer_list<size_type> l)
: tensor_expression_type<self_type>()
, extents_ (std::move(l))
, strides_ (extents_)
, data_ (extents_.product())
{
}
/** @brief Constructs a tensor with a \c shape
*
* By default, its elements are initialized to 0.
*
* @code tensor<float> A{extents{4,2,3}}; @endcode
*
* @param s initial tensor dimension extents
*/
explicit BOOST_UBLAS_INLINE
tensor (extents_type const& s)
: tensor_expression_type<self_type>() //tensor_container<self_type>()
, extents_ (s)
, strides_ (extents_)
, data_ (extents_.product())
{}
/** @brief Constructs a tensor with a \c shape and initiates it with one-dimensional data
*
* @code tensor<float> A{extents{4,2,3}, array }; @endcode
*
*
* @param s initial tensor dimension extents
* @param a container of \c array_type that is copied according to the storage layout
*/
BOOST_UBLAS_INLINE
tensor (extents_type const& s, const array_type &a)
: tensor_expression_type<self_type>() //tensor_container<self_type>()
, extents_ (s)
, strides_ (extents_)
, data_ (a)
{
if(this->extents_.product() != this->data_.size())
throw std::runtime_error("Error in boost::numeric::ublas::tensor: size of provided data and specified extents do not match.");
}
/** @brief Constructs a tensor using a shape tuple and initiates it with a value.
*
* @code tensor<float> A{extents{4,2,3}, 1 }; @endcode
*
* @param e initial tensor dimension extents
* @param i initial value of all elements of type \c value_type
*/
BOOST_UBLAS_INLINE
tensor (extents_type const& e, const value_type &i)
: tensor_expression_type<self_type>() //tensor_container<self_type> ()
, extents_ (e)
, strides_ (extents_)
, data_ (extents_.product(), i)
{}
/** @brief Constructs a tensor from another tensor
*
* @param v tensor to be copied.
*/
BOOST_UBLAS_INLINE
tensor (const tensor &v)
: tensor_expression_type<self_type>()
, extents_ (v.extents_)
, strides_ (v.strides_)
, data_ (v.data_ )
{}
/** @brief Constructs a tensor from another tensor
*
* @param v tensor to be moved.
*/
BOOST_UBLAS_INLINE
tensor (tensor &&v)
: tensor_expression_type<self_type>() //tensor_container<self_type> ()
, extents_ (std::move(v.extents_))
, strides_ (std::move(v.strides_))
, data_ (std::move(v.data_ ))
{}
/** @brief Constructs a tensor with a matrix
*
* \note Initially the tensor will be two-dimensional.
*
* @param v matrix to be copied.
*/
BOOST_UBLAS_INLINE
tensor (const matrix_type &v)
: tensor_expression_type<self_type>()
, extents_ ()
, strides_ ()
, data_ (v.data())
{
if(!data_.empty()){
extents_ = extents_type{v.size1(),v.size2()};
strides_ = strides_type(extents_);
}
}
/** @brief Constructs a tensor with a matrix
*
* \note Initially the tensor will be two-dimensional.
*
* @param v matrix to be moved.
*/
BOOST_UBLAS_INLINE
tensor (matrix_type &&v)
: tensor_expression_type<self_type>()
, extents_ {}
, strides_ {}
, data_ {}
{
if(v.size1()*v.size2() != 0){
extents_ = extents_type{v.size1(),v.size2()};
strides_ = strides_type(extents_);
data_ = std::move(v.data());
}
}
/** @brief Constructs a tensor using a \c vector
*
* @note It is assumed that vector is column vector
* @note Initially the tensor will be one-dimensional.
*
* @param v vector to be copied.
*/
BOOST_UBLAS_INLINE
tensor (const vector_type &v)
: tensor_expression_type<self_type>()
, extents_ ()
, strides_ ()
, data_ (v.data())
{
if(!data_.empty()){
extents_ = extents_type{data_.size(),1};
strides_ = strides_type(extents_);
}
}
/** @brief Constructs a tensor using a \c vector
*
* @param v vector to be moved.
*/
BOOST_UBLAS_INLINE
tensor (vector_type &&v)
: tensor_expression_type<self_type>()
, extents_ {}
, strides_ {}
, data_ {}
{
if(v.size() != 0){
extents_ = extents_type{v.size(),1};
strides_ = strides_type(extents_);
data_ = std::move(v.data());
}
}
/** @brief Constructs a tensor with another tensor with a different layout
*
* @param other tensor with a different layout to be copied.
*/
BOOST_UBLAS_INLINE
template<class other_layout>
tensor (const tensor<value_type, other_layout> &other)
: tensor_expression_type<self_type> ()
, extents_ (other.extents())
, strides_ (other.extents())
, data_ (other.extents().product())
{
copy(this->rank(), this->extents().data(),
this->data(), this->strides().data(),
other.data(), other.strides().data());
}
/** @brief Constructs a tensor with an tensor expression
*
* @code tensor<float> A = B + 3 * C; @endcode
*
* @note type must be specified of tensor must be specified.
* @note dimension extents are extracted from tensors within the expression.
*
* @param expr tensor expression
*/
BOOST_UBLAS_INLINE
template<class derived_type>
tensor (const tensor_expression_type<derived_type> &expr)
: tensor_expression_type<self_type> ()
, extents_ ( detail::retrieve_extents(expr) )
, strides_ ( extents_ )
, data_ ( extents_.product() )
{
static_assert( detail::has_tensor_types<self_type, tensor_expression_type<derived_type>>::value,
"Error in boost::numeric::ublas::tensor: expression does not contain a tensor. cannot retrieve shape.");
detail::eval( *this, expr );
}
/** @brief Constructs a tensor with a matrix expression
*
* @code tensor<float> A = B + 3 * C; @endcode
*
* @note matrix expression is evaluated and pushed into a temporary matrix before assignment.
* @note extents are automatically extracted from the temporary matrix
*
* @param expr matrix expression
*/
BOOST_UBLAS_INLINE
template<class derived_type>
tensor (const matrix_expression_type<derived_type> &expr)
: tensor( matrix_type ( expr ) )
{
}
/** @brief Constructs a tensor with a vector expression
*
* @code tensor<float> A = b + 3 * b; @endcode
*
* @note matrix expression is evaluated and pushed into a temporary matrix before assignment.
* @note extents are automatically extracted from the temporary matrix
*
* @param expr vector expression
*/
BOOST_UBLAS_INLINE
template<class derived_type>
tensor (const vector_expression_type<derived_type> &expr)
: tensor( vector_type ( expr ) )
{
}
/** @brief Evaluates the tensor_expression and assigns the results to the tensor
*
* @code A = B + C * 2; @endcode
*
* @note rank and dimension extents of the tensors in the expressions must conform with this tensor.
*
* @param expr expression that is evaluated.
*/
BOOST_UBLAS_INLINE
template<class derived_type>
tensor &operator = (const tensor_expression_type<derived_type> &expr)
{
detail::eval(*this, expr);
return *this;
}
tensor& operator=(tensor other)
{
swap (*this, other);
return *this;
}
tensor& operator=(const_reference v)
{
std::fill(this->begin(), this->end(), v);
return *this;
}
/** @brief Returns true if the tensor is empty (\c size==0) */
BOOST_UBLAS_INLINE
bool empty () const {
return this->data_.empty();
}
/** @brief Returns the size of the tensor */
BOOST_UBLAS_INLINE
size_type size () const {
return this->data_.size ();
}
/** @brief Returns the size of the tensor */
BOOST_UBLAS_INLINE
size_type size (size_type r) const {
return this->extents_.at(r);
}
/** @brief Returns the number of dimensions/modes of the tensor */
BOOST_UBLAS_INLINE
size_type rank () const {
return this->extents_.size();
}
/** @brief Returns the number of dimensions/modes of the tensor */
BOOST_UBLAS_INLINE
size_type order () const {
return this->extents_.size();
}
/** @brief Returns the strides of the tensor */
BOOST_UBLAS_INLINE
strides_type const& strides () const {
return this->strides_;
}
/** @brief Returns the extents of the tensor */
BOOST_UBLAS_INLINE
extents_type const& extents () const {
return this->extents_;
}
/** @brief Returns a \c const reference to the container. */
BOOST_UBLAS_INLINE
const_pointer data () const {
return this->data_.data();
}
/** @brief Returns a \c const reference to the container. */
BOOST_UBLAS_INLINE
pointer data () {
return this->data_.data();
}
/** @brief Element access using a single index.
*
* @code auto a = A[i]; @endcode
*
* @param i zero-based index where 0 <= i < this->size()
*/
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
return this->data_[i];
}
/** @brief Element access using a single index.
*
*
* @code A[i] = a; @endcode
*
* @param i zero-based index where 0 <= i < this->size()
*/
BOOST_UBLAS_INLINE
reference operator [] (size_type i)
{
return this->data_[i];
}
/** @brief Element access using a multi-index or single-index.
*
*
* @code auto a = A.at(i,j,k); @endcode or
* @code auto a = A.at(i); @endcode
*
* @param i zero-based index where 0 <= i < this->size() if sizeof...(is) == 0, else 0<= i < this->size(0)
* @param is zero-based indices where 0 <= is[r] < this->size(r) where 0 < r < this->rank()
*/
template<class ... size_types>
BOOST_UBLAS_INLINE
const_reference at (size_type i, size_types ... is) const {
if constexpr (sizeof...(is) == 0)
return this->data_[i];
else
return this->data_[detail::access<0ul>(size_type(0),this->strides_,i,std::forward<size_types>(is)...)];
}
/** @brief Element access using a multi-index or single-index.
*
*
* @code A.at(i,j,k) = a; @endcode or
* @code A.at(i) = a; @endcode
*
* @param i zero-based index where 0 <= i < this->size() if sizeof...(is) == 0, else 0<= i < this->size(0)
* @param is zero-based indices where 0 <= is[r] < this->size(r) where 0 < r < this->rank()
*/
BOOST_UBLAS_INLINE
template<class ... size_types>
reference at (size_type i, size_types ... is) {
if constexpr (sizeof...(is) == 0)
return this->data_[i];
else
return this->data_[detail::access<0ul>(size_type(0),this->strides_,i,std::forward<size_types>(is)...)];
}
/** @brief Element access using a single index.
*
*
* @code A(i) = a; @endcode
*
* @param i zero-based index where 0 <= i < this->size()
*/
BOOST_UBLAS_INLINE
const_reference operator()(size_type i) const {
return this->data_[i];
}
/** @brief Element access using a single index.
*
* @code A(i) = a; @endcode
*
* @param i zero-based index where 0 <= i < this->size()
*/
BOOST_UBLAS_INLINE
reference operator()(size_type i){
return this->data_[i];
}
/** @brief Generates a tensor index for tensor contraction
*
*
* @code auto Ai = A(_i,_j,k); @endcode
*
* @param i placeholder
* @param is zero-based indices where 0 <= is[r] < this->size(r) where 0 < r < this->rank()
*/
BOOST_UBLAS_INLINE
template<std::size_t I, class ... index_types>
decltype(auto) operator() (index::index_type<I> p, index_types ... ps) const
{
constexpr auto N = sizeof...(ps)+1;
if( N != this->rank() )
throw std::runtime_error("Error in boost::numeric::ublas::operator(): size of provided index_types does not match with the rank.");
return std::make_pair( std::cref(*this), std::make_tuple( p, std::forward<index_types>(ps)... ) );
}
/** @brief Reshapes the tensor
*
*
* (1) @code A.reshape(extents{m,n,o}); @endcode or
* (2) @code A.reshape(extents{m,n,o},4); @endcode
*
* If the size of this smaller than the specified extents than
* default constructed (1) or specified (2) value is appended.
*
* @note rank of the tensor might also change.
*
* @param e extents with which the tensor is reshaped.
* @param v value which is appended if the tensor is enlarged.
*/
BOOST_UBLAS_INLINE
void reshape (extents_type const& e, value_type v = value_type{})
{
this->extents_ = e;
this->strides_ = strides_type(this->extents_);
if(e.product() != this->size())
this->data_.resize (this->extents_.product(), v);
}
friend void swap(tensor& lhs, tensor& rhs) {
std::swap(lhs.data_ , rhs.data_ );
std::swap(lhs.extents_, rhs.extents_);
std::swap(lhs.strides_, rhs.strides_);
}
/// \brief return an iterator on the first element of the tensor
BOOST_UBLAS_INLINE
const_iterator begin () const {
return data_.begin ();
}
/// \brief return an iterator on the first element of the tensor
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return data_.cbegin ();
}
/// \brief return an iterator after the last element of the tensor
BOOST_UBLAS_INLINE
const_iterator end () const {
return data_.end();
}
/// \brief return an iterator after the last element of the tensor
BOOST_UBLAS_INLINE
const_iterator cend () const {
return data_.cend ();
}
/// \brief Return an iterator on the first element of the tensor
BOOST_UBLAS_INLINE
iterator begin () {
return data_.begin();
}
/// \brief Return an iterator at the end of the tensor
BOOST_UBLAS_INLINE
iterator end () {
return data_.end();
}
/// \brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return data_.rbegin();
}
/// \brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return data_.crbegin();
}
/// \brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return data_.rend();
}
/// \brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return data_.crend();
}
/// \brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)
BOOST_UBLAS_INLINE
reverse_iterator rbegin () {
return data_.rbegin();
}
/// \brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)
BOOST_UBLAS_INLINE
reverse_iterator rend () {
return data_.rend();
}
#if 0
// -------------
// Serialization
// -------------
/// Serialize a tensor into and archive as defined in Boost
/// \param ar Archive object. Can be a flat file, an XML file or any other stream
/// \param file_version Optional file version (not yet used)
template<class Archive>
void serialize(Archive & ar, const unsigned int /* file_version */){
ar & serialization::make_nvp("data",data_);
}
#endif
private:
extents_type extents_;
strides_type strides_;
array_type data_;
};
}}} // namespaces
#endif
| 8,113 |
438 |
<reponame>eaton-lab/toyplot
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
"""Functionality for performing unit conversions.
"""
import numbers
import re
def convert(value, target, default=None, reference=None):
"""Convert quantities using real-world units.
Supported unit abbreviations include: centimeter, centimeters, cm,
decimeter, decimeters, dm, in, inch, inches, m, meter, meters, mm,
millimeter, millimeters, pc, pica, picas, point, points, pt, pixel, pixels,
and px.
Relative quantities can be specified using %.
Parameters
----------
value: number, string or (number, string) tuple
Value to be converted. The value may be a number (in which case the
`default` parameter must specify the default unit of measure), a string
containing a number and unit abbreviation, or a (value, units) tuple.
target: string
Unit of measure to convert to.
default: optional string
Default unit of measure to use when `value` is a plain number, or when
`reference` has been specified.
reference: optional number
When the caller specifies a relative measure using % as the unit abbreviation,
the returned value will equal `value` * 0.01 * `reference`. Note that the
reference *must* be specified in `target` units.
Returns
-------
Returns `value` converted to the `target` units, as a floating point number.
"""
if isinstance(value, numbers.Number):
if value == 0:
return 0
if default is None:
raise ValueError("Value doesn't contain units, and no default units specified.")
value = (value, default)
elif isinstance(value, str):
if value == "0":
return 0
value, units = re.match(r"([^a-zA-Z%]+)([a-zA-Z%]+)\Z", value).groups()
value = (float(value), units)
if not isinstance(value, tuple):
raise ValueError("Value must be a number, string or (number, string) tuple.")
if not len(value) == 2:
raise ValueError("Value must be a number, string or (number, string) tuple.")
if not isinstance(value[0], numbers.Number):
raise ValueError("Value must be a number, string or (number, string) tuple.")
if not isinstance(value[1], str):
raise ValueError("Value must be a number, string or (number, string) tuple.")
value, units = value
units = units.lower()
if units == "%":
if reference is None:
raise ValueError("Relative values require a reference.")
return value * 0.01 * reference
if units not in convert._conversions:
raise ValueError("Unknown unit of measure: %s" % units)
target = target.lower()
if target not in convert._conversions:
raise ValueError("Unknown unit of measure: %s" % target)
return value * convert._conversions[units] / convert._conversions[target]
convert._conversions = {
"centimeter": 28.3464567,
"centimeters": 28.3464567,
"cm": 28.3464567,
"decimeter": 283.464567,
"decimeters": 283.464567,
"dm": 283.464567,
"in": 72.0,
"inch": 72.0,
"inches": 72.0,
"m": 2834.64567,
"meter": 2834.64567,
"meters": 2834.64567,
"millimeter": 2.83464567,
"millimeters": 2.83464567,
"mm": 2.83464567,
"pc": 12.0,
"pica": 12.0,
"picas": 12.0,
"pixel": 72.0 / 96.0,
"pixels": 72.0 / 96.0,
"point": 1.0,
"points": 1.0,
"pt": 1.0,
"px": 72.0 / 96.0,
}
| 1,351 |
521 |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <signal.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <syslog.h>
#include <getopt.h>
#include <pcap.h>
#define SNAPLEN 1600
/*
* FIXME: is there a way to detect the version of the libpcap library?
* Version 0.9 has pcap_inject; version 0.8 doesn't, but both report
* their version number as 2.4.
*/
#define HAVE_PCAP_INJECT 0
struct hijack {
pcap_t *pcap;
int fd;
int datalink;
int filtered;
unsigned long rx_count;
unsigned long tx_count;
};
struct hijack_listener {
struct sockaddr_un sun;
int fd;
};
struct hijack_options {
char interface[IF_NAMESIZE];
int daemonise;
};
static int daemonised = 0;
static int signalled = 0;
static void flag_signalled ( int signal __attribute__ (( unused )) ) {
signalled = 1;
}
#if ! HAVE_PCAP_INJECT
/**
* Substitute for pcap_inject(), if this version of libpcap doesn't
* have it. Will almost certainly only work under Linux.
*
*/
int pcap_inject ( pcap_t *pcap, const void *data, size_t len ) {
int fd;
char *errbuf = pcap_geterr ( pcap );
fd = pcap_get_selectable_fd ( pcap );
if ( fd < 0 ) {
snprintf ( errbuf, PCAP_ERRBUF_SIZE,
"could not get file descriptor" );
return -1;
}
if ( write ( fd, data, len ) != len ) {
snprintf ( errbuf, PCAP_ERRBUF_SIZE,
"could not write data: %s", strerror ( errno ) );
return -1;
}
return len;
}
#endif /* ! HAVE_PCAP_INJECT */
/**
* Log error message
*
*/
static __attribute__ (( format ( printf, 2, 3 ) )) void
logmsg ( int level, const char *format, ... ) {
va_list ap;
va_start ( ap, format );
if ( daemonised ) {
vsyslog ( ( LOG_DAEMON | level ), format, ap );
} else {
vfprintf ( stderr, format, ap );
}
va_end ( ap );
}
/**
* Open pcap device
*
*/
static int hijack_open ( const char *interface, struct hijack *hijack ) {
char errbuf[PCAP_ERRBUF_SIZE];
/* Open interface via pcap */
errbuf[0] = '\0';
hijack->pcap = pcap_open_live ( interface, SNAPLEN, 1, 0, errbuf );
if ( ! hijack->pcap ) {
logmsg ( LOG_ERR, "Failed to open %s: %s\n",
interface, errbuf );
goto err;
}
if ( errbuf[0] )
logmsg ( LOG_WARNING, "Warning: %s\n", errbuf );
/* Set capture interface to non-blocking mode */
if ( pcap_setnonblock ( hijack->pcap, 1, errbuf ) < 0 ) {
logmsg ( LOG_ERR, "Could not make %s non-blocking: %s\n",
interface, errbuf );
goto err;
}
/* Get file descriptor for select() */
hijack->fd = pcap_get_selectable_fd ( hijack->pcap );
if ( hijack->fd < 0 ) {
logmsg ( LOG_ERR, "Cannot get selectable file descriptor "
"for %s\n", interface );
goto err;
}
/* Get link layer type */
hijack->datalink = pcap_datalink ( hijack->pcap );
return 0;
err:
if ( hijack->pcap )
pcap_close ( hijack->pcap );
return -1;
}
/**
* Close pcap device
*
*/
static void hijack_close ( struct hijack *hijack ) {
pcap_close ( hijack->pcap );
}
/**
* Install filter for hijacked connection
*
*/
static int hijack_install_filter ( struct hijack *hijack,
char *filter ) {
struct bpf_program program;
/* Compile filter */
if ( pcap_compile ( hijack->pcap, &program, filter, 1, 0 ) < 0 ) {
logmsg ( LOG_ERR, "could not compile filter \"%s\": %s\n",
filter, pcap_geterr ( hijack->pcap ) );
goto err_nofree;
}
/* Install filter */
if ( pcap_setfilter ( hijack->pcap, &program ) < 0 ) {
logmsg ( LOG_ERR, "could not install filter \"%s\": %s\n",
filter, pcap_geterr ( hijack->pcap ) );
goto err;
}
logmsg ( LOG_INFO, "using filter \"%s\"\n", filter );
pcap_freecode ( &program );
return 0;
err:
pcap_freecode ( &program );
err_nofree:
return -1;
}
/**
* Set up filter for hijacked ethernet connection
*
*/
static int hijack_filter_ethernet ( struct hijack *hijack, const char *buf,
size_t len ) {
char filter[55]; /* see format string */
struct ether_header *ether_header = ( struct ether_header * ) buf;
unsigned char *hwaddr = ether_header->ether_shost;
if ( len < sizeof ( *ether_header ) )
return -1;
snprintf ( filter, sizeof ( filter ), "broadcast or multicast or "
"ether host %02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0],
hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5] );
return hijack_install_filter ( hijack, filter );
}
/**
* Set up filter for hijacked connection
*
*/
static int hijack_filter ( struct hijack *hijack, const char *buf,
size_t len ) {
switch ( hijack->datalink ) {
case DLT_EN10MB:
return hijack_filter_ethernet ( hijack, buf, len );
default:
logmsg ( LOG_ERR, "unsupported protocol %s: cannot filter\n",
( pcap_datalink_val_to_name ( hijack->datalink ) ?
pcap_datalink_val_to_name ( hijack->datalink ) :
"UNKNOWN" ) );
/* Return success so we don't get called again */
return 0;
}
}
/**
* Forward data from hijacker
*
*/
static ssize_t forward_from_hijacker ( struct hijack *hijack, int fd ) {
char buf[SNAPLEN];
ssize_t len;
/* Read packet from hijacker */
len = read ( fd, buf, sizeof ( buf ) );
if ( len < 0 ) {
logmsg ( LOG_ERR, "read from hijacker failed: %s\n",
strerror ( errno ) );
return -1;
}
if ( len == 0 )
return 0;
/* Set up filter if not already in place */
if ( ! hijack->filtered ) {
if ( hijack_filter ( hijack, buf, len ) == 0 )
hijack->filtered = 1;
}
/* Transmit packet to network */
if ( pcap_inject ( hijack->pcap, buf, len ) != len ) {
logmsg ( LOG_ERR, "write to hijacked port failed: %s\n",
pcap_geterr ( hijack->pcap ) );
return -1;
}
hijack->tx_count++;
return len;
};
/**
* Forward data to hijacker
*
*/
static ssize_t forward_to_hijacker ( int fd, struct hijack *hijack ) {
struct pcap_pkthdr *pkt_header;
const unsigned char *pkt_data;
ssize_t len;
/* Receive packet from network */
if ( pcap_next_ex ( hijack->pcap, &pkt_header, &pkt_data ) < 0 ) {
logmsg ( LOG_ERR, "read from hijacked port failed: %s\n",
pcap_geterr ( hijack->pcap ) );
return -1;
}
if ( pkt_header->caplen != pkt_header->len ) {
logmsg ( LOG_ERR, "read partial packet (%d of %d bytes)\n",
pkt_header->caplen, pkt_header->len );
return -1;
}
if ( pkt_header->caplen == 0 )
return 0;
len = pkt_header->caplen;
/* Write packet to hijacker */
if ( write ( fd, pkt_data, len ) != len ) {
logmsg ( LOG_ERR, "write to hijacker failed: %s\n",
strerror ( errno ) );
return -1;
}
hijack->rx_count++;
return len;
};
/**
* Run hijacker
*
*/
static int run_hijacker ( const char *interface, int fd ) {
struct hijack hijack;
fd_set fdset;
int max_fd;
ssize_t len;
logmsg ( LOG_INFO, "new connection for %s\n", interface );
/* Open connection to network */
memset ( &hijack, 0, sizeof ( hijack ) );
if ( hijack_open ( interface, &hijack ) < 0 )
goto err;
/* Do the forwarding */
max_fd = ( ( fd > hijack.fd ) ? fd : hijack.fd );
while ( 1 ) {
/* Wait for available data */
FD_ZERO ( &fdset );
FD_SET ( fd, &fdset );
FD_SET ( hijack.fd, &fdset );
if ( select ( ( max_fd + 1 ), &fdset, NULL, NULL, 0 ) < 0 ) {
logmsg ( LOG_ERR, "select failed: %s\n",
strerror ( errno ) );
goto err;
}
if ( FD_ISSET ( fd, &fdset ) ) {
len = forward_from_hijacker ( &hijack, fd );
if ( len < 0 )
goto err;
if ( len == 0 )
break;
}
if ( FD_ISSET ( hijack.fd, &fdset ) ) {
len = forward_to_hijacker ( fd, &hijack );
if ( len < 0 )
goto err;
if ( len == 0 )
break;
}
}
hijack_close ( &hijack );
logmsg ( LOG_INFO, "closed connection for %s\n", interface );
logmsg ( LOG_INFO, "received %ld packets, sent %ld packets\n",
hijack.rx_count, hijack.tx_count );
return 0;
err:
if ( hijack.pcap )
hijack_close ( &hijack );
return -1;
}
/**
* Open listener socket
*
*/
static int open_listener ( const char *interface,
struct hijack_listener *listener ) {
/* Create socket */
listener->fd = socket ( PF_UNIX, SOCK_SEQPACKET, 0 );
if ( listener->fd < 0 ) {
logmsg ( LOG_ERR, "Could not create socket: %s\n",
strerror ( errno ) );
goto err;
}
/* Bind to local filename */
listener->sun.sun_family = AF_UNIX,
snprintf ( listener->sun.sun_path, sizeof ( listener->sun.sun_path ),
"/var/run/hijack-%s", interface );
if ( bind ( listener->fd, ( struct sockaddr * ) &listener->sun,
sizeof ( listener->sun ) ) < 0 ) {
logmsg ( LOG_ERR, "Could not bind socket to %s: %s\n",
listener->sun.sun_path, strerror ( errno ) );
goto err;
}
/* Set as a listening socket */
if ( listen ( listener->fd, 0 ) < 0 ) {
logmsg ( LOG_ERR, "Could not listen to %s: %s\n",
listener->sun.sun_path, strerror ( errno ) );
goto err;
}
return 0;
err:
if ( listener->fd >= 0 )
close ( listener->fd );
return -1;
}
/**
* Listen on listener socket
*
*/
static int listen_for_hijackers ( struct hijack_listener *listener,
const char *interface ) {
int fd;
pid_t child;
int rc;
logmsg ( LOG_INFO, "Listening on %s\n", listener->sun.sun_path );
while ( ! signalled ) {
/* Accept new connection, interruptibly */
siginterrupt ( SIGINT, 1 );
siginterrupt ( SIGHUP, 1 );
fd = accept ( listener->fd, NULL, 0 );
siginterrupt ( SIGINT, 0 );
siginterrupt ( SIGHUP, 0 );
if ( fd < 0 ) {
if ( errno == EINTR ) {
continue;
} else {
logmsg ( LOG_ERR, "accept failed: %s\n",
strerror ( errno ) );
goto err;
}
}
/* Fork child process */
child = fork();
if ( child < 0 ) {
logmsg ( LOG_ERR, "fork failed: %s\n",
strerror ( errno ) );
goto err;
}
if ( child == 0 ) {
/* I am the child; run the hijacker */
rc = run_hijacker ( interface, fd );
close ( fd );
exit ( rc );
}
close ( fd );
}
logmsg ( LOG_INFO, "Stopped listening on %s\n",
listener->sun.sun_path );
return 0;
err:
if ( fd >= 0 )
close ( fd );
return -1;
}
/**
* Close listener socket
*
*/
static void close_listener ( struct hijack_listener *listener ) {
close ( listener->fd );
unlink ( listener->sun.sun_path );
}
/**
* Print usage
*
*/
static void usage ( char **argv ) {
logmsg ( LOG_ERR,
"Usage: %s [options]\n"
"\n"
"Options:\n"
" -h|--help Print this help message\n"
" -i|--interface intf Use specified network interface\n"
" -n|--nodaemon Run in foreground\n",
argv[0] );
}
/**
* Parse command-line options
*
*/
static int parse_options ( int argc, char **argv,
struct hijack_options *options ) {
static struct option long_options[] = {
{ "interface", 1, NULL, 'i' },
{ "nodaemon", 0, NULL, 'n' },
{ "help", 0, NULL, 'h' },
{ },
};
int c;
/* Set default options */
memset ( options, 0, sizeof ( *options ) );
strncpy ( options->interface, "eth0", sizeof ( options->interface ) );
options->daemonise = 1;
/* Parse command-line options */
while ( 1 ) {
int option_index = 0;
c = getopt_long ( argc, argv, "i:hn", long_options,
&option_index );
if ( c < 0 )
break;
switch ( c ) {
case 'i':
strncpy ( options->interface, optarg,
sizeof ( options->interface ) );
break;
case 'n':
options->daemonise = 0;
break;
case 'h':
usage( argv );
return -1;
case '?':
/* Unrecognised option */
return -1;
default:
logmsg ( LOG_ERR, "Unrecognised option '-%c'\n", c );
return -1;
}
}
/* Check there's nothing left over on the command line */
if ( optind != argc ) {
usage ( argv );
return -1;
}
return 0;
}
/**
* Daemonise
*
*/
static int daemonise ( const char *interface ) {
char pidfile[16 + IF_NAMESIZE + 4]; /* "/var/run/hijack-<intf>.pid" */
char pid[16];
int pidlen;
int fd = -1;
/* Daemonise */
if ( daemon ( 0, 0 ) < 0 ) {
logmsg ( LOG_ERR, "Could not daemonise: %s\n",
strerror ( errno ) );
goto err;
}
daemonised = 1; /* Direct messages to syslog now */
/* Open pid file */
snprintf ( pidfile, sizeof ( pidfile ), "/var/run/hijack-%s.pid",
interface );
fd = open ( pidfile, ( O_WRONLY | O_CREAT | O_TRUNC ),
( S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) );
if ( fd < 0 ) {
logmsg ( LOG_ERR, "Could not open %s for writing: %s\n",
pidfile, strerror ( errno ) );
goto err;
}
/* Write pid to file */
pidlen = snprintf ( pid, sizeof ( pid ), "%d\n", getpid() );
if ( write ( fd, pid, pidlen ) != pidlen ) {
logmsg ( LOG_ERR, "Could not write %s: %s\n",
pidfile, strerror ( errno ) );
goto err;
}
close ( fd );
return 0;
err:
if ( fd >= 0 )
close ( fd );
return -1;
}
int main ( int argc, char **argv ) {
struct hijack_options options;
struct hijack_listener listener;
struct sigaction sa;
/* Parse command-line options */
if ( parse_options ( argc, argv, &options ) < 0 )
exit ( 1 );
/* Set up syslog connection */
openlog ( basename ( argv[0] ), LOG_PID, LOG_DAEMON );
/* Set up listening socket */
if ( open_listener ( options.interface, &listener ) < 0 )
exit ( 1 );
/* Daemonise on demand */
if ( options.daemonise ) {
if ( daemonise ( options.interface ) < 0 )
exit ( 1 );
}
/* Avoid creating zombies */
memset ( &sa, 0, sizeof ( sa ) );
sa.sa_handler = SIG_IGN;
sa.sa_flags = SA_RESTART | SA_NOCLDWAIT;
if ( sigaction ( SIGCHLD, &sa, NULL ) < 0 ) {
logmsg ( LOG_ERR, "Could not set SIGCHLD handler: %s",
strerror ( errno ) );
exit ( 1 );
}
/* Set 'signalled' flag on SIGINT or SIGHUP */
sa.sa_handler = flag_signalled;
sa.sa_flags = SA_RESTART | SA_RESETHAND;
if ( sigaction ( SIGINT, &sa, NULL ) < 0 ) {
logmsg ( LOG_ERR, "Could not set SIGINT handler: %s",
strerror ( errno ) );
exit ( 1 );
}
if ( sigaction ( SIGHUP, &sa, NULL ) < 0 ) {
logmsg ( LOG_ERR, "Could not set SIGHUP handler: %s",
strerror ( errno ) );
exit ( 1 );
}
/* Listen for hijackers */
if ( listen_for_hijackers ( &listener, options.interface ) < 0 )
exit ( 1 );
close_listener ( &listener );
return 0;
}
| 5,834 |
365 |
<gh_stars>100-1000
import os
import build_utils
from build_utils import MINOS_ROOT
from minos_config import Log
from minos_config import TANK_DEFAULT_IP
from minos_config import TANK_DEFAULT_PORT
from minos_config import TANK_PREREQUISITE_PYTHON_LIBS
STOP_PROCESS_SCRIPT = os.getenv("STOP_PROCESS_SCRIPT")
TANK_ROOT = os.getenv("TANK_ROOT")
TANK_PID_FILE = os.getenv("TANK_PID_FILE")
def _build(args):
Log.print_info("Building tank server")
# Check and install prerequisite python libraries
Log.print_info("Check and install prerequisite python libraries")
build_utils.check_and_install_modules(TANK_PREREQUISITE_PYTHON_LIBS)
# Output build information
if args.tank_ip != TANK_DEFAULT_IP or args.tank_port != TANK_DEFAULT_PORT:
build_utils.output_build_info(args.component, 'tank_ip', args.tank_ip)
build_utils.output_build_info(args.component, 'tank_port', args.tank_port)
build_utils.output_build_info(args.component, 'build_status', 'success')
Log.print_info("The component %s is built successfully" % args.component)
def _do_start(args):
tank_ip = build_utils.get_build_info_option('tank', 'tank_ip')
tank_port = build_utils.get_build_info_option('tank', 'tank_port')
if tank_ip and tank_port:
args.tank_ip = tank_ip
args.tank_port = int(tank_port)
build_utils.start_daemon_process('Tank server', TANK_PID_FILE,
TANK_ROOT, './start_tank.sh', args.tank_ip, str(args.tank_port))
def _do_stop():
build_utils.stop_daemon_process('Tank server', TANK_PID_FILE,
TANK_ROOT, STOP_PROCESS_SCRIPT)
def start(args):
if not build_utils.get_build_info_option('tank', 'build_status') == 'success':
_build(args)
_do_start(args)
def stop(args):
_do_stop()
| 645 |
16,461 |
#import <AVFoundation/AVFoundation.h>
#import <ExpoModulesCore/EXViewManager.h>
#import <ExpoModulesCore/EXExportedModule.h>
#import <ExpoModulesCore/EXModuleRegistryConsumer.h>
#import <EXCamera/EXCamera.h>
@interface EXCameraManager : EXViewManager <EXModuleRegistryConsumer>
@end
| 99 |
1,872 |
<reponame>dragontamer8740/PixivUtil2
{
"body": {
"id": "685832",
"title": "■2019 11月 おまけ",
"coverImageUrl": "https://pixiv.pximg.net/c/1200x630_90_a2_g5/fanbox/public/images/post/685832/cover/hxpGNTfnFeTUz4tK8hlJbBZU.jpeg",
"feeRequired": 250,
"publishedDatetime": "2019-12-01T01:26:40+09:00",
"updatedDatetime": "2019-12-01T01:27:48+09:00",
"type": "file",
"body": {
"text": "あかいしですー\n2019年11月の支援者特典のおまけ没データになります。\n\n超能力姉妹の「甘々囁き耳かき&射精禁止尿道責め長時間発狂コース」\nhttps://www.pixiv.net/artworks/77756074\n\nの中盤の没展開バージョンとかと\n\n呪われたアクメ防具を装備しちゃってアクメ敗北する聖騎士少女\nhttps://www.pixiv.net/artworks/78043224\n\nのパイロット版(2ページだったバージョン)を入れてます。\n\n良ければ、お楽しみください。\n\n",
"files": [
{
"id": "Yc6qgIkAbo6phcc9drs4YMcT",
"name": "11月おまけ",
"extension": "zip",
"size": 42158422,
"url": "https://fanbox.pixiv.net/files/post/685832/Yc6qgIkAbo6phcc9drs4YMcT.zip"
}
]
},
"tags": [],
"excerpt": "あかいしですー\n2019年11月の支援者特典のおまけ没データになります。\n\n超能力姉妹の「甘々囁き耳かき&射精禁止尿道責め長時間発狂コース」\nhttps://www.pixiv.net/artworks/77756074\n\nの中盤の没展開バージョンとかと\n\n呪われたアクメ防具を装備しちゃってアクメ敗北する聖騎士少女\nhttps://www.pixiv.net/artworks/78...",
"isLiked": false,
"likeCount": 9,
"commentCount": 0,
"restrictedFor": null,
"user": {
"userId": "91029",
"name": "あかいししろいし",
"iconUrl": "https://pixiv.pximg.net/c/160x160_90_a2_g5/fanbox/public/images/user/91029/icon/88cadMWRtY4Rak2TYCO2nxra.jpeg"
},
"status": "published",
"commentList": {
"items": [],
"nextUrl": null
},
"nextPost": {
"id": "736673",
"title": "■2019 12 定期連絡",
"publishedDatetime": "2019-12-29 04:34:14"
},
"prevPost": {
"id": "685682",
"title": "■2019 11 定期連絡",
"publishedDatetime": "2019-12-01 00:32:37"
},
"imageForShare": "https://pixiv.pximg.net/c/1200x630_90_a2_g5/fanbox/public/images/post/685832/cover/hxpGNTfnFeTUz4tK8hlJbBZU.jpeg"
}
}
| 1,281 |
826 |
<gh_stars>100-1000
#pragma once
#include <map>
#include <string>
namespace weserv {
namespace nginx {
/**
* Represents a non-streaming HTTP GET-request.
*/
class HTTPRequest {
public:
/**
* HTTPRequest constructor.
*/
HTTPRequest() = default;
/**
* Request properties.
*/
const ngx_str_t &url() const {
return url_;
}
HTTPRequest &set_url(const ngx_str_t &value) {
url_ = value;
return *this;
}
const std::map<std::string, ngx_str_t> &request_headers() const {
return headers_;
}
HTTPRequest &set_header(const std::string &name, const ngx_str_t &value) {
headers_[name] = value;
return *this;
}
ngx_uint_t max_redirects() const {
return max_redirects_;
}
HTTPRequest &set_max_redirects(ngx_uint_t value) {
max_redirects_ = value;
return *this;
}
ngx_uint_t redirect_count() const {
return redirect_count_;
}
HTTPRequest &operator++() // ++A
{
redirect_count_++;
return *this;
}
HTTPRequest operator++(int) // A++
{
HTTPRequest result(*this);
++(*this);
return result;
}
private:
/**
* Target URI.
*/
ngx_str_t url_{};
/**
* Request headers.
*/
std::map<std::string, ngx_str_t> headers_;
/**
* Maximum number of redirects.
*/
ngx_uint_t max_redirects_ = 0;
/**
* The number of HTTP redirects made on its current connection.
*/
ngx_uint_t redirect_count_ = 0;
};
} // namespace nginx
} // namespace weserv
| 738 |
5,788 |
/*
* 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.db.protocol.mysql.packet.binlog.row.column.value.decimal;
import lombok.Getter;
import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.row.column.MySQLBinlogColumnDef;
import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.row.column.value.MySQLBinlogProtocolValue;
import org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* NEWDECIMAL type value of MySQL binlog protocol.
*
* @see <a href="https://github.com/mysql/mysql-server/blob/5.7/strings/decimal.c">bin2decimal</a>
*/
public final class MySQLDecimalBinlogProtocolValue implements MySQLBinlogProtocolValue {
private static final int DEC_BYTE_SIZE = 4;
private static final int DIG_PER_DEC = 9;
private static final int[] DIG_TO_BYTES = {0, 1, 1, 2, 2, 3, 3, 4, 4, 4};
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
DecimalMetaData decimalMetaData = new DecimalMetaData(columnDef.getColumnMeta());
return toDecimal(decimalMetaData, payload.readStringFixByBytes(decimalMetaData.getTotalByteLength()));
}
private static BigDecimal toDecimal(final DecimalMetaData metaData, final byte[] value) {
boolean positive = (value[0] & 0x80) == 0x80;
value[0] ^= 0x80;
if (!positive) {
for (int i = 0; i < value.length; i++) {
value[i] ^= 0xFF;
}
}
BigDecimal integerValue = decodeIntegerValue(metaData, value);
BigDecimal scaleValue = decodeScaleValue(metaData, value);
BigDecimal result = integerValue.add(scaleValue);
return positive ? result : result.negate();
}
private static BigDecimal decodeIntegerValue(final DecimalMetaData metaData, final byte[] value) {
int offset = DIG_TO_BYTES[metaData.getExtraIntegerSize()];
BigDecimal result = offset > 0 ? BigDecimal.valueOf(readFixedLengthIntBE(value, 0, offset)) : BigDecimal.ZERO;
for (; offset < metaData.getIntegerByteLength(); offset += DEC_BYTE_SIZE) {
int i = readFixedLengthIntBE(value, offset, DEC_BYTE_SIZE);
result = result.movePointRight(DIG_PER_DEC).add(BigDecimal.valueOf(i));
}
return result;
}
private static BigDecimal decodeScaleValue(final DecimalMetaData metaData, final byte[] value) {
BigDecimal result = BigDecimal.ZERO;
int shift = 0;
int offset = metaData.getIntegerByteLength();
int scale = metaData.getScale();
for (; shift + DIG_PER_DEC <= scale; shift += DIG_PER_DEC, offset += DEC_BYTE_SIZE) {
result = result.add(BigDecimal.valueOf(readFixedLengthIntBE(value, offset, DEC_BYTE_SIZE)).movePointLeft(shift + DIG_PER_DEC));
}
if (shift < scale) {
result = result.add(BigDecimal.valueOf(readFixedLengthIntBE(value, offset, DIG_TO_BYTES[scale - shift])).movePointLeft(scale));
}
return result;
}
private static int readFixedLengthIntBE(final byte[] bytes, final int offset, final int length) {
int result = 0;
for (int i = offset; i < (offset + length); i++) {
result = (result << 8) | (short) (0xff & bytes[i]);
}
return result;
}
@Getter
private static final class DecimalMetaData {
private final int scale;
private final int extraIntegerSize;
private final int integerByteLength;
private final int totalByteLength;
private DecimalMetaData(final int metaData) {
scale = metaData & 0xFF;
int precision = metaData >> 8;
int integer = precision - scale;
int fullIntegerSize = integer / DIG_PER_DEC;
extraIntegerSize = integer - fullIntegerSize * DIG_PER_DEC;
integerByteLength = (fullIntegerSize << 2) + DIG_TO_BYTES[extraIntegerSize];
int fullScaleSize = scale / DIG_PER_DEC;
int extraScaleSize = scale - fullScaleSize * DIG_PER_DEC;
totalByteLength = integerByteLength + (fullScaleSize << 2) + DIG_TO_BYTES[extraScaleSize];
}
}
}
| 1,977 |
372 |
<filename>clients/google-api-services-content/v2.1/1.31.0/com/google/api/services/content/model/AccountStatus.java
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.content.model;
/**
* The status of an account, i.e., information about its products, which is computed offline and not
* returned immediately at insertion time.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class AccountStatus extends com.google.api.client.json.GenericJson {
/**
* The ID of the account for which the status is reported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String accountId;
/**
* A list of account level issues.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<AccountStatusAccountLevelIssue> accountLevelIssues;
/**
* Identifies what kind of resource this is. Value: the fixed string "`content#accountStatus`"
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* List of product-related data by channel, destination, and country. Data in this field may be
* delayed by up to 30 minutes.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<AccountStatusProducts> products;
/**
* Whether the account's website is claimed or not.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean websiteClaimed;
/**
* The ID of the account for which the status is reported.
* @return value or {@code null} for none
*/
public java.lang.String getAccountId() {
return accountId;
}
/**
* The ID of the account for which the status is reported.
* @param accountId accountId or {@code null} for none
*/
public AccountStatus setAccountId(java.lang.String accountId) {
this.accountId = accountId;
return this;
}
/**
* A list of account level issues.
* @return value or {@code null} for none
*/
public java.util.List<AccountStatusAccountLevelIssue> getAccountLevelIssues() {
return accountLevelIssues;
}
/**
* A list of account level issues.
* @param accountLevelIssues accountLevelIssues or {@code null} for none
*/
public AccountStatus setAccountLevelIssues(java.util.List<AccountStatusAccountLevelIssue> accountLevelIssues) {
this.accountLevelIssues = accountLevelIssues;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "`content#accountStatus`"
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "`content#accountStatus`"
* @param kind kind or {@code null} for none
*/
public AccountStatus setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* List of product-related data by channel, destination, and country. Data in this field may be
* delayed by up to 30 minutes.
* @return value or {@code null} for none
*/
public java.util.List<AccountStatusProducts> getProducts() {
return products;
}
/**
* List of product-related data by channel, destination, and country. Data in this field may be
* delayed by up to 30 minutes.
* @param products products or {@code null} for none
*/
public AccountStatus setProducts(java.util.List<AccountStatusProducts> products) {
this.products = products;
return this;
}
/**
* Whether the account's website is claimed or not.
* @return value or {@code null} for none
*/
public java.lang.Boolean getWebsiteClaimed() {
return websiteClaimed;
}
/**
* Whether the account's website is claimed or not.
* @param websiteClaimed websiteClaimed or {@code null} for none
*/
public AccountStatus setWebsiteClaimed(java.lang.Boolean websiteClaimed) {
this.websiteClaimed = websiteClaimed;
return this;
}
@Override
public AccountStatus set(String fieldName, Object value) {
return (AccountStatus) super.set(fieldName, value);
}
@Override
public AccountStatus clone() {
return (AccountStatus) super.clone();
}
}
| 1,635 |
5,169 |
{
"name": "NetworkState",
"version": "0.0.2",
"summary": "A very easy way to determine NetworkState",
"description": "A simple way to determine the NetworkState for your application.\nNetworkState.isConnectedToNetwork() will return a bool and you are on your way.",
"homepage": "https://github.com/garethpaul/NetworkState",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "http://twitter.com/gpj",
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/garethpaul/NetworkState.git",
"tag": "0.0.2"
},
"source_files": "NetworkState/*.{swift}",
"frameworks": "SystemConfiguration"
}
| 268 |
2,151 |
<reponame>zipated/src
// Copyright 2013 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 <stdint.h>
#include "base/files/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h"
#include "content/public/browser/browser_thread.h"
namespace extensions {
// static
scoped_refptr<StorageDeviceList>
RemovableStorageProvider::PopulateDeviceList() {
return nullptr;
}
} // namespace extensions
| 185 |
373 |
/** @file
@copyright
Copyright 2019 - 2021 Intel Corporation. <BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _DDR4_SPD_REGS_H_
#define _DDR4_SPD_REGS_H_
//
// DDR4 SPD Spec 4.0 Register Definitions
//
/* Byte 132 (0x084) (Registered): RDIMM Thermal Heat Spreader Solution */
#define SPD_RDIMM_RDIMM_THERMAL_HEAT_SPREADER_SOLUTION_REG 0x0084
typedef union {
struct {
UINT8 heat_spreader_thermal_characteristics : 7;
/* Bits[0:6]
Heat Spreader Thermal Characteristics
0 = Undefined
All other settings to be defined
*/
UINT8 heat_spreader_solution : 1;
/* Bits[7]
Heat Spreader Solution
0 = Heat spreader solution is not incorporated onto this assembly
1 = Heat spreader solution is incorporated onto this assembly
*/
} Bits;
UINT8 Data;
} RDIMM_RDIMM_THERMAL_HEAT_SPREADER_SOLUTION_STRUCT;
#endif // #ifndef _DDR4_SPD_REGS_H_
| 661 |
4,640 |
/*
* 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.
*/
/*!
* \brief Placeholder op.
* \file placeholder_op.cc
*/
#include <tvm/runtime/registry.h>
#include <tvm/te/operation.h>
namespace tvm {
namespace te {
// PlaceholderOpNode
TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<PlaceholderOpNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const PlaceholderOpNode*>(node.get());
p->stream << "placeholder(" << op->name << ", " << op << ")";
});
TVM_REGISTER_NODE_TYPE(PlaceholderOpNode);
int PlaceholderOpNode::num_outputs() const { return 1; }
Array<IterVar> PlaceholderOpNode::root_iter_vars() const { return {}; }
DataType PlaceholderOpNode::output_dtype(size_t i) const {
ICHECK_EQ(i, 0U);
return dtype;
}
Array<PrimExpr> PlaceholderOpNode::output_shape(size_t i) const {
ICHECK_EQ(i, 0U);
return shape;
}
PlaceholderOp::PlaceholderOp(std::string name, Array<PrimExpr> shape, DataType dtype) {
auto n = make_object<PlaceholderOpNode>();
n->name = name;
n->shape = shape;
n->dtype = dtype;
data_ = std::move(n);
}
Tensor placeholder(Array<PrimExpr> shape, DataType dtype, std::string name) {
return PlaceholderOp(name, shape, dtype).output(0);
}
TVM_REGISTER_GLOBAL("te.Placeholder")
.set_body_typed([](Array<PrimExpr> shape, DataType dtype, std::string name) {
return placeholder(shape, dtype, name);
});
Array<Tensor> PlaceholderOpNode::InputTensors() const { return {}; }
Operation PlaceholderOpNode::ReplaceInputs(const Operation& self,
const std::unordered_map<Tensor, Tensor>& rmap) const {
return self;
}
void PlaceholderOpNode::PropBoundToInputs(
const Operation& self, arith::Analyzer* analyzer,
const std::unordered_map<const VarNode*, IntSet>& dom_map,
std::unordered_map<Tensor, TensorDom>* out_dom_map) const {}
void PlaceholderOpNode::GatherBound(const Operation& self,
const std::unordered_map<Tensor, TensorDom>& tensor_dom,
std::unordered_map<IterVar, Range>* out_dom_map) const {}
Stmt PlaceholderOpNode::BuildRealize(const Stage& stage,
const std::unordered_map<IterVar, Range>& realize_map,
const Stmt& body, String storage_scope) const {
return body;
}
Stmt PlaceholderOpNode::BuildProvide(const Stage& stage,
const std::unordered_map<IterVar, Range>& dom_map,
bool debug_keep_trivial_loop) const {
return Stmt();
}
} // namespace te
} // namespace tvm
| 1,320 |
1,473 |
/*
* Copyright 2019 NAVER Corp.
*
* 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.navercorp.pinpoint.bootstrap.util.spring;
import org.junit.Test;
import java.util.Map;
/**
* copy from spring-framework
* https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java
* https://github.com/naver/pinpoint/issues/5890
* potential bug fix
* This bug does not affect the pinpoint
* Pinpoint does not use templateVariable(always null)
* @author <NAME>(emeroad)
*/
public class AntPathMatcherTest {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
/**
* SPR-7787
*/
@Test
public void extractUriTemplateVarsRegexQualifiers() {
Map<String, String> result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar",
"com.example-sources-1.0.0.jar");
// skip
// no assertj dependency.
}
}
| 517 |
514 |
<reponame>programmerjake/microwatt
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <poll.h>
#include "sim_vhpi_c.h"
/* Should we exit simulation on ctrl-c or pass it through? */
#define EXIT_ON_CTRL_C
static struct termios oldt;
static void disable_raw_mode(void)
{
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}
static void enable_raw_mode(void)
{
static bool initialized = false;
if (!initialized) {
static struct termios newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
cfmakeraw(&newt);
#ifdef EXIT_ON_CTRL_C
newt.c_lflag |= ISIG;
#endif
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
initialized = true;
atexit(disable_raw_mode);
}
}
void sim_console_read(unsigned char *__rt)
{
int ret;
unsigned long val = 0;
enable_raw_mode();
ret = read(STDIN_FILENO, &val, 1);
if (ret != 1) {
fprintf(stderr, "%s: read of stdin returns %d\n", __func__, ret);
exit(1);
}
//fprintf(stderr, "read returns %c\n", val);
to_std_logic_vector(val, __rt, 64);
}
void sim_console_poll(unsigned char *__rt)
{
int ret;
struct pollfd fdset[1];
uint8_t val = 0;
enable_raw_mode();
memset(fdset, 0, sizeof(fdset));
fdset[0].fd = STDIN_FILENO;
fdset[0].events = POLLIN;
ret = poll(fdset, 1, 0);
//fprintf(stderr, "poll returns %d\n", ret);
if (ret == 1) {
if (fdset[0].revents & POLLIN)
val = 1;
// fprintf(stderr, "poll revents: 0x%x\n", fdset[0].revents);
}
to_std_logic_vector(val, __rt, 64);
}
void sim_console_write(unsigned char *__rs)
{
uint8_t val;
val = from_std_logic_vector(__rs, 64);
fprintf(stderr, "%c", val);
}
| 751 |
1,145 |
#pragma once
#include <rapidjson/rapidjson.h>
#include <common/SignalVector.hpp>
#include "providers/irc/IrcChannel2.hpp"
#include "providers/irc/IrcServer.hpp"
class QAbstractTableModel;
namespace chatterino {
enum class IrcAuthType { Anonymous, Custom, Pass, Sasl };
struct IrcServerData {
QString host;
int port = 6697;
bool ssl = true;
QString user;
QString nick;
QString real;
IrcAuthType authType = IrcAuthType::Anonymous;
void getPassword(QObject *receiver,
std::function<void(const QString &)> &&onLoaded) const;
void setPassword(const QString &password);
QStringList connectCommands;
int id;
};
class Irc
{
public:
Irc();
static Irc &instance();
static inline void *const noEraseCredentialCaller =
reinterpret_cast<void *>(1);
SignalVector<IrcServerData> connections;
QAbstractTableModel *newConnectionModel(QObject *parent);
ChannelPtr getOrAddChannel(int serverId, QString name);
void save();
void load();
int uniqueId();
private:
int currentId_{};
bool loaded_{};
// Servers have a unique id.
// When a server gets changed it gets removed and then added again.
// So we store the channels of that server in abandonedChannels_ temporarily.
// Or if the server got removed permanently then it's still stored there.
std::unordered_map<int, std::unique_ptr<IrcServer>> servers_;
std::unordered_map<int, std::vector<std::weak_ptr<Channel>>>
abandonedChannels_;
};
} // namespace chatterino
| 567 |
8,629 |
#pragma once
#include <Core/BackgroundSchedulePool.h>
#include <atomic>
#include <memory>
#include <string>
namespace DB
{
class FileLogDirectoryWatcher;
class DirectoryWatcherBase : WithContext
{
/// Most of code in this class is copy from the Poco project:
/// https://github.com/ClickHouse-Extras/poco/blob/clickhouse/Foundation/src/DirectoryWatcher.cpp
/// This class is used to get notifications about changes
/// to the filesystem, more precisely, to a specific
/// directory. Changes to a directory are reported via
/// events.
///
/// A thread will be created that watches the specified
/// directory for changes. Events are reported in the context
/// of this thread.
///
/// Note that changes to files in subdirectories of the watched
/// directory are not reported. Separate DirectoryWatcher objects
/// must be created for these directories if they should be watched.
public:
enum DirectoryEventType
{
DW_ITEM_ADDED = 1,
/// A new item has been created and added to the directory.
DW_ITEM_REMOVED = 2,
/// An item has been removed from the directory.
DW_ITEM_MODIFIED = 4,
/// An item has been modified.
DW_ITEM_MOVED_FROM = 8,
/// An item has been renamed or moved. This event delivers the old name.
DW_ITEM_MOVED_TO = 16
/// An item has been renamed or moved. This event delivers the new name.
};
enum DirectoryEventMask
{
/// Enables all event types.
DW_FILTER_ENABLE_ALL = 31,
/// Disables all event types.
DW_FILTER_DISABLE_ALL = 0
};
struct DirectoryEvent
{
DirectoryEvent(const std::string & f, DirectoryEventType ev) : path(f), event(ev) { }
/// The directory or file that has been changed.
const std::string path;
/// The kind of event.
DirectoryEventType event;
};
DirectoryWatcherBase() = delete;
DirectoryWatcherBase(const DirectoryWatcherBase &) = delete;
DirectoryWatcherBase & operator=(const DirectoryWatcherBase &) = delete;
/// Creates a DirectoryWatcher for the directory given in path.
/// To enable only specific events, an eventMask can be specified by
/// OR-ing the desired event IDs (e.g., DW_ITEM_ADDED | DW_ITEM_MODIFIED).
explicit DirectoryWatcherBase(
FileLogDirectoryWatcher & owner_, const std::string & path_, ContextPtr context_, int event_mask_ = DW_FILTER_ENABLE_ALL);
~DirectoryWatcherBase();
/// Returns the value of the eventMask passed to the constructor.
int eventMask() const { return event_mask; }
/// Returns the directory being watched.
const std::string & directory() const;
void watchFunc();
protected:
void start();
void stop();
private:
FileLogDirectoryWatcher & owner;
using TaskThread = BackgroundSchedulePool::TaskHolder;
TaskThread watch_task;
std::atomic<bool> stopped{false};
const std::string path;
int event_mask;
uint64_t milliseconds_to_wait;
int fd;
};
}
| 1,062 |
1,738 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzCore/std/smart_ptr/intrusive_ptr.h>
#include <AzCore/std/string/string.h>
namespace ScriptEvents
{
class ScriptEventsHandler;
namespace Internal
{
//! Script Events are bound to their respective handlers through Bind requests
class BindingRequest
: public AZ::EBusTraits
{
public:
struct BindingParameters
{
AZStd::string_view m_eventName;
AZ::BehaviorValueParameter* m_address;
AZ::BehaviorValueParameter* m_parameters;
AZ::u32 m_parameterCount;
AZ::BehaviorValueParameter* m_returnValue;
BindingParameters()
: m_address(nullptr)
, m_parameterCount(0)
, m_parameters(nullptr)
, m_returnValue(nullptr)
{}
};
//! Binding requests are done using a unique ID from the EBus/method name as the address
using BusIdType = AZ::Uuid;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
//! Request a bound event to be invoked given the parameters specified
virtual void Bind(const BindingParameters&) = 0;
virtual void Connect(const AZ::BehaviorValueParameter* address, ScriptEventsHandler* handler) = 0;
virtual void Disconnect(const AZ::BehaviorValueParameter* address, ScriptEventsHandler* handler) = 0;
virtual void RemoveHandler(ScriptEventsHandler*) = 0;
};
using BindingRequestBus = AZ::EBus<BindingRequest>;
}
}
| 906 |
940 |
<filename>tests/examplefiles/noexcept.cpp
void* operator new (std::size_t size);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value)noexcept;
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value);
void* operator new (std::size_t size);
void* operator new (std::size_t size) noexcept;
void* operator new (std::size_t size)noexcept;
| 161 |
394 |
<filename>jaxrs-delegates/src/test/java/org/wso2/msf4j/delegates/MediaTypeHeaderProviderTest.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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.msf4j.delegates;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.ws.rs.core.MediaType;
/**
* Media Type Header Provider test class.
*/
public class MediaTypeHeaderProviderTest extends Assert {
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullValue() throws Exception {
MediaType.valueOf(null);
}
@Test
public void testTypeWithExtendedParameters() {
MediaType mt = MediaType.valueOf("multipart/related;type=application/dicom+xml");
assertEquals("multipart", mt.getType());
assertEquals("related", mt.getSubtype());
;
}
@Test
public void testTypeWithExtendedParametersQuote() {
MediaType mt = MediaType.valueOf("multipart/related;type=\"application/dicom+xml\"");
assertEquals("multipart", mt.getType());
assertEquals("related", mt.getSubtype());
}
@Test
public void testTypeWithExtendedAndBoundaryParameter() {
MediaType mt = MediaType.valueOf(
"multipart/related; type=application/dicom+xml; " +
"boundary=\"uuid:b9aecb2a-ab37-48d6-a1cd-b2f4f7fa63cb\"");
assertEquals("multipart", mt.getType());
assertEquals("related", mt.getSubtype());
}
@Test
public void testSimpleType() {
MediaType m = MediaType.valueOf("text/html");
assertEquals(m, new MediaType("text", "html"), "Media type was not parsed correctly");
assertEquals(MediaType.valueOf("text/html "), new MediaType("text", "html"),
"Media type was not parsed correctly");
}
@Test
public void testBadType() {
try {
new MediaTypeHeaderProvider().fromString("texthtml");
fail("Parse exception must've been thrown");
} catch (Exception pe) {
// expected
}
}
@Test
public void testTypeWithParameters() {
MediaType mt = MediaType.valueOf("text/html;q=1234;b=4321");
assertEquals("text", mt.getType());
assertEquals("html", mt.getSubtype());
}
@Test
public void testSimpleToString() {
MediaTypeHeaderProvider provider =
new MediaTypeHeaderProvider();
assertEquals("text/plain", provider.toString(new MediaType("text", "plain")),
"simple media type is not serialized");
}
}
| 1,222 |
794 |
<reponame>kingBook/cross-2.1.5<filename>CrossApp/platform/win32/CCApplication.cpp
#include "CCApplication.h"
#include "CCEGLView.h"
#include "basics/CAApplication.h"
#include <algorithm>
#include "platform/CAFileUtils.h"
/**
@brief This function change the PVRFrame show/hide setting in register.
@param bEnable If true show the PVRFrame window, otherwise hide.
*/
static void PVRFrameEnableControlWindow(bool bEnable);
NS_CC_BEGIN
// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;
CCApplication::CCApplication()
: m_hInstance(NULL)
, m_hAccelTable(NULL)
{
m_hInstance = GetModuleHandle(NULL);
m_nAnimationInterval.QuadPart = 0;
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication = this;
}
CCApplication::~CCApplication()
{
CC_ASSERT(this == sm_pSharedApplication);
sm_pSharedApplication = NULL;
}
int CCApplication::run()
{
PVRFrameEnableControlWindow(false);
// Main message loop:
MSG msg;
LARGE_INTEGER nFreq;
LARGE_INTEGER nLast;
LARGE_INTEGER nNow;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nLast);
// Initialize instance and cocos2d.
if (!applicationDidFinishLaunching())
{
return 0;
}
CCEGLView* pMainWnd = CCEGLView::sharedOpenGLView();
pMainWnd->centerWindow();
ShowWindow(pMainWnd->getHWnd(), SW_SHOW);
while (1)
{
if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Get current time tick.
QueryPerformanceCounter(&nNow);
// If it's the time to draw next frame, draw it, else sleep a while.
if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart)
{
nLast.QuadPart = nNow.QuadPart;
CAApplication::getApplication()->mainLoop();
}
else
{
Sleep(0);
}
continue;
}
if (WM_QUIT == msg.message)
{
// Quit message loop.
break;
}
// Deal with windows message.
if (! m_hAccelTable || ! TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
void CCApplication::setAnimationInterval(double interval)
{
LARGE_INTEGER nFreq;
QueryPerformanceFrequency(&nFreq);
m_nAnimationInterval.QuadPart = (LONGLONG)(interval * nFreq.QuadPart);
}
//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////
CCApplication* CCApplication::sharedApplication()
{
CC_ASSERT(sm_pSharedApplication);
return sm_pSharedApplication;
}
LanguageType CCApplication::getCurrentLanguage()
{
LanguageType ret = LanguageType::ENGLISH;
LCID localeID = GetUserDefaultLCID();
unsigned short primaryLanguageID = localeID & 0xFF;
switch (primaryLanguageID)
{
case LANG_CHINESE:
ret = LanguageType::CHINESE;
break;
case LANG_ENGLISH:
ret = LanguageType::ENGLISH;
break;
case LANG_FRENCH:
ret = LanguageType::FRENCH;
break;
case LANG_ITALIAN:
ret = LanguageType::ITALIAN;
break;
case LANG_GERMAN:
ret = LanguageType::GERMAN;
break;
case LANG_SPANISH:
ret = LanguageType::SPANISH;
break;
case LANG_DUTCH:
ret = LanguageType::DUTCH;
break;
case LANG_RUSSIAN:
ret = LanguageType::RUSSIAN;
break;
case LANG_KOREAN:
ret = LanguageType::KOREAN;
break;
case LANG_JAPANESE:
ret = LanguageType::JAPANESE;
break;
case LANG_HUNGARIAN:
ret = LanguageType::HUNGARIAN;
break;
case LANG_PORTUGUESE:
ret = LanguageType::PORTUGUESE;
break;
case LANG_ARABIC:
ret = LanguageType::ARABIC;
break;
case LANG_NORWEGIAN:
ret = LanguageType::NORWEGIAN;
break;
case LANG_POLISH:
ret = LanguageType::POLISH;
break;
case LANG_TURKISH:
ret = LanguageType::TURKISH;
break;
case LANG_UKRAINIAN:
ret = LanguageType::UKRAINIAN;
break;
case LANG_ROMANIAN:
ret = LanguageType::ROMANIAN;
break;
case LANG_BULGARIAN:
ret = LanguageType::BULGARIAN;
break;
}
return ret;
}
TargetPlatform CCApplication::getTargetPlatform()
{
return kTargetWindows;
}
void CCApplication::setResourceRootPath(const std::string& rootResDir)
{
m_resourceRootPath = rootResDir;
std::replace(m_resourceRootPath.begin(), m_resourceRootPath.end(), '\\', '/');
if (m_resourceRootPath[m_resourceRootPath.length() - 1] != '/')
{
m_resourceRootPath += '/';
}
FileUtils* pFileUtils = FileUtils::getInstance();
std::vector<std::string> searchPaths = pFileUtils->getSearchPaths();
searchPaths.insert(searchPaths.begin(), m_resourceRootPath);
pFileUtils->setSearchPaths(searchPaths);
}
const std::string& CCApplication::getResourceRootPath(void)
{
return m_resourceRootPath;
}
void CCApplication::setStartupScriptFilename(const std::string& startupScriptFile)
{
m_startupScriptFilename = startupScriptFile;
std::replace(m_startupScriptFilename.begin(), m_startupScriptFilename.end(), '\\', '/');
}
NS_CC_END
//////////////////////////////////////////////////////////////////////////
// Local function
//////////////////////////////////////////////////////////////////////////
static void PVRFrameEnableControlWindow(bool bEnable)
{
HKEY hKey = 0;
// Open PVRFrame control key, if not exist create it.
if(ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER,
L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\",
0,
0,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
0,
&hKey,
NULL))
{
return;
}
const WCHAR* wszValue = L"hide_gui";
const WCHAR* wszNewData = (bEnable) ? L"NO" : L"YES";
WCHAR wszOldData[256] = {0};
DWORD dwSize = sizeof(wszOldData);
LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, NULL, (LPBYTE)wszOldData, &dwSize);
if (ERROR_FILE_NOT_FOUND == status // the key not exist
|| (ERROR_SUCCESS == status // or the hide_gui value is exist
&& 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal
{
dwSize = sizeof(WCHAR) * (wcslen(wszNewData) + 1);
RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE *)wszNewData, dwSize);
}
RegCloseKey(hKey);
}
| 3,142 |
310 |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash
import dash_bootstrap_components as dbc
from jupyter_dash import JupyterDash
from .apps import cohort_app
class cohort():
def __init__(self, x_test, model):
self.data = x_test
self.model = model
def main_function(self, mode):
external_stylesheets = ['https://raw.githubusercontent.com/rab657/explainx/master/explainx.css',
dbc.themes.BOOTSTRAP,
{
'href': 'https://fonts.googleapis.com/css?family=Montserrat',
'rel': 'stylesheet'
}
]
cohort = JupyterDash(__name__, external_stylesheets=external_stylesheets, suppress_callback_exceptions=True)
cohort.title = "explainX.ai - Model Performance Analysis"
cohort.layout = cohort_app.test_func(self.data, self.model, cohort)
debug_value = False
if mode == None:
import random
port = random.randint(4000, 5000)
return cohort.run_server(port=port, debug=debug_value, dev_tools_ui=debug_value,
dev_tools_props_check=debug_value, dev_tools_silence_routes_logging=True,
dev_tools_hot_reload=True)
else:
import random
port = random.randint(4000, 5000)
return cohort.run_server(mode='inline', port=port, debug=debug_value, dev_tools_ui=debug_value,
dev_tools_props_check=debug_value, dev_tools_silence_routes_logging=True,
dev_tools_hot_reload=True)
| 931 |
1,738 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/std/containers/unordered_set.h>
#include <AzCore/std/string/string.h>
#include <AzFramework/Asset/AssetCatalogBus.h>
#include <StaticData/StaticDataBus.h>
#include <IStaticDataMonitor.h>
#include <CrySystemBus.h>
namespace CloudCanvas
{
namespace StaticData
{
class StaticDataMonitor :
public StaticDataMonitorRequestBus::Handler
, public AzFramework::AssetCatalogEventBus::Handler
, public AZ::Data::AssetBus::MultiHandler
, public StaticDataUpdateBus::Handler
, public CrySystemEventBus::Handler
{
public:
StaticDataMonitor();
~StaticDataMonitor();
void Initialize();
void RemoveAll() override;
void AddPath(const AZStd::string& sanitizedPath, bool isFile) override;
void RemovePath(const AZStd::string& sanitizedPath) override;
void AddAsset(const AZ::Data::AssetId& sanitizedPath) override;
void RemoveAsset(const AZ::Data::AssetId& sanitizedPath) override;
//AssetCatalogEventBus
void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override;
void OnCatalogAssetAdded(const AZ::Data::AssetId& assetId) override;
void OnCatalogAssetRemoved(const AZ::Data::AssetId& assetId, const AZ::Data::AssetInfo& assetInfo) override;
// AssetDatabaseBus
void OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
// StaticDataUpdateBus
void StaticDataFileAdded(const AZStd::string& filePath) override;
void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& systemInitParams) override;
private:
bool IsMonitored(const AZ::Data::AssetId& assetId);
bool IsMonitored(const AZ::Data::AssetInfo& assetInfo);
void OnFileChanged(const AZStd::string& filePath);
AZStd::string GetSanitizedName(const char* pathName) const override; // Do any sort of path sanitizing so output events line up
static AZStd::string GetAssetFilenameFromAssetId(const AZ::Data::AssetId& assetId);
static AZStd::string GetAssetFilenameFromAssetInfo(const AZ::Data::AssetInfo& assetInfo);
AZStd::unordered_set<AZ::Data::AssetId> m_monitoredAssets;
AZStd::unordered_set<AZStd::string> m_monitoredPaths;
};
}
}
| 1,129 |
5,939 |
package io.grpc.override;
import java.util.logging.Level;
import java.util.logging.Logger;
import scala.Option;
import scala.Some;
import com.twitter.util.Local;
import io.grpc.Context;
import io.grpc.Context.Storage;
/**
* A default implementation of grpc-context's Storage that is compatible
* with Twitter `Futures`.
*
* See https://grpc.io/grpc-java/javadoc/io/grpc/Context.Storage.html for
* the reason why this class must exist at `io.grpc.override.ContextStorageOverride`.
*/
public final class ContextStorageOverride extends Storage {
private static final Logger LOGGER = Logger.getLogger("io.grpc.override.ContextStorageOverride");
private final Local<Context> storage;
public ContextStorageOverride() {
this.storage = new Local<>();
}
@Override
public Context current() {
Option<Context> ctx = storage.apply();
if (ctx.isEmpty()) {
return null;
} else {
return ctx.get();
}
}
@Override
public void detach(Context toDetach, Context toRestore) {
if (current() != toDetach) {
LOGGER.log(
Level.SEVERE,
"Context was not attached when detaching",
new Throwable().fillInStackTrace()
);
}
doAttach(toRestore);
}
@Override
public Context doAttach(Context toAttach) {
Context current = current();
storage.set(Some.apply(toAttach));
return current;
}
}
| 492 |
2,326 |
<filename>src/rime/language.cc
//
// Copyright RIME Developers
// Distributed under the BSD License
//
#include <rime/common.h>
#include <rime/language.h>
namespace rime {
// "luna_pinyin.extra" has language component "luna_pinyin".
string Language::get_language_component(const string& name) {
size_t dot = name.find('.');
if (dot != string::npos && dot != 0)
return name.substr(0, dot);
return name;
}
} // namespace rime
| 157 |
603 |
/* Copyright (c) 2014-2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if USEOPENGL
/**
This file contains helpers for resource interoperability between OpenGL and Vulkan.
they only exist if the shared_sources project is compiled with Vulkan AND OpenGL support.
> WARNING: untested code
*/
#pragma once
#include <nvvk/images_vk.hpp>
#include <nvvk/memorymanagement_vkgl.hpp>
namespace nvvk {
// Objects
struct BufferDmaGL
{
VkBuffer buffer = VK_NULL_HANDLE;
GLuint bufferGL = 0;
AllocationID allocation;
};
struct ImageDmaGL
{
VkImage image = VK_NULL_HANDLE;
GLuint texGL = 0;
AllocationID allocation;
};
//////////////////////////////////////////////////////////////////////////
/**
# class nvkk::AllocatorDmaGL
This utility has the same operations like nvvk::AllocatorDMA (see for more help), but
targets interop between OpenGL and Vulkan.
It uses nvkk::DeviceMemoryAllocatorGL to provide BufferDmaGL and ImageDmaGL utility classes that wrap an nvvk::AllocationID
as well as the native Vulkan and OpenGL resource objects.
*/
//--------------------------------------------------------------------------------------------------
// Allocator for buffers, images using Device Memory Allocator
//
class AllocatorDmaGL
{
public:
AllocatorDmaGL(AllocatorDmaGL const&) = delete;
AllocatorDmaGL& operator=(AllocatorDmaGL const&) = delete;
AllocatorDmaGL() = default;
//--------------------------------------------------------------------------------------------------
// Initialization of the allocator
void init(VkDevice device, VkPhysicalDevice physicalDevice, nvvk::DeviceMemoryAllocatorGL* allocator, VkDeviceSize stagingBlockSize = NVVK_DEFAULT_STAGING_BLOCKSIZE)
{
m_device = device;
m_allocator = allocator;
m_staging.init(device, physicalDevice, stagingBlockSize);
}
void deinit() { m_staging.deinit(); }
// sets memory priority for VK_EXT_memory_priority
void setPriority(float priority) { m_allocator->setPriority(priority); }
//--------------------------------------------------------------------------------------------------
// Basic buffer creation
BufferDmaGL createBuffer(const VkBufferCreateInfo& info, VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//--------------------------------------------------------------------------------------------------
// Simple buffer creation
BufferDmaGL createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//--------------------------------------------------------------------------------------------------
// Staging buffer creation, uploading data to device buffer
BufferDmaGL createBuffer(VkCommandBuffer cmd,
VkDeviceSize size,
VkBufferUsageFlags usage,
const void* data = nullptr,
VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//--------------------------------------------------------------------------------------------------
// Staging buffer creation, uploading data to device buffer
template <typename T>
BufferDmaGL createBuffer(VkCommandBuffer cmd,
VkDeviceSize size,
VkBufferUsageFlags usage,
const std::vector<T>& data,
VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
{
BufferDmaGL resultBuffer = createBuffer(size, usage, memProps);
if(data)
{
VkDeviceSize size = sizeof(T) * data.size();
m_staging.cmdToBuffer(cmd, resultBuffer.buffer, 0, size, data.data());
}
return resultBuffer;
}
//--------------------------------------------------------------------------------------------------
// Basic image creation
ImageDmaGL createImage(const VkImageCreateInfo& info, GLenum formatGL, VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//--------------------------------------------------------------------------------------------------
// Create an image with data, data is assumed to be from first level & layer only
//
ImageDmaGL createImage(VkCommandBuffer cmd,
const VkImageCreateInfo& info,
GLenum formatGL,
VkImageLayout layout,
VkDeviceSize size,
const void* data,
VkMemoryPropertyFlags memProps = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//--------------------------------------------------------------------------------------------------
// implicit staging operations triggered by create are managed here
void finalizeStaging(VkFence fence = VK_NULL_HANDLE) { m_staging.finalizeResources(fence); }
void finalizeAndReleaseStaging(VkFence fence = VK_NULL_HANDLE)
{
m_staging.finalizeResources(fence);
m_staging.releaseResources();
}
void releaseStaging() { m_staging.releaseResources(); }
StagingMemoryManager& getStaging() { return m_staging; }
const StagingMemoryManager& getStaging() const { return m_staging; }
//--------------------------------------------------------------------------------------------------
// Destroy
//
void destroy(BufferDmaGL& buffer);
void destroy(ImageDmaGL& image);
//--------------------------------------------------------------------------------------------------
// Other
//
void* map(const BufferDmaGL& buffer) { return m_allocator->map(buffer.allocation); }
void unmap(const BufferDmaGL& buffer) { m_allocator->unmap(buffer.allocation); }
private:
VkDevice m_device{VK_NULL_HANDLE};
nvvk::DeviceMemoryAllocatorGL* m_allocator{nullptr};
nvvk::StagingMemoryManager m_staging;
};
} // namespace nvvk
#endif
| 2,447 |
528 |
import numpy as np
from opytimark.markers.n_dimensional import Rastrigin, Sphere
from opytimizer import Opytimizer
from opytimizer.functions import WeightedFunction
from opytimizer.optimizers.swarm import PSO
from opytimizer.spaces import SearchSpace
# Random seed for experimental consistency
np.random.seed(0)
# Number of agents and decision variables
n_agents = 20
n_variables = 2
# Lower and upper bounds (has to be the same size as `n_variables`)
lower_bound = [-10, -10]
upper_bound = [10, 10]
# Creates the space, optimizer and function
space = SearchSpace(n_agents, n_variables, lower_bound, upper_bound)
optimizer = PSO()
function = WeightedFunction([Rastrigin(), Sphere()], [0.5, 0.5])
# Bundles every piece into Opytimizer class
opt = Opytimizer(space, optimizer, function, save_agents=False)
# Runs the optimization task
opt.start(n_iterations=1000)
| 279 |
2,996 |
<reponame>Elyahu41/Terasology
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.identity.storageServiceClient;
import org.terasology.engine.identity.ClientIdentity;
import org.terasology.engine.identity.PrivateIdentityCertificate;
import org.terasology.engine.identity.PublicIdentityCertificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents an identity (a server public - client public - client private certificates triplet).
*/
class IdentityBundle {
private PublicIdentityCertificate server;
private PublicIdentityCertificate clientPublic;
private PrivateIdentityCertificate clientPrivate;
IdentityBundle(PublicIdentityCertificate server, PublicIdentityCertificate clientPublic, PrivateIdentityCertificate clientPrivate) {
this.server = server;
this.clientPublic = clientPublic;
this.clientPrivate = clientPrivate;
}
IdentityBundle(PublicIdentityCertificate server, ClientIdentity client) {
this(server, client.getPlayerPublicCertificate(), client.getPlayerPrivateCertificate());
}
public PublicIdentityCertificate getServer() {
return server;
}
public ClientIdentity getClient() {
return new ClientIdentity(clientPublic, clientPrivate);
}
public static Map<PublicIdentityCertificate, ClientIdentity> listToMap(List<IdentityBundle> ls) {
Map<PublicIdentityCertificate, ClientIdentity> result = new HashMap<>();
for (IdentityBundle item: ls) {
result.put(item.server, new ClientIdentity(item.clientPublic, item.clientPrivate));
}
return result;
}
}
| 551 |
852 |
#ifndef DataFormats_SiStripCommon_SiStripConstants_H
#define DataFormats_SiStripCommon_SiStripConstants_H
#include "DataFormats/SiStripCommon/interface/Constants.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForCablingSource.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForCommissioningAnalysis.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForDqm.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForHardwareSystems.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForHistoType.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForGranularity.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForKeyType.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForLogger.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForMonitorable.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForPresentation.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForRunType.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForView.h"
#endif // DataFormats_SiStripCommon_SiStripConstants_H
| 365 |
5,169 |
<reponame>Gantios/Specs
{
"name": "ZoomPlugin",
"version": "1.0.1",
"summary": "ZoomPlugin for FaceAPI",
"license": {
"type": "commercial",
"text": " MIT\n"
},
"homepage": "https://regulaforensics.com",
"authors": {
"RegulaForensics": "<EMAIL>"
},
"source": {
"http": "http://pods.regulaforensics.com/ZoomPlugin/1.0.1/ZoomPlugin.zip"
},
"platforms": {
"ios": "8.3.0"
},
"ios": {
"resources": "Zoom.strings",
"vendored_frameworks": [
"ZoomPlugin.framework",
"ZoomAuthentication.framework"
]
}
}
| 273 |
532 |
#ifndef OPENSIM_MOCO_ABOUT_H_
#define OPENSIM_MOCO_ABOUT_H_
/* -------------------------------------------------------------------------- *
* OpenSim: About.h *
* -------------------------------------------------------------------------- *
* Copyright (c) 2019 Stanford University and the Authors *
* *
* Author(s): <NAME> *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include "osimMocoDLL.h"
#include <string>
namespace OpenSim {
OSIMMOCO_API std::string GetMocoVersionAndDate();
OSIMMOCO_API std::string GetMocoVersion();
}
#endif // OPENSIM_MOCO_ABOUT_H_
| 740 |
310 |
package com.playtika.test.common.properties;
import com.github.dockerjava.api.model.Capability;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.With;
import org.springframework.validation.annotation.Validated;
import org.testcontainers.containers.BindMode;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Validated
@Data
public abstract class CommonContainerProperties {
/**
* Specify custom Docker image for the container.
*/
private String dockerImage;
/**
* Overrides only version of the Docker image.
*/
private String dockerImageVersion;
/**
* Maximum time in seconds until embedded container should have started.
*/
private long waitTimeoutInSeconds = 60;
/**
* Enable embedded container.
*/
private boolean enabled = true;
/**
* Reuse embedded container.
*/
private boolean reuseContainer = false;
/**
* Whether to pull a docker image each time.
*/
private boolean usePullAlwaysPolicy = false;
/**
* Container startup command.
*/
private String[] command;
/**
* Set environment variables for the container.
*/
private Map<String, String> env = new HashMap<>();
/**
* Files/directories that should be copied to the container.
*/
@Valid
private List<CopyFileProperties> filesToInclude = new ArrayList<>();
/**
* Files/directories that should be mounted as container volumes.
*/
@Valid
private List<MountVolume> mountVolumes = new ArrayList<>();
/**
* The Linux capabilities that should be enabled.
*/
private List<Capability> capabilities = new ArrayList<>();
public Duration getTimeoutDuration() {
return Duration.ofSeconds(waitTimeoutInSeconds);
}
/**
* Specify default Docker image that is used by org.testcontainers:xyz module,
* so that we can mark your custom image as a compatible with the default one.
* <p>
* For more details check {@link com.playtika.test.common.utils.ContainerUtils#getDockerImageName}.
*/
public abstract String getDefaultDockerImage();
/**
* Copy a local file or directory from the classpath into the container.
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@With
public static class CopyFileProperties {
@NotBlank
String classpathResource;
@NotBlank
String containerPath;
}
/**
* Mount a local file or directory from the host as a container volume with READ_ONLY or READ_WRITE access mode.
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@With
public static class MountVolume {
@NotBlank
String hostPath;
@NotBlank
String containerPath;
@NotNull
BindMode mode = BindMode.READ_ONLY;
}
}
| 1,098 |
22,040 |
<gh_stars>1000+
import pytest
from spacy.util import compile_prefix_regex
from spacy.lang.punctuation import TOKENIZER_PREFIXES
PUNCT_OPEN = ["(", "[", "{", "*"]
PUNCT_CLOSE = [")", "]", "}", "*"]
PUNCT_PAIRED = [("(", ")"), ("[", "]"), ("{", "}"), ("*", "*")]
@pytest.mark.parametrize("text", ["(", "((", "<"])
def test_en_tokenizer_handles_only_punct(en_tokenizer, text):
tokens = en_tokenizer(text)
assert len(tokens) == len(text)
@pytest.mark.parametrize("punct", PUNCT_OPEN)
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_open_punct(en_tokenizer, punct, text):
tokens = en_tokenizer(punct + text)
assert len(tokens) == 2
assert tokens[0].text == punct
assert tokens[1].text == text
@pytest.mark.parametrize("punct", PUNCT_CLOSE)
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_close_punct(en_tokenizer, punct, text):
tokens = en_tokenizer(text + punct)
assert len(tokens) == 2
assert tokens[0].text == text
assert tokens[1].text == punct
@pytest.mark.parametrize("punct", PUNCT_OPEN)
@pytest.mark.parametrize("punct_add", ["`"])
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_two_diff_open_punct(en_tokenizer, punct, punct_add, text):
tokens = en_tokenizer(punct + punct_add + text)
assert len(tokens) == 3
assert tokens[0].text == punct
assert tokens[1].text == punct_add
assert tokens[2].text == text
@pytest.mark.parametrize("punct", PUNCT_CLOSE)
@pytest.mark.parametrize("punct_add", ["'"])
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_two_diff_close_punct(en_tokenizer, punct, punct_add, text):
tokens = en_tokenizer(text + punct + punct_add)
assert len(tokens) == 3
assert tokens[0].text == text
assert tokens[1].text == punct
assert tokens[2].text == punct_add
@pytest.mark.parametrize("punct", PUNCT_OPEN)
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_same_open_punct(en_tokenizer, punct, text):
tokens = en_tokenizer(punct + punct + punct + text)
assert len(tokens) == 4
assert tokens[0].text == punct
assert tokens[3].text == text
@pytest.mark.parametrize("punct", PUNCT_CLOSE)
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_same_close_punct(en_tokenizer, punct, text):
tokens = en_tokenizer(text + punct + punct + punct)
assert len(tokens) == 4
assert tokens[0].text == text
assert tokens[1].text == punct
@pytest.mark.parametrize("text", ["'The"])
def test_en_tokenizer_splits_open_appostrophe(en_tokenizer, text):
tokens = en_tokenizer(text)
assert len(tokens) == 2
assert tokens[0].text == "'"
@pytest.mark.parametrize("text", ["Hello''"])
def test_en_tokenizer_splits_double_end_quote(en_tokenizer, text):
tokens = en_tokenizer(text)
assert len(tokens) == 2
tokens_punct = en_tokenizer("''")
assert len(tokens_punct) == 1
@pytest.mark.parametrize("punct_open,punct_close", PUNCT_PAIRED)
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_splits_open_close_punct(
en_tokenizer, punct_open, punct_close, text
):
tokens = en_tokenizer(punct_open + text + punct_close)
assert len(tokens) == 3
assert tokens[0].text == punct_open
assert tokens[1].text == text
assert tokens[2].text == punct_close
@pytest.mark.parametrize("punct_open,punct_close", PUNCT_PAIRED)
@pytest.mark.parametrize("punct_open2,punct_close2", [("`", "'")])
@pytest.mark.parametrize("text", ["Hello"])
def test_en_tokenizer_two_diff_punct(
en_tokenizer, punct_open, punct_close, punct_open2, punct_close2, text
):
tokens = en_tokenizer(punct_open2 + punct_open + text + punct_close + punct_close2)
assert len(tokens) == 5
assert tokens[0].text == punct_open2
assert tokens[1].text == punct_open
assert tokens[2].text == text
assert tokens[3].text == punct_close
assert tokens[4].text == punct_close2
@pytest.mark.parametrize("text,punct", [("(can't", "(")])
def test_en_tokenizer_splits_pre_punct_regex(text, punct):
en_search_prefixes = compile_prefix_regex(TOKENIZER_PREFIXES).search
match = en_search_prefixes(text)
assert match.group() == punct
def test_en_tokenizer_splits_bracket_period(en_tokenizer):
text = "(And a 6a.m. run through Washington Park)."
tokens = en_tokenizer(text)
assert tokens[len(tokens) - 1].text == "."
| 1,784 |
2,674 |
<gh_stars>1000+
// Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: <NAME> <<EMAIL>>
#ifndef INTERACTION_CORE_HPP
#define INTERACTION_CORE_HPP
#include <stdlib.h> // free
#include <stddef.h> // size_t, ptrdiff_t
#include <limits> // numeric_limits
#include <atomic>
#include "ebm_native.h"
#include "logging.h"
#include "zones.h"
#include "ebm_internal.hpp"
// feature includes
#include "Feature.hpp"
// dataset depends on features
#include "DataSetInteraction.hpp"
namespace DEFINED_ZONE_NAME {
#ifndef DEFINED_ZONE_NAME
#error DEFINED_ZONE_NAME must be defined
#endif // DEFINED_ZONE_NAME
class InteractionShell;
class InteractionCore final {
// std::atomic_size_t used to be standard layout and trivial, but the C++ standard comitee judged that an error
// and revoked the trivial nature of the class. So, this means our BoosterCore class needs to have a constructor
// and destructor
// https://stackoverflow.com/questions/48794325/why-stdatomic-is-not-trivial-type-in-only-visual-c
// https://stackoverflow.com/questions/41308372/stdatomic-for-built-in-types-non-lock-free-vs-trivial-destructor
std::atomic_size_t m_REFERENCE_COUNT;
ptrdiff_t m_runtimeLearningTypeOrCountTargetClasses;
size_t m_cFeatures;
Feature * m_aFeatures;
int m_cLogEnterMessages;
int m_cLogExitMessages;
DataSetInteraction m_dataFrame;
INLINE_ALWAYS ~InteractionCore() {
// this only gets called after our reference count has been decremented to zero
m_dataFrame.Destruct();
free(m_aFeatures);
};
INLINE_ALWAYS InteractionCore() noexcept :
m_REFERENCE_COUNT(1), // we're not visible on any other thread yet, so no synchronization required
m_runtimeLearningTypeOrCountTargetClasses(0),
m_cFeatures(0),
m_aFeatures(nullptr),
m_cLogEnterMessages(0),
m_cLogExitMessages(0)
{
m_dataFrame.InitializeZero();
}
public:
INLINE_ALWAYS void AddReferenceCount() {
// incrementing reference counts can be relaxed memory order since we're guaranteed to be above 1,
// so no result will change our behavior below
// https://www.boost.org/doc/libs/1_59_0/doc/html/atomic/usage_examples.html
m_REFERENCE_COUNT.fetch_add(1, std::memory_order_relaxed);
};
INLINE_ALWAYS ptrdiff_t GetRuntimeLearningTypeOrCountTargetClasses() {
return m_runtimeLearningTypeOrCountTargetClasses;
}
INLINE_ALWAYS int * GetPointerCountLogEnterMessages() {
return &m_cLogEnterMessages;
}
INLINE_ALWAYS int * GetPointerCountLogExitMessages() {
return &m_cLogExitMessages;
}
INLINE_ALWAYS const DataSetInteraction * GetDataSetInteraction() const {
return &m_dataFrame;
}
INLINE_ALWAYS const Feature * GetFeatures() const {
return m_aFeatures;
}
INLINE_ALWAYS size_t GetCountFeatures() const {
return m_cFeatures;
}
static void Free(InteractionCore * const pInteractionCore);
static ErrorEbmType Create(
InteractionShell * const pInteractionShell,
const ptrdiff_t runtimeLearningTypeOrCountTargetClasses,
const size_t cFeatures,
const FloatEbmType * const optionalTempParams,
const BoolEbmType * const aFeaturesCategorical,
const IntEbmType * const aFeaturesBinCount,
const size_t cSamples,
const void * const aTargets,
const IntEbmType * const aBinnedData,
const FloatEbmType * const aWeights,
const FloatEbmType * const aPredictorScores
);
};
} // DEFINED_ZONE_NAME
#endif // INTERACTION_CORE_HPP
| 1,324 |
1,540 |
package test.listeners;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.Test;
import test.SimpleBaseTest;
public class ResultContextTest extends SimpleBaseTest {
@Test
public void testResultContext() {
TestNG tng = create(ResultContextListenerSample.class);
tng.run();
Assert.assertTrue(
ResultContextListener.contextProvided, "Test context was not provided to the listener");
}
}
| 141 |
407 |
<filename>plugins/gui/src/selection_details_widget/tree_navigation/selection_tree_view.cpp
#include "gui/selection_details_widget/tree_navigation/selection_tree_view.h"
#include "gui/graph_widget/contexts/graph_context.h"
#include "gui/gui_globals.h"
#include "gui/selection_details_widget/tree_navigation/selection_tree_model.h"
#include "gui/user_action/action_create_object.h"
#include "gui/user_action/action_add_items_to_object.h"
#include "gui/user_action/user_action_compound.h"
#include <QApplication>
#include <QClipboard>
#include <QHeaderView>
#include <QMenu>
#include <QMouseEvent>
namespace hal
{
SelectionTreeView::SelectionTreeView(QWidget* parent) : QTreeView(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
mSelectionTreeModel = new SelectionTreeModel(this);
mSelectionTreeProxyModel = new SelectionTreeProxyModel(this);
mSelectionTreeProxyModel->setSourceModel(mSelectionTreeModel);
setModel(mSelectionTreeProxyModel);
setDefaultColumnWidth();
header()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignCenter);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QTreeView::customContextMenuRequested, this, &SelectionTreeView::handleCustomContextMenuRequested);
}
void SelectionTreeView::setDefaultColumnWidth()
{
setColumnWidth(SelectionTreeModel::sNameColumn, 160);
setColumnWidth(SelectionTreeModel::sIdColumn, 40);
setColumnWidth(SelectionTreeModel::sTypeColumn, 80);
header()->setStretchLastSection(true);
}
void SelectionTreeView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
const SelectionTreeItem* sti = current.isValid() ? itemFromIndex(current) : nullptr;
Q_EMIT triggerSelection(sti);
}
void SelectionTreeView::mouseDoubleClickEvent(QMouseEvent* event)
{
QPoint point = viewport()->mapFromGlobal(event->globalPos());
;
QModelIndex index = indexAt(point);
if (index.isValid())
{
SelectionTreeItem* item = itemFromIndex(index);
Q_EMIT itemDoubleClicked(item);
}
}
SelectionTreeItem* SelectionTreeView::itemFromIndex(const QModelIndex& index) const
{
// topmost element if no valid index given
QModelIndex proxyIndex = index.isValid() ? index : mSelectionTreeProxyModel->index(0, 0, rootIndex());
if (!proxyIndex.isValid())
return nullptr;
QModelIndex modelIndex = mSelectionTreeProxyModel->mapToSource(proxyIndex);
return static_cast<SelectionTreeItem*>(modelIndex.internalPointer());
}
void SelectionTreeView::handleCustomContextMenuRequested(const QPoint& point)
{
QModelIndex index = indexAt(point);
if (index.isValid())
{
QMenu menu;
SelectionTreeItem* item = itemFromIndex(index);
if (item)
{
switch (item->itemType())
{
case SelectionTreeItem::TreeItemType::ModuleItem:
menu.addAction(QIcon(":/icons/python"), "Extract Module as python code (copy to clipboard)", [item]() {
QApplication::clipboard()->setText("netlist.get_module_by_id(" + QString::number(item->id()) + ")");
});
menu.addAction("Isolate in new view", [this, item]() { Q_EMIT handleIsolationViewAction(item); });
break;
case SelectionTreeItem::TreeItemType::GateItem:
menu.addAction(QIcon(":/icons/python"), "Extract Gate as python code (copy to clipboard)", [item]() {
QApplication::clipboard()->setText("netlist.get_gate_by_id(" + QString::number(item->id()) + ")");
});
menu.addAction("Isolate in new view", [this, item]() { Q_EMIT handleIsolationViewAction(item); });
break;
case SelectionTreeItem::TreeItemType::NetItem:
menu.addAction(QIcon(":/icons/python"), "Extract Net as python code (copy to clipboard)", [item]() {
QApplication::clipboard()->setText("netlist.get_net_by_id(" + QString::number(item->id()) + ")");
});
break;
default: // make compiler happy and handle irrelevant MaxItem, NullItem
break;
}
}
menu.addAction("Focus item in Graph View", [this, item]() { Q_EMIT focusItemClicked(item); });
menu.exec(viewport()->mapToGlobal(point));
}
}
void SelectionTreeView::handleIsolationViewAction(const SelectionTreeItem* sti)
{
u32 id = sti->id();
QString name = "";
QSet<u32> gateId;
QSet<u32> moduleId;
if (sti->itemType() == SelectionTreeItem::TreeItemType::GateItem)
{
name = "Isolated Gate(ID: " + QString::number(id) + ")";
gateId.insert(id);
}
else if (sti->itemType() == SelectionTreeItem::TreeItemType::ModuleItem)
{
name = "Isolated Module(ID: " + QString::number(id) + ")";
moduleId.insert(id);
}
else
{
return;
}
u32 cnt = 0;
while (true)
{
++cnt;
QString contextName = name + " " + QString::number(cnt);
if (!gGraphContextManager->contextWithNameExists(contextName))
{
UserActionCompound* act = new UserActionCompound;
act->setUseCreatedObject();
act->addAction(new ActionCreateObject(UserActionObjectType::Context,
contextName));
act->addAction(new ActionAddItemsToObject(moduleId, gateId));
act->exec();
return;
}
}
}
void SelectionTreeView::populate(bool mVisible)
{
if (mSelectionTreeProxyModel->isGraphicsBusy())
return;
setSelectionMode(QAbstractItemView::NoSelection);
selectionModel()->clear();
mSelectionTreeModel->fetchSelection(mVisible);
if (mVisible)
{
show();
setSelectionMode(QAbstractItemView::SingleSelection);
QModelIndex defaultSel = mSelectionTreeProxyModel->index(0, 0, rootIndex());
if (defaultSel.isValid())
selectionModel()->setCurrentIndex(defaultSel, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
else
hide();
}
void SelectionTreeView::handleFilterTextChanged(const QString& filter_text)
{
mSelectionTreeProxyModel->handleFilterTextChanged(filter_text);
expandAll();
QModelIndex defaultSel = mSelectionTreeProxyModel->index(0, 0, rootIndex());
if (defaultSel.isValid())
selectionModel()->setCurrentIndex(defaultSel, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
SelectionTreeProxyModel* SelectionTreeView::proxyModel()
{
return mSelectionTreeProxyModel;
}
} // namespace hal
| 3,316 |
376 |
<reponame>15five/django-pg-zero-downtime-migrations
# Generated by Django 3.0a1 on 2019-10-14 19:39
import django.contrib.postgres.indexes
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('good_flow_app', '0027_drop_brin_index'),
]
operations = [
migrations.AddIndex(
model_name='testtable',
index=django.contrib.postgres.indexes.BrinIndex(
condition=models.Q(test_field_int__isnull=False),
fields=['test_field_int'],
name='test_index',
),
),
]
| 296 |
403 |
#include "vg_util.h"
#include <vg/vg.h>
#include <bx/bx.h>
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
#include <xmmintrin.h>
#include <immintrin.h>
#endif
BX_PRAGMA_DIAGNOSTIC_IGNORED_GCC("-Wimplicit-fallthrough=0")
namespace vgutil
{
bool invertMatrix3(const float* __restrict t, float* __restrict inv)
{
// nvgTransformInverse
double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
if (det > -1e-6 && det < 1e-6) {
inv[0] = inv[2] = 1.0f;
inv[1] = inv[3] = inv[4] = inv[5] = 0.0f;
return false;
}
invdet = 1.0 / det;
inv[0] = (float)(t[3] * invdet);
inv[2] = (float)(-t[2] * invdet);
inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
inv[1] = (float)(-t[1] * invdet);
inv[3] = (float)(t[0] * invdet);
inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
return true;
}
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
void memset32(void* __restrict dst, uint32_t n, const void* __restrict src)
{
const __m128 s128 = _mm_load_ps1((const float*)src);
float* d = (float*)dst;
uint32_t iter = n >> 4;
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n & 15;
if (rem >= 8) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 8;
}
if (rem >= 4) {
_mm_storeu_ps(d, s128);
d += 4;
rem -= 4;
}
switch (rem) {
case 3: *d++ = *(const float*)src;
case 2: *d++ = *(const float*)src;
case 1: *d = *(const float*)src;
}
}
void memset64(void* __restrict dst, uint32_t n64, const void* __restrict src)
{
const float* s = (const float*)src;
const __m128 s0 = _mm_load_ss(&s[0]);
const __m128 s1 = _mm_load_ss(&s[1]);
const __m128 s0011 = _mm_shuffle_ps(s0, s1, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 s128 = _mm_shuffle_ps(s0011, s0011, _MM_SHUFFLE(2, 0, 2, 0));
float* d = (float*)dst;
uint32_t iter = n64 >> 3; // 8 64-bit values per iteration (== 16 floats / iter)
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n64 & 7;
if (rem >= 4) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 4;
}
if (rem >= 2) {
_mm_storeu_ps(d, s128);
d += 4;
rem -= 2;
}
if (rem) {
d[0] = s[0];
d[1] = s[1];
}
}
void memset128(void* __restrict dst, uint32_t n128, const void* __restrict src)
{
const __m128 s128 = _mm_loadu_ps((const float*)src);
float* d = (float*)dst;
uint32_t iter = n128 >> 2; // 4 128-bit values per iteration (== 16 floats / iter)
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n128 & 3;
if (rem >= 2) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 2;
}
if (rem) {
_mm_storeu_ps(d, s128);
}
}
void batchTransformPositions(const float* __restrict src, uint32_t n, float* __restrict dst, const float* __restrict mtx)
{
const __m128 mtx0123 = _mm_loadu_ps(mtx);
const __m128 mtx45 = _mm_loadl_pi(_mm_setzero_ps(), (const __m64*)(mtx + 4));
const __m128 mtx0 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 mtx1 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(1, 1, 1, 1));
const __m128 mtx2 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(2, 2, 2, 2));
const __m128 mtx3 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(3, 3, 3, 3));
const __m128 mtx4 = _mm_shuffle_ps(mtx45, mtx45, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 mtx5 = _mm_shuffle_ps(mtx45, mtx45, _MM_SHUFFLE(1, 1, 1, 1));
const uint32_t iter = n >> 3;
for (uint32_t i = 0; i < iter; ++i) {
// x' = m[0] * x + m[2] * y + m[4];
// y' = m[1] * x + m[3] * y + m[5];
const __m128 xy01 = _mm_loadu_ps(src + 0); // { x0, y0, x1, y1 }
const __m128 xy23 = _mm_loadu_ps(src + 4); // { x2, y2, x3, y3 }
const __m128 xy45 = _mm_loadu_ps(src + 8); // { x4, y4, x5, y5 }
const __m128 xy67 = _mm_loadu_ps(src + 12); // { x6, y6, x7, y7 }
const __m128 x0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(2, 0, 2, 0)); // { x0, x1, x2, x3 }
const __m128 y0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(3, 1, 3, 1)); // { y0, y1, y2, y3 }
const __m128 x4567 = _mm_shuffle_ps(xy45, xy67, _MM_SHUFFLE(2, 0, 2, 0)); // { x0, x1, x2, x3 }
const __m128 y4567 = _mm_shuffle_ps(xy45, xy67, _MM_SHUFFLE(3, 1, 3, 1)); // { y0, y1, y2, y3 }
const __m128 resx0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx0), mtx4), _mm_mul_ps(y0123, mtx2)); // { xi * m[0] + yi * m[2] + m[4] }
const __m128 resy0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx1), mtx5), _mm_mul_ps(y0123, mtx3)); // { x1 * m[1] + yi * m[3] + m[5] }
const __m128 resx4567 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x4567, mtx0), mtx4), _mm_mul_ps(y4567, mtx2)); // { xi * m[0] + yi * m[2] + m[4] }
const __m128 resy4567 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x4567, mtx1), mtx5), _mm_mul_ps(y4567, mtx3)); // { x1 * m[1] + yi * m[3] + m[5] }
const __m128 resx01_resy01 = _mm_movelh_ps(resx0123, resy0123); // { rx0, rx1, ry0, ry1 }
const __m128 resx23_resy23 = _mm_movehl_ps(resy0123, resx0123); // { rx2, rx3, ry2, ry3 }
const __m128 resx45_resy45 = _mm_movelh_ps(resx4567, resy4567); // { rx4, rx5, ry4, ry5 }
const __m128 resx67_resy67 = _mm_movehl_ps(resy4567, resx4567); // { rx6, rx7, ry6, ry7 }
const __m128 resxy01 = _mm_shuffle_ps(resx01_resy01, resx01_resy01, _MM_SHUFFLE(3, 1, 2, 0)); // { rx0, ry0, rx1, ry1 }
const __m128 resxy23 = _mm_shuffle_ps(resx23_resy23, resx23_resy23, _MM_SHUFFLE(3, 1, 2, 0)); // { rx2, ry2, rx3, ry3 }
const __m128 resxy45 = _mm_shuffle_ps(resx45_resy45, resx45_resy45, _MM_SHUFFLE(3, 1, 2, 0)); // { rx4, ry4, rx5, ry5 }
const __m128 resxy67 = _mm_shuffle_ps(resx67_resy67, resx67_resy67, _MM_SHUFFLE(3, 1, 2, 0)); // { rx6, ry6, rx7, ry7 }
_mm_storeu_ps(dst + 0, resxy01);
_mm_storeu_ps(dst + 4, resxy23);
_mm_storeu_ps(dst + 8, resxy45);
_mm_storeu_ps(dst + 12, resxy67);
src += 16;
dst += 16;
}
uint32_t rem = n & 7;
if (rem >= 4) {
const __m128 xy01 = _mm_loadu_ps(src + 0);
const __m128 xy23 = _mm_loadu_ps(src + 4);
const __m128 x0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(2, 0, 2, 0));
const __m128 y0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(3, 1, 3, 1));
const __m128 resx0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx0), mtx4), _mm_mul_ps(y0123, mtx2));
const __m128 resy0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx1), mtx5), _mm_mul_ps(y0123, mtx3));
const __m128 resx01_resy01 = _mm_movelh_ps(resx0123, resy0123);
const __m128 resx23_resy23 = _mm_movehl_ps(resy0123, resx0123);
const __m128 resxy01 = _mm_shuffle_ps(resx01_resy01, resx01_resy01, _MM_SHUFFLE(3, 1, 2, 0));
const __m128 resxy23 = _mm_shuffle_ps(resx23_resy23, resx23_resy23, _MM_SHUFFLE(3, 1, 2, 0));
_mm_storeu_ps(dst + 0, resxy01);
_mm_storeu_ps(dst + 4, resxy23);
src += 8;
dst += 8;
rem -= 4;
}
switch (rem) {
case 3:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
dst += 2;
case 2:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
dst += 2;
case 1:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
}
}
#else
void memset32(void* __restrict dst, uint32_t n, const void* __restrict src)
{
const uint32_t s = *(const uint32_t*)src;
uint32_t* d = (uint32_t*)dst;
while (n-- > 0) {
*d++ = s;
}
}
void memset64(void* __restrict dst, uint32_t n64, const void* __restrict src)
{
const uint32_t s0 = *((const uint32_t*)src + 0);
const uint32_t s1 = *((const uint32_t*)src + 1);
uint32_t* d = (uint32_t*)dst;
while (n64-- > 0) {
d[0] = s0;
d[1] = s1;
d += 2;
}
}
void memset128(void* __restrict dst, uint32_t n128, const void* __restrict src)
{
const uint32_t s0 = *((const uint32_t*)src + 0);
const uint32_t s1 = *((const uint32_t*)src + 1);
const uint32_t s2 = *((const uint32_t*)src + 2);
const uint32_t s3 = *((const uint32_t*)src + 3);
uint32_t* d = (uint32_t*)dst;
while (n128-- > 0) {
d[0] = s0;
d[1] = s1;
d[2] = s2;
d[3] = s3;
d += 4;
}
}
void batchTransformPositions(const float* __restrict v, uint32_t n, float* __restrict p, const float* __restrict mtx)
{
for (uint32_t i = 0; i < n; ++i) {
const uint32_t id = i << 1;
transformPos2D(v[id], v[id + 1], mtx, &p[id]);
}
}
#endif
void genQuadIndices_unaligned(uint16_t* dst, uint32_t n, uint16_t firstVertexID)
{
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
BX_ALIGN_DECL(16, static const uint16_t delta[]) = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15
};
const __m128i xmm_delta0 = _mm_load_si128((const __m128i*)&delta[0]);
const __m128i xmm_delta1 = _mm_load_si128((const __m128i*)&delta[8]);
const __m128i xmm_delta2 = _mm_load_si128((const __m128i*)&delta[16]);
const uint32_t numIter = n >> 2; // 4 quads per iteration
for (uint32_t i = 0; i < numIter; ++i) {
const __m128i id = _mm_set1_epi16(firstVertexID);
const __m128i id0 = _mm_add_epi16(id, xmm_delta0);
const __m128i id1 = _mm_add_epi16(id, xmm_delta1);
const __m128i id2 = _mm_add_epi16(id, xmm_delta2);
_mm_storeu_si128((__m128i*)(dst + 0), id0);
_mm_storeu_si128((__m128i*)(dst + 8), id1);
_mm_storeu_si128((__m128i*)(dst + 16), id2);
dst += 24;
firstVertexID += 16;
}
uint32_t rem = n & 3;
switch (rem) {
case 3:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
case 2:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
case 1:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
}
#else
while (n-- > 0) {
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
}
#endif
}
void batchTransformTextQuads(const float* __restrict quads, uint32_t n, const float* __restrict mtx, float* __restrict transformedVertices)
{
#if VG_CONFIG_ENABLE_SIMD
const bx::simd128_t mtx0 = bx::simd_splat(mtx[0]);
const bx::simd128_t mtx1 = bx::simd_splat(mtx[1]);
const bx::simd128_t mtx2 = bx::simd_splat(mtx[2]);
const bx::simd128_t mtx3 = bx::simd_splat(mtx[3]);
const bx::simd128_t mtx4 = bx::simd_splat(mtx[4]);
const bx::simd128_t mtx5 = bx::simd_splat(mtx[5]);
const uint32_t iter = n >> 1; // 2 quads per iteration
for (uint32_t i = 0; i < iter; ++i) {
bx::simd128_t q0 = bx::simd_ld(quads); // (x0, y0, x1, y1)
bx::simd128_t q1 = bx::simd_ld(quads + 8); // (x2, y2, x3, y3)
bx::simd128_t x0123 = bx::simd_shuf_xyAB(bx::simd_swiz_xzxz(q0), bx::simd_swiz_xzxz(q1)); // (x0, x1, x2, x3)
bx::simd128_t y0123 = bx::simd_shuf_xyAB(bx::simd_swiz_ywyw(q0), bx::simd_swiz_ywyw(q1)); // (y0, y1, y2, y3)
bx::simd128_t x0123_m0 = bx::simd_mul(x0123, mtx0); // (x0, x1, x2, x3) * mtx[0]
bx::simd128_t x0123_m1 = bx::simd_mul(x0123, mtx1); // (x0, x1, x2, x3) * mtx[1]
bx::simd128_t y0123_m2 = bx::simd_mul(y0123, mtx2); // (y0, y1, y2, y3) * mtx[2]
bx::simd128_t y0123_m3 = bx::simd_mul(y0123, mtx3); // (y0, y1, y2, y3) * mtx[3]
// v0.x = x0_m0 + y0_m2 + m4
// v1.x = x1_m0 + y0_m2 + m4
// v2.x = x1_m0 + y1_m2 + m4
// v3.x = x0_m0 + y1_m2 + m4
// v0.y = x0_m1 + y0_m3 + m5
// v1.y = x1_m1 + y0_m3 + m5
// v2.y = x1_m1 + y1_m3 + m5
// v3.y = x0_m1 + y1_m3 + m5
bx::simd128_t x0110_m0 = bx::simd_swiz_xyyx(x0123_m0);
bx::simd128_t x0110_m1 = bx::simd_swiz_xyyx(x0123_m1);
bx::simd128_t y0011_m2 = bx::simd_swiz_xxyy(y0123_m2);
bx::simd128_t y0011_m3 = bx::simd_swiz_xxyy(y0123_m3);
bx::simd128_t v0123_x = bx::simd_add(x0110_m0, bx::simd_add(y0011_m2, mtx4));
bx::simd128_t v0123_y = bx::simd_add(x0110_m1, bx::simd_add(y0011_m3, mtx5));
bx::simd128_t v01 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v0123_x, v0123_y));
bx::simd128_t v23 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v0123_x, v0123_y));
bx::simd_st(transformedVertices, v01);
bx::simd_st(transformedVertices + 4, v23);
// v4.x = x2_m0 + y2_m2 + m4
// v5.x = x3_m0 + y2_m2 + m4
// v6.x = x3_m0 + y3_m2 + m4
// v7.x = x2_m0 + y3_m2 + m4
// v4.y = x2_m1 + y2_m3 + m5
// v5.y = x3_m1 + y2_m3 + m5
// v6.y = x3_m1 + y3_m3 + m5
// v7.y = x2_m1 + y3_m3 + m5
bx::simd128_t x2332_m0 = bx::simd_swiz_zwwz(x0123_m0);
bx::simd128_t x2332_m1 = bx::simd_swiz_zwwz(x0123_m1);
bx::simd128_t y2233_m2 = bx::simd_swiz_zzww(y0123_m2);
bx::simd128_t y2233_m3 = bx::simd_swiz_zzww(y0123_m3);
bx::simd128_t v4567_x = bx::simd_add(x2332_m0, bx::simd_add(y2233_m2, mtx4));
bx::simd128_t v4567_y = bx::simd_add(x2332_m1, bx::simd_add(y2233_m3, mtx5));
bx::simd128_t v45 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v4567_x, v4567_y));
bx::simd128_t v67 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v4567_x, v4567_y));
bx::simd_st(transformedVertices + 8, v45);
bx::simd_st(transformedVertices + 12, v67);
quads += 16;
transformedVertices += 16;
}
const uint32_t rem = n & 1;
if (rem) {
bx::simd128_t q0 = bx::simd_ld(quads);
bx::simd128_t x0101 = bx::simd_swiz_xzxz(q0); // (x0, x1, x0, x1)
bx::simd128_t y0101 = bx::simd_swiz_ywyw(q0); // (y0, y1, y0, y1)
bx::simd128_t x0101_m0 = bx::simd_mul(x0101, mtx0); // (x0, x1, x0, x1) * mtx[0]
bx::simd128_t x0101_m1 = bx::simd_mul(x0101, mtx1); // (x0, x1, x0, x1) * mtx[1]
bx::simd128_t y0101_m2 = bx::simd_mul(y0101, mtx2); // (y0, y1, y0, y1) * mtx[2]
bx::simd128_t y0101_m3 = bx::simd_mul(y0101, mtx3); // (y0, y1, y0, y1) * mtx[3]
// v0.x = x0_m0 + y0_m2 + m4
// v1.x = x1_m0 + y0_m2 + m4
// v2.x = x1_m0 + y1_m2 + m4
// v3.x = x0_m0 + y1_m2 + m4
// v0.y = x0_m1 + y0_m3 + m5
// v1.y = x1_m1 + y0_m3 + m5
// v2.y = x1_m1 + y1_m3 + m5
// v3.y = x0_m1 + y1_m3 + m5
bx::simd128_t x0110_m0 = bx::simd_swiz_xyyx(x0101_m0);
bx::simd128_t x0110_m1 = bx::simd_swiz_xyyx(x0101_m1);
bx::simd128_t y0011_m2 = bx::simd_swiz_xxyy(y0101_m2);
bx::simd128_t y0011_m3 = bx::simd_swiz_xxyy(y0101_m3);
bx::simd128_t v0123_x = bx::simd_add(x0110_m0, bx::simd_add(y0011_m2, mtx4));
bx::simd128_t v0123_y = bx::simd_add(x0110_m1, bx::simd_add(y0011_m3, mtx5));
bx::simd128_t v01 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v0123_x, v0123_y));
bx::simd128_t v23 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v0123_x, v0123_y));
bx::simd_st(transformedVertices, v01);
bx::simd_st(transformedVertices + 4, v23);
}
#else
for (uint32_t i = 0; i < n; ++i) {
const float* q = &quads[i * 8];
const uint32_t s = i << 3;
transformPos2D(q[0], q[1], mtx, &transformedVertices[s + 0]);
transformPos2D(q[2], q[1], mtx, &transformedVertices[s + 2]);
transformPos2D(q[2], q[3], mtx, &transformedVertices[s + 4]);
transformPos2D(q[0], q[3], mtx, &transformedVertices[s + 6]);
}
#endif
}
void batchTransformDrawIndices(const uint16_t* __restrict src, uint32_t n, uint16_t* __restrict dst, uint16_t delta)
{
if (delta == 0) {
bx::memCopy(dst, src, sizeof(uint16_t) * n);
return;
}
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
const __m128i xmm_delta = _mm_set1_epi16(delta);
const uint32_t iter32 = n >> 5;
for (uint32_t i = 0; i < iter32; ++i) {
const __m128i s0 = _mm_loadu_si128((const __m128i*)src);
const __m128i s1 = _mm_loadu_si128((const __m128i*)(src + 8));
const __m128i s2 = _mm_loadu_si128((const __m128i*)(src + 16));
const __m128i s3 = _mm_loadu_si128((const __m128i*)(src + 24));
const __m128i d0 = _mm_add_epi16(s0, xmm_delta);
const __m128i d1 = _mm_add_epi16(s1, xmm_delta);
const __m128i d2 = _mm_add_epi16(s2, xmm_delta);
const __m128i d3 = _mm_add_epi16(s3, xmm_delta);
// NOTE: Proper alignment of dst buffer isn't guaranteed because it's part of the global IndexBuffer.
_mm_storeu_si128((__m128i*)dst, d0);
_mm_storeu_si128((__m128i*)(dst + 8), d1);
_mm_storeu_si128((__m128i*)(dst + 16), d2);
_mm_storeu_si128((__m128i*)(dst + 24), d3);
src += 32;
dst += 32;
}
uint32_t rem = n & 31;
if (rem >= 16) {
const __m128i s0 = _mm_loadu_si128((const __m128i*)src);
const __m128i s1 = _mm_loadu_si128((const __m128i*)(src + 8));
const __m128i d0 = _mm_add_epi16(s0, xmm_delta);
const __m128i d1 = _mm_add_epi16(s1, xmm_delta);
_mm_storeu_si128((__m128i*)dst, d0);
_mm_storeu_si128((__m128i*)(dst + 8), d1);
src += 16;
dst += 16;
rem -= 16;
}
if (rem >= 8) {
__m128i s0 = _mm_loadu_si128((const __m128i*)src);
__m128i d0 = _mm_add_epi16(s0, xmm_delta);
_mm_storeu_si128((__m128i*)dst, d0);
src += 8;
dst += 8;
rem -= 8;
}
switch (rem) {
case 7: *dst++ = *src++ + delta;
case 6: *dst++ = *src++ + delta;
case 5: *dst++ = *src++ + delta;
case 4: *dst++ = *src++ + delta;
case 3: *dst++ = *src++ + delta;
case 2: *dst++ = *src++ + delta;
case 1: *dst = *src + delta;
}
#else
for (uint32_t i = 0; i < n; ++i) {
*dst++ = *src + delta;
src++;
}
#endif
}
void convertA8_to_RGBA8(uint32_t* rgba, const uint8_t* a8, uint32_t w, uint32_t h, uint32_t rgbColor)
{
const uint32_t rgb0 = rgbColor & 0x00FFFFFF;
int numPixels = w * h;
for (int i = 0; i < numPixels; ++i) {
*rgba++ = rgb0 | (((uint32_t)* a8) << 24);
++a8;
}
}
}
| 9,781 |
2,322 |
/*
* objsel.h
*
* Object Picker Dialog
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef __OBJSEL_H_
#define __OBJSEL_H_
#ifdef __cplusplus
extern "C" {
#endif
DEFINE_GUID(CLSID_DsObjectPicker, 0x17d6ccd8, 0x3b7b, 0x11d2, 0xb9,0xe0,0x00,0xc0,0x4f,0xd8,0xdb,0xf7);
DEFINE_GUID(IID_IDsObjectPicker, 0x0c87e64e, 0x3b7a, 0x11d2, 0xb9,0xe0,0x00,0xc0,0x4f,0xd8,0xdb,0xf7);
#define CFSTR_DSOP_DS_SELECTION_LIST TEXT("CFSTR_DSOP_DS_SELECTION_LIST")
/* up-level scope filters in the DSOP_UPLEVEL_FILTER_FLAGS structure */
#define DSOP_FILTER_INCLUDE_ADVANCED_VIEW (0x1)
#define DSOP_FILTER_USERS (0x2)
#define DSOP_FILTER_BUILTIN_GROUPS (0x4)
#define DSOP_FILTER_WELL_KNOWN_PRINCIPALS (0x8)
#define DSOP_FILTER_UNIVERSAL_GROUPS_DL (0x10)
#define DSOP_FILTER_UNIVERSAL_GROUPS_SE (0x20)
#define DSOP_FILTER_GLOBAL_GROUPS_DL (0x40)
#define DSOP_FILTER_GLOBAL_GROUPS_SE (0x80)
#define DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL (0x100)
#define DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE (0x200)
#define DSOP_FILTER_CONTACTS (0x400)
#define DSOP_FILTER_COMPUTERS (0x800)
#define DSOP_FILTER_SERVICE_ACCOUNTS (0x1000)
#define DSOP_FILTER_PASSWORDSETTINGS_OBJECTS (0x2000)
typedef struct _DSOP_UPLEVEL_FILTER_FLAGS
{
ULONG flBothModes;
ULONG flMixedModeOnly;
ULONG flNativeModeOnly;
} DSOP_UPLEVEL_FILTER_FLAGS, *PDSOP_UPLEVEL_FILTER_FLAGS;
/* down-level scope filters in the DSOP_FILTER_FLAGS structure */
#define DSOP_DOWNLEVEL_FILTER_USERS (0x80000001)
#define DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS (0x80000002)
#define DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS (0x80000004)
#define DSOP_DOWNLEVEL_FILTER_COMPUTERS (0x80000008)
#define DSOP_DOWNLEVEL_FILTER_WORLD (0x80000010)
#define DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER (0x80000020)
#define DSOP_DOWNLEVEL_FILTER_ANONYMOUS (0x80000040)
#define DSOP_DOWNLEVEL_FILTER_BATCH (0x80000080)
#define DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER (0x80000100)
#define DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP (0x80000200)
#define DSOP_DOWNLEVEL_FILTER_DIALUP (0x80000400)
#define DSOP_DOWNLEVEL_FILTER_INTERACTIVE (0x80000800)
#define DSOP_DOWNLEVEL_FILTER_NETWORK (0x80001000)
#define DSOP_DOWNLEVEL_FILTER_SERVICE (0x80002000)
#define DSOP_DOWNLEVEL_FILTER_SYSTEM (0x80004000)
#define DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS (0x80008000)
#define DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER (0x80010000)
#define DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS (0x80020000)
#define DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE (0x80040000)
#define DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE (0x80080000)
#define DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON (0x80100000)
typedef struct _DSOP_FILTER_FLAGS
{
DSOP_UPLEVEL_FILTER_FLAGS Uplevel;
ULONG flDownlevel;
} DSOP_FILTER_FLAGS, *PDSOP_FILTER_FLAGS;
/* ADsPath format flags in the DSOP_SCOPE_INIT_INFO structure */
#define DSOP_SCOPE_FLAG_STARTING_SCOPE (0x1)
#define DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT (0x2)
#define DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP (0x4)
#define DSOP_SCOPE_FLAG_WANT_PROVIDER_GC (0x8)
#define DSOP_SCOPE_FLAG_WANT_SID_PATH (0x10)
#define DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH (0x20)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS (0x40)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS (0x80)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS (0x100)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS (0x200)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_SERVICE_ACCOUNTS (0x400)
#define DSOP_SCOPE_FLAG_DEFAULT_FILTER_PASSWORDSETTINGS_OBJECTS (0x800)
typedef struct _DSOP_SCOPE_INIT_INFO
{
ULONG cbSize;
ULONG flType;
ULONG flScope;
DSOP_FILTER_FLAGS FilterFlags;
PCWSTR pwzDcName;
PCWSTR pwzADsPath;
HRESULT hr;
} DSOP_SCOPE_INIT_INFO, *PDSOP_SCOPE_INIT_INFO;
typedef const DSOP_SCOPE_INIT_INFO *PCDSOP_SCOPE_INIT_INFO;
/* object picker options in the DSOP_INIT_INFO structure */
#define DSOP_FLAG_MULTISELECT (0x1)
#define DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK (0x2)
typedef struct _DSOP_INIT_INFO
{
ULONG cbSize;
PCWSTR pwzTargetComputer;
ULONG cDsScopeInfos;
PDSOP_SCOPE_INIT_INFO aDsScopeInfos;
ULONG flOptions;
ULONG cAttributesToFetch;
PCWSTR *apwzAttributeNames;
} DSOP_INIT_INFO, *PDSOP_INIT_INFO;
typedef const DSOP_INIT_INFO *PCDSOP_INIT_INFO;
/* selection scope types in the DS_SELECTION structure */
#define DSOP_SCOPE_TYPE_TARGET_COMPUTER (0x1)
#define DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN (0x2)
#define DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN (0x4)
#define DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN (0x8)
#define DSOP_SCOPE_TYPE_GLOBAL_CATALOG (0x10)
#define DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN (0x20)
#define DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN (0x40)
#define DSOP_SCOPE_TYPE_WORKGROUP (0x80)
#define DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE (0x100)
#define DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE (0x200)
typedef struct _DS_SELECTION
{
PWSTR pwzName;
PWSTR pwzADsPath;
PWSTR pwzClass;
PWSTR pwzUPN;
VARIANT *pvarFetchedAttributes;
ULONG flScopeType;
} DS_SELECTION, *PDS_SELECTION;
typedef struct _DS_SELECTION_LIST
{
ULONG cItems;
ULONG cFetchedAttributes;
DS_SELECTION aDsSelection[ANYSIZE_ARRAY];
} DS_SELECTION_LIST, *PDS_SELECTION_LIST;
/*****************************************************************************
* IDsObjectPicker interface
*/
#define INTERFACE IDsObjectPicker
DECLARE_INTERFACE_(IDsObjectPicker,IUnknown)
{
/*** IUnknown methods ***/
STDMETHOD_(HRESULT,QueryInterface)(THIS_ REFIID riid, void** ppvObject) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
/*** IDsObjectPicker methods ***/
STDMETHOD(Initialize)(THIS_ PDSOP_INIT_INFO pInitInfo) PURE;
STDMETHOD(InvokeDialog)(THIS_ HWND hwndParent, IDataObject** ppdoSelections) PURE;
};
#undef INTERFACE
#ifdef __cplusplus
}
#endif
#endif /* __OBJSEL_H_ */
| 2,929 |
4,625 |
<gh_stars>1000+
// Copyright 2017 JanusGraph Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.janusgraph.diskstorage.util;
import org.janusgraph.diskstorage.ReadBuffer;
/**
* Implementation of {@link ReadBuffer} against a byte array.
*
* Note, that the position does not impact the state of the object. Meaning, equals, hashcode,
* and compare ignore the position.
*
* @author <NAME> (<EMAIL>)
*/
public class ReadArrayBuffer extends StaticArrayBuffer implements ReadBuffer {
public ReadArrayBuffer(byte[] array) {
super(array);
}
ReadArrayBuffer(StaticArrayBuffer buffer) {
super(buffer);
}
protected ReadArrayBuffer(byte[] array, int limit) {
super(array, 0,limit);
}
@Override
void reset(int newOffset, int newLimit) {
position=0;
super.reset(newOffset,newLimit);
}
/*
############ IDENTICAL CODE #############
*/
private transient int position=0;
private int updatePos(int update) {
int pos = position;
position+=update;
return pos;
}
@Override
public int getPosition() {
return position;
}
@Override
public boolean hasRemaining() {
return position<length();
}
@Override
public void movePositionTo(int newPosition) {
assert newPosition >= 0 && newPosition <= length();
position = newPosition;
}
@Override
public byte getByte() {
return getByte(updatePos(1));
}
@Override
public boolean getBoolean() {
return getBoolean(updatePos(1));
}
@Override
public short getShort() {
return getShort(updatePos(2));
}
@Override
public int getInt() {
return getInt(updatePos(4));
}
@Override
public long getLong() {
return getLong(updatePos(8));
}
@Override
public char getChar() {
return getChar(updatePos(2));
}
@Override
public float getFloat() {
return getFloat(updatePos(4));
}
@Override
public double getDouble() {
return getDouble(updatePos(8));
}
//------
public byte[] getBytes(int length) {
byte[] result = super.getBytes(position,length);
position += length*BYTE_LEN;
return result;
}
public short[] getShorts(int length) {
short[] result = super.getShorts(position,length);
position += length*SHORT_LEN;
return result;
}
public int[] getInts(int length) {
int[] result = super.getInts(position,length);
position += length*INT_LEN;
return result;
}
public long[] getLongs(int length) {
long[] result = super.getLongs(position,length);
position += length*LONG_LEN;
return result;
}
public char[] getChars(int length) {
char[] result = super.getChars(position,length);
position += length*CHAR_LEN;
return result;
}
public float[] getFloats(int length) {
float[] result = super.getFloats(position,length);
position += length*FLOAT_LEN;
return result;
}
public double[] getDoubles(int length) {
double[] result = super.getDoubles(position,length);
position += length*DOUBLE_LEN;
return result;
}
@Override
public<T> T asRelative(final Factory<T> factory) {
if (position==0) return as(factory);
else {
return as((array, offset, limit) -> factory.get(array,offset+position,limit));
}
}
@Override
public ReadBuffer subrange(int length, boolean invert) {
return super.subrange(position,length,invert).asReadBuffer();
}
}
| 1,611 |
381 |
from rpython.rlib.parsing.regexparse import make_runner
def test_simple():
r = make_runner("a*")
assert r.recognize("aaaaa")
assert r.recognize("")
assert not r.recognize("aaaaaaaaaaaaaaaaaaaaaaaaaa ")
r = make_runner("a*bc|d")
assert r.recognize("aaaaabc")
assert r.recognize("bc")
assert r.recognize("d")
assert not r.recognize("abcd")
r = make_runner("(ab)*|a*b*")
assert r.recognize("ababababab")
assert r.recognize("aaaabb")
assert not r.recognize("abababaabb")
r = make_runner(".*")
assert r.recognize("kjsadfq3jlflASDF@#$")
assert r.recognize("vka afj ASF# A")
def test_quoted_1():
r = make_runner("\\(*")
assert r.recognize("(")
assert not r.recognize("\\(")
r = make_runner("(\\x61a)*")
assert r.recognize("aa")
assert r.recognize("aaaaaa")
assert not r.recognize("a")
assert not r.recognize("aabb")
r = make_runner("(\\x61a)*")
assert r.recognize("aa")
assert r.recognize("aaaaaa")
assert not r.recognize("a")
assert not r.recognize("aabb")
def test_range():
r = make_runner("[A-Z]")
assert r.recognize("A")
assert r.recognize("F")
assert r.recognize("Z")
assert not r.recognize("j")
r = make_runner("[a-ceg-i]")
assert r.recognize("a")
assert r.recognize("b")
assert r.recognize("c")
assert r.recognize("e")
assert r.recognize("g")
assert r.recognize("h")
assert r.recognize("i")
assert not r.recognize("d")
assert not r.recognize("f")
r = make_runner("[^a-ceg-i]")
assert not r.recognize("a")
assert not r.recognize("b")
assert not r.recognize("c")
assert not r.recognize("e")
assert not r.recognize("g")
assert not r.recognize("h")
assert not r.recognize("i")
assert r.recognize("d")
assert r.recognize("f")
def test_plus():
r = make_runner("[0-9]+")
assert r.recognize("09123")
assert not r.recognize("")
r = make_runner("a+b+")
assert r.recognize("ab")
assert r.recognize("aaaaabbb")
assert not r.recognize("b")
assert not r.recognize("a")
assert not r.recognize("c")
def test_quoted_2():
r = make_runner('\\[|\\]|\\|')
assert r.recognize("[")
assert r.recognize("|")
assert r.recognize("]")
assert not r.recognize("]]")
def test_questionmark():
r = make_runner("ab?")
assert r.recognize("a")
assert r.recognize("ab")
r = make_runner("0|(\\+|\\-)?[1-9][0-9]*")
assert r.recognize("0")
assert not r.recognize("00")
assert r.recognize("12341")
assert not r.recognize("021314")
assert r.recognize("+12314")
assert r.recognize("-12314")
def test_repetition():
r = make_runner('a{15}')
assert r.recognize("a" * 15)
assert not r.recognize("a" * 14)
assert not r.recognize("a" * 16)
assert not r.recognize("b" * 15)
r = make_runner('a{2,10}')
assert r.recognize("a" * 2)
assert r.recognize("a" * 5)
assert r.recognize("a" * 10)
assert not r.recognize("a")
assert not r.recognize("a" + "b")
assert not r.recognize("a" * 11)
assert not r.recognize("a" * 12)
r = make_runner('a{3,}')
assert r.recognize("a" * 3)
assert r.recognize("a" * 5)
assert r.recognize("a" * 10)
assert r.recognize("a" * 12)
assert not r.recognize("a")
assert not r.recognize("a" + "b")
assert not r.recognize("a" * 2)
def test_quotes():
r = make_runner('"[^\\"]*"')
assert r.recognize('"abc"')
assert r.recognize('"asdfefveeaa"')
assert not r.recognize('"""')
r = make_runner('\\n\\x0a')
assert not r.recognize("n\n")
assert r.recognize("\n\n")
r = make_runner('\\12\\012')
assert r.recognize("\n\n")
r = make_runner('\\377\\xff')
assert r.recognize("\xff\xff")
r = make_runner('\\?')
assert r.recognize("?")
assert not r.recognize("a")
def test_comment():
r = make_runner("(/\\*[^\\*/]*\\*/)")
assert r.recognize("/*asdfasdfasdf*/")
def test_singlequote():
r = make_runner("'")
assert r.recognize("'")
assert not r.recognize('"')
r = make_runner("'..*'")
assert r.recognize("'adadf'")
assert not r.recognize("'adfasdf")
r = make_runner("([a-z]([a-zA-Z0-9]|_)*)|('..*')")
assert r.recognize("aasdf")
assert r.recognize("'X'")
assert not r.recognize("''")
def test_unescape():
from rpython.rlib.parsing.regexparse import unescape
s = "".join(["\\x%s%s" % (a, b) for a in "0123456789abcdefABCDEF"
for b in "0123456789ABCDEFabcdef"])
assert unescape(s) == eval("'" + s + "'")
def test_escaped_quote():
r = make_runner(r'"[^\\"]*(\\.[^\\"]*)*"')
assert r.recognize(r'""')
assert r.recognize(r'"a"')
assert r.recognize(r'"a\"b"')
assert r.recognize(r'"\\\""')
assert not r.recognize(r'"\\""')
def test_number():
r = make_runner(r"\-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][\+\-]?[0-9]+)?")
assert r.recognize("-0.912E+0001")
assert not r.recognize("-0.a912E+0001")
assert r.recognize("5")
def test_charclass():
r = make_runner(r"\d")
assert r.recognize('0')
assert r.recognize('5')
assert r.recognize('9')
assert not r.recognize('d')
r = make_runner(r"\d{2,}")
assert r.recognize('09')
assert r.recognize('158')
assert not r.recognize('1')
r = make_runner(r"\D")
assert r.recognize('d')
assert r.recognize('\n')
assert not r.recognize('0')
assert not r.recognize('1234')
r = make_runner(r"\s\S")
assert r.recognize(' d')
assert r.recognize('\t9')
assert not r.recognize('d ')
assert not r.recognize('99')
assert not r.recognize('\r\r')
r = make_runner(r"\w+")
assert r.recognize('word')
assert r.recognize('variable_name')
assert r.recognize('abc123')
assert not r.recognize('word\n')
assert not r.recognize('hey hey')
r = make_runner(r"\w\W\w")
assert r.recognize('9 9')
assert r.recognize('_\fx')
assert not r.recognize('\n\r\t')
def test_charclass_in_range():
r = make_runner(r"[\de]")
assert r.recognize('0')
assert r.recognize('5')
assert r.recognize('9')
assert r.recognize('e')
assert not r.recognize('d')
r = make_runner(r"[\de]{2,}")
assert r.recognize('09')
assert r.recognize('158')
assert r.recognize('3eee')
assert not r.recognize('1')
assert not r.recognize('ddee')
r = make_runner(r"[\D5]")
assert r.recognize('d')
assert r.recognize('\n')
assert r.recognize('5')
assert not r.recognize('0')
r = make_runner(r"[\s][\S]")
assert r.recognize(' d')
assert r.recognize('\t9')
assert not r.recognize('d ')
assert not r.recognize('99')
assert not r.recognize('\r\r')
r = make_runner(r"[\w]+\W[\w]+")
assert r.recognize('hey hey')
assert not r.recognize('word')
assert not r.recognize('variable_name')
| 3,092 |
1,264 |
/*
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;
import static org.assertj.core.api.Assertions.*;
import org.bson.Document;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link GeoCommandStatistics}.
*
* @author <NAME>
* @author <NAME>
* @soundtrack Fruitcake - <NAME> (The Inside of the Outside)
*/
public class GeoCommandStatisticsUnitTests {
@Test // DATAMONGO-1361
public void rejectsNullCommandResult() {
assertThatIllegalArgumentException().isThrownBy(() -> GeoCommandStatistics.from(null));
}
@Test // DATAMONGO-1361
public void fallsBackToNanIfNoAverageDistanceIsAvailable() {
GeoCommandStatistics statistics = GeoCommandStatistics.from(new Document("stats", null));
assertThat(statistics.getAverageDistance()).isNaN();
statistics = GeoCommandStatistics.from(new Document("stats", new Document()));
assertThat(statistics.getAverageDistance()).isNaN();
}
@Test // DATAMONGO-1361
public void returnsAverageDistanceIfPresent() {
GeoCommandStatistics statistics = GeoCommandStatistics
.from(new Document("stats", new Document("avgDistance", 1.5)));
assertThat(statistics.getAverageDistance()).isEqualTo(1.5);
}
}
| 531 |
5,169 |
<reponame>Gantios/Specs
{
"name": "BOSEngine",
"version": "0.0.1",
"summary": "This is the framw work used for BOSEngine",
"description": "This is the framw work used for Bos activities",
"homepage": "https://github.com/appsfreedom1/BOS-Framework",
"license": "MIT",
"authors": {
"vishnu": "<EMAIL>"
},
"platforms": {
"ios": "10.0"
},
"source": {
"git": "https://github.com/appsfreedom1/BOS-Framework.git",
"tag": "0.0.1"
},
"source_files": "BOSEngine/*.{h,m}"
}
| 215 |
370 |
#pragma once
#include "Trinity.TSL.CodeGen.h"
#include "OptionalFieldCalculator.h"
#include "AccessorType.h"
#include <string>
#include "SyntaxNode.h"
using std::string;
namespace Trinity
{
namespace Codegen
{
extern std::string target_namespace;
extern bool contains_substring_index;
extern int celltype_offset;
extern std::vector<NFieldType*> *TSLDataTypeVector;
extern std::vector<NFieldType*> *TSLExternalParserDataTypeVector;
extern std::vector<NFieldType*> *TSLSerializerDataTypeVector;
extern std::vector<std::unique_ptr<NFieldType>> *TSLSubstringIndexedListTypes;
extern std::vector<NCell*>* TSLIndexIdentifierCellVector;
extern std::vector<NStruct*>* TSLIndexIdentifierStructVector;
extern std::unordered_map<NStructBase*, std::vector<NField*>*>* TSLIndexIdentifierSubstructureMap;
extern std::unordered_map<NStructBase*, std::vector<NField*>*>* TSLIndexIdentifierTargetMap;
extern std::unordered_map<NField*, int>* TSLIndexFieldIdMap;
extern std::unordered_map<NIndex*, int>* TSLIndexIdMap;
extern std::vector<NIndex*>* TSLIndexTargetVector;
std::string GetDataTypeString(NFieldType* n_field_type);
std::string GetDataTypeDisplayString(NFieldType* n_field_type);
std::string GetNonNullableValueTypeString(NFieldType* n_field_type);
inline int GetCellTypeOffset()
{
return celltype_offset;
}
inline std::string GetNamespace()
{
return target_namespace;
}
inline std::string GetString(std::string* str)
{
return *str;
}
inline std::string GetString(NFieldType* n_field_type)
{
return GetDataTypeString(n_field_type);
}
template<typename T>
inline std::string GetString(std::unique_ptr<T> &ptr)
{
return GetString(ptr.get());
}
inline std::string GetString(int val)
{
return std::to_string(val);
}
inline std::string GetString(const std::string& val)
{
return val;
}
inline std::string Discard(const std::string& str)
{
return "";
}
inline const std::string Discard(int x)
{
return "";
}
inline const std::string Discard(const std::string* str)
{
return "";
}
bool data_type_need_accessor(NFieldType* type);
bool data_type_compatible_with_cell(NFieldType* type, NCell* cell);
bool data_type_need_string_parse(NFieldType *type, NFieldType* cell_field);
bool data_type_need_bool_convert(NFieldType *type, NFieldType* cell_field);
bool data_type_need_tostring(NFieldType *type, NFieldType* cell_field);
bool data_type_need_external_parser(NFieldType* type);
bool data_type_need_set_field(NFieldType* type, std::vector<NFieldType*>* type_list);
bool data_type_need_type_id(NFieldType* type, std::vector<NFieldType*>* type_list);
bool data_type_is_not_duplicate_nested_list_of_array(NFieldType* type, std::vector<NFieldType*>* type_list);
bool data_type_is_not_duplicate_array(NFieldType* type, std::vector<NFieldType*>* type_list);
bool data_type_is_length_prefixed(NFieldType* type);
std::string data_type_get_array_type_with_size_string(NFieldType* type);
std::string data_type_get_array_size_specifier_string(NFieldType* type);
std::string data_type_get_accessor_name(NFieldType* type);
std::string get_comm_class_basename(NProtocolGroup* protocol_group);
std::string get_comm_protocol_trinitymessagetype(NProtocol* protocol);
std::string get_comm_protocol_type_string(NProtocol* protocol);
std::string get_http_handler_parameters(NProtocol* protocol);
std::string get_http_handler_calling_parameters(NProtocol* protocol);
std::string get__index_member_name(NIndex* idx);
std::string get__index_access_path_for_cell(NIndex* idx);
std::string get_signature_string(NStructBase*);
}
}
| 2,082 |
1,040 |
<filename>Src/Vessel/Quadcopter/PropulsionSubsys.h
// Copyright (c) <NAME>
// Licensed under the MIT License
#ifndef __PROPULSIONSUBSYS_H
#define __PROPULSIONSUBSYS_H
#include "QuadcopterSubsys.h"
class Rotor;
class PropulsionSubsystem : public QuadcopterSubsystem {
public:
PropulsionSubsystem(Quadcopter *qc);
double getAtmDensity() const;
double getMaxThrust() const;
void setDirectMode(bool active);
void setAutoHeading(bool active);
void setHeadingCmd(double heading);
void setCourseCmd(double course);
void setCourseCmd(double course, double hspd);
void unsetCourseCmd();
void setHspdCmd(double hspd);
void unsetHspdCmd();
void setVspdCmd(double vspd);
void unsetVspdCmd();
void setAltCmd(double alt);
void unsetAltCmd();
void clbkPreStep(double simt, double simdt, double mjd);
enum RotorId {
ROTOR_FL,
ROTOR_FR,
ROTOR_BL,
ROTOR_BR
};
enum ThrottleMode {
THROTTLE_DIRECT,
THROTTLE_VSPD
};
enum AttitudeMode {
ATTITUDE_DIRECT,
ATTITUDE_CMD
};
protected:
double TiltAngle() const;
void HoldActivate(bool active);
void HoldHspd(double hh_tgt);
void HoldVspd(double vh_tgt);
void HoldAlt(double alt_tgt);
void SetAttitude(double pitch_cmd, double roll_cmd, double &p_diff, double &b_diff);
void SetYawVelocity(double yaw_cmd, double &y_diff);
bool SetHeading(double hdg_cmd, double &y_diff);
void SetCourse(double course_cmd, double tilt_cmd, double &pitch, double &roll);
void SetHspdVector(double course_cmd, double hspd_cmd, double &pitch, double &roll);
private:
Rotor *m_rotor[4];
double m_throttle;
double m_holdT;
double m_pHspdT;
double m_pvh;
double m_phh;
double m_pvx, m_pvz;
double m_headingCmd;
double m_courseCmd;
double m_hspdCmd;
double m_vspdCmd;
double m_altCmd;
double m_tiltTgt;
bool m_headingActive;
bool m_courseActive;
bool m_hspdActive;
bool m_vspdActive;
bool m_altActive;
bool m_holdActive;
bool m_autoHeading;
ThrottleMode m_throttleMode;
AttitudeMode m_attitudeMode;
};
#endif // !__PROPULSIONSUBSYS_H
| 826 |
615 |
/* ************************************************************************
* Copyright 2013 Advanced Micro Devices, 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.
* ************************************************************************/
//#define DEBUG_TBMV
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <clBLAS.h>
#include <devinfo.h>
#include "clblas-internal.h"
#include "solution_seq.h"
clblasStatus
doTbmv(
CLBlasKargs *kargs,
clblasOrder order,
clblasUplo uplo,
clblasTranspose trans,
clblasDiag diag,
size_t N,
size_t K,
const cl_mem A,
size_t offa,
size_t lda,
cl_mem x,
size_t offx,
int incx,
cl_mem y, // Scratch Buffer
cl_uint numCommandQueues,
cl_command_queue *commandQueues,
cl_uint numEventsInWaitList,
const cl_event *eventWaitList,
cl_event *events)
{
cl_int err;
ListHead seq;
size_t sizeOfVector;
cl_event *newEventWaitList;
clblasStatus retCode = clblasSuccess;
if (!clblasInitialized) {
return clblasNotInitialized;
}
/* Validate arguments */
if ((retCode = checkMemObjects(A, x, y, true, A_MAT_ERRSET, X_VEC_ERRSET, Y_VEC_ERRSET))) {
#ifdef DEBUG_TBMV
printf("Invalid mem object..\n");
#endif
return retCode;
}
if ((retCode = checkBandedMatrixSizes(kargs->dtype, order, trans, N, N, K, 0, A, offa, lda, A_MAT_ERRSET))) {
#ifdef DEBUG_TBMV
printf("Invalid Size for A\n");
#endif
return retCode;
}
if ((retCode = checkVectorSizes(kargs->dtype, N, x, offx, incx, X_VEC_ERRSET))) {
#ifdef DEBUG_TBMV
printf("Invalid Size for X\n");
#endif
return retCode;
}
if ((retCode = checkVectorSizes(kargs->dtype, N, y, 0, incx, Y_VEC_ERRSET))) {
#ifdef DEBUG_TBMV
printf("Invalid Size for scratch vector\n");
#endif
return retCode;
}
#ifdef DEBUG_TBMV
printf("DoTbmv being called...\n");
#endif
if ((commandQueues == NULL) || (numCommandQueues == 0))
{
return clblasInvalidValue;
}
numCommandQueues = 1;
if ((numEventsInWaitList !=0) && (eventWaitList == NULL))
{
return clblasInvalidEventWaitList;
}
newEventWaitList = malloc((numEventsInWaitList+1) * sizeof(cl_event));
if (newEventWaitList == NULL)
{
return clblasOutOfHostMemory;
}
if (numEventsInWaitList != 0 )
{
memcpy(newEventWaitList, eventWaitList, numEventsInWaitList*sizeof(cl_event));
}
/*
* ASSUMPTION:
* doTBMV assumes "commandQueue" of 0. The same is reflected in
* "makeSolutionSeq" as well. If either of them changes in future,
* this code needs to be revisited.
*/
sizeOfVector = (1 + (N-1)*abs(incx)) * dtypeSize(kargs->dtype);
err = clEnqueueCopyBuffer(commandQueues[0], x, y, offx*dtypeSize(kargs->dtype), 0, sizeOfVector,
numEventsInWaitList, eventWaitList, &newEventWaitList[numEventsInWaitList]);
if (err != CL_SUCCESS)
{
free(newEventWaitList);
return err;
}
kargs->order = order;
kargs->uplo = uplo;
kargs->transA = trans;
kargs->diag = diag;
kargs->M = N;
kargs->N = N;
if( uplo == clblasUpper )
{
kargs->KL = 0;
kargs->KU = K;
}
else {
kargs->KL = K;
kargs->KU = 0;
}
kargs->A = A;
kargs->lda.matrix = lda;
kargs->B = y; // Now it becomes x = A * y
kargs->ldb.Vector = incx;
kargs->C = x;
kargs->ldc.Vector = incx;
kargs->offBX = 0; // Not used by assignKargs(); Just for clarity
kargs->offCY = offx;
kargs->offa = offa;
kargs->offA = offa;
#ifdef DEBUG_TBMV
printf("Calling makeSolutionSeq : TBMV\n");
#endif
listInitHead(&seq);
err = makeSolutionSeq(CLBLAS_GBMV, kargs, numCommandQueues, commandQueues,
numEventsInWaitList+1, newEventWaitList, events, &seq);
if (err == CL_SUCCESS) {
err = executeSolutionSeq(&seq);
}
freeSolutionSeq(&seq);
free(newEventWaitList);
return (clblasStatus)err;
}
clblasStatus
clblasStbmv(
clblasOrder order,
clblasUplo uplo,
clblasTranspose trans,
clblasDiag diag,
size_t N,
size_t K,
const cl_mem A,
size_t offa,
size_t lda,
cl_mem X,
size_t offx,
int incx,
cl_mem scratchBuff,
cl_uint numCommandQueues,
cl_command_queue *commandQueues,
cl_uint numEventsInWaitList,
const cl_event *eventWaitList,
cl_event *events)
{
CLBlasKargs kargs;
#ifdef DEBUG_TBMV
printf("STBMV Called\n");
#endif
memset(&kargs, 0, sizeof(kargs));
kargs.dtype = TYPE_FLOAT;
kargs.pigFuncID = CLBLAS_TBMV;
return doTbmv(&kargs, order, uplo, trans, diag, N, K, A, offa, lda, X, offx, incx, scratchBuff, numCommandQueues, commandQueues,
numEventsInWaitList, eventWaitList, events);
}
clblasStatus
clblasDtbmv(
clblasOrder order,
clblasUplo uplo,
clblasTranspose trans,
clblasDiag diag,
size_t N,
size_t K,
const cl_mem A,
size_t offa,
size_t lda,
cl_mem X,
size_t offx,
int incx,
cl_mem scratchBuff,
cl_uint numCommandQueues,
cl_command_queue *commandQueues,
cl_uint numEventsInWaitList,
const cl_event *eventWaitList,
cl_event *events)
{
CLBlasKargs kargs;
#ifdef DEBUG_TBMV
printf("DTBMV called\n");
#endif
memset(&kargs, 0, sizeof(kargs));
kargs.dtype = TYPE_DOUBLE;
kargs.pigFuncID = CLBLAS_TBMV;
return doTbmv(&kargs, order, uplo, trans, diag, N, K, A, offa, lda, X, offx, incx, scratchBuff, numCommandQueues, commandQueues,
numEventsInWaitList, eventWaitList, events);
}
clblasStatus
clblasCtbmv(
clblasOrder order,
clblasUplo uplo,
clblasTranspose trans,
clblasDiag diag,
size_t N,
size_t K,
const cl_mem A,
size_t offa,
size_t lda,
cl_mem X,
size_t offx,
int incx,
cl_mem scratchBuff,
cl_uint numCommandQueues,
cl_command_queue *commandQueues,
cl_uint numEventsInWaitList,
const cl_event *eventWaitList,
cl_event *events)
{
CLBlasKargs kargs;
#ifdef DEBUG_TBMV
printf("CTBMV called\n");
#endif
memset(&kargs, 0, sizeof(kargs));
kargs.dtype = TYPE_COMPLEX_FLOAT;
kargs.pigFuncID = CLBLAS_TBMV;
return doTbmv(&kargs, order, uplo, trans, diag, N, K, A, offa, lda, X, offx, incx, scratchBuff, numCommandQueues, commandQueues,
numEventsInWaitList, eventWaitList, events);
}
clblasStatus
clblasZtbmv(
clblasOrder order,
clblasUplo uplo,
clblasTranspose trans,
clblasDiag diag,
size_t N,
size_t K,
const cl_mem A,
size_t offa,
size_t lda,
cl_mem X,
size_t offx,
int incx,
cl_mem scratchBuff,
cl_uint numCommandQueues,
cl_command_queue *commandQueues,
cl_uint numEventsInWaitList,
const cl_event *eventWaitList,
cl_event *events)
{
CLBlasKargs kargs;
#ifdef DEBUG_TBMV
printf("ZTBMV called\n");
#endif
memset(&kargs, 0, sizeof(kargs));
kargs.dtype = TYPE_COMPLEX_DOUBLE;
kargs.pigFuncID = CLBLAS_TBMV;
return doTbmv(&kargs, order, uplo, trans, diag, N, K, A, offa, lda, X, offx, incx, scratchBuff, numCommandQueues, commandQueues,
numEventsInWaitList, eventWaitList, events);
}
| 3,434 |
521 |
/**
* @file src/dwarfparser/dwarf_resources.cpp
* @brief Implementation of classes representing resources.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <iostream>
#include "retdec/dwarfparser/dwarf_resources.h"
using namespace std;
namespace retdec {
namespace dwarfparser {
/**
* @brief Print contents of this class.
*/
void DwarfResources::dump()
{
cout << endl;
cout << "==================== Resources ====================" << endl;
cout << endl;
cout << "Register mapping:" << endl;
const char *s0 = "Idx";
const char *s1 = "Dwarf num.";
const char *s2 = "Array num.";
const char *s3 = "Name";
printf("\t%4s %10s %10s %-30s\n", s0, s1, s2, s3);
unsigned idx = 0;
map<Dwarf_Half, RealReg>::iterator mIter;
for(mIter=m_regMaps.begin(); mIter!=m_regMaps.end(); ++mIter)
{
printf("\t%4d %10d %10d %-30s\n",
idx,
(*mIter).first,
(*mIter).second.arrayNum,
(*mIter).second.name.c_str()
);
idx++;
}
cout << endl;
}
/**
* @brief Gets DWARF register number and returns its content.
* @param n DWARF register number.
* @return value of the given register.
*/
Dwarf_Signed DwarfResources::getReg(Dwarf_Half n)
{
(void) n;
return EMPTY_SIGNED;
}
/**
* @brief Gets name of register array and number in register array and returns content of that register.
* @param name is a name of register array.
* @param number is a number in register array.
* @return value of the given register.
*/
Dwarf_Signed DwarfResources::getReg(std::string name, Dwarf_Addr number)
{
(void) name;
(void) number;
return EMPTY_SIGNED;
}
/**
* @brief Gets address and returns its content.
* @param a Address to get.
* @return Value on the given address.
* @note It use only one (always the first) address name space at the moment.
*/
Dwarf_Signed DwarfResources::getAddr(Dwarf_Addr a)
{
(void) a;
return EMPTY_SIGNED;
}
/**
* @brief Gets content of program counter register.
* @return Value of program counter.
*/
Dwarf_Addr DwarfResources::getPcReg()
{
return EMPTY_SIGNED;
}
/**
* @brief Gets DWARF register number and sets name of register array and
* its index number used in architecture.
* @param reg Register number used by DWARF.
* @param n Name of register array in architecture to set.
* @param a Index number of register in register array to set.
*/
void DwarfResources::setReg(Dwarf_Half reg, string *n, Dwarf_Addr *a)
{
map<Dwarf_Half, RealReg>::iterator iter;
iter = m_regMaps.find(reg);
if (iter == m_regMaps.end())
{
DWARF_ERROR("DwarfResources::setReg(): DWARF register num is not mapped to a register.");
}
else
{
RealReg rr = (*iter).second;
*n = rr.name;
*a = rr.arrayNum;
}
}
/**
* @brief Init mapping of DWARF register numbers to names using
* default -- well known mapping for architectures.
* @param m Architecture which default mapping will be used.
*/
void DwarfResources::initMappingDefault(eDefaultMap m)
{
switch (m)
{
//
// Mapping is the same as the one generated by compiler.
// MIPS-32.
//
case MIPS:
{
unsigned i = 0;
string general = "gpregs";
for (unsigned j=0; j<32; j++, i++)
m_regMaps[i] = RealReg(general, j);
// Mapping same as in files from compiler.
// But according to tests, fpu registers begin on number 32.
// Single precision.
string fpu_s = "fpuregs_s";
for (unsigned j=0; j<32; j++, i++)
m_regMaps[i] = RealReg(fpu_s, j);
// Double precision - on MIPS 32.
string fpu_d = "fpuregs_d";
i = 32;
for (unsigned j=0; j<16; j++, i=i+2)
{
m_regMaps[i+i+1] = RealReg(fpu_d, i-32);
}
break;
}
//
// Only first 16 general registers are mapped.
// Name of register array was taken from ARM semantics specification (resource_name record).
//
case ARM:
{
unsigned i;
string general = "regs";
for (i=0; i<16; i++)
m_regMaps[i] = RealReg(general, i);
m_regMaps[128] = RealReg("spsr", 0);
break;
}
//
// Only 8 general registers (32-bit) are mapped.
// Name of register array was taken from x86 semantics specification (resource_name record).
//
case X86:
{
unsigned i;
string general = "gp32";
for (i=0; i<8; i++)
m_regMaps[i] = RealReg(general, i);
break;
}
//
// Default.
//
default:
{
DWARF_ERROR("DwarfResources::initMappingDefault: unrecognized type of default mapping used.");
initMappingDefault(MIPS);
break;
}
}
}
} // namespace dwarfparser
} // namespace retdec
| 1,736 |
7,857 |
<reponame>NeryHenrique/nodegui<gh_stars>1000+
#pragma once
#include <napi.h>
#include <QPointer>
#include "Extras/Export/export.h"
#include "QtWidgets/QWidget/qwidget_macro.h"
#include "nlcdnumber.hpp"
class DLL_EXPORT QLCDNumberWrap : public Napi::ObjectWrap<QLCDNumberWrap> {
QWIDGET_WRAPPED_METHODS_DECLARATION
private:
QPointer<NLCDNumber> instance;
public:
static Napi::Object init(Napi::Env env, Napi::Object exports);
QLCDNumberWrap(const Napi::CallbackInfo& info);
~QLCDNumberWrap();
NLCDNumber* getInternalInstance();
// class constructor
static Napi::FunctionReference constructor;
// wrapped methods
Napi::Value checkOverflow(const Napi::CallbackInfo& info);
Napi::Value display(const Napi::CallbackInfo& info);
Napi::Value setBinMode(const Napi::CallbackInfo& info);
Napi::Value setDecMode(const Napi::CallbackInfo& info);
Napi::Value setHexMode(const Napi::CallbackInfo& info);
Napi::Value setOctMode(const Napi::CallbackInfo& info);
};
| 356 |
746 |
package org.protege.editor.core;
/**
* <NAME>
* Stanford Center for Biomedical Informatics Research
* 7 Nov 2016
*/
public interface HasUpdateState {
/**
* Update the state of this object
*/
void updateState();
}
| 78 |
348 |
<gh_stars>100-1000
{"nom":"Fargues-sur-Ourbise","circ":"2ème circonscription","dpt":"Lot-et-Garonne","inscrits":330,"abs":164,"votants":166,"blancs":13,"nuls":7,"exp":146,"res":[{"nuance":"REM","nom":"<NAME>","voix":91},{"nuance":"FN","nom":"<NAME>","voix":55}]}
| 108 |
1,059 |
/* SPDX-License-Identifier: BSD-2-Clause */
#include <tilck/common/basic_defs.h>
#include <tilck/common/assert.h>
#include <tilck/common/string_util.h>
#include <tilck/common/fat32_base.h>
/*
* The following code uses in many cases the CamelCase naming convention
* because it is based on the Microsoft's public document:
*
* Microsoft Extensible Firmware Initiative
* FAT32 File System Specification
*
* FAT: General Overview of On-Disk Format
*
* Version 1.03, December 6, 2000
*
* Keeping the exact same names as the official document, helps a lot.
*/
#define FAT_ENTRY_LAST ((char)0)
#define FAT_ENTRY_AVAILABLE ((char)0xE5)
static u8 shortname_checksum(u8 *shortname)
{
u8 sum = 0;
for (int i = 0; i < 11; i++) {
// NOTE: The operation is an unsigned char rotate right
sum = (u8)( ((sum & 1u) ? 0x80u : 0u) + (sum >> 1u) + *shortname++ );
}
return sum;
}
static const bool fat32_valid_chars[256] =
{
[0 ... 32] = 0,
[33] = 0, /* ! */
[34] = 0, /* " */
[35] = 1, /* # */
[36] = 1, /* $ */
[37] = 1, /* % */
[38] = 1, /* & */
[39] = 1, /* ' */
[40] = 1, /* ( */
[41] = 1, /* ) */
[42] = 0, /* * */
[43] = 1, /* + */
[44] = 1, /* , */
[45] = 1, /* - */
[46] = 1, /* . */
[47] = 0, /* / */
[48] = 1, /* 0 */
[49] = 1, /* 1 */
[50] = 1, /* 2 */
[51] = 1, /* 3 */
[52] = 1, /* 4 */
[53] = 1, /* 5 */
[54] = 1, /* 6 */
[55] = 1, /* 7 */
[56] = 1, /* 8 */
[57] = 1, /* 9 */
[58] = 0, /* : */
[59] = 1, /* ; */
[60] = 0, /* < */
[61] = 1, /* = */
[62] = 0, /* > */
[63] = 0, /* ? */
[64] = 1, /* @ */
[65] = 1, /* A */
[66] = 1, /* B */
[67] = 1, /* C */
[68] = 1, /* D */
[69] = 1, /* E */
[70] = 1, /* F */
[71] = 1, /* G */
[72] = 1, /* H */
[73] = 1, /* I */
[74] = 1, /* J */
[75] = 1, /* K */
[76] = 1, /* L */
[77] = 1, /* M */
[78] = 1, /* N */
[79] = 1, /* O */
[80] = 1, /* P */
[81] = 1, /* Q */
[82] = 1, /* R */
[83] = 1, /* S */
[84] = 1, /* T */
[85] = 1, /* U */
[86] = 1, /* V */
[87] = 1, /* W */
[88] = 1, /* X */
[89] = 1, /* Y */
[90] = 1, /* Z */
[91] = 1, /* [ */
[92] = 0, /* \ */
[93] = 1, /* ] */
[94] = 1, /* ^ */
[95] = 1, /* _ */
[96] = 1, /* ` */
[97] = 1, /* a */
[98] = 1, /* b */
[99] = 1, /* c */
[100] = 1, /* d */
[101] = 1, /* e */
[102] = 1, /* f */
[103] = 1, /* g */
[104] = 1, /* h */
[105] = 1, /* i */
[106] = 1, /* j */
[107] = 1, /* k */
[108] = 1, /* l */
[109] = 1, /* m */
[110] = 1, /* n */
[111] = 1, /* o */
[112] = 1, /* p */
[113] = 1, /* q */
[114] = 1, /* r */
[115] = 1, /* s */
[116] = 1, /* t */
[117] = 1, /* u */
[118] = 1, /* v */
[119] = 1, /* w */
[120] = 1, /* x */
[121] = 1, /* y */
[122] = 1, /* z */
[123] = 1, /* { */
[124] = 0, /* | */
[125] = 1, /* } */
[126] = 1, /* ~ */
[127 ... 255] = 0,
};
bool fat32_is_valid_filename_character(char c)
{
return fat32_valid_chars[(u8)c];
}
/*
* WARNING: this implementation supports only the ASCII subset of UTF16.
*/
static void fat_handle_long_dir_entry(struct fat_walk_long_name_ctx *ctx,
struct fat_long_entry *le)
{
char entrybuf[13] = {0};
int ebuf_size=0;
if (ctx->lname_chksum != le->LDIR_Chksum) {
bzero(ctx->lname_buf, sizeof(ctx->lname_chksum));
ctx->lname_sz = 0;
ctx->lname_chksum = le->LDIR_Chksum;
ctx->is_valid = true;
}
if (!ctx->is_valid)
return;
for (int i = 0; i < 10; i += 2) {
u8 c = le->LDIR_Name1[i];
/* NON-ASCII characters are NOT supported */
if (le->LDIR_Name1[i+1] != 0) {
ctx->is_valid = false;
return;
}
if (c == 0 || c == 0xFF)
goto end;
entrybuf[ebuf_size++] = (char)c;
}
for (int i = 0; i < 12; i += 2) {
u8 c = le->LDIR_Name2[i];
/* NON-ASCII characters are NOT supported */
if (le->LDIR_Name2[i+1] != 0) {
ctx->is_valid = false;
return;
}
if (c == 0 || c == 0xFF)
goto end;
entrybuf[ebuf_size++] = (char)c;
}
for (int i = 0; i < 4; i += 2) {
u8 c = le->LDIR_Name3[i];
/* NON-ASCII characters are NOT supported */
if (le->LDIR_Name3[i+1] != 0) {
ctx->is_valid = false;
return;
}
if (c == 0 || c == 0xFF)
goto end;
entrybuf[ebuf_size++] = (char)c;
}
end:
for (int i = ebuf_size-1; i >= 0; i--) {
char c = entrybuf[i];
if (!fat32_is_valid_filename_character(c)) {
ctx->is_valid = false;
break;
}
ctx->lname_buf[ctx->lname_sz++] = (u8) c;
}
}
static const char *
finalize_long_name(struct fat_walk_long_name_ctx *ctx,
struct fat_entry *e)
{
const s16 e_checksum = shortname_checksum((u8 *)e->DIR_Name);
if (ctx->lname_chksum == e_checksum) {
ctx->lname_buf[ctx->lname_sz] = 0;
str_reverse((char *)ctx->lname_buf, (size_t)ctx->lname_sz);
return (const char *) ctx->lname_buf;
}
return NULL;
}
int
fat_walk(struct fat_walk_static_params *p, u32 cluster)
{
struct fat_walk_long_name_ctx *const ctx = p->ctx;
const u32 entries_per_cluster = fat_get_dir_entries_per_cluster(p->h);
struct fat_entry *dentries = NULL;
ASSERT(p->ft == fat16_type || p->ft == fat32_type);
if (cluster == 0)
dentries = fat_get_rootdir(p->h, p->ft, &cluster);
if (ctx) {
bzero(ctx->lname_buf, sizeof(ctx->lname_buf));
ctx->lname_sz = 0;
ctx->lname_chksum = -1;
ctx->is_valid = false;
}
while (true) {
if (cluster != 0) {
/*
* if cluster != 0, cluster is used and entry is overriden.
* That's because on FAT16 we know only the sector of the root dir.
* In that case, fat_get_rootdir() returns 0 as cluster. In all the
* other cases, we need only the cluster.
*/
dentries = fat_get_pointer_to_cluster_data(p->h, cluster);
}
ASSERT(dentries != NULL);
for (u32 i = 0; i < entries_per_cluster; i++) {
if (ctx && is_long_name_entry(&dentries[i])) {
fat_handle_long_dir_entry(ctx, (void *)&dentries[i]);
continue;
}
// the first "file" is the volume ID. Skip it.
if (dentries[i].volume_id)
continue;
// the entry was used, but now is free
if (dentries[i].DIR_Name[0] == FAT_ENTRY_AVAILABLE)
continue;
// that means all the rest of the entries are free.
if (dentries[i].DIR_Name[0] == FAT_ENTRY_LAST)
return 0;
const char *long_name_ptr = NULL;
if (ctx && ctx->lname_sz > 0 && ctx->is_valid)
long_name_ptr = finalize_long_name(ctx, &dentries[i]);
int ret = p->cb(p->h, p->ft, dentries + i, long_name_ptr, p->arg);
if (ctx) {
ctx->lname_sz = 0;
ctx->lname_chksum = -1;
}
if (ret) {
/* the callback returns a value != 0 to request a walk STOP. */
return 0;
}
}
/*
* In case fat_walk has been called on the root dir on a FAT16,
* cluster is 0 (invalid) and there is no next cluster in the chain. This
* fact seriously limits the number of items in the root dir of a FAT16
* volume.
*/
if (cluster == 0)
break;
/*
* If we're here, it means that there is more then one cluster for the
* entries of this directory. We have to follow the chain.
*/
u32 val = fat_read_fat_entry(p->h, p->ft, 0, cluster);
if (fat_is_end_of_clusterchain(p->ft, val))
break; // that's it: we hit an exactly full cluster.
/* We do not handle BAD CLUSTERS */
ASSERT(!fat_is_bad_cluster(p->ft, val));
cluster = val;
}
return 0;
}
u32 fat_get_cluster_count(struct fat_hdr *hdr)
{
const u32 FATSz = fat_get_FATSz(hdr);
const u32 TotSec = fat_get_TotSec(hdr);
const u32 RootDirSectors = fat_get_root_dir_sectors(hdr);
const u32 FatAreaSize = hdr->BPB_NumFATs * FATSz;
const u32 DataSec = TotSec-(hdr->BPB_RsvdSecCnt+FatAreaSize+RootDirSectors);
return DataSec / hdr->BPB_SecPerClus;
}
enum fat_type fat_get_type(struct fat_hdr *hdr)
{
const u32 CountofClusters = fat_get_cluster_count(hdr);
if (CountofClusters < 4085) {
/* Volume is FAT12 */
return fat12_type;
} else if (CountofClusters < 65525) {
/* Volume is FAT16 */
return fat16_type;
} else {
/* Volume is FAT32 */
return fat32_type;
}
}
static void *
fat_get_entry_ptr(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clu)
{
STATIC_ASSERT(fat16_type == 2);
STATIC_ASSERT(fat32_type == 4);
ASSERT(ft == fat16_type || ft == fat32_type);
ASSERT(fatN < h->BPB_NumFATs);
const u32 FATSz = fat_get_FATSz(h);
const u32 FATOffset = clu * ft;
const u32 ThisFATSecNum =
fatN * FATSz + h->BPB_RsvdSecCnt + (FATOffset / h->BPB_BytsPerSec);
const u32 ThisFATEntOffset = FATOffset % h->BPB_BytsPerSec;
u8 *const SecBuf = (u8*)h + ThisFATSecNum * h->BPB_BytsPerSec;
return SecBuf + ThisFATEntOffset;
}
/*
* Reads the entry in the FAT 'fatN' for cluster 'clusterN'.
* The entry may be 16 or 32 bit. It returns 32-bit integer for convenience.
*/
u32
fat_read_fat_entry(struct fat_hdr *h, enum fat_type ft, u32 fatN, u32 clusterN)
{
void *ptr;
ASSERT(ft == fat16_type || ft == fat32_type);
ptr = fat_get_entry_ptr(h, ft, fatN, clusterN);
return ft == fat16_type ? *(u16 *)ptr : (*(u32 *)ptr) & 0x0FFFFFFF;
}
void
fat_write_fat_entry(struct fat_hdr *h,
enum fat_type ft,
u32 fatN,
u32 clusterN,
u32 value)
{
void *ptr;
ASSERT(ft == fat16_type || ft == fat32_type);
ptr = fat_get_entry_ptr(h, ft, fatN, clusterN);
if (ft == fat16_type) {
ASSERT((value & 0xFFFF0000U) == 0); /* the top 16 bits cannot be used */
*(u16 *)ptr = (u16)value;
} else {
ASSERT((value & 0xF0000000U) == 0); /* the top 4 bits cannot be used */
u32 oldval = *(u32 *)ptr & 0xF0000000U;
*(u32 *)ptr = oldval | value;
}
}
u32 fat_get_first_data_sector(struct fat_hdr *hdr)
{
u32 RootDirSectors = fat_get_root_dir_sectors(hdr);
u32 FATSz;
if (hdr->BPB_FATSz16 != 0) {
FATSz = hdr->BPB_FATSz16;
} else {
struct fat32_header2 *h32 = (struct fat32_header2*) (hdr+1);
FATSz = h32->BPB_FATSz32;
}
u32 FirstDataSector = hdr->BPB_RsvdSecCnt +
(hdr->BPB_NumFATs * FATSz) + RootDirSectors;
return FirstDataSector;
}
u32 fat_get_sector_for_cluster(struct fat_hdr *hdr, u32 N)
{
u32 FirstDataSector = fat_get_first_data_sector(hdr);
// FirstSectorofCluster
return ((N - 2) * hdr->BPB_SecPerClus) + FirstDataSector;
}
struct fat_entry *
fat_get_rootdir(struct fat_hdr *hdr, enum fat_type ft, u32 *cluster /* out */)
{
ASSERT(ft == fat16_type || ft == fat32_type);
u32 sector;
if (ft == fat16_type) {
u32 FirstDataSector =
(u32)hdr->BPB_RsvdSecCnt + (u32)(hdr->BPB_NumFATs * hdr->BPB_FATSz16);
sector = FirstDataSector;
*cluster = 0; /* On FAT16 the root dir entry is NOT a cluster chain! */
} else {
/* FAT32 case */
struct fat32_header2 *h32 = (struct fat32_header2 *) (hdr + 1);
*cluster = h32->BPB_RootClus;
sector = fat_get_sector_for_cluster(hdr, *cluster);
}
return (struct fat_entry*) ((u8*)hdr + (hdr->BPB_BytsPerSec * sector));
}
void fat_get_short_name(struct fat_entry *entry, char *destbuf)
{
u32 i = 0;
u32 d = 0;
for (i = 0; i < 8 && entry->DIR_Name[i] != ' '; i++) {
char c = entry->DIR_Name[i];
destbuf[d++] =
(entry->DIR_NTRes & FAT_ENTRY_NTRES_BASE_LOW_CASE)
? (char)tolower(c)
: c;
}
i = 8; // beginning of the extension part.
if (entry->DIR_Name[i] != ' ') {
destbuf[d++] = '.';
for (; i < 11 && entry->DIR_Name[i] != ' '; i++) {
char c = entry->DIR_Name[i];
destbuf[d++] =
(entry->DIR_NTRes & FAT_ENTRY_NTRES_EXT_LOW_CASE)
? (char)tolower(c)
: c;
}
}
destbuf[d] = 0;
}
static bool fat_fetch_next_component(struct fat_search_ctx *ctx)
{
ASSERT(ctx->pcl == 0);
/*
* Fetch a path component from the abspath: we'll use it while iterating
* the whole directory. On a match, we reset pcl and start a new walk on
* the subdirectory.
*/
while (*ctx->path && *ctx->path != '/') {
ctx->pc[ctx->pcl++] = *ctx->path++;
}
ctx->pc[ctx->pcl++] = 0;
return ctx->pcl != 0;
}
int fat_search_entry_cb(struct fat_hdr *hdr,
enum fat_type ft,
struct fat_entry *entry,
const char *long_name,
void *arg)
{
struct fat_search_ctx *ctx = arg;
if (ctx->pcl == 0) {
if (!fat_fetch_next_component(ctx)) {
// The path was empty, so no path component has been fetched.
return -1;
}
}
/*
* NOTE: the following is NOT fully FAT32 compliant: for long names this
* code compares file names using a CASE SENSITIVE comparison!
* This HACK allows a UNIX system like Tilck to use FAT32 [case sensitivity
* is a MUST in UNIX] by just forcing each file to have a long name, even
* when that is not necessary.
*/
if (long_name) {
if (strcmp(long_name, ctx->pc)) {
// no match, continue.
return 0;
}
// we have a long-name match (case sensitive)
} else {
/*
* no long name: for short names, we do a compliant case INSENSITIVE
* string comparison.
*/
fat_get_short_name(entry, ctx->shortname);
if (stricmp(ctx->shortname, ctx->pc)) {
// no match, continue.
return 0;
}
// we have a short-name match (case insensitive)
}
// we've found a match.
if (ctx->single_comp || *ctx->path == 0) {
ctx->result = entry; // if the path ended, that's it. Just return.
return -1;
}
/*
* The next char in path MUST be a '/' since otherwise
* fat_fetch_next_component() would have continued, until a '/' or a
* '\0' is hit.
*/
ASSERT(*ctx->path == '/');
// path's next char is a '/': maybe there are more components in the path.
ctx->path++;
if (*ctx->path == 0) {
/*
* The path just ended with '/'. That's OK only if entry is acutally is
* a directory.
*/
if (entry->directory)
ctx->result = entry;
else
ctx->not_dir = true;
return -1;
}
if (!entry->directory)
return -1; // if the entry is not a directory, we failed.
// The path did not end: we have to do a walk in the sub-dir.
ctx->pcl = 0;
ctx->subdir_cluster = fat_get_first_cluster(entry);
return -1;
}
void
fat_init_search_ctx(struct fat_search_ctx *ctx,
const char *path,
bool single_comp)
{
bzero(ctx, sizeof(struct fat_search_ctx));
#ifdef __clang_analyzer__
ctx->pcl = 0; /* SA: make it sure ctx.pcl is zeroed */
ctx->result = NULL; /* SA: make it sure ctx.result is zeroed */
#endif
ctx->path = path;
ctx->single_comp = single_comp;
}
struct fat_entry *
fat_search_entry(struct fat_hdr *hdr,
enum fat_type ft,
const char *abspath,
int *err)
{
struct fat_walk_static_params walk_params;
struct fat_search_ctx ctx;
if (ft == fat_unknown)
ft = fat_get_type(hdr);
ASSERT(*abspath == '/');
abspath++;
if (!*abspath) {
/* the whole abspath was just '/' */
u32 unused;
return fat_get_rootdir(hdr, ft, &unused);
}
walk_params = (struct fat_walk_static_params) {
.ctx = &ctx.walk_ctx,
.h = hdr,
.ft = ft,
.cb = &fat_search_entry_cb,
.arg = &ctx,
};
fat_init_search_ctx(&ctx, abspath, false);
fat_walk(&walk_params, 0);
while (ctx.subdir_cluster) {
const u32 cluster = ctx.subdir_cluster;
ctx.subdir_cluster = 0;
fat_walk(&walk_params, cluster);
}
if (err) {
if (ctx.not_dir)
*err = -20; /* -ENOTDIR */
else
*err = !ctx.result ? -2 /* ENOENT */: 0;
}
return ctx.result;
}
size_t fat_get_file_size(struct fat_entry *entry)
{
return entry->DIR_FileSize;
}
size_t
fat_read_whole_file(struct fat_hdr *hdr,
struct fat_entry *entry,
char *dest_buf,
size_t dest_buf_size)
{
const enum fat_type ft = fat_get_type(hdr);
const u32 cs = fat_get_cluster_size(hdr);
const size_t fsize = entry->DIR_FileSize;
u32 cluster = fat_get_first_cluster(entry);
size_t tot_read = 0;
do {
char *data = fat_get_pointer_to_cluster_data(hdr, cluster);
const size_t file_rem = fsize - tot_read;
const size_t dest_buf_rem = dest_buf_size - tot_read;
const size_t rem = MIN(file_rem, dest_buf_rem);
if (rem <= cs) {
// read what is needed
memcpy(dest_buf + tot_read, data, rem);
tot_read += rem;
break;
}
// read the whole cluster
memcpy(dest_buf + tot_read, data, cs);
tot_read += cs;
ASSERT((fsize - tot_read) > 0);
// find the next cluster
u32 fatval = fat_read_fat_entry(hdr, ft, 0, cluster);
if (fat_is_end_of_clusterchain(ft, fatval)) {
// rem is still > 0, this should NOT be the last cluster.
// Still, everything could happen. Just stop.
break;
}
// we do not expect BAD CLUSTERS
ASSERT(!fat_is_bad_cluster(ft, fatval));
cluster = fatval; // go reading the new cluster in the chain.
} while (tot_read < fsize);
return tot_read;
}
struct compact_ctx {
struct fat_walk_static_params walk_params;
u32 ffc; /* first free cluster */
};
static int
fat_compact_walk_cb(struct fat_hdr *hdr,
enum fat_type ft,
struct fat_entry *e,
const char *longname,
void *arg)
{
const u32 first_clu = fat_get_first_cluster(e);
const u32 clu_size = fat_get_cluster_size(hdr);
u32 clu = first_clu, next_clu, last_clu = 0;
struct compact_ctx *const ctx = arg;
{
char name[16];
fat_get_short_name(e, name);
if (is_dot_or_dotdot(name, (int)strlen(name)))
return 0; /* It makes no sense to visit '.' and '..' */
}
do {
next_clu = fat_read_fat_entry(hdr, ft, 0, clu);
/* Move forward `ctx->ffc`, if necessary */
while (fat_read_fat_entry(hdr, ft, 0, ctx->ffc)) {
ctx->ffc++;
}
if (clu > ctx->ffc) {
void *src = fat_get_pointer_to_cluster_data(hdr, clu);
void *dest = fat_get_pointer_to_cluster_data(hdr, ctx->ffc);
memcpy(dest, src, clu_size);
if (clu == first_clu)
fat_set_first_cluster(e, ctx->ffc);
else
fat_write_fat_entry(hdr, ft, 0, last_clu, ctx->ffc);
fat_write_fat_entry(hdr, ft, 0, ctx->ffc, next_clu);
fat_write_fat_entry(hdr, ft, 0, clu, 0);
clu = ctx->ffc++;
}
last_clu = clu;
clu = next_clu;
} while (!fat_is_end_of_clusterchain(ft, clu));
if (e->directory) {
fat_walk(&ctx->walk_params, fat_get_first_cluster(e));
}
return 0;
}
void fat_compact_clusters(struct fat_hdr *hdr)
{
const u32 count = fat_get_cluster_count(hdr);
const enum fat_type ft = fat_get_type(hdr);
struct compact_ctx cctx;
for (cctx.ffc = 0; cctx.ffc < count; cctx.ffc++) {
if (!fat_read_fat_entry(hdr, ft, 0, cctx.ffc))
break;
}
cctx.walk_params = (struct fat_walk_static_params) {
.ctx = NULL,
.h = hdr,
.ft = ft,
.cb = &fat_compact_walk_cb,
.arg = &cctx,
};
fat_walk(&cctx.walk_params, 0);
}
u32
fat_get_first_free_cluster_off(struct fat_hdr *hdr)
{
u32 clu, ff_sector;
const u32 cluster_count = fat_get_cluster_count(hdr);
const enum fat_type ft = fat_get_type(hdr);
for (clu = 0; clu < cluster_count; clu++) {
if (!fat_read_fat_entry(hdr, ft, 0, clu))
break;
}
ff_sector = fat_get_sector_for_cluster(hdr, clu);
return (ff_sector + 1) * hdr->BPB_BytsPerSec;
}
u32
fat_calculate_used_bytes(struct fat_hdr *hdr)
{
const u32 cluster_count = fat_get_cluster_count(hdr);
const enum fat_type ft = fat_get_type(hdr);
u32 val, clu, ff_sector;
for (clu = cluster_count; clu > 0; clu--) {
val = fat_read_fat_entry(hdr, ft, 0, clu-1);
if (val && !fat_is_bad_cluster(ft, val))
break;
}
if (!clu)
return 0; /* fat partition completely corrupt */
ff_sector = fat_get_sector_for_cluster(hdr, clu);
return (ff_sector + 1) * hdr->BPB_BytsPerSec;
}
bool fat_is_first_data_sector_aligned(struct fat_hdr *hdr, u32 page_size)
{
u32 fdc = fat_get_first_data_sector(hdr);
u32 fdc_off = fdc * hdr->BPB_BytsPerSec;
return (fdc_off % page_size) == 0;
}
/*
* Aligns the first data sector to `page_size`, by moving all the data sectors
* by a number of bytes between 0 and page_size-1.
*
* WARNING: this function assumes it is safe to write up to 1 page after the
* value returned by fat_calculate_used_bytes().
*/
void fat_align_first_data_sector(struct fat_hdr *hdr, u32 page_size)
{
const u32 used = fat_calculate_used_bytes(hdr);
const u32 fdc = fat_get_first_data_sector(hdr);
const u32 bps = hdr->BPB_BytsPerSec;
const u32 fdc_off = fdc * bps;
const u32 rem = page_size - (fdc_off % page_size);
const u32 rem_sectors = rem / hdr->BPB_BytsPerSec;
const u32 res_data = hdr->BPB_RsvdSecCnt * bps;
char *const data = (char *)hdr + res_data;
ASSERT((page_size % bps) == 0);
ASSERT((rem % bps) == 0);
if (!rem)
return; /* already aligned, nothing to do */
/* Make sure fat_is_first_data_sector_aligned() returns false */
ASSERT(!fat_is_first_data_sector_aligned(hdr, page_size));
/* Move forward the data by `rem` bytes */
memmove(data + rem, data, used - res_data);
/* Increase the number of reserved sectors by `rem_sectors` */
hdr->BPB_RsvdSecCnt += rem_sectors;
/* Now, make sure fat_is_first_data_sector_aligned() returns true */
ASSERT(fat_is_first_data_sector_aligned(hdr, page_size));
/* Finally, zero the data now part of the reserved sectors */
bzero(data, rem);
}
| 10,842 |
4,606 |
from dagster import repository
@repository(name="repo_one")
def repo_one_symbol():
return []
@repository
def repo_two():
return []
| 53 |
1,850 |
package com.alibaba.jvm.sandbox.repeater.plugin.core.impl;
import com.alibaba.jvm.sandbox.repeater.plugin.core.cache.RepeatCache;
import com.alibaba.jvm.sandbox.repeater.plugin.core.trace.SequenceGenerator;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.Invocation;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.MockInvocation;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.mock.MockRequest;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.mock.MockResponse;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.mock.MockResponse.Action;
import com.alibaba.jvm.sandbox.repeater.plugin.domain.mock.SelectResult;
import com.alibaba.jvm.sandbox.repeater.plugin.exception.RepeatException;
import com.alibaba.jvm.sandbox.repeater.plugin.spi.MockStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link AbstractMockStrategy}抽象的mock策略执行;子类只需要实现{@code select}方法即可
* <p>
*
* @author zhaoyb1990
*/
public abstract class AbstractMockStrategy implements MockStrategy {
protected final static Logger log = LoggerFactory.getLogger(AbstractMockStrategy.class);
/**
* 选择出回放的invocation
*
* @param request mock回放请求
* @return 选择结果
*/
protected abstract SelectResult select(final MockRequest request);
@Override
public MockResponse execute(final MockRequest request) {
MockResponse response;
try {
/*
* before select hook;
*/
MockInterceptorFacade.instance().beforeSelect(request);
/*
* do select
*/
SelectResult select = select(request);
Invocation invocation = select.getInvocation();
MockInvocation mi = new MockInvocation();
mi.setIndex(SequenceGenerator.generate(request.getTraceId() + "#"));
mi.setCurrentUri(request.getIdentity().getUri());
mi.setCurrentArgs(request.getArgumentArray());
mi.setTraceId(request.getTraceId());
mi.setCost(select.getCost());
mi.setRepeatId(request.getRepeatId());
// add mock invocation
RepeatCache.addMockInvocation(mi);
// matching success
if (select.isMatch() && invocation != null) {
response = MockResponse.builder()
.action(invocation.getThrowable() == null ? Action.RETURN_IMMEDIATELY : Action.THROWS_IMMEDIATELY)
.throwable(invocation.getThrowable())
.invocation(invocation)
.build();
mi.setSuccess(true);
mi.setOriginUri(invocation.getIdentity().getUri());
mi.setOriginArgs(invocation.getRequest());
} else {
response = MockResponse.builder()
.action(Action.THROWS_IMMEDIATELY)
.throwable(new RepeatException("no matching invocation found")).build();
}
/*
* before return hook;
*/
MockInterceptorFacade.instance().beforeReturn(request, response);
} catch (Throwable throwable) {
log.error("[Error-0000]-uncaught exception occurred when execute mock strategy, type={}", type(), throwable);
response = MockResponse.builder().
action(Action.THROWS_IMMEDIATELY)
.throwable(throwable)
.build();
}
return response;
}
}
| 1,634 |
647 |
<gh_stars>100-1000
import torch
import numpy as np
import torch.nn.functional as F
import torch.optim as optim
from deeprobust.graph.defense import GCN
from deeprobust.graph.global_attack import Random
from deeprobust.graph.targeted_attack import Nettack
from deeprobust.graph.utils import *
from deeprobust.graph.data import Dataset
from deeprobust.graph.data import PtbDataset
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=15, help='Random seed.')
parser.add_argument('--dataset', type=str, default='citeseer', choices=['cora', 'cora_ml', 'citeseer', 'polblogs', 'pubmed'], help='dataset')
parser.add_argument('--ptb_rate', type=float, default=0.05, help='pertubation rate')
args = parser.parse_args()
args.cuda = torch.cuda.is_available()
print('cuda: %s' % args.cuda)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# make sure you use the same data splits as you generated attacks
np.random.seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
# load original dataset (to get clean features and labels)
data = Dataset(root='/tmp/', name=args.dataset)
adj, features, labels = data.adj, data.features, data.labels
idx_train, idx_val, idx_test = data.idx_train, data.idx_val, data.idx_test
# Setup Target Model
model = GCN(nfeat=features.shape[1], nclass=labels.max()+1,
nhid=16, dropout=0, with_relu=False, with_bias=True, device=device)
model = model.to(device)
# test on original adj
print('=== test on original adj ===')
model.fit(features, adj, labels, idx_train)
output = model.output
acc_test = accuracy(output[idx_test], labels[idx_test])
print("Test set results:",
"accuracy= {:.4f}".format(acc_test.item()))
print('=== Adversarial Training for Evasion Attack===')
adversary = Random()
adv_train_model = GCN(nfeat=features.shape[1], nclass=labels.max()+1,
nhid=16, dropout=0, with_relu=False, with_bias=True, device=device)
adv_train_model = adv_train_model.to(device)
adv_train_model.initialize()
n_perturbations = int(0.01 * (adj.sum()//2))
for i in tqdm(range(100)):
# modified_adj = adversary.attack(features, adj)
adversary.attack(adj, n_perturbations=n_perturbations, type='add')
modified_adj = adversary.modified_adj
adv_train_model.fit(features, modified_adj, labels, idx_train, train_iters=50, initialize=False)
adv_train_model.eval()
# test directly or fine tune
print('=== test on perturbed adj ===')
output = adv_train_model.predict()
acc_test = accuracy(output[idx_test], labels[idx_test])
print("Test set results:",
"accuracy= {:.4f}".format(acc_test.item()))
# set up Surrogate & Nettack to attack the graph
import random
target_nodes = random.sample(idx_test.tolist(), 20)
# Setup Surrogate model
surrogate = GCN(nfeat=features.shape[1], nclass=labels.max().item()+1,
nhid=16, dropout=0, with_relu=False, with_bias=False, device=device)
surrogate = surrogate.to(device)
surrogate.fit(features, adj, labels, idx_train)
all_margins = []
all_adv_margins = []
for target_node in target_nodes:
# set up Nettack
adversary = Nettack(surrogate, nnodes=adj.shape[0], attack_structure=True, attack_features=True, device=device)
adversary = adversary.to(device)
degrees = adj.sum(0).A1
n_perturbations = int(degrees[target_node]) + 2
adversary.attack(features, adj, labels, target_node, n_perturbations)
perturbed_adj = adversary.modified_adj
model = GCN(nfeat=features.shape[1], nclass=labels.max()+1,
nhid=16, dropout=0, with_relu=False, with_bias=True, device=device)
model = model.to(device)
print('=== testing GCN on perturbed graph ===')
model.fit(features, perturbed_adj, labels, idx_train)
output = model.output
margin = classification_margin(output[target_node], labels[target_node])
all_margins.append(margin)
print('=== testing adv-GCN on perturbed graph ===')
output = adv_train_model.predict(features, perturbed_adj)
adv_margin = classification_margin(output[target_node], labels[target_node])
all_adv_margins.append(adv_margin)
print("No adversarial training: classfication margin for {0} nodes: {1}".format(len(target_nodes), np.mean(all_margins)))
print("Adversarial training: classfication margin for {0} nodes: {1}".format(len(target_nodes), np.mean(all_adv_margins)))
| 1,621 |
634 |
<filename>modules/base/analysis-impl/src/main/java/com/intellij/codeHighlighting/EditorBoundHighlightingPass.java
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.codeHighlighting;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;
import javax.annotation.Nonnull;
/**
* The pass which should be applied to every editor, even if there are many for this document.
*
* Ordinary {@link TextEditorHighlightingPass} is document-bound,
* i.e. after the pass finishes the markup is stored in the document.
* For example, there is no point to recalculate syntax errors for each splitted editor of the same document.
* This pass however is for editor-specific markup, e.g. code folding.
*/
public abstract class EditorBoundHighlightingPass extends TextEditorHighlightingPass {
@Nonnull
protected final Editor myEditor;
@Nonnull
protected final PsiFile myFile;
protected EditorBoundHighlightingPass(@Nonnull Editor editor,
@Nonnull PsiFile psiFile,
boolean runIntentionPassAfter) {
super(psiFile.getProject(), editor.getDocument(), runIntentionPassAfter);
myEditor = editor;
myFile = psiFile;
}
}
| 559 |
877 |
<filename>osint/gravatar.py
#!/usr/bin/env python
# Copyright (c) 2013, LCI Technology Group, LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of LCI Technology Group, LLC nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Gravatar.py takes a file with a list of email address, one on each line, and
# searches Gravatar for information about the email address. If address is
# registered with Gravatar, then selected data points are extracted from the
# Gravatar profile.
#
import sys
import hashlib
import requests
#------------------------------------------------------------------------------
# Functions
#------------------------------------------------------------------------------
def get_gravatar(email):
'''
Generate an MD5 hash of the email address and query the Gravatar server
for the profile associated with that hash. Return the associated data in
JSON format.
'''
email_hash = hashlib.md5(email).hexdigest()
resp = requests.get('http://en.gravatar.com/{0}.json'.format(email_hash))
data = {}
if resp.status_code == 200:
try:
print '[+] Found email address {0}.'.format(email)
data = resp.json()
except ValueError:
print '[-] Could not convert response to JSON.'
elif resp.status_code == 404:
print("[-] Account not found.")
else:
print '[-] Received status {0}'.format(resp.status_code)
return data
def get_profile(email):
'''
Parse the Gravatar JSON profile to extract specific data points if they
exist. Return the list of parsed profile entries.
'''
prof = get_gravatar(email)
entries = []
if prof != {}:
for e in prof['entry']:
entry = {}
entry['email'] = email
entry['username'] = e.get('preferredUsername', '')
entry['location'] = e.get('currentLocation', '')
entry['name'] = get_name(e.get('name'))
entry['phoneNumbers'] = get_phoneNumbers(e.get('phoneNumbers'))
entry['accounts'] = get_accounts(e.get('accounts'))
entry['instantMsgs'] = get_instantMsgs(e.get('ims'))
entry['cryptoCurrency'] = get_cryptoCurrency(e.get('currency'))
entries.append(entry)
return entries
def get_name(name):
'''
Extract the formatted name from a name dictionary.
'''
if name is None:
return ''
elif name == []:
return ''
else:
return name.get('formatted', '')
def get_phoneNumbers(data):
'''
Extract the Phone Numbers from the results.
'''
phoneNumbers = []
if data is None:
return phoneNumbers
else:
for b in data:
phone = {}
phone['type'] = b.get('type', '')
phone['value'] = b.get('value', '')
phoneNumbers.append(phone)
return phoneNumbers
def get_accounts(data):
'''
Build a list of accounts by extracting specific data points if they exist.
Return the list of accounts extracted.
'''
accounts = []
if data is None:
return accounts
else:
for a in data:
account = {}
account['username'] = a.get('username', '')
account['url'] = a.get('url', '')
accounts.append(account)
return accounts
def get_cryptoCurrency(data):
'''
Extract the BTC Address.
'''
cryptoCurrency = []
if data is None:
return cryptoCurrency
else:
for c in data:
currency = {}
currency['type'] = c.get('type', '')
currency['value'] = c.get('value', '')
cryptoCurrency.append(currency)
return cryptoCurrency
def get_instantMsgs(data):
'''
Build a list of instant message account by extracting specific data points if they exist.
Return the list of accounts extracted.
'''
instantMsgs = []
if data is None:
return instantMsgs
else:
for d in data:
ims = {}
ims['type'] = d.get('type', '')
ims['value'] = d.get('value', '')
instantMsgs.append(ims)
return instantMsgs
def print_profile(profile):
'''
Print the profile in a readable format.
'''
for p in profile:
print(p['email'])
print('-' * len(p['email']))
print('Name: {}'.format(p['name']))
print('Username: {}'.format(p['username']))
print('Location: {}'.format(p['location']))
print('Accounts:')
for account in p['accounts']:
print(' Username: {}'.format(account['username']))
print(' URL: {}'.format(account['url']))
print('Instant Message:')
for instantMsg in p['instantMsgs']:
print(' Provider: {}'.format(instantMsg['type']))
print(' Handle: {}'.format(instantMsg['value']))
print('Phone:')
for phone in p['phoneNumbers']:
print(' Type: {}'.format(phone['type']))
print(' Number: {}'.format(phone['value']))
print('CyptoCurrency:')
for currency in p['cryptoCurrency']:
print(' Type: {}'.format(currency['type']))
print(' Address: {}'.format(currency['value']))
print()
#-----------------------------------------------------------------------------
# Main Program
#-----------------------------------------------------------------------------
#
# Parse command line arguments using argparse
#
if len(sys.argv) != 2:
print 'Usage: gravatar.py email_file'
sys.exit(1)
email_file = sys.argv[1]
profiles = []
with open(sys.argv[1]) as emails:
for email in emails:
email = email.rstrip('\r\n')
profile = get_profile(email)
if profile != []:
profiles.append(profile)
for profile in profiles:
print_profile(profile)
| 2,726 |
551 |
#include "Etterna/Globals/global.h"
#include "ActorUtil.h"
#include "Quad.h"
#include "RageUtil/Graphics/RageTextureManager.h"
REGISTER_ACTOR_CLASS(Quad);
Quad::Quad()
{
Load(TEXTUREMAN->GetDefaultTextureID());
}
void
Quad::LoadFromNode(const XNode* pNode)
{
// HACK: Bypass Sprite's texture loading. Sprite should really derive from
// Quad.
Actor::LoadFromNode(pNode);
}
| 148 |
1,599 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Helper class used to convert a user LO configuration into a list of frequencies."""
from qiskit.pulse.channels import DriveChannel, MeasureChannel
from qiskit.pulse.configuration import LoConfig
from qiskit.exceptions import QiskitError
class LoConfigConverter:
"""This class supports to convert LoConfig into ~`lo_freq` attribute of configs.
The format of LO frequency setup can be easily modified by replacing
``get_qubit_los`` and ``get_meas_los`` to align with your backend.
"""
def __init__(
self,
qobj_model,
qubit_lo_freq=None,
meas_lo_freq=None,
qubit_lo_range=None,
meas_lo_range=None,
**run_config,
):
"""Create new converter.
Args:
qobj_model (Union[PulseQobjExperimentConfig, QasmQobjExperimentConfig): qobj model for
experiment config.
qubit_lo_freq (Optional[List[float]]): List of default qubit LO frequencies in Hz.
meas_lo_freq (Optional[List[float]]): List of default meas LO frequencies in Hz.
qubit_lo_range (Optional[List[List[float]]]): List of qubit LO ranges,
each of form ``[range_min, range_max]`` in Hz.
meas_lo_range (Optional[List[List[float]]]): List of measurement LO ranges,
each of form ``[range_min, range_max]`` in Hz.
n_qubits (int): Number of qubits in the system.
run_config (dict): experimental configuration.
"""
self.qobj_model = qobj_model
self.qubit_lo_freq = qubit_lo_freq
self.meas_lo_freq = meas_lo_freq
self.run_config = run_config
self.n_qubits = self.run_config.get("n_qubits", None)
self.default_lo_config = LoConfig()
if qubit_lo_range:
for i, lo_range in enumerate(qubit_lo_range):
self.default_lo_config.add_lo_range(DriveChannel(i), lo_range)
if meas_lo_range:
for i, lo_range in enumerate(meas_lo_range):
self.default_lo_config.add_lo_range(MeasureChannel(i), lo_range)
def __call__(self, user_lo_config):
"""Return experiment config w/ LO values property configured.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
Union[PulseQobjExperimentConfig, QasmQobjExperimentConfig]: Qobj experiment config.
"""
lo_config = {}
q_los = self.get_qubit_los(user_lo_config)
if q_los:
lo_config["qubit_lo_freq"] = [freq / 1e9 for freq in q_los]
m_los = self.get_meas_los(user_lo_config)
if m_los:
lo_config["meas_lo_freq"] = [freq / 1e9 for freq in m_los]
return self.qobj_model(**lo_config)
def get_qubit_los(self, user_lo_config):
"""Set experiment level qubit LO frequencies. Use default values from job level if
experiment level values not supplied. If experiment level and job level values not supplied,
raise an error. If configured LO frequency is the same as default, this method returns
``None``.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
List[float]: A list of qubit LOs.
Raises:
QiskitError: When LO frequencies are missing and no default is set at job level.
"""
_q_los = None
# try to use job level default values
if self.qubit_lo_freq:
_q_los = self.qubit_lo_freq.copy()
# otherwise initialize list with ``None`` entries
elif self.n_qubits:
_q_los = [None] * self.n_qubits
# fill experiment level LO's
if _q_los:
for channel, lo_freq in user_lo_config.qubit_los.items():
self.default_lo_config.check_lo(channel, lo_freq)
_q_los[channel.index] = lo_freq
if _q_los == self.qubit_lo_freq:
return None
# if ``None`` remains in LO's, indicates default not provided and user value is missing
# raise error
if None in _q_los:
raise QiskitError(
"Invalid experiment level qubit LO's. Must either pass values "
"for all drive channels or pass 'default_qubit_los'."
)
return _q_los
def get_meas_los(self, user_lo_config):
"""Set experiment level meas LO frequencies. Use default values from job level if experiment
level values not supplied. If experiment level and job level values not supplied, raise an
error. If configured LO frequency is the same as default, this method returns ``None``.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
List[float]: A list of measurement LOs.
Raises:
QiskitError: When LO frequencies are missing and no default is set at job level.
"""
_m_los = None
# try to use job level default values
if self.meas_lo_freq:
_m_los = self.meas_lo_freq.copy()
# otherwise initialize list with ``None`` entries
elif self.n_qubits:
_m_los = [None] * self.n_qubits
# fill experiment level LO's
if _m_los:
for channel, lo_freq in user_lo_config.meas_los.items():
self.default_lo_config.check_lo(channel, lo_freq)
_m_los[channel.index] = lo_freq
if _m_los == self.meas_lo_freq:
return None
# if ``None`` remains in LO's, indicates default not provided and user value is missing
# raise error
if None in _m_los:
raise QiskitError(
"Invalid experiment level measurement LO's. Must either pass "
"values for all measurement channels or pass 'default_meas_los'."
)
return _m_los
| 2,811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.