max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,976
from PIL import Image import os from os.path import join #iPhone 5 display resolution i5size = (1136, 640) def change_size(picdir): for root, dirs, files in os.walk(picdir): for name in files: filename = join(root, name) print filename change_picsize(filename) def change_picsize(filename): im = Image.open(filename) w = im.width; h = im.height; if(w > i5size[0]): im = im.resize((i5size[0], h)) else: pass if(h > i5size[1]): im = im.resize((im.width, i5size[1])) else: pass im.save(filename.split('.')[0] + '2.jpg') if __name__ == '__main__': change_size('test')
373
634
/* * Copyright 2000-2012 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.openapi.fileChooser; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import consulo.annotation.DeprecationInfo; import consulo.ui.annotation.RequiredUIAccess; import consulo.util.concurrent.AsyncResult; import consulo.util.dataholder.Key; import javax.annotation.Nonnull; import javax.annotation.Nullable; public interface FileChooserDialog { Key<Boolean> PREFER_LAST_OVER_TO_SELECT = PathChooserDialog.PREFER_LAST_OVER_EXPLICIT; /** * @deprecated Please use {@link #choose(Project, VirtualFile...)} because * it supports several selections */ @Deprecated @Nonnull default VirtualFile[] choose(@Nullable VirtualFile toSelect, @Nullable Project project) { return toSelect == null ? choose(project) : choose(project, toSelect); } /** * Choose one or more files * * @param project use this project (you may pass null if you already set project in ctor) * @param toSelect files to be selected automatically. * @return files chosen by user */ @Nonnull @Deprecated @DeprecationInfo("Use #chooseAsync") default VirtualFile[] choose(@Nullable Project project, @Nonnull VirtualFile... toSelect) { throw new UnsupportedOperationException("desktop only"); } /** * Choose one or more files * * @param project use this project (you may pass null if you already set project in ctor) * @param toSelect files to be selected automatically. */ @RequiredUIAccess @Nonnull default AsyncResult<VirtualFile[]> chooseAsync(@Nullable Project project, @Nonnull VirtualFile[] toSelect) { throw new AbstractMethodError(); } }
674
19,438
/* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/NonnullPtrVector.h> #include <AK/RefPtr.h> #include <AK/WeakPtr.h> #include <DevTools/HackStudio/ProjectTemplate.h> #include <LibCore/FileWatcher.h> #include <LibGUI/Model.h> namespace HackStudio { class ProjectTemplatesModel final : public GUI::Model { public: static NonnullRefPtr<ProjectTemplatesModel> create() { return adopt_ref(*new ProjectTemplatesModel()); } enum Column { Icon = 0, Id, Name, __Count }; virtual ~ProjectTemplatesModel() override; RefPtr<ProjectTemplate> template_for_index(const GUI::ModelIndex& index); virtual int row_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; virtual int column_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; virtual String column_name(int) const override; virtual GUI::Variant data(const GUI::ModelIndex&, GUI::ModelRole) const override; void update(); void rescan_templates(); private: explicit ProjectTemplatesModel(); NonnullRefPtrVector<ProjectTemplate> m_templates; Vector<ProjectTemplate*> m_mapping; RefPtr<Core::FileWatcher> m_file_watcher; }; }
462
1,603
<filename>metadata-io/src/main/java/com/linkedin/metadata/timeline/data/PatchOperation.java package com.linkedin.metadata.timeline.data; import lombok.Builder; import lombok.Value; @Value @Builder public class PatchOperation { String op; String path; String value; }
91
320
<filename>aliyun-spring-boot-starters/aliyun-rds-spring-boot-starter/src/main/java/com/alibaba/cloud/spring/boot/rds/actuate/endpoint/RdsPerformanceEndpoint.java /* * Copyright 2013-2018 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 com.alibaba.cloud.spring.boot.rds.actuate.endpoint; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; import com.alibaba.cloud.spring.boot.rds.env.RdsProperties; import com.aliyuncs.rds.model.v20140815.DescribeDBInstancePerformanceRequest; import com.aliyuncs.rds.model.v20140815.DescribeDBInstancePerformanceResponse; import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesResponse; /** * show rds preformance info by api. * * @author <a href="mailto:<EMAIL>">theonefx</a> */ @Endpoint(id = "rdsPerformance") public class RdsPerformanceEndpoint extends AbstractInvoker { private static final String MYSQL_DEFAULT_KEYS = "MySQL_NetworkTraffic,MySQL_QPSTPS,MySQL_Sessions," + "MySQL_InnoDBBufferRatio,MySQL_InnoDBDataReadWriten,MySQL_InnoDBLogRequests,MySQL_InnoDBLogWrites," + "MySQL_TempDiskTableCreates,MySQL_MyISAMKeyBufferRatio,MySQL_MyISAMKeyReadWrites,MySQL_COMDML," + "MySQL_RowDML,MySQL_MemCpuUsage,MySQL_IOPS,MySQL_DetailedSpaceUsage,MySQL_CPS,slavestat"; private static final String SQL_SERVER_DEFAULT_KEYS = "SQLServer_Transactions,SQLServer_Sessions," + "SQLServer_BufferHit,SQLServer_FullScans,SQLServer_SQLCompilations,SQLServer_CheckPoint," + "SQLServer_Logins,SQLServer_LockTimeout,SQLServer_Deadlock,SQLServer_LockWaits," + "SQLServer_NetworkTraffic,SQLServer_QPS,SQLServer_InstanceCPUUsage,SQLServer_IOPS,SQLServer_SpaceUsage"; private static final String POSTGRE_SQL_DEFAULT_KEYS = "MemoryUsage,CpuUsage,PgSQL_SpaceUsage,PgSQL_IOPS," + "PgSQL_Session"; private static final Long TIME_RANGE = 12L * 60 * 60 * 1000; @Autowired private RdsProperties rdsProperties; @ReadOperation public Map<String, Object> describeDBWithInstances() { Map<String, Object> map = new LinkedHashMap<>(); List<DescribeDBInstancesResponse.DBInstance> instances = getInstances(); instances.forEach(instance -> { Map<String, Object> dataOfInstance = performanceInfo(instance); map.put(instance.getDBInstanceId(), dataOfInstance); }); return map; } @ReadOperation public Map<String, Object> describeDBWithInstance(@Selector String instanceId) { DescribeDBInstancesResponse.DBInstance instance = getInstance(instanceId); if (instance == null) { return null; } else { return performanceInfo(instance); } } private Map<String, Object> performanceInfo( DescribeDBInstancesResponse.DBInstance instance) { String keys = getKeys(instance); if (keys == null || keys.length() == 0) { return Collections.emptyMap(); } Date end = new Date(); Date start = new Date(end.getTime() - TIME_RANGE); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); DescribeDBInstancePerformanceRequest req = new DescribeDBInstancePerformanceRequest(); req.setDBInstanceId(instance.getDBInstanceId()); req.setStartTime(simpleDateFormat.format(start)); req.setEndTime(simpleDateFormat.format(end)); req.setKey(keys); DescribeDBInstancePerformanceResponse resp = invoke(req); if (resp == null) { return Collections.emptyMap(); } return resp.getPerformanceKeys().stream() .collect(Collectors.toMap( DescribeDBInstancePerformanceResponse.PerformanceKey::getKey, Function.identity(), (x, y) -> x)); } private String getKeys(DescribeDBInstancesResponse.DBInstance instance) { if (rdsProperties.getPerformanceKey() != null && rdsProperties.getPerformanceKey().length() > 0) { return rdsProperties.getPerformanceKey(); } String engine = instance.getEngine(); /** * MySQL SQLServer PostgreSQL PPAS MariaDB */ switch (engine) { case "MySQL": return MYSQL_DEFAULT_KEYS; case "SQLServer": return SQL_SERVER_DEFAULT_KEYS; case "PostgreSQL": return POSTGRE_SQL_DEFAULT_KEYS; default: } return null; } }
2,179
1,334
<gh_stars>1000+ # Generated by Django 2.1.7 on 2019-02-18 07:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("common", "0010_apisettings"), ] operations = [ migrations.AlterField( model_name="apisettings", name="apikey", field=models.CharField(blank=True, max_length=16), ), ]
185
1,909
/* * Copyright 2008-2014 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.batch.sample.domain.order; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.DefaultFieldSet; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.batch.sample.domain.order.internal.OrderItemReader; public class OrderItemReaderTests { private OrderItemReader provider; private ItemReader<FieldSet> input; @Before @SuppressWarnings("unchecked") public void setUp() { input = mock(ItemReader.class); provider = new OrderItemReader(); provider.setFieldSetReader(input); } /* * OrderItemProvider is responsible for retrieving validated value object * from input source. OrderItemProvider.next(): - reads lines from the input * source - returned as fieldsets - pass fieldsets to the mapper - mapper * will create value object - pass value object to validator - returns * validated object * * In testNext method we are going to test these responsibilities. So we * need create mock objects for input source, mapper and validator. */ @Test @SuppressWarnings("unchecked") public void testNext() throws Exception { FieldSet headerFS = new DefaultFieldSet(new String[] { Order.LINE_ID_HEADER }); FieldSet customerFS = new DefaultFieldSet(new String[] { Customer.LINE_ID_NON_BUSINESS_CUST }); FieldSet billingFS = new DefaultFieldSet(new String[] { Address.LINE_ID_BILLING_ADDR }); FieldSet shippingFS = new DefaultFieldSet(new String[] { Address.LINE_ID_SHIPPING_ADDR }); FieldSet billingInfoFS = new DefaultFieldSet(new String[] { BillingInfo.LINE_ID_BILLING_INFO }); FieldSet shippingInfoFS = new DefaultFieldSet(new String[] { ShippingInfo.LINE_ID_SHIPPING_INFO }); FieldSet itemFS = new DefaultFieldSet(new String[] { LineItem.LINE_ID_ITEM }); FieldSet footerFS = new DefaultFieldSet(new String[] { Order.LINE_ID_FOOTER, "100", "3", "3" }, new String[] { "ID", "TOTAL_PRICE", "TOTAL_LINE_ITEMS", "TOTAL_ITEMS" }); when(input.read()).thenReturn(headerFS, customerFS, billingFS, shippingFS, billingInfoFS, shippingInfoFS, itemFS, itemFS, itemFS, footerFS, null); Order order = new Order(); Customer customer = new Customer(); Address billing = new Address(); Address shipping = new Address(); BillingInfo billingInfo = new BillingInfo(); ShippingInfo shippingInfo = new ShippingInfo(); LineItem item = new LineItem(); @SuppressWarnings("rawtypes") FieldSetMapper mapper = mock(FieldSetMapper.class); when(mapper.mapFieldSet(headerFS)).thenReturn(order); when(mapper.mapFieldSet(customerFS)).thenReturn(customer); when(mapper.mapFieldSet(billingFS)).thenReturn(billing); when(mapper.mapFieldSet(shippingFS)).thenReturn(shipping); when(mapper.mapFieldSet(billingInfoFS)).thenReturn(billingInfo); when(mapper.mapFieldSet(shippingInfoFS)).thenReturn(shippingInfo); when(mapper.mapFieldSet(itemFS)).thenReturn(item); provider.setAddressMapper(mapper); provider.setBillingMapper(mapper); provider.setCustomerMapper(mapper); provider.setHeaderMapper(mapper); provider.setItemMapper(mapper); provider.setShippingMapper(mapper); Object result = provider.read(); assertNotNull(result); Order o = (Order) result; assertEquals(o, order); assertEquals(o.getCustomer(), customer); assertFalse(o.getCustomer().isBusinessCustomer()); assertEquals(o.getBillingAddress(), billing); assertEquals(o.getShippingAddress(), shipping); assertEquals(o.getBilling(), billingInfo); assertEquals(o.getShipping(), shippingInfo); assertEquals(3, o.getLineItems().size()); for (LineItem lineItem : o.getLineItems()) { assertEquals(lineItem, item); } assertNull(provider.read()); } }
1,488
337
package com.brucetoo.listvideoplay.videomanage.playermessages; import com.brucetoo.listvideoplay.videomanage.PlayerMessageState; import com.brucetoo.listvideoplay.videomanage.manager.VideoPlayerManagerCallback; import com.brucetoo.listvideoplay.videomanage.ui.VideoPlayerView; /** * This is generic PlayerMessage for setDataSource */ public abstract class SetDataSourceMessage extends PlayerMessage{ public SetDataSourceMessage(VideoPlayerView videoPlayerView, VideoPlayerManagerCallback callback) { super(videoPlayerView, callback); } @Override protected PlayerMessageState stateBefore() { return PlayerMessageState.SETTING_DATA_SOURCE; } @Override protected PlayerMessageState stateAfter() { return PlayerMessageState.DATA_SOURCE_SET; } }
267
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Hum", "definitions": [ "Make a low, steady continuous sound like that of a bee.", "Sing with closed lips.", "(of a place) be filled with a low, steady continuous sound.", "Be in a state of great activity.", "Smell unpleasant." ], "parts-of-speech": "Verb" }
148
1,733
/* setenforce.c - Set the current SELinux mode * * Copyright 2014 The Android Open Source Project USE_SETENFORCE(NEWTOY(setenforce, "<1>1", TOYFLAG_USR|TOYFLAG_SBIN)) config SETENFORCE bool "setenforce" default y depends on TOYBOX_SELINUX help usage: setenforce [enforcing|permissive|1|0] Sets whether SELinux is enforcing (1) or permissive (0). */ #define FOR_setenforce #include "toys.h" void setenforce_main(void) { char *new = *toys.optargs; int state, ret; if (!is_selinux_enabled()) error_exit("SELinux is disabled"); else if (!strcmp(new, "1") || !strcasecmp(new, "enforcing")) state = 1; else if (!strcmp(new, "0") || !strcasecmp(new, "permissive")) state = 0; else error_exit("Invalid state: %s", new); ret = security_setenforce(state); if (ret == -1) perror_msg("Couldn't set enforcing status to '%s'", new); }
329
1,124
#include "sorting.h" void interop_sort(int numbers[], size_t size) { int* start = &numbers[0]; int* end = &numbers[0] + size; std::sort(start, end, [](int x, int y) { return x > y; }); }
87
442
<filename>extlibs/vili/src/node.cpp<gh_stars>100-1000 #include <iostream> #include <iterator> #include <vili/node.hpp> #include <vili/utils.hpp> std::string indent(const std::string& text) { return vili::utils::string::replace(text, "\n", "\n "); } namespace vili { node_iterator::node_iterator(array::iterator value) : m_ptr(value) { } node_iterator::node_iterator(object::iterator value) : m_ptr(value) { } node_iterator::node_iterator(const node_iterator& other_it) : m_ptr(other_it.m_ptr) { } node_iterator& node_iterator::operator++() { if (std::holds_alternative<array::iterator>(m_ptr)) { ++std::get<array::iterator>(m_ptr); } else { ++std::get<object::iterator>(m_ptr); } return *this; } bool node_iterator::operator!=(const node_iterator& rhs) const { if (std::holds_alternative<array::iterator>(m_ptr)) { return std::get<array::iterator>(m_ptr) != std::get<array::iterator>(rhs.m_ptr); } else { return std::get<object::iterator>(m_ptr) != std::get<object::iterator>(rhs.m_ptr); } } node& node_iterator::operator*() { if (std::holds_alternative<array::iterator>(m_ptr)) { return *std::get<array::iterator>(m_ptr); } else { return std::get<object::iterator>(m_ptr)->second; } } const_node_iterator::const_node_iterator(array::const_iterator value) : m_ptr(value) { } const_node_iterator::const_node_iterator(object::const_iterator value) : m_ptr(value) { } const_node_iterator::const_node_iterator(const const_node_iterator& other_it) : m_ptr(other_it.m_ptr) { } const_node_iterator& const_node_iterator::operator++() { if (std::holds_alternative<array::const_iterator>(m_ptr)) { ++std::get<array::const_iterator>(m_ptr); } else { ++std::get<object::const_iterator>(m_ptr); } return *this; } bool const_node_iterator::operator!=(const const_node_iterator& rhs) const { if (std::holds_alternative<array::const_iterator>(m_ptr)) { return std::get<array::const_iterator>(m_ptr) != std::get<array::const_iterator>(rhs.m_ptr); } else { return std::get<object::const_iterator>(m_ptr) != std::get<object::const_iterator>(rhs.m_ptr); } } const node& const_node_iterator::operator*() { if (std::holds_alternative<array::const_iterator>(m_ptr)) { return *std::get<array::const_iterator>(m_ptr); } else { return std::get<object::const_iterator>(m_ptr)->second; } } std::string node::dump_array() const { const auto& vector = std::get<array>(m_data); std::string dump_value = "["; for (auto it = vector.begin(); it != vector.end(); ++it) { dump_value += it->dump() + (it != (vector.end() - 1) ? ", " : ""); } dump_value += "]"; return dump_value; } std::string node::dump_object(bool root) const { const auto& map = std::get<object>(m_data); std::string dump_value = (root) ? "" : "{\n"; size_t index = 0; const size_t max_size = this->size(); for (const auto& [key, value] : map) { if (!value.is_null()) { dump_value += " " + key + ": " + indent(value.dump()); if (index < max_size - 1) { dump_value += ",\n"; } else { dump_value += "\n"; } } index++; } if (!root) dump_value += "}"; return dump_value; } node node::from_type(node_type type) { if (type == node_type::integer) { return vili::integer {}; } else if (type == node_type::number) { return vili::number {}; } else if (type == node_type::boolean) { return vili::boolean {}; } else if (type == node_type::string) { return vili::string {}; } else if (type == node_type::array) { return vili::array {}; } else if (type == node_type::object) { return vili::object {}; } else { throw exceptions::invalid_node_type(unknown_typename, VILI_EXC_INFO); } } node::node(int value) { m_data = static_cast<integer>(value); } node::node(integer value) { m_data = value; } node::node(number value) { m_data = value; } node::node(const string& value) { m_data = value; } node::node(std::string_view value) { m_data = std::string(value); } node::node(boolean value) { m_data = value; } node::node(const char* value) { m_data = std::string(value); } node::node(const array& value) { m_data = value; } node::node(const object& value) { m_data = value; } node::node(const node& copy) { m_data = copy.m_data; } node::node(node&& move) noexcept { m_data = std::move(move.m_data); } void node::operator=(const node& copy) { m_data = copy.m_data; } node_type node::type() const { if (is_null()) return node_type::null; else if (std::holds_alternative<integer>(m_data)) return node_type::integer; else if (std::holds_alternative<number>(m_data)) return node_type::number; else if (std::holds_alternative<boolean>(m_data)) return node_type::boolean; else if (std::holds_alternative<string>(m_data)) return node_type::string; else if (std::holds_alternative<object>(m_data)) return node_type::object; else if (std::holds_alternative<array>(m_data)) return node_type::array; else throw exceptions::invalid_node_type(unknown_typename, VILI_EXC_INFO); } std::string node::dump(bool root) const { if (is_null()) return ""; else if (is<number>()) return utils::string::truncate_float(std::to_string(as<number>())); else if (is<integer>()) return std::to_string(as<integer>()); else if (is<string>()) return utils::string::quote(as<string>()); else if (is<boolean>()) return (as<boolean>() ? "true" : "false"); else if (is<array>()) return dump_array(); else if (is<object>()) return dump_object(root); else throw exceptions::invalid_node_type(unknown_typename, VILI_EXC_INFO); } bool node::is_primitive() const { if (is<integer>() || is<number>() || is<string>() || is<boolean>()) return true; return false; } bool node::is_container() const { if (is<array>() || is<object>()) return true; return false; } bool node::is_null() const { if (m_data.index()) return false; return true; } bool node::is_integer() const { return is<integer>(); } bool node::is_number() const { return is<number>(); } bool node::is_numeric() const { return is<integer>() || is<number>(); } bool node::is_boolean() const { return is<boolean>(); } bool node::is_string() const { return is<string>(); } bool node::is_array() const { return is<array>(); } bool node::is_object() const { return is<object>(); } boolean node::as_boolean() const { return as<boolean>(); } integer node::as_integer() const { return as<integer>(); } number node::as_number() const { return as<number>(); } string node::as_string() const { return as<string>(); } array node::as_array() const { return as<array>(); } object node::as_object() const { return as<object>(); } node& node::operator[](const char* key) { return operator[](std::string(key)); } node& node::operator[](const std::string& key) { if (is<object>()) { auto& map = std::get<object>(m_data); return map[key]; } throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } node& node::operator[](const size_t index) { return this->at(index); } const node & node::operator[](const char *key) const { return this->at(key); } const node & node::operator[](const std::string &key) const { return this->at(key); } const node & node::operator[](size_t index) const { return this->at(index); } size_t node::size() const { if (is<array>()) { return std::get<array>(m_data).size(); } if (is<object>()) { return std::get<object>(m_data).size(); } throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } bool node::empty() const { return this->size() == 0; } void node::clear() { if (is<array>()) { std::get<array>(m_data).clear(); } else if (is<object>()) { std::get<object>(m_data).clear(); } else { throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); // TODO: Add array type } } node::operator std::string_view() const { return as<string>(); } node::operator const std::basic_string<char> &() const { return as<string>(); } node::operator integer() const { return as<integer>(); } node::operator int() const { return static_cast<int>(as<integer>()); } node::operator number() const { return as<number>(); } node::operator boolean() const { return as<boolean>(); } node::operator unsigned() const { return static_cast<unsigned>(as<integer>()); } bool node::operator==(const vili::node& other) const { return m_data == other.m_data; } bool node::operator!=(const vili::node& other) const { return m_data != other.m_data; } std::ostream& operator<<(std::ostream& os, const node& elem) { os << elem.dump(); return os; } void node::push(const node& value) { if (is<array>()) { std::get<array>(m_data).push_back(value); } else { throw exceptions::invalid_cast( array_typename, to_string(type()), VILI_EXC_INFO); } } void node::insert(size_t index, const node& value) { if (is<array>()) { auto& vector = std::get<array>(m_data); vector.insert(vector.cbegin() + index, value); } else { throw exceptions::invalid_cast( array_typename, to_string(type()), VILI_EXC_INFO); } } void node::insert(const std::string& key, node value) { if (is<object>()) { auto& map = std::get<object>(m_data); map.emplace(key, std::move(value)); } else { throw exceptions::invalid_cast( object_typename, to_string(type()), VILI_EXC_INFO); } } void node::merge(node& value) { if (is<object>() && value.is<object>()) { for (auto [key, val] : value.items()) { if (this->contains(key)) this->at(key).merge(val); else (*this)[key] = val; } } else if (is<array>() && value.is<array>()) { for (node& node : value) { this->push(node); } } else { m_data = value.m_data; } } bool node::contains(const std::string& key) const { if (is<object>()) { const vili::object& map = std::get<object>(m_data); if (map.find(key) != map.cend()) { return true; } return false; } else { throw exceptions::invalid_cast( object_typename, to_string(type()), VILI_EXC_INFO); } } void node::erase(size_t index) { if (is<array>()) { auto& vector = std::get<array>(m_data); if (index < vector.size()) { vector.erase(vector.cbegin() + index); } else { throw exceptions::array_index_overflow( index, vector.size(), VILI_EXC_INFO); } } else { throw exceptions::invalid_cast( array_typename, to_string(type()), VILI_EXC_INFO); } } void node::erase(size_t begin, size_t end) { if (is<array>()) { auto& vector = std::get<array>(m_data); if (begin < vector.size() && end < vector.size()) { vector.erase(vector.cbegin() + begin, vector.cbegin() + end); } else { throw exceptions::array_index_overflow( begin, vector.size(), VILI_EXC_INFO); // TODO: Add end bound check } } else { throw exceptions::invalid_cast( array_typename, to_string(type()), VILI_EXC_INFO); } } void node::erase(const std::string& key) { if (is<object>()) { auto& map = std::get<object>(m_data); if (const auto& element = map.find(key); element != map.end()) { map.erase(element); } else { throw exceptions::unknown_child_node(key, VILI_EXC_INFO); } } else { throw exceptions::invalid_cast( object_typename, to_string(type()), VILI_EXC_INFO); } } node& node::front() { if (is<array>()) { return std::get<array>(m_data).front(); } if (is<object>()) { auto& map = std::get<object>(m_data); return map.begin()->second; } throw exceptions::invalid_cast( object_typename, to_string(type()), VILI_EXC_INFO); // TODO: Add array } node& node::back() { if (is<array>()) { return std::get<array>(m_data).back(); } if (is<object>()) { auto& map = std::get<object>(m_data); auto& ref = map.rbegin()->second; return ref; } throw exceptions::invalid_cast( object_typename, to_string(type()), VILI_EXC_INFO); // TODO: Add array } node_iterator node::begin() { if (is<array>()) { auto& vector = std::get<array>(m_data); return std::get<array>(m_data).begin(); } else if (is<object>()) { auto& map = std::get<object>(m_data); return map.begin(); } else { throw exceptions::invalid_cast(container_typename, to_string(type()), VILI_EXC_INFO); } } node_iterator node::end() { if (is<array>()) { auto& vector = std::get<array>(m_data); return vector.end(); } else if (is<object>()) { auto& map = std::get<object>(m_data); return map.end(); } else { throw exceptions::invalid_cast(container_typename, to_string(type()), VILI_EXC_INFO); } } const_node_iterator node::begin() const { if (is<array>()) { auto& vector = std::get<array>(m_data); return std::get<array>(m_data).begin(); } else if (is<object>()) { auto& map = std::get<object>(m_data); return map.begin(); } else { throw exceptions::invalid_cast(container_typename, to_string(type()), VILI_EXC_INFO); } } const_node_iterator node::end() const { if (is<array>()) { auto& vector = std::get<array>(m_data); return vector.end(); } else if (is<object>()) { auto& map = std::get<object>(m_data); return map.end(); } else { throw exceptions::invalid_cast(container_typename, to_string(type()), VILI_EXC_INFO); } } object& node::items() { if (is<object>()) { auto& map = std::get<object>(m_data); return map; } else { throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } } const object& node::items() const { if (is<object>()) { auto& map = std::get<object>(m_data); return map; } else { throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } } node& node::at(const std::string& key) { if (is<object>()) { auto& map = std::get<object>(m_data); if (auto element = map.find(key); element != map.end()) { return element->second; } else { throw exceptions::unknown_child_node(key, VILI_EXC_INFO); } } throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } node& node::at(size_t index) { if (is<array>()) { auto& vector = std::get<array>(m_data); if (index < vector.size()) { return vector.at(index); } throw exceptions::array_index_overflow(index, vector.size(), VILI_EXC_INFO); } throw exceptions::invalid_cast(array_typename, to_string(type()), VILI_EXC_INFO); } const node& node::at(const std::string& key) const { if (is<object>()) { auto& map = std::get<object>(m_data); if (const auto element = map.find(key); element != map.end()) { return element->second; } else { throw exceptions::unknown_child_node(key, VILI_EXC_INFO); } } throw exceptions::invalid_cast(object_typename, to_string(type()), VILI_EXC_INFO); } const node& node::at(size_t index) const { if (is<array>()) { auto& vector = std::get<array>(m_data); if (index < vector.size()) { return vector.at(index); } throw exceptions::array_index_overflow(index, vector.size(), VILI_EXC_INFO); } throw exceptions::invalid_cast(array_typename, to_string(type()), VILI_EXC_INFO); } node_data& node::data() { return m_data; } }
10,697
5,119
#include "common.h" namespace bpftrace { namespace test { namespace codegen { TEST(codegen, call_uptr) { test("k:f { @=*uptr((int16*) arg0 ); }", std::string(NAME) + "_1"); test("k:f { @=*uptr((int32*) arg0 ); }", std::string(NAME) + "_2"); } } // namespace codegen } // namespace test } // namespace bpftrace
129
780
<filename>statics/src/main/java/com/codeborne/selenide/junit5/BrowserPerTestStrategyExtension.java<gh_stars>100-1000 package com.codeborne.selenide.junit5; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import javax.annotation.ParametersAreNonnullByDefault; import static com.codeborne.selenide.WebDriverRunner.closeWebDriver; /** * By using this extension browser will be automatically closed after each test. * <br> * To use this extension, extend your test class with it: * <br> * {@code @ExtendWith({BrowserPerTestStrategyExtension.class}} * <br> * Or register extension in test class: * <br> * {@code @RegisterExtension static BrowserPerTestStrategyExtension browserPerTestStrategy = new BrowserPerTestStrategyExtension();} * <br> * * @author simple-elf * @since 5.21.0 */ @ParametersAreNonnullByDefault public class BrowserPerTestStrategyExtension implements AfterEachCallback { @Override public void afterEach(final ExtensionContext context) { closeWebDriver(); } }
327
654
<gh_stars>100-1000 package com.hannesdorfmann.swipeback.interpolator; import android.view.animation.Interpolator; /** * Interpolator which, when drawn from 0 to 1, looks like half a sine-wave. Used for smoother opening/closing when * peeking at the drawer. */ public class SinusoidalInterpolator implements Interpolator { @Override public float getInterpolation(float input) { return (float) (0.5f + 0.5f * Math.sin(input * Math.PI - Math.PI / 2.f)); } }
169
3,657
<reponame>lipawisc/LoganSquare package com.bluelinelabs.logansquare.processor.model; import com.bluelinelabs.logansquare.annotation.JsonField; import com.bluelinelabs.logansquare.annotation.JsonObject; @JsonObject public class SimpleGenericStringModel extends SimpleGenericModel<String> { @JsonField public String anotherString; }
118
9,516
import dgl import unittest import backend as F from dgl.dataloading import AsyncTransferer @unittest.skipIf(F._default_context_str == 'cpu', reason="CPU transfer not allowed") def test_async_transferer_to_other(): cpu_ones = F.ones([100,75,25], dtype=F.int32, ctx=F.cpu()) tran = AsyncTransferer(F.ctx()) t = tran.async_copy(cpu_ones, F.ctx()) other_ones = t.wait() assert F.context(other_ones) == F.ctx() assert F.array_equal(F.copy_to(other_ones, ctx=F.cpu()), cpu_ones) def test_async_transferer_from_other(): other_ones = F.ones([100,75,25], dtype=F.int32, ctx=F.ctx()) tran = AsyncTransferer(F.ctx()) try: t = tran.async_copy(other_ones, F.cpu()) except ValueError: # correctly threw an error pass else: # should have thrown an error assert False if __name__ == '__main__': test_async_transferer_to_other() test_async_transferer_from_other()
442
337
<filename>manga_py/cli/_args_debug.py import argparse import platform import pkg_resources from ..meta import version from ._requirements import requirements requires = [] def package_version(name: str) -> str: try: pkg = __import__(name) return pkg.__version__ except ImportError: try: return pkg_resources.get_distribution(name).version except pkg_resources.DistributionNotFound: return '' def print_versions(versions): length = [max(len(v[i]) for v in versions) for i in [0, 1]] for line in versions: print(f"{line[0]:{length[0]}} | {line[1]:{length[1]}}") class DebugVersionAction(argparse.Action): def __init__( self, option_strings, dest, default=None, required=False, help=None, ): super().__init__( option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help ) def print_versions_help(self): versions = [ ("Component", "Version"), ("---", "---"), ("OS", platform.platform(aliased=True)), ("python", platform.python_version()), ("pip", package_version('pip')), ("manga-py", version), ] print_versions(versions) print("") module_versions = [ ("Module", "Version"), ("---", "---"), ] module_versions.extend( sorted( [(req, package_version(req)) for req in requirements] ) ) print_versions(module_versions) def __call__(self, parser, namespace, values, option_string=None): self.print_versions_help() exit(0) def _args_debug(args_parser): # pragma: no cover args = args_parser.add_argument_group('Debug / Simulation options') args.add_argument( '-h', '--help', action='help', help=( 'Show this help and exit.' ) ) args.add_argument( '--print-json', action='store_true', help=( 'Print information about the results in the JSON format (after completion).' ) ) args.add_argument( '--simulate', action='store_true', help=( 'Simulate running %(prog)s, where: ' '1) do not download files and, ' '2) do not write anything on disk.' ) ) # deprecated args.add_argument( '--show-current-chapter-info', action='store_true', help=( 'Show current processing chapter info.' ) ) # deprecated args.add_argument( '--save-current-chapter-info', action='store_true', help=( 'Save current processing chapter info into a JSON file.' ) ) args.add_argument( '--show-chapter-info', action='store_true', help=( 'Show current processing chapter info.' ) ) args.add_argument( '--save-chapter-info', action='store_true', help=( 'Save current processing chapter info into a JSON file.' ) ) args.add_argument( '--save-manga-info', action='store_true', help=( 'Saves the manga data in a into a JSON file at the root of the download folder.' ) ) args.add_argument( '--debug', action='store_true', help=( 'Debug %(prog)s.' ) ) args.add_argument( '--debug-version', action=DebugVersionAction, help=( 'Print debug version info.' ) ) args.add_argument( '-q', '--quiet', action='store_true', help=( 'Dont show any messages.' ) )
1,944
4,645
import unittest from ..iorw import load_notebook_node from ..exceptions import PapermillMissingParameterException from ..parameterize import parameterize_notebook, parameterize_path, add_builtin_parameters from . import get_notebook_path from datetime import datetime class TestNotebookParametrizing(unittest.TestCase): def count_nb_injected_parameter_cells(self, nb): return len( [c for c in nb.cells if 'injected-parameters' in c.get('metadata', {}).get('tags', [])] ) def test_no_tag_copying(self): # Test that injected cell does not copy other tags test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) test_nb.cells[0]['metadata']['tags'].append('some tag') test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) cell_zero = test_nb.cells[0] self.assertTrue('some tag' in cell_zero.get('metadata').get('tags')) self.assertTrue('parameters' in cell_zero.get('metadata').get('tags')) cell_one = test_nb.cells[1] self.assertTrue('some tag' not in cell_one.get('metadata').get('tags')) self.assertTrue('injected-parameters' in cell_one.get('metadata').get('tags')) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) def test_injected_parameters_tag(self): test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) cell_zero = test_nb.cells[0] self.assertTrue('parameters' in cell_zero.get('metadata').get('tags')) self.assertTrue('injected-parameters' not in cell_zero.get('metadata').get('tags')) cell_one = test_nb.cells[1] self.assertTrue('injected-parameters' in cell_one.get('metadata').get('tags')) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) def test_repeated_run_injected_parameters_tag(self): test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 0) test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) parameterize_notebook(test_nb, {'msg': 'Hello'}) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) def test_no_parameter_tag(self): test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) test_nb.cells[0]['metadata']['tags'] = [] test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) cell_zero = test_nb.cells[0] self.assertTrue('injected-parameters' in cell_zero.get('metadata').get('tags')) self.assertTrue('parameters' not in cell_zero.get('metadata').get('tags')) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) def test_repeated_run_no_parameters_tag(self): test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) test_nb.cells[0]['metadata']['tags'] = [] self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 0) test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}) self.assertEqual(self.count_nb_injected_parameter_cells(test_nb), 1) def test_custom_comment(self): test_nb = load_notebook_node(get_notebook_path("simple_execute.ipynb")) test_nb = parameterize_notebook(test_nb, {'msg': 'Hello'}, comment='This is a custom comment') cell_one = test_nb.cells[1] first_line = cell_one['source'].split('\n')[0] self.assertEqual(first_line, '# This is a custom comment') class TestBuiltinParameters(unittest.TestCase): def test_add_builtin_parameters_keeps_provided_parameters(self): with_builtin_parameters = add_builtin_parameters({"foo": "bar"}) self.assertEqual(with_builtin_parameters["foo"], "bar") def test_add_builtin_parameters_adds_dict_of_builtins(self): with_builtin_parameters = add_builtin_parameters({"foo": "bar"}) self.assertIn("pm", with_builtin_parameters) self.assertIsInstance(with_builtin_parameters["pm"], type({})) def test_add_builtin_parameters_allows_to_override_builtin(self): with_builtin_parameters = add_builtin_parameters({"pm": "foo"}) self.assertEqual(with_builtin_parameters["pm"], "foo") def test_builtin_parameters_include_run_uuid(self): with_builtin_parameters = add_builtin_parameters({"foo": "bar"}) self.assertIn("run_uuid", with_builtin_parameters["pm"]) def test_builtin_parameters_include_current_datetime_local(self): with_builtin_parameters = add_builtin_parameters({"foo": "bar"}) self.assertIn("current_datetime_local", with_builtin_parameters["pm"]) self.assertIsInstance(with_builtin_parameters["pm"]["current_datetime_local"], datetime) def test_builtin_parameters_include_current_datetime_utc(self): with_builtin_parameters = add_builtin_parameters({"foo": "bar"}) self.assertIn("current_datetime_utc", with_builtin_parameters["pm"]) self.assertIsInstance(with_builtin_parameters["pm"]["current_datetime_utc"], datetime) class TestPathParameterizing(unittest.TestCase): def test_plain_text_path_with_empty_parameters_object(self): self.assertEqual(parameterize_path("foo/bar", {}), "foo/bar") def test_plain_text_path_with_none_parameters(self): self.assertEqual(parameterize_path("foo/bar", None), "foo/bar") def test_plain_text_path_with_unused_parameters(self): self.assertEqual(parameterize_path("foo/bar", {"baz": "quux"}), "foo/bar") def test_path_with_single_parameter(self): self.assertEqual(parameterize_path("foo/bar/{baz}", {"baz": "quux"}), "foo/bar/quux") def test_path_with_boolean_parameter(self): self.assertEqual(parameterize_path("foo/bar/{baz}", {"baz": False}), "foo/bar/False") def test_path_with_dict_parameter(self): self.assertEqual( parameterize_path("foo/{bar[baz]}/", {"bar": {"baz": "quux"}}), "foo/quux/" ) def test_path_with_list_parameter(self): self.assertEqual(parameterize_path("foo/{bar[0]}/", {"bar": [1, 2, 3]}), "foo/1/") self.assertEqual(parameterize_path("foo/{bar[2]}/", {"bar": [1, 2, 3]}), "foo/3/") def test_path_with_none_parameter(self): self.assertEqual(parameterize_path("foo/bar/{baz}", {"baz": None}), "foo/bar/None") def test_path_with_numeric_parameter(self): self.assertEqual(parameterize_path("foo/bar/{baz}", {"baz": 42}), "foo/bar/42") def test_path_with_numeric_format_string(self): self.assertEqual(parameterize_path("foo/bar/{baz:03d}", {"baz": 42}), "foo/bar/042") def test_path_with_float_format_string(self): self.assertEqual(parameterize_path("foo/bar/{baz:.03f}", {"baz": 0.3}), "foo/bar/0.300") def test_path_with_multiple_parameter(self): self.assertEqual( parameterize_path("{foo}/{baz}", {"foo": "bar", "baz": "quux"}), "bar/quux" ) def test_parameterized_path_with_undefined_parameter(self): with self.assertRaises(PapermillMissingParameterException) as context: parameterize_path("{foo}", {}) self.assertEqual(str(context.exception), "Missing parameter 'foo'") def test_parameterized_path_with_none_parameters(self): with self.assertRaises(PapermillMissingParameterException) as context: parameterize_path("{foo}", None) self.assertEqual(str(context.exception), "Missing parameter 'foo'")
3,301
1,379
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import paddle # TODO: Complete type-hint and doc string. def blackman_window(win_len, dtype=np.float32): arcs = np.pi * np.arange(win_len) / float(win_len) win = np.asarray( [0.42 - 0.5 * np.cos(2 * arc) + 0.08 * np.cos(4 * arc) for arc in arcs], dtype=dtype) return paddle.to_tensor(win) def compute_amplitude(waveforms, lengths=None, amp_type="avg", scale="linear"): if len(waveforms.shape) == 1: waveforms = waveforms.unsqueeze(0) assert amp_type in ["avg", "peak"] assert scale in ["linear", "dB"] if amp_type == "avg": if lengths is None: out = paddle.mean(paddle.abs(waveforms), axis=1, keepdim=True) else: wav_sum = paddle.sum(paddle.abs(waveforms), axis=1, keepdim=True) out = wav_sum / lengths elif amp_type == "peak": out = paddle.max(paddle.abs(waveforms), axis=1, keepdim=True) else: raise NotImplementedError if scale == "linear": return out elif scale == "dB": return paddle.clip(20 * paddle.log10(out), min=-80) else: raise NotImplementedError def dB_to_amplitude(SNR): return 10**(SNR / 20) def convolve1d( waveform, kernel, padding=0, pad_type="constant", stride=1, groups=1, ): if len(waveform.shape) != 3: raise ValueError("Convolve1D expects a 3-dimensional tensor") # Padding can be a tuple (left_pad, right_pad) or an int if isinstance(padding, list): waveform = paddle.nn.functional.pad( x=waveform, pad=padding, mode=pad_type, data_format='NLC', ) # Move time dimension last, which pad and fft and conv expect. # (N, L, C) -> (N, C, L) waveform = waveform.transpose([0, 2, 1]) kernel = kernel.transpose([0, 2, 1]) convolved = paddle.nn.functional.conv1d( x=waveform, weight=kernel, stride=stride, groups=groups, padding=padding if not isinstance(padding, list) else 0, ) # Return time dimension to the second dimension. return convolved.transpose([0, 2, 1]) def notch_filter(notch_freq, filter_width=101, notch_width=0.05): # Check inputs assert 0 < notch_freq <= 1 assert filter_width % 2 != 0 pad = filter_width // 2 inputs = paddle.arange(filter_width, dtype='float32') - pad # Avoid frequencies that are too low notch_freq += notch_width # Define sinc function, avoiding division by zero def sinc(x): def _sinc(x): return paddle.sin(x) / x # The zero is at the middle index res = paddle.concat( [_sinc(x[:pad]), paddle.ones([1]), _sinc(x[pad + 1:])]) return res # Compute a low-pass filter with cutoff frequency notch_freq. hlpf = sinc(3 * (notch_freq - notch_width) * inputs) # import torch # hlpf *= paddle.to_tensor(torch.blackman_window(filter_width).detach().numpy()) hlpf *= blackman_window(filter_width) hlpf /= paddle.sum(hlpf) # Compute a high-pass filter with cutoff frequency notch_freq. hhpf = sinc(3 * (notch_freq + notch_width) * inputs) # hhpf *= paddle.to_tensor(torch.blackman_window(filter_width).detach().numpy()) hhpf *= blackman_window(filter_width) hhpf /= -paddle.sum(hhpf) hhpf[pad] += 1 # Adding filters creates notch filter return (hlpf + hhpf).reshape([1, -1, 1]) def reverberate(waveforms, rir_waveform, sample_rate, impulse_duration=0.3, rescale_amp="avg"): orig_shape = waveforms.shape if len(waveforms.shape) > 3 or len(rir_waveform.shape) > 3: raise NotImplementedError # if inputs are mono tensors we reshape to 1, samples if len(waveforms.shape) == 1: waveforms = waveforms.unsqueeze(0).unsqueeze(-1) elif len(waveforms.shape) == 2: waveforms = waveforms.unsqueeze(-1) if len(rir_waveform.shape) == 1: # convolve1d expects a 3d tensor ! rir_waveform = rir_waveform.unsqueeze(0).unsqueeze(-1) elif len(rir_waveform.shape) == 2: rir_waveform = rir_waveform.unsqueeze(-1) # Compute the average amplitude of the clean orig_amplitude = compute_amplitude(waveforms, waveforms.shape[1], rescale_amp) # Compute index of the direct signal, so we can preserve alignment impulse_index_start = rir_waveform.abs().argmax(axis=1).item() impulse_index_end = min( impulse_index_start + int(sample_rate * impulse_duration), rir_waveform.shape[1]) rir_waveform = rir_waveform[:, impulse_index_start:impulse_index_end, :] rir_waveform = rir_waveform / paddle.norm(rir_waveform, p=2) rir_waveform = paddle.flip(rir_waveform, [1]) waveforms = convolve1d( waveform=waveforms, kernel=rir_waveform, padding=[rir_waveform.shape[1] - 1, 0], ) # Rescale to the peak amplitude of the clean waveform waveforms = rescale(waveforms, waveforms.shape[1], orig_amplitude, rescale_amp) if len(orig_shape) == 1: waveforms = waveforms.squeeze(0).squeeze(-1) if len(orig_shape) == 2: waveforms = waveforms.squeeze(-1) return waveforms def rescale(waveforms, lengths, target_lvl, amp_type="avg", scale="linear"): assert amp_type in ["peak", "avg"] assert scale in ["linear", "dB"] batch_added = False if len(waveforms.shape) == 1: batch_added = True waveforms = waveforms.unsqueeze(0) waveforms = normalize(waveforms, lengths, amp_type) if scale == "linear": out = target_lvl * waveforms elif scale == "dB": out = dB_to_amplitude(target_lvl) * waveforms else: raise NotImplementedError("Invalid scale, choose between dB and linear") if batch_added: out = out.squeeze(0) return out def normalize(waveforms, lengths=None, amp_type="avg", eps=1e-14): assert amp_type in ["avg", "peak"] batch_added = False if len(waveforms.shape) == 1: batch_added = True waveforms = waveforms.unsqueeze(0) den = compute_amplitude(waveforms, lengths, amp_type) + eps if batch_added: waveforms = waveforms.squeeze(0) return waveforms / den
2,956
656
""" These are Pytest hooks that are necessary to ensure that no build artifacts are leftover from previous runs. """ import pathlib, nimporter_cli def pytest_sessionstart(session): nimporter_cli.clean(pathlib.Path())
66
5,325
<gh_stars>1000+ from .model import SegmentationModel from .modules import ( Conv2dReLU, Attention, ) from .heads import ( SegmentationHead, ClassificationHead, )
66
764
<filename>erc20/0x49184E6dAe8C8ecD89d8Bdc1B950c597b8167c90.json {"symbol": "LIBERTAS","address": "0x49184E6dAe8C8ecD89d8Bdc1B950c597b8167c90","overview":{"en": ""},"email": "<EMAIL>","website": "https://libertas.network/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/TheRealLibertas","telegram": "https://t.me/libertasproject","github": "https://github.com/Kyle-Allbright/Libertas-Static-Website"}}
173
700
<reponame>vkleen/skidl # -*- coding: utf-8 -*- # The MIT License (MIT) - Copyright (c) 2016-2021 <NAME>. """ Command-line program to convert a netlist into an equivalent SKiDL program. """ from __future__ import ( # isort:skip absolute_import, division, print_function, unicode_literals, ) import argparse import logging import os import shutil import sys from builtins import open from future import standard_library from .netlist_to_skidl import netlist_to_skidl from .pckg_info import __version__ standard_library.install_aliases() ############################################################################### # Command-line interface. ############################################################################### def main(): parser = argparse.ArgumentParser( description="A Python package for textually describing circuit schematics." ) parser.add_argument( "--version", "-v", action="version", version="skidl " + __version__ ) parser.add_argument( "--input", "-i", nargs=1, type=str, metavar="file.net", help="Netlist input file.", ) parser.add_argument( "--output", "-o", nargs=1, type=str, metavar="file.py", help="Output file for SKiDL code.", ) parser.add_argument( "--overwrite", "-w", action="store_true", help="Overwrite an existing file." ) parser.add_argument( "--nobackup", "-nb", action="store_true", help="Do *not* create backups before modifying files. " + "(Default is to make backup files.)", ) parser.add_argument( "--debug", "-d", nargs="?", type=int, default=0, metavar="LEVEL", help="Print debugging info. (Larger LEVEL means more info.)", ) args = parser.parse_args() logger = logging.getLogger("netlist_to_skidl") if args.debug is not None: log_level = logging.DEBUG + 1 - args.debug handler = logging.StreamHandler(sys.stdout) handler.setLevel(log_level) logger.addHandler(handler) logger.setLevel(log_level) if args.input is None: logger.critical("Hey! Give me some netlist files!") sys.exit(2) if args.output is None: print("Hey! I need some place where I can store the SKiDL code!") sys.exit(1) for file in args.output: if os.path.isfile(file): if not args.overwrite and args.nobackup: logger.critical( "File {} already exists! Use the --overwrite option to " + "allow modifications to it or allow backups.".format(file) ) sys.exit(1) if not args.nobackup: # Create a backup file. index = 1 # Start with this backup file suffix. while True: backup_file = file + ".{}.bak".format(index, file) if not os.path.isfile(backup_file): # Found an unused backup file name, so make backup. shutil.copy(file, backup_file) break # Backup done, so break out of loop. index += 1 # Else keep looking for an unused backup file name. skidl_code = netlist_to_skidl(args.input[0]) open(args.output[0], "w").write(skidl_code) ############################################################################### # Main entrypoint. ############################################################################### if __name__ == "__main__": main()
1,548
2,151
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageGeneratorCG.h" #include "SkPixmapPriv.h" #ifdef SK_BUILD_FOR_MAC #include <ApplicationServices/ApplicationServices.h> #endif #ifdef SK_BUILD_FOR_IOS #include <CoreGraphics/CoreGraphics.h> #include <ImageIO/ImageIO.h> #include <MobileCoreServices/MobileCoreServices.h> #endif static CGImageSourceRef data_to_CGImageSrc(SkData* data) { CGDataProviderRef cgData = CGDataProviderCreateWithData(data, data->data(), data->size(), nullptr); if (!cgData) { return nullptr; } CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(cgData, 0); CGDataProviderRelease(cgData); return imageSrc; } #ifdef SK_LEGACY_NEW_FROM_ENCODED_CG SkImageGenerator* SkImageGeneratorCG::NewFromEncodedCG(SkData* data) { return MakeFromEncodedCG(sk_ref_sp(data)).release(); } #endif std::unique_ptr<SkImageGenerator> SkImageGeneratorCG::MakeFromEncodedCG(sk_sp<SkData> data) { CGImageSourceRef imageSrc = data_to_CGImageSrc(data.get()); if (!imageSrc) { return nullptr; } // Make sure we call CFRelease to free the imageSrc. Since CFRelease actually takes // a const void*, we must cast the imageSrc to a const void*. SkAutoTCallVProc<const void, CFRelease> autoImageSrc(imageSrc); CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSrc, 0, nullptr); if (!properties) { return nullptr; } CFNumberRef widthRef = (CFNumberRef) (CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth)); CFNumberRef heightRef = (CFNumberRef) (CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight)); if (nullptr == widthRef || nullptr == heightRef) { return nullptr; } int width, height; if (!CFNumberGetValue(widthRef, kCFNumberIntType, &width) || !CFNumberGetValue(heightRef, kCFNumberIntType, &height)) { return nullptr; } bool hasAlpha = (bool) (CFDictionaryGetValue(properties, kCGImagePropertyHasAlpha)); SkAlphaType alphaType = hasAlpha ? kPremul_SkAlphaType : kOpaque_SkAlphaType; SkImageInfo info = SkImageInfo::MakeS32(width, height, alphaType); auto origin = kDefault_SkEncodedOrigin; auto orientationRef = (CFNumberRef) (CFDictionaryGetValue(properties, kCGImagePropertyOrientation)); int originInt; if (orientationRef && CFNumberGetValue(orientationRef, kCFNumberIntType, &originInt)) { origin = (SkEncodedOrigin) originInt; } if (SkPixmapPriv::ShouldSwapWidthHeight(origin)) { info = SkPixmapPriv::SwapWidthHeight(info); } // FIXME: We have the opportunity to extract color space information here, // though I think it makes sense to wait until we understand how // we want to communicate it to the generator. return std::unique_ptr<SkImageGenerator>(new SkImageGeneratorCG(info, autoImageSrc.release(), std::move(data), origin)); } SkImageGeneratorCG::SkImageGeneratorCG(const SkImageInfo& info, const void* imageSrc, sk_sp<SkData> data, SkEncodedOrigin origin) : INHERITED(info) , fImageSrc(imageSrc) , fData(std::move(data)) , fOrigin(origin) {} sk_sp<SkData> SkImageGeneratorCG::onRefEncodedData() { return fData; } bool SkImageGeneratorCG::onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options&) { if (kN32_SkColorType != info.colorType()) { // FIXME: Support other colorTypes. return false; } switch (info.alphaType()) { case kOpaque_SkAlphaType: if (kOpaque_SkAlphaType != this->getInfo().alphaType()) { return false; } break; case kPremul_SkAlphaType: break; default: return false; } CGImageRef image = CGImageSourceCreateImageAtIndex((CGImageSourceRef) fImageSrc.get(), 0, nullptr); if (!image) { return false; } SkAutoTCallVProc<CGImage, CGImageRelease> autoImage(image); SkPixmap dst(info, pixels, rowBytes); auto decode = [&image](const SkPixmap& pm) { // FIXME: Using SkCopyPixelsFromCGImage (as opposed to swizzling // ourselves) greatly restricts the color and alpha types that we // support. If we swizzle ourselves, we can add support for: // kUnpremul_SkAlphaType // 16-bit per component RGBA // kGray_8_SkColorType // Additionally, it would be interesting to compare the performance // of SkSwizzler with CG's built in swizzler. return SkCopyPixelsFromCGImage(pm, image); }; return SkPixmapPriv::Orient(dst, fOrigin, decode); }
2,004
376
<filename>build/php7/ice/image/gd.zep.h extern zend_class_entry *ice_image_gd_ce; ZEPHIR_INIT_CLASS(Ice_Image_Gd); PHP_METHOD(Ice_Image_Gd, __construct); PHP_METHOD(Ice_Image_Gd, check); PHP_METHOD(Ice_Image_Gd, __destruct); PHP_METHOD(Ice_Image_Gd, loadImage); PHP_METHOD(Ice_Image_Gd, doResize); PHP_METHOD(Ice_Image_Gd, doCrop); PHP_METHOD(Ice_Image_Gd, doRotate); PHP_METHOD(Ice_Image_Gd, doFlip); PHP_METHOD(Ice_Image_Gd, doSharpen); PHP_METHOD(Ice_Image_Gd, doReflection); PHP_METHOD(Ice_Image_Gd, doWatermark); PHP_METHOD(Ice_Image_Gd, doBackground); PHP_METHOD(Ice_Image_Gd, doSave); PHP_METHOD(Ice_Image_Gd, doRender); PHP_METHOD(Ice_Image_Gd, saveFunction); PHP_METHOD(Ice_Image_Gd, create); ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd___construct, 0, 0, 1) #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0) #else ZEND_ARG_INFO(0, file) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_check, 0, 0, _IS_BOOL, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_check, 0, 0, _IS_BOOL, NULL, 0) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_loadimage, 0, 0, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_loadimage, 0, 0, IS_VOID, NULL, 0) #endif ZEND_END_ARG_INFO() #else #define arginfo_ice_image_gd_loadimage NULL #endif #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doresize, 0, 2, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doresize, 0, 2, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_doresize, 0, 0, 2) #define arginfo_ice_image_gd_doresize NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, width, IS_LONG, 0) #else ZEND_ARG_INFO(0, width) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, height, IS_LONG, 0) #else ZEND_ARG_INFO(0, height) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_docrop, 0, 4, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_docrop, 0, 4, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_docrop, 0, 0, 4) #define arginfo_ice_image_gd_docrop NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, width, IS_LONG, 0) #else ZEND_ARG_INFO(0, width) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, height, IS_LONG, 0) #else ZEND_ARG_INFO(0, height) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, offsetX, IS_LONG, 0) #else ZEND_ARG_INFO(0, offsetX) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, offsetY, IS_LONG, 0) #else ZEND_ARG_INFO(0, offsetY) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dorotate, 0, 1, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dorotate, 0, 1, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_dorotate, 0, 0, 1) #define arginfo_ice_image_gd_dorotate NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, degrees, IS_LONG, 0) #else ZEND_ARG_INFO(0, degrees) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doflip, 0, 1, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doflip, 0, 1, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_doflip, 0, 0, 1) #define arginfo_ice_image_gd_doflip NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, direction, IS_LONG, 0) #else ZEND_ARG_INFO(0, direction) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dosharpen, 0, 1, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dosharpen, 0, 1, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_dosharpen, 0, 0, 1) #define arginfo_ice_image_gd_dosharpen NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, amount, IS_LONG, 0) #else ZEND_ARG_INFO(0, amount) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doreflection, 0, 3, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_doreflection, 0, 3, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_doreflection, 0, 0, 3) #define arginfo_ice_image_gd_doreflection NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, height, IS_LONG, 0) #else ZEND_ARG_INFO(0, height) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, opacity, IS_LONG, 0) #else ZEND_ARG_INFO(0, opacity) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, fadeIn, _IS_BOOL, 0) #else ZEND_ARG_INFO(0, fadeIn) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dowatermark, 0, 4, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dowatermark, 0, 4, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_dowatermark, 0, 0, 4) #define arginfo_ice_image_gd_dowatermark NULL #endif ZEND_ARG_OBJ_INFO(0, watermark, Ice\\Image, 0) #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, offsetX, IS_LONG, 0) #else ZEND_ARG_INFO(0, offsetX) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, offsetY, IS_LONG, 0) #else ZEND_ARG_INFO(0, offsetY) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, opacity, IS_LONG, 0) #else ZEND_ARG_INFO(0, opacity) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70100 #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dobackground, 0, 4, IS_VOID, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dobackground, 0, 4, IS_VOID, NULL, 0) #endif #else ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_dobackground, 0, 0, 4) #define arginfo_ice_image_gd_dobackground NULL #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, r, IS_LONG, 0) #else ZEND_ARG_INFO(0, r) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, g, IS_LONG, 0) #else ZEND_ARG_INFO(0, g) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, b, IS_LONG, 0) #else ZEND_ARG_INFO(0, b) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, opacity, IS_LONG, 0) #else ZEND_ARG_INFO(0, opacity) #endif ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dosave, 0, 1, _IS_BOOL, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dosave, 0, 1, _IS_BOOL, NULL, 0) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, file, IS_STRING, 0) #else ZEND_ARG_INFO(0, file) #endif ZEND_ARG_INFO(0, quality) ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dorender, 0, 2, IS_STRING, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_dorender, 0, 2, IS_STRING, NULL, 0) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, type, IS_STRING, 0) #else ZEND_ARG_INFO(0, type) #endif ZEND_ARG_INFO(0, quality) ZEND_END_ARG_INFO() #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_savefunction, 0, 2, IS_ARRAY, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_image_gd_savefunction, 0, 2, IS_ARRAY, NULL, 0) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, extension, IS_STRING, 0) #else ZEND_ARG_INFO(0, extension) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, quality, IS_LONG, 0) #else ZEND_ARG_INFO(0, quality) #endif ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_image_gd_create, 0, 0, 2) #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, width, IS_LONG, 0) #else ZEND_ARG_INFO(0, width) #endif #if PHP_VERSION_ID >= 70200 ZEND_ARG_TYPE_INFO(0, height, IS_LONG, 0) #else ZEND_ARG_INFO(0, height) #endif ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(ice_image_gd_method_entry) { PHP_ME(Ice_Image_Gd, __construct, arginfo_ice_image_gd___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Ice_Image_Gd, check, arginfo_ice_image_gd_check, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME(Ice_Image_Gd, __destruct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_ME(Ice_Image_Gd, loadImage, arginfo_ice_image_gd_loadimage, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doResize, arginfo_ice_image_gd_doresize, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doCrop, arginfo_ice_image_gd_docrop, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doRotate, arginfo_ice_image_gd_dorotate, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doFlip, arginfo_ice_image_gd_doflip, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doSharpen, arginfo_ice_image_gd_dosharpen, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doReflection, arginfo_ice_image_gd_doreflection, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doWatermark, arginfo_ice_image_gd_dowatermark, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doBackground, arginfo_ice_image_gd_dobackground, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doSave, arginfo_ice_image_gd_dosave, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, doRender, arginfo_ice_image_gd_dorender, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, saveFunction, arginfo_ice_image_gd_savefunction, ZEND_ACC_PROTECTED) PHP_ME(Ice_Image_Gd, create, arginfo_ice_image_gd_create, ZEND_ACC_PROTECTED) PHP_FE_END };
4,748
325
#include <catch.hpp> #include <iostream> #include <thread> #include "utility/NewHeaderDependency.hpp" #include "Globals.hpp" #include "WaitForReload.hpp" TEST_CASE("Adding new header dependency in runtime", "[common]") { int v1 = 52; int v2 = 65; int sum = v1 + v2; int mul = v1 * v2; REQUIRE(newHeaderDependencyComputeResult(v1, v2) == sum); std::cout << "JET_TEST: disable(new_header:1); enable(new_header:2)" << std::endl; waitForReload(); REQUIRE(newHeaderDependencyComputeResult(v1, v2) == mul); std::cout << "JET_TEST: disable(new_header:3); enable(new_header:4)" << std::endl; waitForReload(); REQUIRE(newHeaderDependencyComputeResult(v1, v2) == mul + sum); }
303
2,739
<filename>wal_e/worker/swift/swift_deleter.py<gh_stars>1000+ from swiftclient.exceptions import ClientException from wal_e import retries from wal_e.worker.base import _Deleter class Deleter(_Deleter): def __init__(self, swift_conn, container): super(Deleter, self).__init__() self.swift_conn = swift_conn self.container = container @retries.retry() def _delete_batch(self, page): # swiftclient doesn't expose mass-delete yet (the raw API supports it # when a particular middleware is installed), so we delete one at a # time. for blob in page: try: self.swift_conn.delete_object(self.container, blob.name) except ClientException as e: # Swallow HTTP 404's they indicate the file doesn't exist, and # that's fine, we were just going to delete it anyways if e.http_status != 404: raise
408
2,212
/* * Copyright 2015 The AppAuth for Android Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.openid.appauth; import static net.openid.appauth.Preconditions.checkArgument; import static net.openid.appauth.Preconditions.checkCollectionNotEmpty; import static net.openid.appauth.Preconditions.checkNotEmpty; import static net.openid.appauth.Preconditions.checkNotNull; import static net.openid.appauth.Preconditions.checkNullOrNotEmpty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(sdk = 16) public class PreconditionsTest { private static final String TEST_MSG = "test"; @Test public void testNotNull() { checkNotNull(new String()); } @Test(expected = NullPointerException.class) public void testNotNull_null() { checkNotNull(null); } @Test public void testNotNullWithMessage() { checkNotNull(new String(), TEST_MSG); } @Test public void testNotNullWithMessage_null() { try { checkNotNull(null, TEST_MSG); fail("Expected NullPointerException not thrown."); } catch (NullPointerException ex) { assertEquals(TEST_MSG, ex.getMessage()); } } @Test public void testCheckArgument() { checkArgument(true); } @Test(expected = IllegalArgumentException.class) public void testCheckArgument_false() { checkArgument(false); } @Test public void testCheckArgumentWithMessage() { checkArgument(true, TEST_MSG); } @Test public void testCheckArgumentWithMessage_false() { try { checkArgument(false, TEST_MSG); fail("Expected IllegalArgumentException not thrown."); } catch (IllegalArgumentException ex) { assertEquals(TEST_MSG, ex.getMessage()); } } @Test public void testCheckNotEmpty() { String testString = "I am not empty"; assertSame(testString, checkNotEmpty(testString, TEST_MSG)); } @Test(expected = NullPointerException.class) public void testCheckNotEmpty_nullString() { checkNotEmpty(null, TEST_MSG); } @Test(expected = IllegalArgumentException.class) public void testCheckNotEmpty_emptyString() { checkNotEmpty("", TEST_MSG); } @Test public void testCheckNullOrNotEmpty() { String testString = "I am not empty"; assertSame(testString, checkNullOrNotEmpty(testString, TEST_MSG)); } @Test public void testCheckNullOrNotEmpty_nullString() { assertNull(checkNullOrNotEmpty(null, TEST_MSG)); } @Test(expected = IllegalArgumentException.class) public void testCheckNullOrNotEmpty_emptyString() { checkNullOrNotEmpty("", TEST_MSG); } @Test(expected = NullPointerException.class) public void testCheckCollectionNotEmpty_withNull() { checkCollectionNotEmpty(null, TEST_MSG); } @Test(expected = IllegalArgumentException.class) public void testCheckCollectionNotEmpty_withEmptyList() { checkCollectionNotEmpty(new ArrayList<Object>(), TEST_MSG); } @Test public void testCheckCollectionNotEmpty() { checkCollectionNotEmpty(Arrays.asList("value1", "value2"), TEST_MSG); } }
1,506
9,782
<gh_stars>1000+ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.common.type.Type; import com.facebook.presto.spi.connector.ConnectorPartitioningHandle; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.OptionalInt; import static com.facebook.presto.hive.BucketFunctionType.HIVE_COMPATIBLE; import static com.facebook.presto.hive.BucketFunctionType.PRESTO_NATIVE; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class HivePartitioningHandle implements ConnectorPartitioningHandle { private final int bucketCount; private final OptionalInt maxCompatibleBucketCount; private final BucketFunctionType bucketFunctionType; private final Optional<List<HiveType>> hiveTypes; private final Optional<List<Type>> types; public static HivePartitioningHandle createHiveCompatiblePartitioningHandle( int bucketCount, List<HiveType> hiveTypes, OptionalInt maxCompatibleBucketCount) { return new HivePartitioningHandle( bucketCount, maxCompatibleBucketCount, HIVE_COMPATIBLE, Optional.of(hiveTypes), Optional.empty()); } public static HivePartitioningHandle createPrestoNativePartitioningHandle( int bucketCount, List<Type> types, OptionalInt maxCompatibleBucketCount) { return new HivePartitioningHandle( bucketCount, maxCompatibleBucketCount, PRESTO_NATIVE, Optional.empty(), Optional.of(types)); } @JsonCreator public HivePartitioningHandle( @JsonProperty("bucketCount") int bucketCount, @JsonProperty("maxCompatibleBucketCount") OptionalInt maxCompatibleBucketCount, @JsonProperty("bucketFunctionType") BucketFunctionType bucketFunctionType, @JsonProperty("hiveTypes") Optional<List<HiveType>> hiveTypes, @JsonProperty("types") Optional<List<Type>> types) { this.bucketCount = bucketCount; this.maxCompatibleBucketCount = maxCompatibleBucketCount; this.bucketFunctionType = requireNonNull(bucketFunctionType, "bucketFunctionType is null"); this.hiveTypes = requireNonNull(hiveTypes, "hiveTypes is null"); this.types = requireNonNull(types, "types is null"); checkArgument(bucketFunctionType.equals(HIVE_COMPATIBLE) && hiveTypes.isPresent() && !types.isPresent() || bucketFunctionType.equals(PRESTO_NATIVE) && !hiveTypes.isPresent() && types.isPresent(), "Type list for bucketFunctionType %s is missing or duplicated. hiveTypes: %s, types: %s", bucketFunctionType, hiveTypes, types); } @JsonProperty public int getBucketCount() { return bucketCount; } @JsonProperty public Optional<List<HiveType>> getHiveTypes() { return hiveTypes; } @JsonProperty public Optional<List<Type>> getTypes() { return types; } @JsonProperty public OptionalInt getMaxCompatibleBucketCount() { return maxCompatibleBucketCount; } @JsonProperty public BucketFunctionType getBucketFunctionType() { return bucketFunctionType; } @Override public String toString() { return format( "buckets=%s, bucketFunctionType=%s, types=%s", bucketCount, bucketFunctionType, bucketFunctionType.equals(HIVE_COMPATIBLE) ? hiveTypes.get() : types.get()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HivePartitioningHandle that = (HivePartitioningHandle) o; return bucketCount == that.bucketCount && bucketFunctionType.equals(that.bucketFunctionType) && Objects.equals(hiveTypes, that.hiveTypes) && Objects.equals(types, that.types); } @Override public int hashCode() { return Objects.hash(bucketCount, bucketFunctionType, hiveTypes, types); } }
2,051
349
<reponame>zzh-python/music-wangyiyun<gh_stars>100-1000 # coding=utf-8 import base64 from cryptography.hazmat.primitives.ciphers import ( Cipher, algorithms, modes ) from cryptography.hazmat.backends import default_backend def aes(text, sec_key): backend = default_backend() pad = 16 - len(text) % 16 text = text + pad * chr(pad) cipher = Cipher( algorithms.AES(sec_key.encode('utf-8')), modes.CBC(b'0102030405060708'), backend=backend ) encryptor = cipher.encryptor() ciphertext = encryptor.update(text.encode('utf-8')) + encryptor.finalize() ciphertext = base64.b64encode(ciphertext) return ciphertext
272
648
{"resourceType":"DataElement","id":"PlanDefinition.action.definition","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/PlanDefinition.action.definition","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"PlanDefinition.action.definition","path":"PlanDefinition.action.definition","short":"Description of the activity to be performed","definition":"A reference to an ActivityDefinition that describes the action to be taken in detail, or a PlanDefinition that describes a series of actions to be taken.","comment":"Note that the definition is optional, and if no definition is specified, a dynamicValue with a root (~) path can be used to define the entire resource dynamically.","min":0,"max":"1","type":[{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/ActivityDefinition"},{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/PlanDefinition"}],"mapping":[{"identity":"workflow","map":"Definition.definition"}]}]}
252
435
{ "copyright_text": "Creative Commons Attribution license (reuse allowed)", "description": "Wouldn't it be cool if there was a way to play and interact with matrices in code like a mathematician can do on paper? What is so cool about that is, that instead of working with matrices as rectangles of numbers like a computer normally does, you can employ structural information while still exploiting most of the freedom you have when scribbling on a piece of paper. At first sight this seems hard to realize efficiently but as we show quite the contrary is the case. A structure driven approach for handling matrices implies great flexibility, speed and fun!\n\nWe will open the presentation with the demonstration of a motivational application from ultrasonic non-destructive testing -- namely the Synthetic Aperture Focusing Technique (SAFT) -- which employs large sparse and strongly structured matrices for focussing spatial irregularities in an observed medium-under-test. We will carve out why thinking about structured representations is reasonable and how scientific computing may benefit from applying additional abstraction steps of a matrix' representation when implementing various kinds of algorithms.\n\nFollowing, we introduce our open-source package 'fastmat' and show how it can be applied to implement real-world problems like the aforementioned SAFT. Due to its sleek architecture we demonstrate how highly intuitive code can be produced with strong proximity to the mathematical formulation of the problem, yet still allowing exploitation of matrix structure in efficient storage and computation. We will demonstrate that the architecture retains the high performance benefits in terms of computation time and memory complexity even for meta operations involving multiple matrices like linear combinations, block structures or matrix-matrix-vector products.\n\nClosing the presentation we will compare the performance of 'fastmat'-based matrix operations against their straightforward dense and unstructured implementations. Further, we will wrap up the opening motivational application in terms of performance and show pros and cons of working with 'fastmat' with respect to implementation effort, flexibility and performance.\n\nTo fully profit from this talk attendees should bring a basic understanding of Python and Numpy. A rough understanding about the general concepts of linear algebra might turn out to be helpful. The 30-minute presentation will be given in english language by <NAME> and <NAME>, both research assistants from the Technische Universit\u00e4t Ilmenau. The presentation slides (also in english) will be made available online shortly after the session. We are happy to answer short questions during and are open for discussions subsequent to the talk.", "duration": 969, "language": "eng", "recorded": "2017-08-31", "related_urls": [ { "label": "schedule", "url": "https://www.euroscipy.org/2017/program.html" } ], "speakers": [ "<NAME>", "<NAME>" ], "tags": [ "fastmat" ], "thumbnail_url": "https://i.ytimg.com/vi/dq5bLgLGae8/maxresdefault.jpg", "title": "fastmat - A simple Package for Fast Linear Transforms", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=dq5bLgLGae8" } ] }
782
3,189
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // @import Foundation; @class NSArray, NSBundle, NSDictionary, NSString, SimRuntimePairingReuirements; @interface SimRuntime : NSObject { unsigned int _version; unsigned int _equivalentIOSVersion; unsigned int _minHostVersion; unsigned int _maxHostVersion; unsigned int _minCoreSimulatorFrameworkVersion; unsigned int _maxCoreSimulatorFrameworkVersion; NSString *_name; NSString *_identifier; NSBundle *_bundle; NSString *_root; NSString *_versionString; NSString *_buildVersionString; NSString *_platformIdentifier; NSDictionary *_supportedFeatures; NSDictionary *_supportedFeaturesConditionalOnDeviceType; NSDictionary *_requiredHostServices; NSDictionary *_forwardHostNotifications; NSDictionary *_forwardHostNotificationsWithState; NSArray *_supportedProductFamilyIDs; SimRuntimePairingReuirements *_pairingRequirements; NSArray *_preferredPairingDeviceTypes; NSDictionary *_environment_extra; void *_libLaunchHostHandle; NSArray *_aliases; } + (unsigned int)equivalentIOSVersionForVersion:(unsigned int)arg1 profile:(id)arg2 platformIdentifier:(id)arg3; + (id)updatedMaxCoreSimulatorVersions; + (id)updatedMaxHostVersions; @property(nonatomic) unsigned int maxCoreSimulatorFrameworkVersion; // @synthesize maxCoreSimulatorFrameworkVersion=_maxCoreSimulatorFrameworkVersion; @property(nonatomic) unsigned int minCoreSimulatorFrameworkVersion; // @synthesize minCoreSimulatorFrameworkVersion=_minCoreSimulatorFrameworkVersion; @property(nonatomic) unsigned int maxHostVersion; // @synthesize maxHostVersion=_maxHostVersion; @property(nonatomic) unsigned int minHostVersion; // @synthesize minHostVersion=_minHostVersion; @property(copy, nonatomic) NSArray *aliases; // @synthesize aliases=_aliases; @property(nonatomic) void *libLaunchHostHandle; // @synthesize libLaunchHostHandle=_libLaunchHostHandle; @property(copy, nonatomic) NSDictionary *environment_extra; // @synthesize environment_extra=_environment_extra; @property(copy, nonatomic) NSArray *preferredPairingDeviceTypes; // @synthesize preferredPairingDeviceTypes=_preferredPairingDeviceTypes; @property(retain, nonatomic) SimRuntimePairingReuirements *pairingRequirements; // @synthesize pairingRequirements=_pairingRequirements; @property(copy, nonatomic) NSArray *supportedProductFamilyIDs; // @synthesize supportedProductFamilyIDs=_supportedProductFamilyIDs; @property(copy, nonatomic) NSDictionary *forwardHostNotificationsWithState; // @synthesize forwardHostNotificationsWithState=_forwardHostNotificationsWithState; @property(copy, nonatomic) NSDictionary *forwardHostNotifications; // @synthesize forwardHostNotifications=_forwardHostNotifications; @property(copy, nonatomic) NSDictionary *requiredHostServices; // @synthesize requiredHostServices=_requiredHostServices; @property(copy, nonatomic) NSDictionary *supportedFeaturesConditionalOnDeviceType; // @synthesize supportedFeaturesConditionalOnDeviceType=_supportedFeaturesConditionalOnDeviceType; @property(copy, nonatomic) NSDictionary *supportedFeatures; // @synthesize supportedFeatures=_supportedFeatures; @property(nonatomic) unsigned int equivalentIOSVersion; // @synthesize equivalentIOSVersion=_equivalentIOSVersion; @property(nonatomic) unsigned int version; // @synthesize version=_version; @property(copy, nonatomic) NSString *platformIdentifier; // @synthesize platformIdentifier=_platformIdentifier; @property(copy, nonatomic) NSString *buildVersionString; // @synthesize buildVersionString=_buildVersionString; @property(copy, nonatomic) NSString *versionString; // @synthesize versionString=_versionString; @property(copy, nonatomic) NSString *root; // @synthesize root=_root; @property(retain, nonatomic) NSBundle *bundle; // @synthesize bundle=_bundle; @property(copy, nonatomic) NSString *identifier; // @synthesize identifier=_identifier; @property(copy, nonatomic) NSString *name; // @synthesize name=_name; - (BOOL)isAvailableWithError:(id *)arg1; @property(readonly, nonatomic) BOOL available; - (id)dyld_simPath; - (BOOL)createInitialContentPath:(id)arg1 error:(id *)arg2; - (id)sampleContentPath; - (long long)compare:(id)arg1; - (BOOL)supportsFeatureConditionally:(id)arg1; - (BOOL)supportsFeature:(id)arg1; - (BOOL)supportsDeviceType:(id)arg1; - (id)platformResourcesPath; - (id)environment; - (id)debugDescription; - (id)description; - (id)initWithBundle:(id)arg1; - (id)initWithPath:(id)arg1; @end
1,432
2,406
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "vpu/utils/error.hpp" #include "ngraph/opsets/opset5.hpp" #include "vpu/ngraph/transformations/extract_dynamic_batch/slice_mat_mul.hpp" namespace vpu { SliceConfiguration sliceMatMul(const ngraph::Node& node) { VPU_THROW_UNLESS(node.get_input_size() == 2, "Expecting operation {} to have {} inputs, got {}", node, 2, node.get_input_size()); VPU_THROW_UNLESS(node.get_output_size() == 1, "Expecting operation {} to have {} outputs, got {}", node, 1, node.get_output_size()); // target networks have MatMul only with constant second input // there are tests on dynamic MatMul with non-constant second input // if try to process MatMul with non-constant second input it will // affect tests and they will fail, since Loop support is not ready yet if (!ngraph::op::is_constant(node.input_value(1).get_node_shared_ptr())) { return {}; } const auto& lhs = node.input_value(0); const auto& lhsPartialShape = lhs.get_partial_shape(); const auto& lhsRank = lhsPartialShape.rank(); VPU_THROW_UNLESS(lhsRank.is_static(), "Expecting operation {} to have static rank for input {}, got {}", node, lhs, lhsPartialShape); const auto& rhs = node.input_value(0); const auto& rhsPartialShape = rhs.get_partial_shape(); const auto& rhsRank = rhsPartialShape.rank(); VPU_THROW_UNLESS(rhsRank.is_static(), "Expecting operation {} to have static rank for input {}, got {}", node, rhs, rhsPartialShape); const auto& lhsRankLength = lhsRank.get_length(); const auto& rhsRankLength = rhsRank.get_length(); const auto maxRankLength = std::max(lhsRankLength, rhsRankLength); if (maxRankLength < 3) { return {}; } const auto isBatchStatic = [](const ngraph::PartialShape& shape) { const auto& rank = shape.rank(); if (rank.is_dynamic()) { return false; } const auto rankLength = rank.get_length(); if (rankLength < 3) { return true; } return std::all_of(shape.rbegin() + 2, shape.rend(), [](const ngraph::Dimension& dimension) { return dimension.is_static(); }); }; if (maxRankLength > 3) { VPU_THROW_UNLESS(isBatchStatic(lhsPartialShape), "Encountered multi-dimensional dynamic batch for operation {}, but it's unsupported", node); VPU_THROW_UNLESS(isBatchStatic(rhsPartialShape), "Encountered multi-dimensional dynamic batch for operation {}, but it's unsupported", node); return {}; } if (isBatchStatic(lhsPartialShape) && isBatchStatic(rhsPartialShape)) { return {}; } if (std::count_if(lhsPartialShape.cbegin(), lhsPartialShape.cend(), [](const ngraph::Dimension& dimension) { return dimension.is_dynamic(); }) > 1 || std::count_if(rhsPartialShape.cbegin(), rhsPartialShape.cend(), [](const ngraph::Dimension& dimension) { return dimension.is_dynamic(); }) > 1) { return {}; } const auto& lhsSliceMode = lhsRankLength < 3 ? SliceMode::Unchanged : SliceMode::Slice; const auto& rhsSliceMode = rhsRankLength < 3 ? SliceMode::Unchanged : SliceMode::Slice; return {{lhsSliceMode, rhsSliceMode}, {SliceMode::Slice}}; } } // namespace vpu
1,251
568
<gh_stars>100-1000 package com.novoda.magicmirror.modules.twitter; import android.os.Handler; import android.os.Looper; import com.novoda.magicmirror.modules.twitter.TwitterModule.TwitterListener; import java.util.concurrent.TimeUnit; import twitter4j.Status; class TweetsFlowRegulator { private static final long REFRESH_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(4); private final Handler handler; private final TweetsBuffer tweetsBuffer; private final TweetPicker tweetPickerAction; static TweetsFlowRegulator newInstance(TwitterListener listener) { Handler handler = new Handler(Looper.getMainLooper()); TweetsBuffer tweetsBuffer = new TweetsBuffer(); return new TweetsFlowRegulator(handler, tweetsBuffer, listener); } TweetsFlowRegulator(Handler handler, TweetsBuffer tweetsBuffer, TwitterListener listener) { this.handler = handler; this.tweetsBuffer = tweetsBuffer; this.tweetPickerAction = new TweetPicker(tweetsBuffer, listener); } private void scheduleNextBeat() { handler.postDelayed(refreshAction, REFRESH_DELAY_MILLIS); } void startTweetPicker() { handler.post(refreshAction); } void stopTweetPicker() { handler.removeCallbacks(refreshAction); } void addTweet(Status tweet) { tweetsBuffer.addTweet(tweet); } private final Runnable refreshAction = new Runnable() { @Override public void run() { handler.post(tweetPickerAction); scheduleNextBeat(); } }; private static class TweetPicker implements Runnable { private final TweetsBuffer tweetsBuffer; private final TwitterListener listener; TweetPicker(TweetsBuffer tweetsBuffer, TwitterListener listener) { this.tweetsBuffer = tweetsBuffer; this.listener = listener; } @Override public void run() { Status tweet = tweetsBuffer.pollTweet(); if (tweet != null) { listener.onNextTweet(tweet); } } } }
815
4,879
package com.mapswithme.maps.widget.placepage; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.mapswithme.maps.base.BaseToolbarActivity; import com.mapswithme.util.statistics.Statistics; public class PlaceDescriptionActivity extends BaseToolbarActivity { @Override protected Class<? extends Fragment> getFragmentClass() { return PlaceDescriptionFragment.class; } public static void start(@NonNull Context context, @NonNull String description, @NonNull String source) { Intent intent = new Intent(context, PlaceDescriptionActivity.class) .putExtra(PlaceDescriptionFragment.EXTRA_DESCRIPTION, description); context.startActivity(intent); Statistics.ParameterBuilder builder = new Statistics.ParameterBuilder() .add(Statistics.EventParam.SOURCE, source); Statistics.INSTANCE.trackEvent(Statistics.EventName.PLACEPAGE_DESCRIPTION_MORE, builder.get(), Statistics.STATISTICS_CHANNEL_REALTIME); } }
373
2,645
/* * Copyright 2020-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.elasticsearch.core.index; import static org.assertj.core.api.Assertions.*; import static org.skyscreamer.jsonassert.JSONAssert.*; import java.util.Map; import java.util.UUID; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.lang.Nullable; import org.springframework.test.context.ContextConfiguration; /** * @author <NAME> */ @SpringIntegrationTest @ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class }) public class TemplateTests { @Autowired ElasticsearchOperations operations; @Test // DATAES-612 void shouldCreateTemplate() { IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); org.springframework.data.elasticsearch.core.document.Document mapping = indexOps.createMapping(TemplateClass.class); Settings settings = indexOps.createSettings(TemplateClass.class); AliasActions aliasActions = new AliasActions( new AliasAction.Add(AliasActionParameters.builderForTemplate().withAliases("alias1", "alias2").build())); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("test-template", "log-*") // .withSettings(settings) // .withMappings(mapping) // .withAliasActions(aliasActions) // .build(); boolean acknowledged = indexOps.putTemplate(putTemplateRequest); assertThat(acknowledged).isTrue(); } @Test // DATAES-612 void shouldReturnNullOnNonExistingGetTemplate() { String templateName = "template" + UUID.randomUUID().toString(); IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); GetTemplateRequest getTemplateRequest = new GetTemplateRequest(templateName); TemplateData templateData = indexOps.getTemplate(getTemplateRequest); assertThat(templateData).isNull(); } @Test // DATAES-612 void shouldGetTemplate() throws JSONException { IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); org.springframework.data.elasticsearch.core.document.Document mapping = indexOps.createMapping(TemplateClass.class); Settings settings = indexOps.createSettings(TemplateClass.class); AliasActions aliasActions = new AliasActions( new AliasAction.Add(AliasActionParameters.builderForTemplate().withAliases("alias1", "alias2").build())); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("test-template", "log-*") // .withSettings(settings) // .withMappings(mapping) // .withAliasActions(aliasActions) // .withOrder(11) // .withVersion(42) // .build(); boolean acknowledged = indexOps.putTemplate(putTemplateRequest); assertThat(acknowledged).isTrue(); GetTemplateRequest getTemplateRequest = new GetTemplateRequest(putTemplateRequest.getName()); TemplateData templateData = indexOps.getTemplate(getTemplateRequest); assertThat(templateData).isNotNull(); assertThat(templateData.getIndexPatterns()).containsExactlyInAnyOrder(putTemplateRequest.getIndexPatterns()); assertEquals(settings.toJson(), templateData.getSettings().toJson(), false); assertEquals(mapping.toJson(), templateData.getMapping().toJson(), false); Map<String, AliasData> aliases = templateData.getAliases(); assertThat(aliases).hasSize(2); AliasData alias1 = aliases.get("alias1"); assertThat(alias1.getAlias()).isEqualTo("alias1"); AliasData alias2 = aliases.get("alias2"); assertThat(alias2.getAlias()).isEqualTo("alias2"); assertThat(templateData.getOrder()).isEqualTo(putTemplateRequest.getOrder()); assertThat(templateData.getVersion()).isEqualTo(putTemplateRequest.getVersion()); } @Test // DATAES-612 void shouldCheckExists() { IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); String templateName = "template" + UUID.randomUUID().toString(); ExistsTemplateRequest existsTemplateRequest = new ExistsTemplateRequest(templateName); boolean exists = indexOps.existsTemplate(existsTemplateRequest); assertThat(exists).isFalse(); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder(templateName, "log-*") // .withOrder(11) // .withVersion(42) // .build(); boolean acknowledged = indexOps.putTemplate(putTemplateRequest); assertThat(acknowledged).isTrue(); exists = indexOps.existsTemplate(existsTemplateRequest); assertThat(exists).isTrue(); } @Test // DATAES-612 void shouldDeleteTemplate() { IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); String templateName = "template" + UUID.randomUUID().toString(); ExistsTemplateRequest existsTemplateRequest = new ExistsTemplateRequest(templateName); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder(templateName, "log-*") // .withOrder(11) // .withVersion(42) // .build(); boolean acknowledged = indexOps.putTemplate(putTemplateRequest); assertThat(acknowledged).isTrue(); boolean exists = indexOps.existsTemplate(existsTemplateRequest); assertThat(exists).isTrue(); acknowledged = indexOps.deleteTemplate(new DeleteTemplateRequest(templateName)); assertThat(acknowledged).isTrue(); exists = indexOps.existsTemplate(existsTemplateRequest); assertThat(exists).isFalse(); } @Document(indexName = "test-template") @Setting(shards = 3) static class TemplateClass { @Id @Nullable private String id; @Field(type = FieldType.Text) @Nullable private String message; @Nullable public String getId() { return id; } public void setId(String id) { this.id = id; } @Nullable public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
2,178
476
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hetu.core.plugin.carbondata; import com.google.inject.Inject; import io.prestosql.plugin.hive.FileFormatDataSourceStats; import io.prestosql.plugin.hive.HdfsEnvironment; import io.prestosql.plugin.hive.HiveACIDWriteType; import io.prestosql.plugin.hive.HiveFileWriter; import io.prestosql.plugin.hive.HiveFileWriterFactory; import io.prestosql.plugin.hive.NodeVersion; import io.prestosql.plugin.hive.metastore.StorageFormat; import io.prestosql.spi.connector.ConnectorSession; import io.prestosql.spi.type.TypeManager; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.io.AcidOutputFormat; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.mapred.JobConf; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.Properties; import static java.util.Objects.requireNonNull; public class CarbondataFileWriterFactory implements HiveFileWriterFactory { private final HdfsEnvironment hdfsEnvironment; private final TypeManager typeManager; private final NodeVersion nodeVersion; private final FileFormatDataSourceStats stats; @Inject public CarbondataFileWriterFactory(HdfsEnvironment hdfsEnvironment, TypeManager typeManager, NodeVersion nodeVersion, FileFormatDataSourceStats stats) { this(typeManager, hdfsEnvironment, nodeVersion, stats); } public CarbondataFileWriterFactory(TypeManager typeManager, HdfsEnvironment hdfsEnvironment, NodeVersion nodeVersion, FileFormatDataSourceStats stats) { this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.typeManager = requireNonNull(typeManager, "typeManager is null"); this.nodeVersion = requireNonNull(nodeVersion, "nodeVersion is null"); this.stats = requireNonNull(stats, "stats is null"); } @Override public Optional<HiveFileWriter> createFileWriter(Path path, List<String> inputColumnNames, StorageFormat storageFormat, Properties schema, JobConf configuration, ConnectorSession session, Optional<AcidOutputFormat.Options> acidOptions, Optional<HiveACIDWriteType> acidWriteType) { try { int taskId = session.getTaskId().getAsInt(); int driverId = session.getDriverId().getAsInt(); int taskWriterCount = session.getTaskWriterCount(); //taskId starts from 0. //driverId starts from 0 and will be < taskWriterCount. //taskWriterCount starts from 1 // for taskId n, buckets will be between n*taskWriterCount (inclusive) and (n+1)*taskWriterCount (exclusive) int bucketNumber = taskId * taskWriterCount + driverId; /* Create a DeleteDeltaFileWriter */ return Optional .of(new CarbondataFileWriter(path, inputColumnNames, schema, configuration, typeManager, acidOptions, acidWriteType, OptionalInt.of(bucketNumber))); } catch (SerDeException e) { throw new RuntimeException("Error while creating carbon file writer", e); } } }
1,592
403
<reponame>jxd134/easeagent<filename>plugins/healthy/src/test/java/com/megaease/easeagent/plugin/healthy/OnApplicationEventInterceptorTest.java /* * Copyright (c) 2021, MegaEase * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.megaease.easeagent.plugin.healthy; import com.megaease.easeagent.plugin.MethodInfo; import com.megaease.easeagent.plugin.api.health.AgentHealth; import com.megaease.easeagent.plugin.bridge.NoOpContext; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationEvent; import static org.mockito.Mockito.mock; public class OnApplicationEventInterceptorTest { @Test public void invokeSuccess() { OnApplicationEventInterceptor interceptor = new OnApplicationEventInterceptor(); ApplicationEvent event = mock(ApplicationReadyEvent.class); MethodInfo methodInfo = MethodInfo.builder().args(new Object[]{event}).build(); interceptor.after(methodInfo, NoOpContext.NO_OP_CONTEXT); Assert.assertTrue(AgentHealth.INSTANCE.isAlive()); Assert.assertTrue(AgentHealth.INSTANCE.isReady()); } @Test public void invokeFail() { OnApplicationEventInterceptor interceptor = new OnApplicationEventInterceptor(); ApplicationEvent event = mock(ApplicationFailedEvent.class); MethodInfo methodInfo = MethodInfo.builder().args(new Object[]{event}).build(); interceptor.after(methodInfo, NoOpContext.NO_OP_CONTEXT); Assert.assertTrue(AgentHealth.INSTANCE.isAlive()); Assert.assertFalse(AgentHealth.INSTANCE.isReady()); } }
716
825
<filename>android/hummer-core/src/main/java/com/didi/hummer/core/engine/napi/jni/JSException.java<gh_stars>100-1000 package com.didi.hummer.core.engine.napi.jni; import android.util.LongSparseArray; import com.didi.hummer.core.engine.JSContext; import com.didi.hummer.core.exception.ExceptionCallback; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by XiaoFeng on 2021/6/29. */ public class JSException { public interface JSExceptionCallback { void onException(long jsContext, String errMsg); } private static LongSparseArray<List<ExceptionCallback>> contextCallbacks = new LongSparseArray<>(); public static void init() { // JS代码产生的Exception init((jsContext, errMsg) -> { dispatchExceptionCallback(jsContext, new com.didi.hummer.core.exception.JSException(errMsg)); }); } private static native void init(JSExceptionCallback callback); // Native代码产生的Exception public static void nativeException(JSContext jsContext, Exception e) { nativeException(jsContext.getIdentify(), e); } // Native代码产生的Exception public static void nativeException(long jsContext, Exception e) { dispatchExceptionCallback(jsContext, e); } /** * 添加ExceptionCallback */ public static void addJSContextExceptionCallback(JSContext jsContext, ExceptionCallback callback) { List<ExceptionCallback> cbList = contextCallbacks.get(jsContext.getIdentify()); if (cbList == null) { cbList = new ArrayList<>(); contextCallbacks.put(jsContext.getIdentify(), cbList); } cbList.add(callback); } /** * 删除指定ExceptionCallback */ public static void removeJSContextExceptionCallback(JSContext jsContext, ExceptionCallback callback) { List<ExceptionCallback> cbList = contextCallbacks.get(jsContext.getIdentify()); if (cbList != null) { Iterator<ExceptionCallback> iterator = cbList.iterator(); while (iterator.hasNext()) { ExceptionCallback cb = iterator.next(); if (cb == callback) { iterator.remove(); } } } } /** * 删除指定JSContext下的所有ExceptionCallback */ public static void removeJSContextExceptionCallback(JSContext jsContext) { contextCallbacks.remove(jsContext.getIdentify()); } /** * 统一派发异常回调 */ private static void dispatchExceptionCallback(long jsContext, Exception e) { List<ExceptionCallback> cbList = contextCallbacks.get(jsContext); if (cbList != null) { for (ExceptionCallback cb : cbList) { if (cb != null) { cb.onException(e); } } } } }
1,194
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.qa.form.jda; import java.util.ArrayList; import junit.framework.Test; import org.netbeans.jellytools.EditorOperator; import org.netbeans.jellytools.NbDialogOperator; import org.netbeans.jellytools.ProjectsTabOperator; import org.netbeans.jellytools.TopComponentOperator; import org.netbeans.jellytools.actions.Action; import org.netbeans.jellytools.modules.form.FormDesignerOperator; import org.netbeans.jellytools.nodes.Node; import org.netbeans.jellytools.nodes.ProjectRootNode; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JComboBoxOperator; import org.netbeans.jemmy.operators.JTableOperator; import org.netbeans.junit.NbModuleSuite; import org.netbeans.junit.NbTestSuite; import org.netbeans.qa.form.ExtJellyTestCase; /** * Testing properties of JDA FrameView node * * @author <NAME> * * <b><NAME></b> * 20 April 2011 NOT WORKS NOW */ public class ApplicationActionsTest extends ExtJellyTestCase { private static String FOO_SIMPLEMETHOD = "FooSimpleMethod"; private static String FOO_METHOD = "FooMethod"; private static String FOO_TEXT = "Foo Text"; private static String FOO_TOOLTIP = "Foo ToolTip"; private static String FOO_LETTER = "F"; private static String FOO_ENABLEDPROPTEXT = "fooEnabledProp"; private static String FOO_SELECTEDPROPTEXT = "fooSelectedProp"; /** Constructor required by JUnit */ public ApplicationActionsTest(String testName) { super(testName); setTestProjectName("JDABasic"+ this.getTimeStamp()); // NOI18N setTestPackageName(getTestProjectName().toLowerCase()); } public static Test suite() { return NbModuleSuite.create(NbModuleSuite.createConfiguration(ApplicationActionsTest.class).addTest( "testCreateJDAProject", "testInvokeWindow", "testCreateNewSimpleAction", "testCreateNewComplexAction", "testGeneratedCodeAndProperties").gui(true).clusters(".*").enableModules(".*")); } /** Creating JDA Basic project */ public void testCreateJDAProject() { createJDABasicProject(); } //** Testing generated code */ public void testInvokeWindow() { new Action("Window|Other|Application Actions",null).perform(); // NOI18N waitAMoment(); // invoke edit dialog for first action in table JTableOperator tableOp = new JTableOperator(getTopComponent()); tableOp.clickOnCell(1, 1); // select first row in table // invoke edit dialog new JButtonOperator(getTopComponent(), "Edit Action").pushNoBlock(); // NOI18N waitAMoment(); // closing edit dialog new JButtonOperator(new NbDialogOperator("Edit Action Properties"), "OK").pushNoBlock(); // NOI18N } //** Testing properties of FrameView node */ public void testCreateNewSimpleAction() { new JButtonOperator(getTopComponent(), "New Action").pushNoBlock(); // NOI18N waitAMoment(); CreateNewActionOperator createOp = new CreateNewActionOperator(); createOp.setMethodName(FOO_SIMPLEMETHOD); createOp.selectNode("Source Packages|" + getTestPackageName() + "|" + getTestProjectName() + "View.java"); // NOI18N createOp.ok(); } //** Testing properties of FrameView node */ public void testCreateNewComplexAction() { new JButtonOperator(getTopComponent(), "New Action").pushNoBlock(); // NOI18N waitAMoment(); CreateNewActionOperator createOp = new CreateNewActionOperator(); createOp.setMethodName(FOO_METHOD); createOp.setText(FOO_TEXT); createOp.setToolTip(FOO_TOOLTIP); createOp.typeLetter(FOO_LETTER); createOp.checkAlt(true); createOp.checkShift(true); createOp.checkCtrl(true); createOp.checkMetaMacOnly(true); createOp.setEnabledPropertyText(FOO_ENABLEDPROPTEXT); createOp.setSelectedPropertyText(FOO_SELECTEDPROPTEXT); createOp.selectNode("Source Packages|" + getTestPackageName() + "|" + getTestProjectName() + "View.java"); // NOI18N createOp.setSmallIcon(); NbDialogOperator iconOp = new NbDialogOperator("Select Icon"); // NOI18N new JComboBoxOperator(iconOp, 0).selectItem(1); new JButtonOperator(iconOp, "OK").push(); // NOI18N createOp.setLargeIcon(); iconOp = new NbDialogOperator("Select Icon"); // NOI18N new JComboBoxOperator(iconOp, 0).selectItem(2); new JButtonOperator(iconOp, "OK").push(); // NOI18N createOp.ok(); } public void testGeneratedCodeAndProperties() { FormDesignerOperator designer = new FormDesignerOperator(getTestProjectName() + "View.java"); // NOI18N ArrayList<String> lines = new ArrayList<String>(); lines.add("public void FooSimpleMethod() {"); // NOI18N lines.add("@Action(enabledProperty = \"fooEnabledProp\", selectedProperty = \"fooSelectedProp\")"); // NOI18N lines.add("public void FooMethod() {"); // NOI18N lines.add("private boolean fooEnabledProp = false;"); // NOI18N lines.add("public boolean isFooEnabledProp() {"); // NOI18N lines.add("public void setFooEnabledProp(boolean b) {"); // NOI18N lines.add("firePropertyChange(\"fooEnabledProp\", old, isFooEnabledProp());"); // NOI18N lines.add("private boolean fooSelectedProp = false;"); // NOI18N lines.add("public boolean isFooSelectedProp() {"); // NOI18N lines.add("public void setFooSelectedProp(boolean b) {"); // NOI18N lines.add("firePropertyChange(\"fooSelectedProp\", old, isFooSelectedProp());"); // NOI18N findInCode(lines, designer); ProjectRootNode prn = new ProjectsTabOperator().getProjectRootNode(getTestProjectName()); prn.select(); String nodePath = "Source Packages|" + getTestPackageName() + ".resources|" + getTestProjectName() + "View.properties"; // NOI18N Node propNode = new Node(prn, nodePath); runPopupOverNode("Edit", propNode); // NOI18N EditorOperator editorOp = new EditorOperator(getTestProjectName() + "View"); // NOI18N String fileContent = editorOp.getText(); lines = new ArrayList<String>(); lines.add("FooSimpleMethod.Action.text="); // NOI18N lines.add("FooSimpleMethod.Action.shortDescription="); // NOI18N lines.add("FooMethod.Action.text=Foo Text"); // NOI18N lines.add("FooMethod.Action.accelerator=shift ctrl meta alt pressed F"); // NOI18N lines.add("FooMethod.Action.largeIcon=splash.png"); // NOI18N lines.add("FooMethod.Action.smallIcon=about.png"); // NOI18N lines.add("FooMethod.Action.icon=about.png"); // NOI18N lines.add("FooMethod.Action.shortDescription=Foo ToolTip"); // NOI18N for (String line : lines) { String msg = "Line \"" + line + "\" not found in "+getTestProjectName() + "View.properties file."; // NOI18N assertTrue(msg, fileContent.contains(line)); } } private TopComponentOperator getTopComponent() { return new TopComponentOperator("Application Actions"); // NOI18N } }
3,339
1,034
/* * Copyright 2013, <NAME>. * Copyright 2013, <NAME>. * Copyright 2016 <NAME> * Copyright 2019-2020 <NAME> * SPDX-License-Identifier: BSL-1.0 * * OpenHMD - Free and Open Source API and drivers for immersive technology. */ /* Oculus Rift S Driver Internal Interface */ #ifndef RIFT_S_HMD_H #define RIFT_S_HMD_H #include "../openhmdi.h" #include "../hid.h" #include "rift-s-protocol.h" #include "rift-s-firmware.h" #include "rift-s-controller.h" #include "rift-s-radio.h" #define MAX_CONTROLLERS 2 struct rift_s_hmd_s { ohmd_context* ctx; int use_count; hid_device* handles[3]; uint32_t last_imu_timestamp; double last_keep_alive; fusion sensor_fusion; vec3f raw_mag, raw_accel, raw_gyro; float temperature; bool display_on; rift_s_device_info_t device_info; rift_s_imu_config_t imu_config; rift_s_imu_calibration imu_calibration; /* Controller state tracking */ int num_active_controllers; rift_s_controller_state controllers[MAX_CONTROLLERS]; /* Radio comms manager */ rift_s_radio_state radio_state; /* OpenHMD output devices */ rift_s_device_priv hmd_dev; rift_s_controller_device touch_dev[MAX_CONTROLLERS]; }; #endif
454
389
<filename>src/CommunityToolkit.Maui.SourceGenerators/Properties/launchSettings.json { "profiles": { "CommunityToolkit.Maui.SourceGenerators": { "commandName": "DebugRoslynComponent", "targetProject": "..\\CommunityToolkit.Maui.UnitTests\\CommunityToolkit.Maui.UnitTests.csproj" } } }
118
369
// Copyright (c) 2017-2021, Mudit<NAME>. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "NullTransform.hpp" using ::audio::transcode::NullTransform; auto NullTransform::transform(const Span &span, const Span &transformSpace) const -> Span { return span; } auto NullTransform::validateInputFormat(const audio::AudioFormat &inputFormat) const noexcept -> bool { return true; } auto NullTransform::transformFormat(const audio::AudioFormat &inputFormat) const noexcept -> audio::AudioFormat { return inputFormat; } auto NullTransform::transformBlockSize(std::size_t inputBufferSize) const noexcept -> std::size_t { return inputBufferSize; } auto NullTransform::transformBlockSizeInverted(std::size_t outputBufferSize) const noexcept -> std::size_t { return outputBufferSize; }
259
640
void Yes() { } void No() { } void eq_int_c(_Float16 a) { if ( a == 1 ) Yes(); else No(); } void eq_long_c(_Float16 a) { if ( a == 1L ) Yes(); else No(); } void eq_double_c(_Float16 a) { if ( a == 1.0 ) Yes(); else No(); } void eq_float16_c(_Float16 a) { if ( a == 1.0f16 ) Yes(); else No(); } void eq_int_cr(_Float16 a) { if ( 1 == a ) Yes(); else No(); } void eq_long_cr(_Float16 a) { if ( 1L == a ) Yes(); else No(); } void eq_double_cr(_Float16 a) { if ( 1.0 == a ) Yes(); else No(); } void eq_float16_cr(_Float16 a) { if ( 1.0f16 == a) Yes(); else No(); } void eq_int(_Float16 a, int b) { if ( a == b ) Yes(); else No(); } void eq_long(_Float16 a, long b) { if ( a == b ) Yes(); else No(); } void eq_double(_Float16 a, double b) { if ( a == b ) Yes(); else No(); } void eq_float16(_Float16 a, _Float16 b) { if ( a == b ) Yes(); else No(); } void eq_int_r(_Float16 a, int b) { if ( b == a ) Yes(); else No(); } void eq_long_r(_Float16 a, long b) { if ( b == a ) Yes(); else No(); } void eq_double_r(_Float16 a, double b) { if ( b == a ) Yes(); else No(); } void eq_float16_r(_Float16 a, _Float16 b) { if ( b == a ) Yes(); else No(); } void lt_int_c(_Float16 a) { if ( a < 1 ) Yes(); else No(); } void lt_long_c(_Float16 a) { if ( a < 1L ) Yes(); else No(); } void lt_double_c(_Float16 a) { if ( a < 1.0 ) Yes(); else No(); } void lt_float16_c(_Float16 a) { if ( a < 1.0f16 ) Yes(); else No(); } void lt_int_cr(_Float16 a) { if ( 1 < a ) Yes(); else No(); } void lt_long_cr(_Float16 a) { if ( 1L < a ) Yes(); else No(); } void lt_double_cr(_Float16 a) { if ( 1.0 < a ) Yes(); else No(); } void lt_float16_cr(_Float16 a) { if ( 1.0f16 < a) Yes(); else No(); } void lt_int(_Float16 a, int b) { if ( a < b ) Yes(); else No(); } void lt_long(_Float16 a, long b) { if ( a < b ) Yes(); else No(); } void lt_double(_Float16 a, double b) { if ( a < b ) Yes(); else No(); } void lt_float16(_Float16 a, _Float16 b) { if ( a < b ) Yes(); else No(); } void lt_int_r(_Float16 a, int b) { if ( b < a ) Yes(); else No(); } void lt_long_r(_Float16 a, long b) { if ( b < a ) Yes(); else No(); } void lt_double_r(_Float16 a, double b) { if ( b < a ) Yes(); else No(); } void lt_float16_r(_Float16 a, _Float16 b) { if ( b < a ) Yes(); else No(); }
1,073
422
<reponame>asharma13524/sample-programs<filename>archive/p/python/baklava.py for i in range(0, 10, 1): print((" " * (10 - i)) + ("*" * (i * 2 + 1))) for i in range(10, -1, -1): print((" " * (10 - i)) + ("*" * (i * 2 + 1)))
109
685
#pragma once #include <Fs/Filesystem.h> #include <List.h> namespace fs { class FsVolume; namespace VolumeManager { enum { VolumeErrorNone, VolumeErrorMisc, VolumeErrorNotDevice, // File is not a device VolumeErrorInvalidFilesystem, // No filesystem for device VolumeErrorVolumeNotFound, // Volume not found }; extern List<FsVolume*>* volumes; void Initialize(); FsVolume* FindVolume(const char* name); // Identify filesystem and mount device using optional name int Mount(FsNode* device, const char* name = nullptr); // Mount device using driver and optional name int Mount(FsNode* device, ::fs::FsDriver* driver, const char* name = nullptr); int Unmount(const char* name); void RegisterVolume(FsVolume* vol); int UnregisterVolume(FsVolume* vol); void MountSystemVolume(); FsVolume* SystemVolume(); } // namespace VolumeManager } // namespace fs
277
2,989
package com.linkedin.databus.client.pub; /* * * Copyright 2013 LinkedIn Corp. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ import java.io.Serializable; /** * An SCN represents a logical clock for one or more databus sources. * @author cbotev */ public interface SCN extends Serializable, Comparable<SCN> { /** * Checks if this SCN is comparable with another SCN. * @param otherSCN the other SCN * @return true iff they are comparable */ boolean isComparable(SCN otherSCN); /** * Compares this SCN to another SCN. The two SCNs should be comparable (see * {@link #isComparable(SCN)}). * @return < 0 if this is smaller; == 0 if they are equal; >0 if this is larger; result is * undefined if the SCNs are not comparable . */ int compareTo(SCN otherSCN); }
425
2,132
<gh_stars>1000+ // Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.depthai; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import org.bytedeco.opencv.opencv_core.*; import static org.bytedeco.opencv.global.opencv_core.*; import org.bytedeco.opencv.opencv_imgproc.*; import static org.bytedeco.opencv.global.opencv_imgproc.*; import static org.bytedeco.depthai.global.depthai.*; /** * StereoDepthConfig message. */ @Namespace("dai") @NoOffset @Properties(inherit = org.bytedeco.depthai.presets.depthai.class) public class StereoDepthConfig extends Buffer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public StereoDepthConfig(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public StereoDepthConfig(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public StereoDepthConfig position(long position) { return (StereoDepthConfig)super.position(position); } @Override public StereoDepthConfig getPointer(long i) { return new StereoDepthConfig((Pointer)this).offsetAddress(i); } /** * Construct StereoDepthConfig message. */ public StereoDepthConfig() { super((Pointer)null); allocate(); } private native void allocate(); public StereoDepthConfig(@SharedPtr RawStereoDepthConfig ptr) { super((Pointer)null); allocate(ptr); } private native void allocate(@SharedPtr RawStereoDepthConfig ptr); /** * Confidence threshold for disparity calculation * @param confThr Confidence threshold value 0..255 */ public native void setConfidenceThreshold(int confThr); /** * Get confidence threshold for disparity calculation */ public native int getConfidenceThreshold(); /** * @param median Set kernel size for disparity/depth median filtering, or disable */ public native void setMedianFilter(MedianFilter median); public native void setMedianFilter(@Cast("dai::MedianFilter") int median); /** * Get median filter setting */ public native MedianFilter getMedianFilter(); /** * A larger value of the parameter means that farther colors within the pixel neighborhood will be mixed together, * resulting in larger areas of semi-equal color. * @param sigma Set sigma value for 5x5 bilateral filter. 0..65535 */ public native void setBilateralFilterSigma(@Cast("uint16_t") short sigma); /** * Get sigma value for 5x5 bilateral filter */ public native @Cast("uint16_t") short getBilateralFilterSigma(); /** * @param threshold Set threshold for left-right, right-left disparity map combine, 0..255 */ public native void setLeftRightCheckThreshold(int threshold); /** * Get threshold for left-right check combine */ public native int getLeftRightCheckThreshold(); /** * Computes and combines disparities in both L-R and R-L directions, and combine them. * * For better occlusion handling, discarding invalid disparity values */ public native void setLeftRightCheck(@Cast("bool") boolean enable); /** * Computes disparity with sub-pixel interpolation (5 fractional bits). * * Suitable for long range. Currently incompatible with extended disparity */ public native void setSubpixel(@Cast("bool") boolean enable); /** * Useful for normalization of the disparity map. * @return Maximum disparity value that the node can return */ public native float getMaxDisparity(); /** * Set explicit configuration. * @param config Explicit configuration */ public native void set(@ByVal RawStereoDepthConfig config); /** * Retrieve configuration data for StereoDepth. * @return config for stereo depth algorithm */ public native @ByVal RawStereoDepthConfig get(); }
1,396
3,976
# -*- coding: UTF-8 -*- # !/usr/bin/python from flask.ext.wtf import Form from wtforms import StringField, TextAreaField, BooleanField, SelectField,SubmitField from wtforms.validators import Required class PostForm(Form): body = TextAreaField("说点什么吧!",validators=[Required()]) submit = SubmitField('提交')
115
2,094
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: Optimizer_test.h (optimization_test) // Authors: <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <optimization/include/SDCAOptimizer.h> /// <summary> Tests that the SDCA duality gap tends to zero in a regression setting after a sufficient number of epochs.</summary> template <typename LossFunctionType, typename RegularizerType> void TestSDCARegressionConvergence(LossFunctionType lossFunction, RegularizerType regularizer, SDCAOptimizerParameters parameters, double earlyStopping, double biasVariance, double inputVariance, double outputVariance); /// <summary> Tests that the SDCA duality gap tends to zero in a classification setting after a sufficient number of epochs.</summary> template <typename LossFunctionType, typename RegularizerType> void TestSDCAClassificationConvergence(LossFunctionType lossFunction, RegularizerType regularizer, SDCAOptimizerParameters parameters, double earlyStopping, double biasVariance, double marginMean, double inputVariance); /// <summary> Tests that SDCA resets correctly.</summary> template <typename LossFunctionType, typename RegularizerType> void TestSDCAReset(LossFunctionType lossFunction, RegularizerType regularizer); #pragma region implementation #include "../include/RandomDataset.h" #include <optimization/include/GetSparseSolution.h> #include <optimization/include/IndexedContainer.h> #include <optimization/include/OptimizationExample.h> #include <optimization/include/SDCAOptimizer.h> #include <optimization/include/VectorSolution.h> #include <testing/include/testing.h> #include <memory> #include <string> using namespace ell; using namespace ell::optimization; // assert that the duality gap tends to zero template <typename LossFunctionType, typename RegularizerType> void TestSDCARegressionConvergence(LossFunctionType lossFunction, RegularizerType regularizer, SDCAOptimizerParameters parameters, double earlyStopping, double biasVariance, double inputVariance, double outputVariance) { size_t count = 500; size_t size = 17; size_t epochs = 50; std::string randomSeedString = "<PASSWORD>"; std::seed_seq seed(randomSeedString.begin(), randomSeedString.end()); std::default_random_engine randomEngine(seed); // create random solution VectorSolution<double, true> solution(size); std::normal_distribution<double> biasDistribution(0, biasVariance); solution.GetBias() = biasDistribution(randomEngine); std::uniform_int_distribution<int> vectorDistribution(-1, 1); solution.GetVector().Generate([&]() { return vectorDistribution(randomEngine); }); // create random dataset auto examples = GetRegressionDataset(count, inputVariance, outputVariance, solution, randomEngine); // create optimizer auto optimizer = MakeSDCAOptimizer<VectorSolution<double, true>>(examples, lossFunction, regularizer, parameters); optimizer.Update(epochs, earlyStopping); double dualityGap = optimizer.GetSolutionInfo().DualityGap(); // perform test std::string lossName = typeid(LossFunctionType).name(); lossName = lossName.substr(lossName.find_last_of(":") + 1); std::string regularizerName = typeid(RegularizerType).name(); regularizerName = regularizerName.substr(regularizerName.find_last_of(":") + 1); testing::ProcessTest("TestSDCARegressionConvergence <" + lossName + ", " + regularizerName + ">", dualityGap <= earlyStopping); } #include <iostream> // assert that the duality gap tends to zero template <typename LossFunctionType, typename RegularizerType> void TestSDCAClassificationConvergence(LossFunctionType lossFunction, RegularizerType regularizer, SDCAOptimizerParameters parameters, double earlyStopping, double biasVariance, double marginMean, double inputVariance) { size_t count = 500; size_t size = 17; size_t epochs = 50; std::string randomSeedString = "<PASSWORD>"; std::seed_seq seed(randomSeedString.begin(), randomSeedString.end()); std::default_random_engine randomEngine(seed); // create random solution VectorSolution<double, true> solution(size); std::normal_distribution<double> biasDistribution(0, biasVariance); solution.GetBias() = biasDistribution(randomEngine); std::uniform_int_distribution<int> vectorDistribution(-1, 1); solution.GetVector().Generate([&]() { return vectorDistribution(randomEngine); }); // create random dataset auto examples = GetClassificationDataset(count, marginMean, inputVariance, solution, randomEngine); // create optimizer auto optimizer = MakeSDCAOptimizer<VectorSolution<double, true>>(examples, lossFunction, regularizer, parameters); optimizer.Update(epochs, earlyStopping); double dualityGap = optimizer.GetSolutionInfo().DualityGap(); std::string lossName = typeid(LossFunctionType).name(); lossName = lossName.substr(lossName.find_last_of(":") + 1); std::string regularizerName = typeid(RegularizerType).name(); regularizerName = regularizerName.substr(regularizerName.find_last_of(":") + 1); testing::ProcessTest("TestSDCAClassificationConvergence <" + lossName + ", " + regularizerName + ">", dualityGap <= earlyStopping); } template <typename LossFunctionType, typename RegularizerType> void TestSDCAReset(LossFunctionType lossFunction, RegularizerType regularizer) { size_t count = 50; size_t size = 5; size_t epochs = 3; std::string randomSeedString = "GoodLuckMan"; std::seed_seq seed(randomSeedString.begin(), randomSeedString.end()); std::default_random_engine randomEngine(seed); // create random dataset auto examples = GetRandomDataset<double, VectorScalarExampleType<double>, VectorRefScalarExampleType<double>>(count, size, randomEngine, 0); // create optimizer auto optimizer1 = MakeSDCAOptimizer<VectorSolution<double, true>>(examples, lossFunction, regularizer, { 0.1, false }); optimizer1.Update(epochs); auto solution1 = optimizer1.GetSolution(); const auto& vector1 = solution1.GetVector(); optimizer1.Reset(); optimizer1.Update(epochs); auto solution2 = optimizer1.GetSolution(); const auto& vector2 = solution2.GetVector(); auto optimizer2 = SDCAOptimizer<VectorSolution<double, true>, LossFunctionType, RegularizerType>(examples); optimizer2.SetLossFunction(lossFunction); optimizer2.SetRegularizer(regularizer); optimizer2.SetParameters({ 0.1, false }); optimizer2.Update(epochs); auto solution3 = optimizer2.GetSolution(); const auto& vector3 = solution3.GetVector(); std::string lossName = typeid(LossFunctionType).name(); lossName = lossName.substr(lossName.find_last_of(":") + 1); std::string regularizerName = typeid(RegularizerType).name(); regularizerName = regularizerName.substr(regularizerName.find_last_of(":") + 1); testing::ProcessTest("TestSDCAReset <" + lossName + ", " + regularizerName + ">", vector1 == vector2 && vector1 == vector3); } template <typename LossFunctionType> void TestGetSparseSolution(LossFunctionType lossFunction, double regularizationParameter) { size_t count = 500; size_t size = 17; double biasVariance = 1.0; double marginMean = 1.0; double inputVariance = 1.0; std::string randomSeedString = "GoodLuckMan"; std::seed_seq seed(randomSeedString.begin(), randomSeedString.end()); std::default_random_engine randomEngine(seed); // create random solution VectorSolution<double, true> targetSolution(size); std::normal_distribution<double> biasDistribution(0, biasVariance); targetSolution.GetBias() = biasDistribution(randomEngine); std::uniform_int_distribution<int> vectorDistribution(-1, 1); targetSolution.GetVector().Generate([&]() { return vectorDistribution(randomEngine); }); auto examples = GetClassificationDataset(count, marginMean, inputVariance, targetSolution, randomEngine); auto trainedSolution1 = GetSparseSolution<VectorSolution<double, true>>(examples, lossFunction, { { 0.7, 0.75 }, { regularizationParameter } }).solution; double nonZeroFraction1 = trainedSolution1.GetVector().Norm0() / trainedSolution1.GetVector().Size(); auto trainedSolution2 = GetSparseSolution<VectorSolution<double, true>>(examples, lossFunction, { { 0.45, 0.5 }, { regularizationParameter } }).solution; double nonZeroFraction2 = trainedSolution2.GetVector().Norm0() / trainedSolution2.GetVector().Size(); auto trainedSolution3 = GetSparseSolution<VectorSolution<double, true>>(examples, lossFunction, { { 0.2, 0.25 }, { regularizationParameter } }).solution; double nonZeroFraction3 = trainedSolution3.GetVector().Norm0() / trainedSolution3.GetVector().Size(); testing::ProcessTest("TestGetSparseSolution", std::abs(nonZeroFraction1 - 0.75) < 0.1 && std::abs(nonZeroFraction2 - 0.5) < 0.1 && std::abs(nonZeroFraction3 - 0.25) < 0.1); } #pragma endregion implementation
2,895
3,453
<gh_stars>1000+ import ipywidgets as widgets from IPython import get_ipython class PrinterX: def __init__(self): self.w = w=widgets.HTML() def show(self): return self.w def write(self,s): self.w.value = s print("Running from within ipython?", get_ipython() is not None) p=PrinterX() p.show() p.write('ffffffffff')
149
2,519
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/catalog/ArrayType.java // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.starrocks.catalog; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.gson.annotations.SerializedName; import com.starrocks.thrift.TColumnType; import com.starrocks.thrift.TTypeDesc; import com.starrocks.thrift.TTypeNode; import com.starrocks.thrift.TTypeNodeType; /** * Describes an ARRAY type. */ public class ArrayType extends Type { @SerializedName(value = "itemType") private Type itemType; public ArrayType(Type itemType) { if (itemType != null && itemType.isDecimalV3()) { throw new InternalError("Decimal32/64/128 is not supported in current version"); } this.itemType = itemType; } public ArrayType(Type itemType, boolean fromSubQuery) { this.itemType = itemType; } public Type getItemType() { return itemType; } @Override public TColumnType toColumnTypeThrift() { Preconditions.checkArgument(false, "ArrayType.toColumnTypeThrift not implemented"); return null; } @Override public boolean matchesType(Type t) { if (t.isPseudoType()) { return t.matchesType(this); } return t.isArrayType() && itemType.matchesType(((ArrayType) t).itemType); } @Override public String toSql(int depth) { if (depth >= MAX_NESTING_DEPTH) { return "ARRAY<...>"; } return String.format("ARRAY<%s>", itemType.toSql(depth + 1)); } @Override public boolean equals(Object other) { if (!(other instanceof ArrayType)) { return false; } ArrayType otherArrayType = (ArrayType) other; return otherArrayType.itemType.equals(itemType); } @Override public void toThrift(TTypeDesc container) { TTypeNode node = new TTypeNode(); container.types.add(node); Preconditions.checkNotNull(itemType); node.setType(TTypeNodeType.ARRAY); itemType.toThrift(container); } @Override protected String prettyPrint(int lpad) { String leftPadding = Strings.repeat(" ", lpad); if (!itemType.isStructType()) { return leftPadding + toSql(); } // Pass in the padding to make sure nested fields are aligned properly, // even if we then strip the top-level padding. String structStr = itemType.prettyPrint(lpad); structStr = structStr.substring(lpad); return String.format("%sARRAY<%s>", leftPadding, structStr); } @Override public String toString() { return String.format("ARRAY<%s>", itemType.toString()); } @Override public ArrayType clone() { ArrayType clone = (ArrayType) super.clone(); clone.itemType = this.itemType.clone(); return clone; } public int getDimensions() { return itemType.isArrayType() ? 1 + ((ArrayType) itemType).getDimensions() : 1; } }
1,484
780
<gh_stars>100-1000 package com.codeborne.selenide.impl; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Optional; public class Arguments { private final Object[] args; public Arguments(@Nullable Object[] args) { this.args = args; } public <T> T nth(int index) { if (args == null) { throw new IllegalArgumentException("Missing arguments"); } if (index >= args.length) { throw new IllegalArgumentException("Missing argument #" + index + " in " + Arrays.toString(args)); } //noinspection unchecked return (T) args[index]; } public int length() { return args == null ? 0 : args.length; } @CheckReturnValue @Nonnull public <T> Optional<T> ofType(@Nonnull Class<T> klass) { if (args == null) return Optional.empty(); for (Object arg : args) { if (arg != null && klass.isAssignableFrom(arg.getClass())) //noinspection unchecked return Optional.of((T) arg); } return Optional.empty(); } }
402
3,442
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.ldap; import java.io.*; import java.net.*; import java.security.*; import javax.net.*; import net.java.sip.communicator.service.certificate.*; import net.java.sip.communicator.util.*; /** * Utility class to delegate the creation of sockets to LDAP servers to our * {@link CertificateService}. * <p> * Note that the documentation says to extend {@link SocketFactory}, but the * LDAP directory context tries to create an unconnected socket without a * hostname first by calling <tt>createSocket</tt>. It would be impossible to * validate the hostname against the certificate, which leads to an insecure * communication. It only calls {@link #createSocket(String, int)} when * <tt>createSocket</tt> is not found * * @author <NAME> */ public class LdapSSLSocketFactoryDelegate { /** * Logger for this class. */ private final static Logger logger = Logger.getLogger(LdapSSLSocketFactoryDelegate.class); /** * Get default SSL socket factory delegate. * * @return default SSL socket factory delegate. */ public static Object getDefault() { return new LdapSSLSocketFactoryDelegate(); } /** * Creates a socket for the specified destination host and port. * * @param host The hostname that the socket connects to. * @param port The port that the socket connects to. * @return The created socket. * @throws IOException * @throws UnknownHostException When the hostname cannot be resolved to an * IP address. */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { try { return LdapServiceImpl .getCertificateService() .getSSLContext( LdapServiceImpl.getCertificateService().getTrustManager( host)).getSocketFactory().createSocket(host, port); } catch (GeneralSecurityException e) { logger.error( "unable to create socket through the certificate service", e); throw new IOException(e.getMessage()); } } }
1,005
11,356
// (C) Copyright <NAME> 2003. // Use, modification and distribution are subject to 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) // See http://www.boost.org/libs/config for the most recent version. #ifndef BOOST_ABI_TEST_HPP #define BOOST_ABI_TEST_HPP #include <boost/config.hpp> #include <boost/cstdint.hpp> #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif // // the following class is designed to break if the ABI // it's compiled with does not match that of the client // calling it.... // struct empty{}; class abi_test : protected empty { private: empty e; char c; boost::int32_t i; public: inline char inline_one()const { return c; } inline boost::int32_t inline_two()const { return i; } virtual char virtual_one()const; virtual boost::int32_t virtual_two()const; abi_test(); }; #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // BOOST_ABI_TEST_HPP
398
5,169
{ "name": "TaskEnginer", "version": "0.0.5", "summary": "TaskEnginer is a split complex task into simple tasks", "description": "TaskEnginer is a split complex task into simple tasks.", "homepage": "http://www.scorplot.com", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "aruisi": "<EMAIL>" }, "source": { "git": "https://github.com/scorplot/TaskEnginer.git", "tag": "0.0.5" }, "platforms": { "ios": "8.0" }, "source_files": "TaskEnginer/Classes/**/*", "dependencies": { "CircleReferenceCheck": [ ] } }
243
3,710
<gh_stars>1000+ #pragma once #ifndef TIIO_SGI_INCLUDED #define TIIO_SGI_INCLUDED #include "tiio.h" //#include "timage_io.h" #include "tproperty.h" #include <QCoreApplication> namespace Tiio { Tiio::ReaderMaker makeSgiReader; Tiio::WriterMaker makeSgiWriter; class SgiWriterProperties final : public TPropertyGroup { Q_DECLARE_TR_FUNCTIONS(SgiWriterProperties) public: TEnumProperty m_pixelSize; TBoolProperty m_compressed; TEnumProperty m_endianess; SgiWriterProperties(); void updateTranslation() override; }; } // namespace #endif
211
13,162
#pragma once #include <b1/rodeos/wasm_ql.hpp> namespace b1::rodeos::wasm_ql { struct http_config { uint32_t num_threads = {}; uint32_t max_request_size = {}; uint64_t idle_timeout_ms = {}; std::string allow_origin = {}; std::string static_dir = {}; std::string address = {}; std::string port = {}; }; struct http_server { virtual ~http_server() {} static std::shared_ptr<http_server> create(const std::shared_ptr<const http_config>& http_config, const std::shared_ptr<const shared_state>& shared_state); virtual void stop() = 0; }; } // namespace b1::rodeos::wasm_ql
326
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_COORDINATION_UNIT_MOJOM_TRAITS_H_ #define SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_COORDINATION_UNIT_MOJOM_TRAITS_H_ #include "base/component_export.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/resource_coordinator/public/mojom/coordination_unit.mojom.h" namespace mojo { template <> struct COMPONENT_EXPORT(RESOURCE_COORDINATOR_PUBLIC_MOJOM) EnumTraits<resource_coordinator::mojom::CoordinationUnitType, resource_coordinator::CoordinationUnitType> { static resource_coordinator::mojom::CoordinationUnitType ToMojom( resource_coordinator::CoordinationUnitType type); static bool FromMojom(resource_coordinator::mojom::CoordinationUnitType input, resource_coordinator::CoordinationUnitType* out); }; template <> struct COMPONENT_EXPORT(RESOURCE_COORDINATOR_PUBLIC_MOJOM) StructTraits<resource_coordinator::mojom::CoordinationUnitIDDataView, resource_coordinator::CoordinationUnitID> { static uint64_t id(const resource_coordinator::CoordinationUnitID& id) { return id.id; } static resource_coordinator::CoordinationUnitType type( const resource_coordinator::CoordinationUnitID& id) { return id.type; } static bool Read( resource_coordinator::mojom::CoordinationUnitIDDataView input, resource_coordinator::CoordinationUnitID* out); }; } // namespace mojo #endif // SERVICES_RESOURCE_COORDINATOR_PUBLIC_CPP_COORDINATION_UNIT_MOJOM_TRAITS_H_
640
716
<filename>exhibitor-core/src/main/java/com/netflix/exhibitor/core/index/IndexList.java /* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.exhibitor.core.index; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.FileFilter; import java.util.List; public class IndexList { private final List<File> indexes; public IndexList(File directory) { File[] filtered = directory.listFiles ( new FileFilter() { @Override public boolean accept(File f) { if ( IndexMetaData.isValid(f) ) { File metaDataFile = IndexMetaData.getMetaDataFile(f); if ( metaDataFile.exists() ) { return true; } } return false; } } ); indexes = (filtered != null) ? ImmutableList.copyOf(filtered) : ImmutableList.<File>of(); } public List<File> getIndexes() { return indexes; } }
794
1,460
<reponame>boomt1337/nitroshare-desktop<gh_stars>1000+ /* * The MIT License (MIT) * * Copyright (c) 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef LIBNITROSHARE_TRANSPORTSERVER_H #define LIBNITROSHARE_TRANSPORTSERVER_H #include <QObject> #include <nitroshare/config.h> class Device; class Transport; /** * @brief Server for receiving and initializing transfers */ class NITROSHARE_EXPORT TransportServer : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name) public: /** * @brief Retrieve the unique identifier for the transport */ virtual QString name() const = 0; /** * @brief Create a transport for sending items to a device * @param device pointer to Device * @return pointer to Transport or nullptr * * This method is invoked to create a transport for sending a bundle to the * specified device. The transport server should use the properties in the * device to create the transport or return nullptr if it cannot. */ virtual Transport *createTransport(Device *device) = 0; Q_SIGNALS: /** * @brief Indicate that an incoming transfer has been received * @param transport pointer to Transport * * The transport should be allocated on the heap and will be properly * deleted when no longer needed. */ void transportReceived(Transport *transport); }; #endif // LIBNITROSHARE_TRANSPORTSERVER_H
750
348
<filename>bin/automated_detection_testing/ci/attack_range_for_testing/helpers/attack_range_controller.py from shutil import which import secrets import string import os import logging import sys import time from helpers import aws_service # Logger logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) LOGGER = logging.getLogger(__name__) def create_random_password(): alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(10)) password = <PASSWORD>' + password + 'n:' return password def configure_attack_range(region, tf_state_store, password, ssh_key_name): sys.path.append(os.path.join(os.getcwd(),'attack_range')) with open('attack_range/attack_range.conf.template', 'r') as file : filedata = file.read() filedata = filedata.replace('attack_range_password = <PASSWORD>', 'attack_range_password = ' + password) filedata = filedata.replace('tf_backend = local', 'tf_backend = remote') filedata = filedata.replace('tf_backend_name = threat_research_attack_range', 'tf_backend_name = ' + tf_state_store) filedata = filedata.replace('region = us-west-2', 'region = ' + region) filedata = filedata.replace('windows_domain_controller = 1', 'windows_domain_controller = 0') filedata = filedata.replace('windows_server_join_domain = 1', 'windows_server_join_domain = 0') filedata = filedata.replace('range_name = default', 'range_name = dt') filedata = filedata.replace('key_name = attack-range-key-pair', 'key_name = ' + ssh_key_name) filedata = filedata.replace('private_key_path = ~/.ssh/id_rsa', 'private_key_path = ' + str(os.getcwd() + "/" + ssh_key_name)) with open('attack_range/attack_range.conf', 'w') as file: file.write(filedata) def build_attack_range(region, tf_state_store, ssh_key_name): password = <PASSWORD>_random_password() configure_attack_range(region, tf_state_store, password, ssh_key_name) module = __import__('attack_range') module.sys.argv = ['attack_range', '--config', 'attack_range/attack_range.conf', 'build'] try: LOGGER.info(f"Build Attack Range") results = module.main(module.sys.argv) except Exception as e: LOGGER.error('Build Error: ' + str(e)) module.sys.argv = ['attack_range', '--config', 'attack_range/attack_range.conf', 'destroy'] module.main(module.sys.argv) sys.exit(1) return password def destroy_attack_range(region, data, tf_state_store): password = data['password'] ssh_key_name = data['ssh_key_name'] configure_attack_range(region, tf_state_store, password, ssh_key_name) module = __import__('attack_range') module.sys.argv = ['attack_range', '--config', 'attack_range/attack_range.conf', 'destroy'] try: LOGGER.info(f"Destroy Attack Range") results = module.main(module.sys.argv) except Exception as e: LOGGER.error('Build Error: ' + str(e)) module.sys.argv = ['attack_range', '--config', 'attack_range/attack_range.conf', 'destroy'] module.main(module.sys.argv) sys.exit(1)
1,160
3,100
/****************************************************************************** * * Project: Multi-resolution Seamless Image Database (MrSID) * Purpose: Read/write LizardTech's MrSID file format - Version 4+ SDK. * Author: <NAME>, <EMAIL> * ****************************************************************************** * Copyright (c) 2003, <NAME> <<EMAIL>> * Copyright (c) 2007-2013, <NAME> <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifdef DEBUG_BOOL #define DO_NOT_USE_DEBUG_BOOL #endif #define NO_DELETE #include "cpl_string.h" #include "gdal_frmts.h" #include "gdaljp2abstractdataset.h" #include "gdaljp2metadata.h" #include "ogr_spatialref.h" #include <string> #include <geo_normalize.h> #include <geovalues.h> CPL_CVSID("$Id$") CPL_C_START double GTIFAngleToDD( double dfAngle, int nUOMAngle ); void CPL_DLL LibgeotiffOneTimeInit(); CPL_C_END #include "mrsiddataset_headers_include.h" #ifdef MRSID_POST5 # define MRSID_HAVE_GETWKT #endif /* getTotalBandData is deprecated by getBandData, at least starting with 8.5 */ #if defined(LTI_SDK_MAJOR) && (LTI_SDK_MAJOR > 8 || (LTI_SDK_MAJOR >= 8 && LTI_SDK_MINOR >= 5)) # define myGetTotalBandData getBandData #else # define myGetTotalBandData getTotalBandData #endif #include "mrsidstream.h" using namespace LizardTech; /* -------------------------------------------------------------------- */ /* Various wrapper templates used to force new/delete to happen */ /* in the same heap. See bug 1213 and MSDN knowledge base */ /* article 122675. */ /* -------------------------------------------------------------------- */ template <class T> class LTIDLLPixel : public T { public: LTIDLLPixel(LTIColorSpace colorSpace, lt_uint16 numBands, LTIDataType dataType) : T(colorSpace,numBands,dataType) {} virtual ~LTIDLLPixel() {} }; template <class T> class LTIDLLReader : public T { public: explicit LTIDLLReader(const LTFileSpec& fileSpec, bool useWorldFile = false) : T(fileSpec, useWorldFile) {} explicit LTIDLLReader(LTIOStreamInf &oStream, bool useWorldFile = false) : T(oStream, useWorldFile) {} explicit LTIDLLReader(LTIOStreamInf *poStream, LTIOStreamInf *poWorldFile = nullptr) : T(poStream, poWorldFile) {} virtual ~LTIDLLReader() {} }; template <class T> class LTIDLLNavigator : public T { public: explicit LTIDLLNavigator(const LTIImage& image ) : T(image) {} virtual ~LTIDLLNavigator() {} }; template <class T> class LTIDLLBuffer : public T { public: LTIDLLBuffer(const LTIPixel& pixelProps, lt_uint32 totalNumCols, lt_uint32 totalNumRows, void** data ) : T(pixelProps,totalNumCols,totalNumRows,data) {} virtual ~LTIDLLBuffer() {} }; template <class T> class LTIDLLCopy : public T { public: explicit LTIDLLCopy(const T& original) : T(original) {} virtual ~LTIDLLCopy() {} }; template <class T> class LTIDLLWriter : public T { public: explicit LTIDLLWriter(LTIImageStage *image) : T(image) {} virtual ~LTIDLLWriter() {} }; template <class T> class LTIDLLDefault : public T { public: LTIDLLDefault() : T() {} virtual ~LTIDLLDefault() {} }; /* -------------------------------------------------------------------- */ /* Interface to MrSID SDK progress reporting. */ /* -------------------------------------------------------------------- */ class MrSIDProgress : public LTIProgressDelegate { public: MrSIDProgress(GDALProgressFunc f, void *arg) : m_f(f), m_arg(arg) {} virtual ~MrSIDProgress() {} virtual LT_STATUS setProgressStatus(float fraction) override { if (!m_f) return LT_STS_BadContext; if( !m_f( fraction, nullptr, m_arg ) ) return LT_STS_Failure; return LT_STS_Success; } private: GDALProgressFunc m_f; void *m_arg; }; /************************************************************************/ /* ==================================================================== */ /* MrSIDDataset */ /* ==================================================================== */ /************************************************************************/ class MrSIDDataset final: public GDALJP2AbstractDataset { friend class MrSIDRasterBand; LTIOStreamInf *poStream; LTIOFileStream oLTIStream; LTIVSIStream oVSIStream; #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 7 LTIImageFilter *poImageReader; #else LTIImageReader *poImageReader; #endif #ifdef MRSID_ESDK LTIGeoFileImageWriter *poImageWriter; #endif LTIDLLNavigator<LTINavigator> *poLTINav; LTIDLLCopy<LTIMetadataDatabase> *poMetadata; const LTIPixel *poNDPixel; LTIDLLBuffer<LTISceneBuffer> *poBuffer; int nBlockXSize; int nBlockYSize; int bPrevBlockRead; int nPrevBlockXOff, nPrevBlockYOff; LTIDataType eSampleType; GDALDataType eDataType; LTIColorSpace eColorSpace; double dfCurrentMag; GTIFDefn *psDefn; MrSIDDataset *poParentDS; int bIsOverview; int nOverviewCount; MrSIDDataset **papoOverviewDS; CPLString osMETFilename; CPLErr OpenZoomLevel( lt_int32 iZoom ); int GetMetadataElement( const char *, void *, int=0 ); void FetchProjParams(); void GetGTIFDefn(); char *GetOGISDefn( GTIFDefn * ); virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int, void *, int, int, GDALDataType, int, int *, GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg* psExtraArg) override; protected: virtual int CloseDependentDatasets() override; virtual CPLErr IBuildOverviews( const char *, int, int *, int, int *, GDALProgressFunc, void * ) override; public: explicit MrSIDDataset(int bIsJPEG2000); ~MrSIDDataset(); static GDALDataset *Open( GDALOpenInfo * poOpenInfo, int bIsJP2 ); virtual char **GetFileList() override; #ifdef MRSID_ESDK static GDALDataset *Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszParamList ); virtual void FlushCache( void ); #endif }; /************************************************************************/ /* ==================================================================== */ /* MrSIDRasterBand */ /* ==================================================================== */ /************************************************************************/ class MrSIDRasterBand final: public GDALPamRasterBand { friend class MrSIDDataset; LTIPixel *poPixel; int nBlockSize; int bNoDataSet; double dfNoDataValue; MrSIDDataset *poGDS; GDALColorInterp eBandInterp; public: MrSIDRasterBand( MrSIDDataset *, int ); ~MrSIDRasterBand(); virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int, void *, int, int, GDALDataType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg) override; virtual CPLErr IReadBlock( int, int, void * ) override; virtual GDALColorInterp GetColorInterpretation() override; CPLErr SetColorInterpretation( GDALColorInterp eNewInterp ) override; virtual double GetNoDataValue( int * ) override; virtual int GetOverviewCount() override; virtual GDALRasterBand *GetOverview( int ) override; virtual CPLErr GetStatistics( int bApproxOK, int bForce, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev ) override; #ifdef MRSID_ESDK virtual CPLErr IWriteBlock( int, int, void * ) override; #endif }; /************************************************************************/ /* MrSIDRasterBand() */ /************************************************************************/ MrSIDRasterBand::MrSIDRasterBand( MrSIDDataset *poDSIn, int nBandIn ) { this->poDS = poDSIn; poGDS = poDSIn; this->nBand = nBandIn; this->eDataType = poDSIn->eDataType; /* -------------------------------------------------------------------- */ /* Set the block sizes and buffer parameters. */ /* -------------------------------------------------------------------- */ nBlockXSize = poDSIn->nBlockXSize; nBlockYSize = poDSIn->nBlockYSize; //#ifdef notdef if( poDS->GetRasterXSize() > 2048 ) nBlockXSize = 1024; if( poDS->GetRasterYSize() > 128 ) nBlockYSize = 128; else nBlockYSize = poDS->GetRasterYSize(); //#endif nBlockSize = nBlockXSize * nBlockYSize; poPixel = new LTIDLLPixel<LTIPixel>( poDSIn->eColorSpace, static_cast<lt_uint16>(poDSIn->nBands), poDSIn->eSampleType ); /* -------------------------------------------------------------------- */ /* Set NoData values. */ /* */ /* This logic is disabled for now since the MrSID nodata */ /* semantics are different than GDAL. In MrSID all bands must */ /* match the nodata value for that band in order for the pixel */ /* to be considered nodata, otherwise all values are valid. */ /* -------------------------------------------------------------------- */ #ifdef notdef if ( poDS->poNDPixel ) { switch( poDS->eSampleType ) { case LTI_DATATYPE_UINT8: case LTI_DATATYPE_SINT8: dfNoDataValue = (double) poDS->poNDPixel->getSampleValueUint8( nBand - 1 ); break; case LTI_DATATYPE_UINT16: dfNoDataValue = (double) poDS->poNDPixel->getSampleValueUint16( nBand - 1 ); break; case LTI_DATATYPE_FLOAT32: dfNoDataValue = poDS->poNDPixel->getSampleValueFloat32( nBand - 1 ); break; case LTI_DATATYPE_SINT16: dfNoDataValue = (double) *(GInt16 *)poDS->poNDPixel->getSampleValueAddr( nBand - 1 ); break; case LTI_DATATYPE_UINT32: dfNoDataValue = (double) *(GUInt32 *)poDS->poNDPixel->getSampleValueAddr( nBand - 1 ); break; case LTI_DATATYPE_SINT32: dfNoDataValue = (double) *(GInt32 *)poDS->poNDPixel->getSampleValueAddr( nBand - 1 ); break; case LTI_DATATYPE_FLOAT64: dfNoDataValue = *(double *)poDS->poNDPixel->getSampleValueAddr( nBand - 1 ); break; case LTI_DATATYPE_INVALID: CPLAssert( false ); break; } bNoDataSet = TRUE; } else #endif { dfNoDataValue = 0.0; bNoDataSet = FALSE; } switch( poGDS->eColorSpace ) { case LTI_COLORSPACE_RGB: if( nBand == 1 ) eBandInterp = GCI_RedBand; else if( nBand == 2 ) eBandInterp = GCI_GreenBand; else if( nBand == 3 ) eBandInterp = GCI_BlueBand; else eBandInterp = GCI_Undefined; break; #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 case LTI_COLORSPACE_RGBA: if( nBand == 1 ) eBandInterp = GCI_RedBand; else if( nBand == 2 ) eBandInterp = GCI_GreenBand; else if( nBand == 3 ) eBandInterp = GCI_BlueBand; else if( nBand == 4 ) eBandInterp = GCI_AlphaBand; else eBandInterp = GCI_Undefined; break; #endif case LTI_COLORSPACE_CMYK: if( nBand == 1 ) eBandInterp = GCI_CyanBand; else if( nBand == 2 ) eBandInterp = GCI_MagentaBand; else if( nBand == 3 ) eBandInterp = GCI_YellowBand; else if( nBand == 4 ) eBandInterp = GCI_BlackBand; else eBandInterp = GCI_Undefined; break; case LTI_COLORSPACE_GRAYSCALE: eBandInterp = GCI_GrayIndex; break; #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 case LTI_COLORSPACE_GRAYSCALEA: if( nBand == 1 ) eBandInterp = GCI_GrayIndex; else if( nBand == 2 ) eBandInterp = GCI_AlphaBand; else eBandInterp = GCI_Undefined; break; case LTI_COLORSPACE_GRAYSCALEA_PM: if( nBand == 1 ) eBandInterp = GCI_GrayIndex; else if( nBand == 2 ) eBandInterp = GCI_AlphaBand; else eBandInterp = GCI_Undefined; break; #endif default: eBandInterp = GCI_Undefined; break; } } /************************************************************************/ /* ~MrSIDRasterBand() */ /************************************************************************/ MrSIDRasterBand::~MrSIDRasterBand() { if ( poPixel ) delete poPixel; } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr MrSIDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { #ifdef MRSID_ESDK if( poGDS->eAccess == GA_Update ) { CPLDebug( "MrSID", "IReadBlock() - DSDK - read on updatable file fails." ); memset( pImage, 0, nBlockSize * GDALGetDataTypeSize(eDataType) / 8 ); return CE_None; } #endif /* MRSID_ESDK */ CPLDebug( "MrSID", "IReadBlock(%d,%d)", nBlockXOff, nBlockYOff ); if ( !poGDS->bPrevBlockRead || poGDS->nPrevBlockXOff != nBlockXOff || poGDS->nPrevBlockYOff != nBlockYOff ) { GInt32 nLine = nBlockYOff * nBlockYSize; GInt32 nCol = nBlockXOff * nBlockXSize; // XXX: The scene, passed to LTIImageStage::read() call must be // inside the image boundaries. So we should detect the last strip and // form the scene properly. CPLDebug( "MrSID", "IReadBlock - read() %dx%d block at %d,%d.", nBlockXSize, nBlockYSize, nCol, nLine ); if(!LT_SUCCESS( poGDS->poLTINav->setSceneAsULWH( nCol, nLine, (nCol+nBlockXSize>poGDS->GetRasterXSize())? (poGDS->GetRasterXSize()-nCol):nBlockXSize, (nLine+nBlockYSize>poGDS->GetRasterYSize())? (poGDS->GetRasterYSize()-nLine):nBlockYSize, poGDS->dfCurrentMag) )) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IReadBlock(): Failed to set scene position." ); return CE_Failure; } if ( !poGDS->poBuffer ) { poGDS->poBuffer = new LTIDLLBuffer<LTISceneBuffer>( *poPixel, nBlockXSize, nBlockYSize, nullptr ); // poGDS->poBuffer = // new LTISceneBuffer( *poPixel, nBlockXSize, nBlockYSize, nullptr ); } if(!LT_SUCCESS(poGDS->poImageReader->read(poGDS->poLTINav->getScene(), *poGDS->poBuffer))) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IReadBlock(): Failed to load image." ); return CE_Failure; } poGDS->bPrevBlockRead = TRUE; poGDS->nPrevBlockXOff = nBlockXOff; poGDS->nPrevBlockYOff = nBlockYOff; } memcpy( pImage, poGDS->poBuffer->myGetTotalBandData(static_cast<lt_uint16>(nBand - 1)), nBlockSize * (GDALGetDataTypeSize(poGDS->eDataType) / 8) ); return CE_None; } #ifdef MRSID_ESDK /************************************************************************/ /* IWriteBlock() */ /************************************************************************/ CPLErr MrSIDRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { CPLAssert( poGDS != nullptr && nBlockXOff >= 0 && nBlockYOff >= 0 && pImage != nullptr ); #ifdef DEBUG CPLDebug( "MrSID", "IWriteBlock(): nBlockXOff=%d, nBlockYOff=%d", nBlockXOff, nBlockYOff ); #endif LTIScene oScene( nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, nBlockXSize, nBlockYSize, 1.0); LTISceneBuffer oSceneBuf( *poPixel, poGDS->nBlockXSize, poGDS->nBlockYSize, &pImage ); if( !LT_SUCCESS(poGDS->poImageWriter->writeBegin(oScene)) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IWriteBlock(): writeBegin failed." ); return CE_Failure; } if( !LT_SUCCESS(poGDS->poImageWriter->writeStrip(oSceneBuf, oScene)) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IWriteBlock(): writeStrip failed." ); return CE_Failure; } if( !LT_SUCCESS(poGDS->poImageWriter->writeEnd()) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IWriteBlock(): writeEnd failed." ); return CE_Failure; } return CE_None; } #endif /* MRSID_ESDK */ /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr MrSIDRasterBand::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg) { /* -------------------------------------------------------------------- */ /* Fallback to default implementation if the whole scanline */ /* without subsampling requested. */ /* -------------------------------------------------------------------- */ if ( nXSize == poGDS->GetRasterXSize() && nXSize == nBufXSize && nYSize == nBufYSize ) { return GDALRasterBand::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace, psExtraArg ); } /* -------------------------------------------------------------------- */ /* Handle via the dataset level IRasterIO() */ /* -------------------------------------------------------------------- */ return poGDS->IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, 1, &nBand, nPixelSpace, nLineSpace, 0, psExtraArg ); } /************************************************************************/ /* GetColorInterpretation() */ /************************************************************************/ GDALColorInterp MrSIDRasterBand::GetColorInterpretation() { return eBandInterp; } /************************************************************************/ /* SetColorInterpretation() */ /* */ /* This would normally just be used by folks using the MrSID code */ /* to read JP2 streams in other formats (such as NITF) and */ /* providing their own color interpretation regardless of what */ /* MrSID might think the stream itself says. */ /************************************************************************/ CPLErr MrSIDRasterBand::SetColorInterpretation( GDALColorInterp eNewInterp ) { eBandInterp = eNewInterp; return CE_None; } /************************************************************************/ /* GetStatistics() */ /* */ /* We override this method so that we can force generation of */ /* statistics if approx ok is true since we know that a small */ /* overview is always available, and that computing statistics */ /* from it is very fast. */ /************************************************************************/ CPLErr MrSIDRasterBand::GetStatistics( int bApproxOK, int bForce, double *pdfMin, double *pdfMax, double *pdfMean, double *pdfStdDev ) { if( bApproxOK ) bForce = TRUE; return GDALPamRasterBand::GetStatistics( bApproxOK, bForce, pdfMin, pdfMax, pdfMean, pdfStdDev ); } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double MrSIDRasterBand::GetNoDataValue( int * pbSuccess ) { if( bNoDataSet ) { if( pbSuccess ) *pbSuccess = bNoDataSet; return dfNoDataValue; } return GDALPamRasterBand::GetNoDataValue( pbSuccess ); } /************************************************************************/ /* GetOverviewCount() */ /************************************************************************/ int MrSIDRasterBand::GetOverviewCount() { return poGDS->nOverviewCount; } /************************************************************************/ /* GetOverview() */ /************************************************************************/ GDALRasterBand *MrSIDRasterBand::GetOverview( int i ) { if( i < 0 || i >= poGDS->nOverviewCount ) return nullptr; else return poGDS->papoOverviewDS[i]->GetRasterBand( nBand ); } /************************************************************************/ /* MrSIDDataset() */ /************************************************************************/ MrSIDDataset::MrSIDDataset(int bIsJPEG2000) : nBlockXSize(0), nBlockYSize(0), eSampleType(LTI_DATATYPE_UINT8), eDataType(GDT_Byte), eColorSpace(LTI_COLORSPACE_INVALID) { poStream = nullptr; poImageReader = nullptr; #ifdef MRSID_ESDK poImageWriter = nullptr; #endif poLTINav = nullptr; poMetadata = nullptr; poNDPixel = nullptr; nBands = 0; poBuffer = nullptr; bPrevBlockRead = FALSE; nPrevBlockXOff = 0; nPrevBlockYOff = 0; psDefn = nullptr; dfCurrentMag = 1.0; bIsOverview = FALSE; poParentDS = this; nOverviewCount = 0; papoOverviewDS = nullptr; poDriver = (GDALDriver*) GDALGetDriverByName( bIsJPEG2000 ? "JP2MrSID" : "MrSID" ); } /************************************************************************/ /* ~MrSIDDataset() */ /************************************************************************/ MrSIDDataset::~MrSIDDataset() { MrSIDDataset::FlushCache(true); #ifdef MRSID_ESDK if ( poImageWriter ) delete poImageWriter; #endif if ( poBuffer ) delete poBuffer; if ( poMetadata ) delete poMetadata; if ( poLTINav ) delete poLTINav; if ( poImageReader && !bIsOverview ) #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 7 { poImageReader->release(); poImageReader = nullptr; } #else delete poImageReader; #endif // points to another member, don't delete poStream = nullptr; if ( psDefn ) delete psDefn; MrSIDDataset::CloseDependentDatasets(); } /************************************************************************/ /* CloseDependentDatasets() */ /************************************************************************/ int MrSIDDataset::CloseDependentDatasets() { int bRet = GDALPamDataset::CloseDependentDatasets(); if ( papoOverviewDS ) { for( int i = 0; i < nOverviewCount; i++ ) delete papoOverviewDS[i]; CPLFree( papoOverviewDS ); papoOverviewDS = nullptr; bRet = TRUE; } return bRet; } /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr MrSIDDataset::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int *panBandMap, GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg* psExtraArg ) { /* -------------------------------------------------------------------- */ /* We need various criteria to skip out to block based methods. */ /* -------------------------------------------------------------------- */ int bUseBlockedIO = bForceCachedIO; if( nYSize == 1 || nXSize * ((double) nYSize) < 100.0 ) bUseBlockedIO = TRUE; if( nBufYSize == 1 || nBufXSize * ((double) nBufYSize) < 100.0 ) bUseBlockedIO = TRUE; if( CPLTestBool( CPLGetConfigOption( "GDAL_ONE_BIG_READ", "NO") ) ) bUseBlockedIO = FALSE; if( bUseBlockedIO ) return GDALDataset::BlockBasedRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace, psExtraArg ); CPLDebug( "MrSID", "RasterIO() - using optimized dataset level IO." ); /* -------------------------------------------------------------------- */ /* What is our requested window relative to the base dataset. */ /* We want to operate from here on as if we were operating on */ /* the full res band. */ /* -------------------------------------------------------------------- */ int nZoomMag = (int) ((1/dfCurrentMag) * 1.0000001); nXOff *= nZoomMag; nYOff *= nZoomMag; nXSize *= nZoomMag; nYSize *= nZoomMag; /* -------------------------------------------------------------------- */ /* We need to figure out the best zoom level to use for this */ /* request. We apply a small fudge factor to make sure that */ /* request just very, very slightly larger than a zoom level do */ /* not force us to the next level. */ /* -------------------------------------------------------------------- */ int iOverview = 0; double dfZoomMag = MIN((nXSize / (double)nBufXSize), (nYSize / (double)nBufYSize)); for( nZoomMag = 1; nZoomMag * 2 < (dfZoomMag + 0.1) && iOverview < poParentDS->nOverviewCount; nZoomMag *= 2, iOverview++ ) {} /* -------------------------------------------------------------------- */ /* Work out the size of the temporary buffer and allocate it. */ /* The temporary buffer will generally be at a moderately */ /* higher resolution than the buffer of data requested. */ /* -------------------------------------------------------------------- */ int nTmpPixelSize; LTIPixel oPixel( eColorSpace, static_cast<lt_uint16>(nBands), eSampleType ); LT_STATUS eLTStatus; unsigned int maxWidth; unsigned int maxHeight; eLTStatus = poImageReader->getDimsAtMag(1.0/nZoomMag,maxWidth,maxHeight); if( !LT_SUCCESS(eLTStatus)) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDataset::IRasterIO(): Failed to get zoomed image dimensions.\n%s", getLastStatusString( eLTStatus ) ); return CE_Failure; } int maxWidthAtL0 = bIsOverview?poParentDS->GetRasterXSize():this->GetRasterXSize(); int maxHeightAtL0 = bIsOverview?poParentDS->GetRasterYSize():this->GetRasterYSize(); int sceneUlXOff = nXOff / nZoomMag; int sceneUlYOff = nYOff / nZoomMag; int sceneWidth = (int)(nXSize * (double) maxWidth / (double)maxWidthAtL0 + 0.99); int sceneHeight = (int)(nYSize * (double) maxHeight / (double)maxHeightAtL0 + 0.99); if( (sceneUlXOff + sceneWidth) > (int) maxWidth ) sceneWidth = maxWidth - sceneUlXOff; if( (sceneUlYOff + sceneHeight) > (int) maxHeight ) sceneHeight = maxHeight - sceneUlYOff; LTISceneBuffer oLTIBuffer( oPixel, sceneWidth, sceneHeight, nullptr ); nTmpPixelSize = GDALGetDataTypeSize( eDataType ) / 8; /* -------------------------------------------------------------------- */ /* Create navigator, and move to the requested scene area. */ /* -------------------------------------------------------------------- */ LTINavigator oNav( *poImageReader ); if( !LT_SUCCESS(oNav.setSceneAsULWH( sceneUlXOff, sceneUlYOff, sceneWidth, sceneHeight, 1.0 / nZoomMag )) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDataset::IRasterIO(): Failed to set scene position." ); return CE_Failure; } CPLDebug( "MrSID", "Dataset:IRasterIO(%d,%d %dx%d -> %dx%d -> %dx%d, zoom=%d)", nXOff, nYOff, nXSize, nYSize, sceneWidth, sceneHeight, nBufXSize, nBufYSize, nZoomMag ); if( !oNav.isSceneValid() ) CPLDebug( "MrSID", "LTINavigator in invalid state." ); /* -------------------------------------------------------------------- */ /* Read into the buffer. */ /* -------------------------------------------------------------------- */ eLTStatus = poImageReader->read(oNav.getScene(),oLTIBuffer); if(!LT_SUCCESS(eLTStatus) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDRasterBand::IRasterIO(): Failed to load image.\n%s", getLastStatusString( eLTStatus ) ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* If we are pulling the data at a matching resolution, try to */ /* do a more direct copy without subsampling. */ /* -------------------------------------------------------------------- */ int iBufLine, iBufPixel; if( nBufXSize == sceneWidth && nBufYSize == sceneHeight ) { for( int iBand = 0; iBand < nBandCount; iBand++ ) { GByte *pabySrcBand = (GByte *) oLTIBuffer.myGetTotalBandData( static_cast<lt_uint16>(panBandMap[iBand] - 1) ); for( int iLine = 0; iLine < nBufYSize; iLine++ ) { GDALCopyWords( pabySrcBand + iLine*nTmpPixelSize*sceneWidth, eDataType, nTmpPixelSize, ((GByte *)pData) + iLine*nLineSpace + iBand * nBandSpace, eBufType, static_cast<int>(nPixelSpace), nBufXSize ); } } } /* -------------------------------------------------------------------- */ /* Manually resample to our target buffer. */ /* -------------------------------------------------------------------- */ else { for( iBufLine = 0; iBufLine < nBufYSize; iBufLine++ ) { int iTmpLine = (int) floor(((iBufLine+0.5) / nBufYSize)*sceneHeight); for( iBufPixel = 0; iBufPixel < nBufXSize; iBufPixel++ ) { int iTmpPixel = (int) floor(((iBufPixel+0.5) / nBufXSize) * sceneWidth); for( int iBand = 0; iBand < nBandCount; iBand++ ) { GByte *pabySrc, *pabyDst; pabyDst = ((GByte *) pData) + nPixelSpace * iBufPixel + nLineSpace * iBufLine + nBandSpace * iBand; pabySrc = (GByte *) oLTIBuffer.myGetTotalBandData( static_cast<lt_uint16>(panBandMap[iBand] - 1) ); pabySrc += (iTmpLine * sceneWidth + iTmpPixel) * nTmpPixelSize; if( eDataType == eBufType ) memcpy( pabyDst, pabySrc, nTmpPixelSize ); else GDALCopyWords( pabySrc, eDataType, 0, pabyDst, eBufType, 0, 1 ); } } } } return CE_None; } /************************************************************************/ /* IBuildOverviews() */ /************************************************************************/ CPLErr MrSIDDataset::IBuildOverviews( const char *, int, int *, int, int *, GDALProgressFunc, void * ) { CPLError( CE_Warning, CPLE_AppDefined, "MrSID overviews are built-in, so building external " "overviews is unnecessary. Ignoring.\n" ); return CE_None; } /************************************************************************/ /* SerializeMetadataRec() */ /************************************************************************/ static CPLString SerializeMetadataRec( const LTIMetadataRecord *poMetadataRec ) { GUInt32 iNumDims = 0; const GUInt32 *paiDims = nullptr; const void *pData = poMetadataRec->getArrayData( iNumDims, paiDims ); CPLString osMetadata; GUInt32 k = 0; for ( GUInt32 i = 0; paiDims != nullptr && i < iNumDims; i++ ) { // stops on large binary data if ( poMetadataRec->getDataType() == LTI_METADATA_DATATYPE_UINT8 && paiDims[i] > 1024 ) return CPLString(); for ( GUInt32 j = 0; j < paiDims[i]; j++ ) { CPLString osTemp; switch( poMetadataRec->getDataType() ) { case LTI_METADATA_DATATYPE_UINT8: case LTI_METADATA_DATATYPE_SINT8: osTemp.Printf( "%d", ((GByte *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_UINT16: osTemp.Printf( "%u", ((GUInt16 *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_SINT16: osTemp.Printf( "%d", ((GInt16 *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_UINT32: osTemp.Printf( "%u", ((GUInt32 *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_SINT32: osTemp.Printf( "%d", ((GInt32 *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_FLOAT32: osTemp.Printf( "%f", ((float *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_FLOAT64: osTemp.Printf( "%f", ((double *)pData)[k++] ); break; case LTI_METADATA_DATATYPE_ASCII: osTemp = ((const char **)pData)[k++]; break; default: break; } if( !osMetadata.empty() ) osMetadata += ','; osMetadata += osTemp; } } return osMetadata; } /************************************************************************/ /* GetMetadataElement() */ /************************************************************************/ int MrSIDDataset::GetMetadataElement( const char *pszKey, void *pValue, int iLength ) { if ( !poMetadata->has( pszKey ) ) return FALSE; const LTIMetadataRecord *poMetadataRec = nullptr; poMetadata->get( pszKey, poMetadataRec ); if ( poMetadataRec == nullptr || !poMetadataRec->isScalar() ) return FALSE; // XXX: return FALSE if we have more than one element in metadata record int iSize; switch( poMetadataRec->getDataType() ) { case LTI_METADATA_DATATYPE_UINT8: case LTI_METADATA_DATATYPE_SINT8: iSize = 1; break; case LTI_METADATA_DATATYPE_UINT16: case LTI_METADATA_DATATYPE_SINT16: iSize = 2; break; case LTI_METADATA_DATATYPE_UINT32: case LTI_METADATA_DATATYPE_SINT32: case LTI_METADATA_DATATYPE_FLOAT32: iSize = 4; break; case LTI_METADATA_DATATYPE_FLOAT64: iSize = 8; break; case LTI_METADATA_DATATYPE_ASCII: iSize = iLength; break; default: iSize = 0; break; } if ( poMetadataRec->getDataType() == LTI_METADATA_DATATYPE_ASCII ) { strncpy( (char *)pValue, ((const char**)poMetadataRec->getScalarData())[0], iSize ); ((char *)pValue)[iSize - 1] = '\0'; } else memcpy( pValue, poMetadataRec->getScalarData(), iSize ); return TRUE; } /************************************************************************/ /* GetFileList() */ /************************************************************************/ char** MrSIDDataset::GetFileList() { char** papszFileList = GDALPamDataset::GetFileList(); if (!osMETFilename.empty()) papszFileList = CSLAddString(papszFileList, osMETFilename.c_str()); return papszFileList; } /************************************************************************/ /* OpenZoomLevel() */ /************************************************************************/ CPLErr MrSIDDataset::OpenZoomLevel( lt_int32 iZoom ) { /* -------------------------------------------------------------------- */ /* Get image geometry. */ /* -------------------------------------------------------------------- */ if ( iZoom != 0 ) { lt_uint32 iWidth, iHeight; dfCurrentMag = LTIUtils::levelToMag( iZoom ); auto eLTStatus = poImageReader->getDimsAtMag( dfCurrentMag, iWidth, iHeight ); if( !LT_SUCCESS(eLTStatus)) { CPLDebug( "MrSID", "Cannot open zoom level %d", iZoom); return CE_Failure; } nRasterXSize = iWidth; nRasterYSize = iHeight; } else { dfCurrentMag = 1.0; nRasterXSize = poImageReader->getWidth(); nRasterYSize = poImageReader->getHeight(); } nBands = poImageReader->getNumBands(); nBlockXSize = nRasterXSize; nBlockYSize = poImageReader->getStripHeight(); CPLDebug( "MrSID", "Opened zoom level %d with size %dx%d.", iZoom, nRasterXSize, nRasterYSize ); try { poLTINav = new LTIDLLNavigator<LTINavigator>( *poImageReader ); } catch ( ... ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDataset::OpenZoomLevel(): " "Failed to create LTINavigator object." ); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Handle sample type and color space. */ /* -------------------------------------------------------------------- */ eColorSpace = poImageReader->getColorSpace(); eSampleType = poImageReader->getDataType(); switch ( eSampleType ) { case LTI_DATATYPE_UINT16: eDataType = GDT_UInt16; break; case LTI_DATATYPE_SINT16: eDataType = GDT_Int16; break; case LTI_DATATYPE_UINT32: eDataType = GDT_UInt32; break; case LTI_DATATYPE_SINT32: eDataType = GDT_Int32; break; case LTI_DATATYPE_FLOAT32: eDataType = GDT_Float32; break; case LTI_DATATYPE_FLOAT64: eDataType = GDT_Float64; break; case LTI_DATATYPE_UINT8: case LTI_DATATYPE_SINT8: default: eDataType = GDT_Byte; break; } /* -------------------------------------------------------------------- */ /* Read georeferencing. */ /* -------------------------------------------------------------------- */ if ( !poImageReader->isGeoCoordImplicit() ) { const LTIGeoCoord& oGeo = poImageReader->getGeoCoord(); oGeo.get( adfGeoTransform[0], adfGeoTransform[3], adfGeoTransform[1], adfGeoTransform[5], adfGeoTransform[2], adfGeoTransform[4] ); adfGeoTransform[0] = adfGeoTransform[0] - adfGeoTransform[1] / 2; adfGeoTransform[3] = adfGeoTransform[3] - adfGeoTransform[5] / 2; bGeoTransformValid = TRUE; } else if( iZoom == 0 ) { bGeoTransformValid = GDALReadWorldFile( GetDescription(), nullptr, adfGeoTransform ) || GDALReadWorldFile( GetDescription(), ".wld", adfGeoTransform ); } /* -------------------------------------------------------------------- */ /* Read wkt. */ /* -------------------------------------------------------------------- */ #ifdef MRSID_HAVE_GETWKT if( !poImageReader->isGeoCoordImplicit() ) { const LTIGeoCoord& oGeo = poImageReader->getGeoCoord(); if( oGeo.getWKT() ) { /* Workaround probable issue with GeoDSK 7 on 64bit Linux */ if (!(m_oSRS.IsEmpty() && !m_oSRS.IsLocal() && STARTS_WITH_CI(oGeo.getWKT(), "LOCAL_CS"))) { m_oSRS.importFromWkt( oGeo.getWKT() ); } } } #endif // HAVE_MRSID_GETWKT /* -------------------------------------------------------------------- */ /* Special case for https://zulu.ssc.nasa.gov/mrsid/mrsid.pl */ /* where LandSat .SID are accompanied by a .met file with the */ /* projection */ /* -------------------------------------------------------------------- */ if (iZoom == 0 && m_oSRS.IsEmpty() && EQUAL(CPLGetExtension(GetDescription()), "sid")) { const char* pszMETFilename = CPLResetExtension(GetDescription(), "met"); VSILFILE* fp = VSIFOpenL(pszMETFilename, "rb"); if (fp) { const char* pszLine = nullptr; int nCountLine = 0; int nUTMZone = 0; int bWGS84 = FALSE; int bUnitsMeter = FALSE; while ( (pszLine = CPLReadLine2L(fp, 200, nullptr)) != nullptr && nCountLine < 1000 ) { ++ nCountLine; if (nCountLine == 1 && strcmp(pszLine, "::MetadataFile") != 0) break; if (STARTS_WITH_CI(pszLine, "Projection UTM ")) nUTMZone = atoi(pszLine + 15); else if (EQUAL(pszLine, "Datum WGS84")) bWGS84 = TRUE; else if (EQUAL(pszLine, "Units Meters")) bUnitsMeter = TRUE; } VSIFCloseL(fp); /* Images in southern hemisphere have negative northings in the */ /* .sdw file. A bit weird, but anyway we must use the northern */ /* UTM SRS for consistency */ if (nUTMZone >= 1 && nUTMZone <= 60 && bWGS84 && bUnitsMeter) { osMETFilename = pszMETFilename; m_oSRS.importFromEPSG(32600 + nUTMZone); m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } } } /* -------------------------------------------------------------------- */ /* Read NoData value. */ /* -------------------------------------------------------------------- */ poNDPixel = poImageReader->getNoDataPixel(); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ int iBand; for( iBand = 1; iBand <= nBands; iBand++ ) SetBand( iBand, new MrSIDRasterBand( this, iBand ) ); return CE_None; } /************************************************************************/ /* MrSIDIdentify() */ /* */ /* Identify method that only supports MrSID files. */ /************************************************************************/ static int MrSIDIdentify( GDALOpenInfo * poOpenInfo ) { if( poOpenInfo->nHeaderBytes < 32 ) return FALSE; if ( !STARTS_WITH_CI((const char *) poOpenInfo->pabyHeader, "msid") ) return FALSE; #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 lt_uint8 gen; bool raster; LT_STATUS eStat = MrSIDImageReaderInterface::getMrSIDGeneration(poOpenInfo->pabyHeader, gen, raster); if (!LT_SUCCESS(eStat) || !raster) return FALSE; #endif return TRUE; } /************************************************************************/ /* MrSIDOpen() */ /* */ /* Open method that only supports MrSID files. */ /************************************************************************/ static GDALDataset* MrSIDOpen( GDALOpenInfo *poOpenInfo ) { if (!MrSIDIdentify(poOpenInfo)) return nullptr; return MrSIDDataset::Open( poOpenInfo, FALSE ); } #ifdef MRSID_J2K static const unsigned char jpc_header[] = {0xff,0x4f}; /************************************************************************/ /* JP2Identify() */ /* */ /* Identify method that only supports JPEG2000 files. */ /************************************************************************/ static int JP2Identify( GDALOpenInfo *poOpenInfo ) { if( poOpenInfo->nHeaderBytes < 32 ) return FALSE; if( memcmp( poOpenInfo->pabyHeader, jpc_header, sizeof(jpc_header) ) == 0 ) { const char *pszExtension = CPLGetExtension( poOpenInfo->pszFilename ); if( !EQUAL(pszExtension,"jpc") && !EQUAL(pszExtension,"j2k") && !EQUAL(pszExtension,"jp2") && !EQUAL(pszExtension,"jpx") && !EQUAL(pszExtension,"j2c") && !EQUAL(pszExtension,"ntf")) return FALSE; } else if( !STARTS_WITH_CI((const char *) poOpenInfo->pabyHeader + 4, "jP ") ) return FALSE; return TRUE; } /************************************************************************/ /* JP2Open() */ /* */ /* Open method that only supports JPEG2000 files. */ /************************************************************************/ static GDALDataset* JP2Open( GDALOpenInfo *poOpenInfo ) { if (!JP2Identify(poOpenInfo)) return nullptr; return MrSIDDataset::Open( poOpenInfo, TRUE ); } #endif // MRSID_J2K /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *MrSIDDataset::Open( GDALOpenInfo * poOpenInfo, int bIsJP2 ) { if(poOpenInfo->fpL) { VSIFCloseL( poOpenInfo->fpL ); poOpenInfo->fpL = nullptr; } /* -------------------------------------------------------------------- */ /* Make sure we have hooked CSV lookup for GDAL_DATA. */ /* -------------------------------------------------------------------- */ LibgeotiffOneTimeInit(); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ LT_STATUS eStat; MrSIDDataset *poDS = new MrSIDDataset(bIsJP2); // try the LTIOFileStream first, since it uses filesystem caching eStat = poDS->oLTIStream.initialize( poOpenInfo->pszFilename, "rb" ); if ( LT_SUCCESS(eStat) ) { eStat = poDS->oLTIStream.open(); if ( LT_SUCCESS(eStat) ) poDS->poStream = &(poDS->oLTIStream); } // fall back on VSI for non-files if ( !LT_SUCCESS(eStat) || !poDS->poStream ) { eStat = poDS->oVSIStream.initialize( poOpenInfo->pszFilename, "rb" ); if ( !LT_SUCCESS(eStat) ) { CPLError( CE_Failure, CPLE_AppDefined, "LTIVSIStream::initialize(): " "failed to open file \"%s\".\n%s", poOpenInfo->pszFilename, getLastStatusString( eStat ) ); delete poDS; return nullptr; } eStat = poDS->oVSIStream.open(); if ( !LT_SUCCESS(eStat) ) { CPLError( CE_Failure, CPLE_AppDefined, "LTIVSIStream::open(): " "failed to open file \"%s\".\n%s", poOpenInfo->pszFilename, getLastStatusString( eStat ) ); delete poDS; return nullptr; } poDS->poStream = &(poDS->oVSIStream); } #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 7 #ifdef MRSID_J2K if ( bIsJP2 ) { J2KImageReader *reader = J2KImageReader::create(); eStat = reader->initialize( *(poDS->poStream) ); poDS->poImageReader = reader; } else #endif /* MRSID_J2K */ { MrSIDImageReader *reader = MrSIDImageReader::create(); eStat = reader->initialize( poDS->poStream, nullptr ); poDS->poImageReader = reader; } #else /* LTI_SDK_MAJOR < 7 */ #ifdef MRSID_J2K if ( bIsJP2 ) { poDS->poImageReader = new LTIDLLReader<J2KImageReader>( *(poDS->poStream), true ); eStat = poDS->poImageReader->initialize(); } else #endif /* MRSID_J2K */ { poDS->poImageReader = new LTIDLLReader<MrSIDImageReader>( poDS->poStream, nullptr ); eStat = poDS->poImageReader->initialize(); } #endif /* LTI_SDK_MAJOR >= 7 */ if ( !LT_SUCCESS(eStat) ) { CPLError( CE_Failure, CPLE_AppDefined, "LTIImageReader::initialize(): " "failed to initialize reader from the stream \"%s\".\n%s", poOpenInfo->pszFilename, getLastStatusString( eStat ) ); delete poDS; return nullptr; } /* -------------------------------------------------------------------- */ /* Read metadata. */ /* -------------------------------------------------------------------- */ poDS->poMetadata = new LTIDLLCopy<LTIMetadataDatabase>( poDS->poImageReader->getMetadata() ); const GUInt32 iNumRecs = poDS->poMetadata->getIndexCount(); for ( GUInt32 i = 0; i < iNumRecs; i++ ) { const LTIMetadataRecord *poMetadataRec = nullptr; if ( LT_SUCCESS(poDS->poMetadata->getDataByIndex(i, poMetadataRec)) ) { const auto osElement = SerializeMetadataRec( poMetadataRec ); char *pszKey = CPLStrdup( poMetadataRec->getTagName() ); char *pszTemp = pszKey; // GDAL metadata keys should not contain ':' and '=' characters. // We will replace them with '_'. do { if ( *pszTemp == ':' || *pszTemp == '=' ) *pszTemp = '_'; } while ( *++pszTemp ); poDS->SetMetadataItem( pszKey, osElement.c_str() ); CPLFree( pszKey ); } } /* -------------------------------------------------------------------- */ /* Add MrSID version. */ /* -------------------------------------------------------------------- */ #ifdef MRSID_J2K if( !bIsJP2 ) #endif { #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 lt_uint8 gen; bool raster; MrSIDImageReaderInterface::getMrSIDGeneration(poOpenInfo->pabyHeader, gen, raster); poDS->SetMetadataItem( "VERSION", CPLString().Printf("MG%d%s", gen, raster ? "" : " LiDAR") ); #else lt_uint8 major; lt_uint8 minor; char letter; MrSIDImageReader* poMrSIDImageReader = (MrSIDImageReader*)poDS->poImageReader; poMrSIDImageReader->getVersion(major, minor, minor, letter); if (major < 2) major = 2; poDS->SetMetadataItem( "VERSION", CPLString().Printf("MG%d", major) ); #endif } poDS->GetGTIFDefn(); /* -------------------------------------------------------------------- */ /* Get number of resolution levels (we will use them as overviews).*/ /* -------------------------------------------------------------------- */ #ifdef MRSID_J2K if( bIsJP2 ) poDS->nOverviewCount = ((J2KImageReader *) (poDS->poImageReader))->getNumLevels(); else #endif poDS->nOverviewCount = ((MrSIDImageReader *) (poDS->poImageReader))->getNumLevels(); if ( poDS->nOverviewCount > 0 ) { lt_int32 i; poDS->papoOverviewDS = (MrSIDDataset **) CPLMalloc( poDS->nOverviewCount * (sizeof(void*)) ); for ( i = 0; i < poDS->nOverviewCount; i++ ) { poDS->papoOverviewDS[i] = new MrSIDDataset(bIsJP2); poDS->papoOverviewDS[i]->poImageReader = poDS->poImageReader; poDS->papoOverviewDS[i]->bIsOverview = TRUE; poDS->papoOverviewDS[i]->poParentDS = poDS; if( poDS->papoOverviewDS[i]->OpenZoomLevel( i + 1 ) != CE_None ) { delete poDS->papoOverviewDS[i]; poDS->nOverviewCount = i; break; } } } /* -------------------------------------------------------------------- */ /* Create object for the whole image. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); if( poDS->OpenZoomLevel( 0 ) != CE_None ) { delete poDS; return nullptr; } CPLDebug( "MrSID", "Opened image: width %d, height %d, bands %d", poDS->nRasterXSize, poDS->nRasterYSize, poDS->nBands ); if( poDS->nBands > 1 ) poDS->SetMetadataItem( "INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE" ); if (bIsJP2) { poDS->LoadJP2Metadata(poOpenInfo); } /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Initialize the overview manager for mask band support. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return poDS; } /************************************************************************/ /* EPSGProjMethodToCTProjMethod() */ /* */ /* Convert between the EPSG enumeration for projection methods, */ /* and the GeoTIFF CT codes. */ /* Explicitly copied from geo_normalize.c of the GeoTIFF package */ /************************************************************************/ static int EPSGProjMethodToCTProjMethod( int nEPSG ) { /* see trf_method.csv for list of EPSG codes */ switch( nEPSG ) { case 9801: return CT_LambertConfConic_1SP; case 9802: return CT_LambertConfConic_2SP; case 9803: return CT_LambertConfConic_2SP; // Belgian variant not supported. case 9804: return CT_Mercator; // 1SP and 2SP not differentiated. case 9805: return CT_Mercator; // 1SP and 2SP not differentiated. case 9806: return CT_CassiniSoldner; case 9807: return CT_TransverseMercator; case 9808: return CT_TransvMercator_SouthOriented; case 9809: return CT_ObliqueStereographic; case 9810: return CT_PolarStereographic; case 9811: return CT_NewZealandMapGrid; case 9812: return CT_ObliqueMercator; // Is hotine actually different? case 9813: return CT_ObliqueMercator_Laborde; case 9814: return CT_ObliqueMercator_Rosenmund; // Swiss. case 9815: return CT_ObliqueMercator; case 9816: /* tunesia mining grid has no counterpart */ return KvUserDefined; } return KvUserDefined; } /* EPSG Codes for projection parameters. Unfortunately, these bear no relationship to the GeoTIFF codes even though the names are so similar. */ #define EPSGNatOriginLat 8801 #define EPSGNatOriginLong 8802 #define EPSGNatOriginScaleFactor 8805 #define EPSGFalseEasting 8806 #define EPSGFalseNorthing 8807 #define EPSGProjCenterLat 8811 #define EPSGProjCenterLong 8812 #define EPSGAzimuth 8813 #define EPSGAngleRectifiedToSkewedGrid 8814 #define EPSGInitialLineScaleFactor 8815 #define EPSGProjCenterEasting 8816 #define EPSGProjCenterNorthing 8817 #define EPSGPseudoStdParallelLat 8818 #define EPSGPseudoStdParallelScaleFactor 8819 #define EPSGFalseOriginLat 8821 #define EPSGFalseOriginLong 8822 #define EPSGStdParallel1Lat 8823 #define EPSGStdParallel2Lat 8824 #define EPSGFalseOriginEasting 8826 #define EPSGFalseOriginNorthing 8827 #define EPSGSphericalOriginLat 8828 #define EPSGSphericalOriginLong 8829 #define EPSGInitialLongitude 8830 #define EPSGZoneWidth 8831 /************************************************************************/ /* SetGTParamIds() */ /* */ /* This is hardcoded logic to set the GeoTIFF parameter */ /* identifiers for all the EPSG supported projections. As the */ /* trf_method.csv table grows with new projections, this code */ /* will need to be updated. */ /* Explicitly copied from geo_normalize.c of the GeoTIFF package. */ /************************************************************************/ static int SetGTParamIds( int nCTProjection, int *panProjParamId, int *panEPSGCodes ) { int anWorkingDummy[7]; if( panEPSGCodes == nullptr ) panEPSGCodes = anWorkingDummy; if( panProjParamId == nullptr ) panProjParamId = anWorkingDummy; memset( panEPSGCodes, 0, sizeof(int) * 7 ); /* psDefn->nParms = 7; */ switch( nCTProjection ) { case CT_CassiniSoldner: case CT_NewZealandMapGrid: panProjParamId[0] = ProjNatOriginLatGeoKey; panProjParamId[1] = ProjNatOriginLongGeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; panEPSGCodes[0] = EPSGNatOriginLat; panEPSGCodes[1] = EPSGNatOriginLong; panEPSGCodes[5] = EPSGFalseEasting; panEPSGCodes[6] = EPSGFalseNorthing; return TRUE; case CT_ObliqueMercator: panProjParamId[0] = ProjCenterLatGeoKey; panProjParamId[1] = ProjCenterLongGeoKey; panProjParamId[2] = ProjAzimuthAngleGeoKey; panProjParamId[3] = ProjRectifiedGridAngleGeoKey; panProjParamId[4] = ProjScaleAtCenterGeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; panEPSGCodes[0] = EPSGProjCenterLat; panEPSGCodes[1] = EPSGProjCenterLong; panEPSGCodes[2] = EPSGAzimuth; panEPSGCodes[3] = EPSGAngleRectifiedToSkewedGrid; panEPSGCodes[4] = EPSGInitialLineScaleFactor; panEPSGCodes[5] = EPSGProjCenterEasting; panEPSGCodes[6] = EPSGProjCenterNorthing; return TRUE; case CT_ObliqueMercator_Laborde: panProjParamId[0] = ProjCenterLatGeoKey; panProjParamId[1] = ProjCenterLongGeoKey; panProjParamId[2] = ProjAzimuthAngleGeoKey; panProjParamId[4] = ProjScaleAtCenterGeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; panEPSGCodes[0] = EPSGProjCenterLat; panEPSGCodes[1] = EPSGProjCenterLong; panEPSGCodes[2] = EPSGAzimuth; panEPSGCodes[4] = EPSGInitialLineScaleFactor; panEPSGCodes[5] = EPSGProjCenterEasting; panEPSGCodes[6] = EPSGProjCenterNorthing; return TRUE; case CT_LambertConfConic_1SP: case CT_Mercator: case CT_ObliqueStereographic: case CT_PolarStereographic: case CT_TransverseMercator: case CT_TransvMercator_SouthOriented: panProjParamId[0] = ProjNatOriginLatGeoKey; panProjParamId[1] = ProjNatOriginLongGeoKey; panProjParamId[4] = ProjScaleAtNatOriginGeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; panEPSGCodes[0] = EPSGNatOriginLat; panEPSGCodes[1] = EPSGNatOriginLong; panEPSGCodes[4] = EPSGNatOriginScaleFactor; panEPSGCodes[5] = EPSGFalseEasting; panEPSGCodes[6] = EPSGFalseNorthing; return TRUE; case CT_LambertConfConic_2SP: panProjParamId[0] = ProjFalseOriginLatGeoKey; panProjParamId[1] = ProjFalseOriginLongGeoKey; panProjParamId[2] = ProjStdParallel1GeoKey; panProjParamId[3] = ProjStdParallel2GeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; panEPSGCodes[0] = EPSGFalseOriginLat; panEPSGCodes[1] = EPSGFalseOriginLong; panEPSGCodes[2] = EPSGStdParallel1Lat; panEPSGCodes[3] = EPSGStdParallel2Lat; panEPSGCodes[5] = EPSGFalseOriginEasting; panEPSGCodes[6] = EPSGFalseOriginNorthing; return TRUE; case CT_SwissObliqueCylindrical: panProjParamId[0] = ProjCenterLatGeoKey; panProjParamId[1] = ProjCenterLongGeoKey; panProjParamId[5] = ProjFalseEastingGeoKey; panProjParamId[6] = ProjFalseNorthingGeoKey; /* EPSG codes? */ return TRUE; default: return FALSE; } } static const char * const papszDatumEquiv[] = { "Militar_Geographische_Institut", "Militar_Geographische_Institute", "World_Geodetic_System_1984", "WGS_1984", "WGS_72_Transit_Broadcast_Ephemeris", "WGS_1972_Transit_Broadcast_Ephemeris", "World_Geodetic_System_1972", "WGS_1972", "European_Terrestrial_Reference_System_89", "European_Reference_System_1989", nullptr }; /************************************************************************/ /* WKTMassageDatum() */ /* */ /* Massage an EPSG datum name into WMT format. Also transform */ /* specific exception cases into WKT versions. */ /* Explicitly copied from the gt_wkt_srs.cpp. */ /************************************************************************/ static void WKTMassageDatum( char ** ppszDatum ) { int i, j; char *pszDatum = *ppszDatum; if (pszDatum[0] == '\0') return; /* -------------------------------------------------------------------- */ /* Translate non-alphanumeric values to underscores. */ /* -------------------------------------------------------------------- */ for( i = 0; pszDatum[i] != '\0'; i++ ) { if( !(pszDatum[i] >= 'A' && pszDatum[i] <= 'Z') && !(pszDatum[i] >= 'a' && pszDatum[i] <= 'z') && !(pszDatum[i] >= '0' && pszDatum[i] <= '9') ) { pszDatum[i] = '_'; } } /* -------------------------------------------------------------------- */ /* Remove repeated and trailing underscores. */ /* -------------------------------------------------------------------- */ for( i = 1, j = 0; pszDatum[i] != '\0'; i++ ) { if( pszDatum[j] == '_' && pszDatum[i] == '_' ) continue; pszDatum[++j] = pszDatum[i]; } if( pszDatum[j] == '_' ) pszDatum[j] = '\0'; else pszDatum[j+1] = '\0'; /* -------------------------------------------------------------------- */ /* Search for datum equivalences. Specific massaged names get */ /* mapped to OpenGIS specified names. */ /* -------------------------------------------------------------------- */ for( i = 0; papszDatumEquiv[i] != nullptr; i += 2 ) { if( EQUAL(*ppszDatum,papszDatumEquiv[i]) ) { CPLFree( *ppszDatum ); *ppszDatum = CPLStrdup( papszDatumEquiv[i+1] ); return; } } } /************************************************************************/ /* FetchProjParams() */ /* */ /* Fetch the projection parameters for a particular projection */ /* from MrSID metadata, and fill the GTIFDefn structure out */ /* with them. */ /* Copied from geo_normalize.c of the GeoTIFF package. */ /************************************************************************/ void MrSIDDataset::FetchProjParams() { double dfNatOriginLong = 0.0, dfNatOriginLat = 0.0, dfRectGridAngle = 0.0; double dfFalseEasting = 0.0, dfFalseNorthing = 0.0, dfNatOriginScale = 1.0; double dfStdParallel1 = 0.0, dfStdParallel2 = 0.0, dfAzimuth = 0.0; /* -------------------------------------------------------------------- */ /* Get the false easting, and northing if available. */ /* -------------------------------------------------------------------- */ if( !GetMetadataElement( "GEOTIFF_NUM::3082::ProjFalseEastingGeoKey", &dfFalseEasting ) && !GetMetadataElement( "GEOTIFF_NUM::3090:ProjCenterEastingGeoKey", &dfFalseEasting ) ) dfFalseEasting = 0.0; if( !GetMetadataElement( "GEOTIFF_NUM::3083::ProjFalseNorthingGeoKey", &dfFalseNorthing ) && !GetMetadataElement( "GEOTIFF_NUM::3091::ProjCenterNorthingGeoKey", &dfFalseNorthing ) ) dfFalseNorthing = 0.0; switch( psDefn->CTProjection ) { /* -------------------------------------------------------------------- */ case CT_Stereographic: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3092::ProjScaleAtNatOriginGeoKey", &dfNatOriginScale ) == 0 ) dfNatOriginScale = 1.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjCenterLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjCenterLongGeoKey; psDefn->ProjParm[4] = dfNatOriginScale; psDefn->ProjParmId[4] = ProjScaleAtNatOriginGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_LambertConfConic_1SP: case CT_Mercator: case CT_ObliqueStereographic: case CT_TransverseMercator: case CT_TransvMercator_SouthOriented: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3092::ProjScaleAtNatOriginGeoKey", &dfNatOriginScale ) == 0 ) dfNatOriginScale = 1.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjNatOriginLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjNatOriginLongGeoKey; psDefn->ProjParm[4] = dfNatOriginScale; psDefn->ProjParmId[4] = ProjScaleAtNatOriginGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_ObliqueMercator: /* hotine */ /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3094::ProjAzimuthAngleGeoKey", &dfAzimuth ) == 0 ) dfAzimuth = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3096::ProjRectifiedGridAngleGeoKey", &dfRectGridAngle ) == 0 ) dfRectGridAngle = 90.0; if( GetMetadataElement( "GEOTIFF_NUM::3092::ProjScaleAtNatOriginGeoKey", &dfNatOriginScale ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3093::ProjScaleAtCenterGeoKey", &dfNatOriginScale ) == 0 ) dfNatOriginScale = 1.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjCenterLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjCenterLongGeoKey; psDefn->ProjParm[2] = dfAzimuth; psDefn->ProjParmId[2] = ProjAzimuthAngleGeoKey; psDefn->ProjParm[3] = dfRectGridAngle; psDefn->ProjParmId[3] = ProjRectifiedGridAngleGeoKey; psDefn->ProjParm[4] = dfNatOriginScale; psDefn->ProjParmId[4] = ProjScaleAtCenterGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_CassiniSoldner: case CT_Polyconic: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3092::ProjScaleAtNatOriginGeoKey", &dfNatOriginScale ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3093::ProjScaleAtCenterGeoKey", &dfNatOriginScale ) == 0 ) dfNatOriginScale = 1.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjNatOriginLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjNatOriginLongGeoKey; psDefn->ProjParm[4] = dfNatOriginScale; psDefn->ProjParmId[4] = ProjScaleAtNatOriginGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_AzimuthalEquidistant: case CT_MillerCylindrical: case CT_Equirectangular: case CT_Gnomonic: case CT_LambertAzimEqualArea: case CT_Orthographic: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjCenterLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjCenterLongGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_Robinson: case CT_Sinusoidal: case CT_VanDerGrinten: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjCenterLongGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_PolarStereographic: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3095::ProjStraightVertPoleLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3092::ProjScaleAtNatOriginGeoKey", &dfNatOriginScale ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3093::ProjScaleAtCenterGeoKey", &dfNatOriginScale ) == 0 ) dfNatOriginScale = 1.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjNatOriginLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjStraightVertPoleLongGeoKey; psDefn->ProjParm[4] = dfNatOriginScale; psDefn->ProjParmId[4] = ProjScaleAtNatOriginGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_LambertConfConic_2SP: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3078::ProjStdParallel1GeoKey", &dfStdParallel1 ) == 0 ) dfStdParallel1 = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3079::ProjStdParallel2GeoKey", &dfStdParallel2 ) == 0 ) dfStdParallel1 = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfNatOriginLat; psDefn->ProjParmId[0] = ProjFalseOriginLatGeoKey; psDefn->ProjParm[1] = dfNatOriginLong; psDefn->ProjParmId[1] = ProjFalseOriginLongGeoKey; psDefn->ProjParm[2] = dfStdParallel1; psDefn->ProjParmId[2] = ProjStdParallel1GeoKey; psDefn->ProjParm[3] = dfStdParallel2; psDefn->ProjParmId[3] = ProjStdParallel2GeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; /* -------------------------------------------------------------------- */ case CT_AlbersEqualArea: case CT_EquidistantConic: /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3078::ProjStdParallel1GeoKey", &dfStdParallel1 ) == 0 ) dfStdParallel1 = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3079::ProjStdParallel2GeoKey", &dfStdParallel2 ) == 0 ) dfStdParallel1 = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3080::ProjNatOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3084::ProjFalseOriginLongGeoKey", &dfNatOriginLong ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3088::ProjCenterLongGeoKey", &dfNatOriginLong ) == 0 ) dfNatOriginLong = 0.0; if( GetMetadataElement( "GEOTIFF_NUM::3081::ProjNatOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3085::ProjFalseOriginLatGeoKey", &dfNatOriginLat ) == 0 && GetMetadataElement( "GEOTIFF_NUM::3089::ProjCenterLatGeoKey", &dfNatOriginLat ) == 0 ) dfNatOriginLat = 0.0; /* notdef: should transform to decimal degrees at this point */ psDefn->ProjParm[0] = dfStdParallel1; psDefn->ProjParmId[0] = ProjStdParallel1GeoKey; psDefn->ProjParm[1] = dfStdParallel2; psDefn->ProjParmId[1] = ProjStdParallel2GeoKey; psDefn->ProjParm[2] = dfNatOriginLat; psDefn->ProjParmId[2] = ProjNatOriginLatGeoKey; psDefn->ProjParm[3] = dfNatOriginLong; psDefn->ProjParmId[3] = ProjNatOriginLongGeoKey; psDefn->ProjParm[5] = dfFalseEasting; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[6] = dfFalseNorthing; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; psDefn->nParms = 7; break; } } /************************************************************************/ /* GetGTIFDefn() */ /* This function borrowed from the GTIFGetDefn() function. */ /* See geo_normalize.c from the GeoTIFF package. */ /************************************************************************/ void MrSIDDataset::GetGTIFDefn() { double dfInvFlattening; /* -------------------------------------------------------------------- */ /* Make sure we have hooked CSV lookup for GDAL_DATA. */ /* -------------------------------------------------------------------- */ LibgeotiffOneTimeInit(); /* -------------------------------------------------------------------- */ /* Initially we default all the information we can. */ /* -------------------------------------------------------------------- */ psDefn = new( GTIFDefn ); psDefn->Model = KvUserDefined; psDefn->PCS = KvUserDefined; psDefn->GCS = KvUserDefined; psDefn->UOMLength = KvUserDefined; psDefn->UOMLengthInMeters = 1.0; psDefn->UOMAngle = KvUserDefined; psDefn->UOMAngleInDegrees = 1.0; psDefn->Datum = KvUserDefined; psDefn->Ellipsoid = KvUserDefined; psDefn->SemiMajor = 0.0; psDefn->SemiMinor = 0.0; psDefn->PM = KvUserDefined; psDefn->PMLongToGreenwich = 0.0; psDefn->ProjCode = KvUserDefined; psDefn->Projection = KvUserDefined; psDefn->CTProjection = KvUserDefined; psDefn->nParms = 0; for( int i = 0; i < MAX_GTIF_PROJPARMS; i++ ) { psDefn->ProjParm[i] = 0.0; psDefn->ProjParmId[i] = 0; } psDefn->MapSys = KvUserDefined; psDefn->Zone = 0; /* -------------------------------------------------------------------- */ /* Try to get the overall model type. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::1024::GTModelTypeGeoKey", &(psDefn->Model) ); /* -------------------------------------------------------------------- */ /* Try to get a PCS. */ /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3072::ProjectedCSTypeGeoKey", &(psDefn->PCS) ) && psDefn->PCS != KvUserDefined ) { /* * Translate this into useful information. */ GTIFGetPCSInfo( psDefn->PCS, nullptr, &(psDefn->ProjCode), &(psDefn->UOMLength), &(psDefn->GCS) ); } /* -------------------------------------------------------------------- */ /* If we have the PCS code, but didn't find it in the CSV files */ /* (likely because we can't find them) we will try some ``jiffy */ /* rules'' for UTM and state plane. */ /* -------------------------------------------------------------------- */ if( psDefn->PCS != KvUserDefined && psDefn->ProjCode == KvUserDefined ) { int nMapSys, nZone; int nGCS = psDefn->GCS; nMapSys = GTIFPCSToMapSys( psDefn->PCS, &nGCS, &nZone ); if( nMapSys != KvUserDefined ) { psDefn->ProjCode = (short) GTIFMapSysToProj( nMapSys, nZone ); psDefn->GCS = (short) nGCS; } } /* -------------------------------------------------------------------- */ /* If the Proj_ code is specified directly, use that. */ /* -------------------------------------------------------------------- */ if( psDefn->ProjCode == KvUserDefined ) GetMetadataElement( "GEOTIFF_NUM::3074::ProjectionGeoKey", &(psDefn->ProjCode) ); if( psDefn->ProjCode != KvUserDefined ) { /* * We have an underlying projection transformation value. Look * this up. For a PCS of ``WGS 84 / UTM 11'' the transformation * would be Transverse Mercator, with a particular set of options. * The nProjTRFCode itself would correspond to the name * ``UTM zone 11N'', and doesn't include datum info. */ GTIFGetProjTRFInfo( psDefn->ProjCode, nullptr, &(psDefn->Projection), psDefn->ProjParm ); /* * Set the GeoTIFF identity of the parameters. */ psDefn->CTProjection = (short) EPSGProjMethodToCTProjMethod( psDefn->Projection ); SetGTParamIds( psDefn->CTProjection, psDefn->ProjParmId, nullptr); psDefn->nParms = 7; } /* -------------------------------------------------------------------- */ /* Try to get a GCS. If found, it will override any implied by */ /* the PCS. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2048::GeographicTypeGeoKey", &(psDefn->GCS) ); /* -------------------------------------------------------------------- */ /* Derive the datum, and prime meridian from the GCS. */ /* -------------------------------------------------------------------- */ if( psDefn->GCS != KvUserDefined ) { GTIFGetGCSInfo( psDefn->GCS, nullptr, &(psDefn->Datum), &(psDefn->PM), &(psDefn->UOMAngle) ); } /* -------------------------------------------------------------------- */ /* Handle the GCS angular units. GeogAngularUnitsGeoKey */ /* overrides the GCS or PCS setting. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2054::GeogAngularUnitsGeoKey", &(psDefn->UOMAngle) ); if( psDefn->UOMAngle != KvUserDefined ) { GTIFGetUOMAngleInfo( psDefn->UOMAngle, nullptr, &(psDefn->UOMAngleInDegrees) ); } /* -------------------------------------------------------------------- */ /* Check for a datum setting, and then use the datum to derive */ /* an ellipsoid. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2050::GeogGeodeticDatumGeoKey", &(psDefn->Datum) ); if( psDefn->Datum != KvUserDefined ) { GTIFGetDatumInfo( psDefn->Datum, nullptr, &(psDefn->Ellipsoid) ); } /* -------------------------------------------------------------------- */ /* Check for an explicit ellipsoid. Use the ellipsoid to */ /* derive the ellipsoid characteristics, if possible. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2056::GeogEllipsoidGeoKey", &(psDefn->Ellipsoid) ); if( psDefn->Ellipsoid != KvUserDefined ) { GTIFGetEllipsoidInfo( psDefn->Ellipsoid, nullptr, &(psDefn->SemiMajor), &(psDefn->SemiMinor) ); } /* -------------------------------------------------------------------- */ /* Check for overridden ellipsoid parameters. It would be nice */ /* to warn if they conflict with provided information, but for */ /* now we just override. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2057::GeogSemiMajorAxisGeoKey", &(psDefn->SemiMajor) ); GetMetadataElement( "GEOTIFF_NUM::2058::GeogSemiMinorAxisGeoKey", &(psDefn->SemiMinor) ); if( GetMetadataElement( "GEOTIFF_NUM::2059::GeogInvFlatteningGeoKey", &dfInvFlattening ) == 1 ) { if( dfInvFlattening != 0.0 ) psDefn->SemiMinor = OSRCalcSemiMinorFromInvFlattening(psDefn->SemiMajor, dfInvFlattening); } /* -------------------------------------------------------------------- */ /* Get the prime meridian info. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::2051::GeogPrimeMeridianGeoKey", &(psDefn->PM) ); if( psDefn->PM != KvUserDefined ) { GTIFGetPMInfo( psDefn->PM, nullptr, &(psDefn->PMLongToGreenwich) ); } else { GetMetadataElement( "GEOTIFF_NUM::2061::GeogPrimeMeridianLongGeoKey", &(psDefn->PMLongToGreenwich) ); psDefn->PMLongToGreenwich = GTIFAngleToDD( psDefn->PMLongToGreenwich, psDefn->UOMAngle ); } /* -------------------------------------------------------------------- */ /* Have the projection units of measure been overridden? We */ /* should likely be doing something about angular units too, */ /* but these are very rarely not decimal degrees for actual */ /* file coordinates. */ /* -------------------------------------------------------------------- */ GetMetadataElement( "GEOTIFF_NUM::3076::ProjLinearUnitsGeoKey", &(psDefn->UOMLength) ); if( psDefn->UOMLength != KvUserDefined ) { GTIFGetUOMLengthInfo( psDefn->UOMLength, nullptr, &(psDefn->UOMLengthInMeters) ); } /* -------------------------------------------------------------------- */ /* Handle a variety of user defined transform types. */ /* -------------------------------------------------------------------- */ if( GetMetadataElement( "GEOTIFF_NUM::3075::ProjCoordTransGeoKey", &(psDefn->CTProjection) ) ) { FetchProjParams(); } /* -------------------------------------------------------------------- */ /* Try to set the zoned map system information. */ /* -------------------------------------------------------------------- */ psDefn->MapSys = GTIFProjToMapSys( psDefn->ProjCode, &(psDefn->Zone) ); /* -------------------------------------------------------------------- */ /* If this is UTM, and we were unable to extract the projection */ /* parameters from the CSV file, just set them directly now, */ /* since it is pretty easy, and a common case. */ /* -------------------------------------------------------------------- */ if( (psDefn->MapSys == MapSys_UTM_North || psDefn->MapSys == MapSys_UTM_South) && psDefn->CTProjection == KvUserDefined ) { psDefn->CTProjection = CT_TransverseMercator; psDefn->nParms = 7; psDefn->ProjParmId[0] = ProjNatOriginLatGeoKey; psDefn->ProjParm[0] = 0.0; psDefn->ProjParmId[1] = ProjNatOriginLongGeoKey; psDefn->ProjParm[1] = psDefn->Zone*6 - 183.0; psDefn->ProjParmId[4] = ProjScaleAtNatOriginGeoKey; psDefn->ProjParm[4] = 0.9996; psDefn->ProjParmId[5] = ProjFalseEastingGeoKey; psDefn->ProjParm[5] = 500000.0; psDefn->ProjParmId[6] = ProjFalseNorthingGeoKey; if( psDefn->MapSys == MapSys_UTM_North ) psDefn->ProjParm[6] = 0.0; else psDefn->ProjParm[6] = 10000000.0; } char* pszProjection = GetOGISDefn( psDefn ); if( pszProjection ) { m_oSRS.importFromWkt(pszProjection); m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } CPLFree(pszProjection); } /************************************************************************/ /* GTIFToCPLRecyleString() */ /* */ /* This changes a string from the libgeotiff heap to the GDAL */ /* heap. */ /************************************************************************/ static void GTIFToCPLRecycleString( char **ppszTarget ) { if( *ppszTarget == nullptr ) return; char *pszTempString = CPLStrdup(*ppszTarget); GTIFFreeMemory( *ppszTarget ); *ppszTarget = pszTempString; } /************************************************************************/ /* GetOGISDefn() */ /* Copied from the gt_wkt_srs.cpp. */ /************************************************************************/ char *MrSIDDataset::GetOGISDefn( GTIFDefn *psDefnIn ) { OGRSpatialReference oSRS; if( psDefnIn->Model != ModelTypeProjected && psDefnIn->Model != ModelTypeGeographic ) return CPLStrdup(""); /* -------------------------------------------------------------------- */ /* If this is a projected SRS we set the PROJCS keyword first */ /* to ensure that the GEOGCS will be a child. */ /* -------------------------------------------------------------------- */ if( psDefnIn->Model == ModelTypeProjected ) { int bPCSNameSet = FALSE; if( psDefnIn->PCS != KvUserDefined ) { char *pszPCSName = nullptr; if( GTIFGetPCSInfo( psDefnIn->PCS, &pszPCSName, nullptr, nullptr, nullptr ) ) bPCSNameSet = TRUE; oSRS.SetNode( "PROJCS", bPCSNameSet ? pszPCSName : "unnamed" ); if( bPCSNameSet ) GTIFFreeMemory( pszPCSName ); oSRS.SetAuthority( "PROJCS", "EPSG", psDefnIn->PCS ); } else { char szPCSName[200]; strcpy( szPCSName, "unnamed" ); if ( GetMetadataElement( "GEOTIFF_NUM::1026::GTCitationGeoKey", szPCSName, sizeof(szPCSName) ) ) oSRS.SetNode( "PROJCS", szPCSName ); } } /* ==================================================================== */ /* Setup the GeogCS */ /* ==================================================================== */ char *pszGeogName = nullptr; char *pszDatumName = nullptr; char *pszPMName = nullptr; char *pszSpheroidName = nullptr; char *pszAngularUnits = nullptr; double dfInvFlattening, dfSemiMajor; char szGCSName[200]; if( GetMetadataElement( "GEOTIFF_NUM::2049::GeogCitationGeoKey", szGCSName, sizeof(szGCSName) ) ) pszGeogName = CPLStrdup(szGCSName); else { GTIFGetGCSInfo( psDefnIn->GCS, &pszGeogName, nullptr, nullptr, nullptr ); GTIFToCPLRecycleString(&pszGeogName); } GTIFGetDatumInfo( psDefnIn->Datum, &pszDatumName, nullptr ); GTIFToCPLRecycleString(&pszDatumName); GTIFGetPMInfo( psDefnIn->PM, &pszPMName, nullptr ); GTIFToCPLRecycleString(&pszPMName); GTIFGetEllipsoidInfo( psDefnIn->Ellipsoid, &pszSpheroidName, nullptr, nullptr ); GTIFToCPLRecycleString(&pszSpheroidName); GTIFGetUOMAngleInfo( psDefnIn->UOMAngle, &pszAngularUnits, nullptr ); GTIFToCPLRecycleString(&pszAngularUnits); if( pszAngularUnits == nullptr ) pszAngularUnits = CPLStrdup("unknown"); if( pszDatumName != nullptr ) WKTMassageDatum( &pszDatumName ); dfSemiMajor = psDefnIn->SemiMajor; if( psDefnIn->SemiMajor == 0.0 ) { CPLFree( pszSpheroidName ); pszSpheroidName = CPLStrdup("unretrievable - using WGS84"); dfSemiMajor = SRS_WGS84_SEMIMAJOR; dfInvFlattening = SRS_WGS84_INVFLATTENING; } else dfInvFlattening = OSRCalcInvFlattening(psDefnIn->SemiMajor,psDefnIn->SemiMinor); oSRS.SetGeogCS( pszGeogName, pszDatumName, pszSpheroidName, dfSemiMajor, dfInvFlattening, pszPMName, psDefnIn->PMLongToGreenwich / psDefnIn->UOMAngleInDegrees, pszAngularUnits, psDefnIn->UOMAngleInDegrees * 0.0174532925199433 ); if( psDefnIn->GCS != KvUserDefined ) oSRS.SetAuthority( "GEOGCS", "EPSG", psDefnIn->GCS ); if( psDefnIn->Datum != KvUserDefined ) oSRS.SetAuthority( "DATUM", "EPSG", psDefnIn->Datum ); if( psDefnIn->Ellipsoid != KvUserDefined ) oSRS.SetAuthority( "SPHEROID", "EPSG", psDefnIn->Ellipsoid ); CPLFree( pszGeogName ); CPLFree( pszDatumName ); CPLFree( pszPMName ); CPLFree( pszSpheroidName ); CPLFree( pszAngularUnits ); /* ==================================================================== */ /* Handle projection parameters. */ /* ==================================================================== */ if( psDefnIn->Model == ModelTypeProjected ) { /* -------------------------------------------------------------------- */ /* Make a local copy of params, and convert back into the */ /* angular units of the GEOGCS and the linear units of the */ /* projection. */ /* -------------------------------------------------------------------- */ double adfParam[10]; int i; for( i = 0; i < MIN(10,psDefnIn->nParms); i++ ) adfParam[i] = psDefnIn->ProjParm[i]; for( ; i < 10; i++) adfParam[i] = 0; adfParam[0] /= psDefnIn->UOMAngleInDegrees; adfParam[1] /= psDefnIn->UOMAngleInDegrees; adfParam[2] /= psDefnIn->UOMAngleInDegrees; adfParam[3] /= psDefnIn->UOMAngleInDegrees; adfParam[5] /= psDefnIn->UOMLengthInMeters; adfParam[6] /= psDefnIn->UOMLengthInMeters; /* -------------------------------------------------------------------- */ /* Translation the fundamental projection. */ /* -------------------------------------------------------------------- */ switch( psDefnIn->CTProjection ) { case CT_TransverseMercator: oSRS.SetTM( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_TransvMercator_SouthOriented: oSRS.SetTMSO( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_Mercator: oSRS.SetMercator( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_ObliqueStereographic: oSRS.SetOS( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_Stereographic: oSRS.SetOS( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_ObliqueMercator: /* hotine */ oSRS.SetHOM( adfParam[0], adfParam[1], adfParam[2], adfParam[3], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_EquidistantConic: oSRS.SetEC( adfParam[0], adfParam[1], adfParam[2], adfParam[3], adfParam[5], adfParam[6] ); break; case CT_CassiniSoldner: oSRS.SetCS( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Polyconic: oSRS.SetPolyconic( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_AzimuthalEquidistant: oSRS.SetAE( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_MillerCylindrical: oSRS.SetMC( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Equirectangular: oSRS.SetEquirectangular( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Gnomonic: oSRS.SetGnomonic( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_LambertAzimEqualArea: oSRS.SetLAEA( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Orthographic: oSRS.SetOrthographic( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Robinson: oSRS.SetRobinson( adfParam[1], adfParam[5], adfParam[6] ); break; case CT_Sinusoidal: oSRS.SetSinusoidal( adfParam[1], adfParam[5], adfParam[6] ); break; case CT_VanDerGrinten: oSRS.SetVDG( adfParam[1], adfParam[5], adfParam[6] ); break; case CT_PolarStereographic: oSRS.SetPS( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_LambertConfConic_2SP: oSRS.SetLCC( adfParam[2], adfParam[3], adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; case CT_LambertConfConic_1SP: oSRS.SetLCC1SP( adfParam[0], adfParam[1], adfParam[4], adfParam[5], adfParam[6] ); break; case CT_AlbersEqualArea: oSRS.SetACEA( adfParam[0], adfParam[1], adfParam[2], adfParam[3], adfParam[5], adfParam[6] ); break; case CT_NewZealandMapGrid: oSRS.SetNZMG( adfParam[0], adfParam[1], adfParam[5], adfParam[6] ); break; } /* -------------------------------------------------------------------- */ /* Set projection units. */ /* -------------------------------------------------------------------- */ char *pszUnitsName = nullptr; GTIFGetUOMLengthInfo( psDefnIn->UOMLength, &pszUnitsName, nullptr ); if( pszUnitsName != nullptr && psDefnIn->UOMLength != KvUserDefined ) { oSRS.SetLinearUnits( pszUnitsName, psDefnIn->UOMLengthInMeters ); oSRS.SetAuthority( "PROJCS|UNIT", "EPSG", psDefnIn->UOMLength ); } else oSRS.SetLinearUnits( "unknown", psDefnIn->UOMLengthInMeters ); GTIFFreeMemory( pszUnitsName ); } /* -------------------------------------------------------------------- */ /* Return the WKT serialization of the object. */ /* -------------------------------------------------------------------- */ char *pszWKT = nullptr; if( oSRS.exportToWkt( &pszWKT ) == OGRERR_NONE ) return pszWKT; else { CPLFree(pszWKT); return nullptr; } } #ifdef MRSID_ESDK /************************************************************************/ /* ==================================================================== */ /* MrSIDDummyImageReader */ /* */ /* This is a helper class to wrap GDAL calls in MrSID interface. */ /* ==================================================================== */ /************************************************************************/ class MrSIDDummyImageReader : public LTIImageReader { public: MrSIDDummyImageReader( GDALDataset *poSrcDS ); ~MrSIDDummyImageReader(); LT_STATUS initialize(); lt_int64 getPhysicalFileSize(void) const { return 0; }; private: GDALDataset *poDS; GDALDataType eDataType; LTIDataType eSampleType; const LTIPixel *poPixel; double adfGeoTransform[6]; virtual LT_STATUS decodeStrip( LTISceneBuffer& stripBuffer, const LTIScene& stripScene ); virtual LT_STATUS decodeBegin( const LTIScene& ) { return LT_STS_Success; }; virtual LT_STATUS decodeEnd() { return LT_STS_Success; }; }; /************************************************************************/ /* MrSIDDummyImageReader() */ /************************************************************************/ MrSIDDummyImageReader::MrSIDDummyImageReader( GDALDataset *poSrcDS ) : LTIImageReader(), poDS(poSrcDS) { poPixel = nullptr; } /************************************************************************/ /* ~MrSIDDummyImageReader() */ /************************************************************************/ MrSIDDummyImageReader::~MrSIDDummyImageReader() { if ( poPixel ) delete poPixel; } /************************************************************************/ /* initialize() */ /************************************************************************/ LT_STATUS MrSIDDummyImageReader::initialize() { LT_STATUS eStat = LT_STS_Uninit; #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 6 if ( !LT_SUCCESS(eStat = LTIImageReader::init()) ) return eStat; #else if ( !LT_SUCCESS(eStat = LTIImageReader::initialize()) ) return eStat; #endif lt_uint16 nBands = (lt_uint16)poDS->GetRasterCount(); LTIColorSpace eColorSpace = LTI_COLORSPACE_RGB; switch ( nBands ) { case 1: eColorSpace = LTI_COLORSPACE_GRAYSCALE; break; case 3: eColorSpace = LTI_COLORSPACE_RGB; break; default: eColorSpace = LTI_COLORSPACE_MULTISPECTRAL; break; } eDataType = poDS->GetRasterBand(1)->GetRasterDataType(); switch ( eDataType ) { case GDT_UInt16: eSampleType = LTI_DATATYPE_UINT16; break; case GDT_Int16: eSampleType = LTI_DATATYPE_SINT16; break; case GDT_UInt32: eSampleType = LTI_DATATYPE_UINT32; break; case GDT_Int32: eSampleType = LTI_DATATYPE_SINT32; break; case GDT_Float32: eSampleType = LTI_DATATYPE_FLOAT32; break; case GDT_Float64: eSampleType = LTI_DATATYPE_FLOAT64; break; case GDT_Byte: default: eSampleType = LTI_DATATYPE_UINT8; break; } poPixel = new LTIDLLPixel<LTIPixel>( eColorSpace, nBands, eSampleType ); if ( !LT_SUCCESS(setPixelProps(*poPixel)) ) return LT_STS_Failure; if ( !LT_SUCCESS(setDimensions(poDS->GetRasterXSize(), poDS->GetRasterYSize())) ) return LT_STS_Failure; if ( poDS->GetGeoTransform( adfGeoTransform ) == CE_None ) { #ifdef MRSID_SDK_40 LTIGeoCoord oGeo( adfGeoTransform[0] + adfGeoTransform[1] / 2, adfGeoTransform[3] + adfGeoTransform[5] / 2, adfGeoTransform[1], adfGeoTransform[5], adfGeoTransform[2], adfGeoTransform[4], nullptr, poDS->GetProjectionRef() ); #else LTIGeoCoord oGeo( adfGeoTransform[0] + adfGeoTransform[1] / 2, adfGeoTransform[3] + adfGeoTransform[5] / 2, adfGeoTransform[1], adfGeoTransform[5], adfGeoTransform[2], adfGeoTransform[4], poDS->GetProjectionRef() ); #endif if ( !LT_SUCCESS(setGeoCoord( oGeo )) ) return LT_STS_Failure; } /*int bSuccess; double dfNoDataValue = poDS->GetNoDataValue( &bSuccess ); if ( bSuccess ) { LTIPixel oNoDataPixel( *poPixel ); lt_uint16 iBand; for (iBand = 0; iBand < (lt_uint16)poDS->GetRasterCount(); iBand++) oNoDataPixel.setSampleValueFloat32( iBand, dfNoDataValue ); if ( !LT_SUCCESS(setNoDataPixel( &oNoDataPixel )) ) return LT_STS_Failure; }*/ setDefaultDynamicRange(); #if !defined(LTI_SDK_MAJOR) || LTI_SDK_MAJOR < 8 setClassicalMetadata(); #endif return LT_STS_Success; } /************************************************************************/ /* decodeStrip() */ /************************************************************************/ LT_STATUS MrSIDDummyImageReader::decodeStrip(LTISceneBuffer& stripData, const LTIScene& stripScene) { const lt_int32 nXOff = stripScene.getUpperLeftCol(); const lt_int32 nYOff = stripScene.getUpperLeftRow(); const lt_int32 nBufXSize = stripScene.getNumCols(); const lt_int32 nBufYSize = stripScene.getNumRows(); const lt_int32 nDataBufXSize = stripData.getTotalNumCols(); const lt_int32 nDataBufYSize = stripData.getTotalNumRows(); const lt_uint16 nBands = poPixel->getNumBands(); void *pData = CPLMalloc(nDataBufXSize * nDataBufYSize * poPixel->getNumBytes()); if ( !pData ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDummyImageReader::decodeStrip(): " "Cannot allocate enough space for scene buffer" ); return LT_STS_Failure; } poDS->RasterIO( GF_Read, nXOff, nYOff, nBufXSize, nBufYSize, pData, nBufXSize, nBufYSize, eDataType, nBands, nullptr, 0, 0, 0, nullptr ); stripData.importDataBSQ( pData ); CPLFree( pData ); return LT_STS_Success; } /************************************************************************/ /* FlushCache() */ /************************************************************************/ void MrSIDDataset::FlushCache(bool bAtClosing) { GDALDataset::FlushCache(bAtClosing); } /************************************************************************/ /* MrSIDCreateCopy() */ /************************************************************************/ static GDALDataset * MrSIDCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { const char* pszVersion = CSLFetchNameValue(papszOptions, "VERSION"); #ifdef MRSID_HAVE_MG4WRITE int iVersion = pszVersion ? atoi(pszVersion) : 4; #else int iVersion = pszVersion ? atoi(pszVersion) : 3; #endif LT_STATUS eStat = LT_STS_Uninit; #ifdef DEBUG bool bMeter = false; #else bool bMeter = true; #endif if (poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr) { CPLError( (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported, "MrSID driver ignores color table. " "The source raster band will be considered as grey level.\n" "Consider using color table expansion (-expand option in gdal_translate)\n"); if (bStrict) return nullptr; } MrSIDProgress oProgressDelegate(pfnProgress, pProgressData); if( LT_FAILURE( eStat = oProgressDelegate.setProgressStatus(0) ) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDProgress.setProgressStatus failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } // Create the file. MrSIDDummyImageReader oImageReader( poSrcDS ); if( LT_FAILURE( eStat = oImageReader.initialize() ) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDummyImageReader.Initialize failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } LTIGeoFileImageWriter *poImageWriter = nullptr; switch (iVersion) { case 2: { // Output Mrsid Version 2 file. #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 LTIDLLDefault<MG2ImageWriter> *poMG2ImageWriter; poMG2ImageWriter = new LTIDLLDefault<MG2ImageWriter>; eStat = poMG2ImageWriter->initialize(&oImageReader); #else LTIDLLWriter<MG2ImageWriter> *poMG2ImageWriter; poMG2ImageWriter = new LTIDLLWriter<MG2ImageWriter>(&oImageReader); eStat = poMG2ImageWriter->initialize(); #endif if( LT_FAILURE( eStat ) ) { delete poMG2ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG2ImageWriter.initialize() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 eStat = poMG2ImageWriter->setEncodingApplication("MrSID Driver", GDALVersionInfo("--version")); if( LT_FAILURE( eStat ) ) { delete poMG2ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG2ImageWriter.setEncodingApplication() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #endif poMG2ImageWriter->setUsageMeterEnabled(bMeter); poMG2ImageWriter->params().setBlockSize(poMG2ImageWriter->params().getBlockSize()); // check for compression option const char* pszValue = CSLFetchNameValue(papszOptions, "COMPRESSION"); if( pszValue != nullptr ) poMG2ImageWriter->params().setCompressionRatio( (float)CPLAtof(pszValue) ); poImageWriter = poMG2ImageWriter; break; } case 3: { // Output Mrsid Version 3 file. #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 LTIDLLDefault<MG3ImageWriter> *poMG3ImageWriter; poMG3ImageWriter = new LTIDLLDefault<MG3ImageWriter>; eStat = poMG3ImageWriter->initialize(&oImageReader); #else LTIDLLWriter<MG3ImageWriter> *poMG3ImageWriter; poMG3ImageWriter = new LTIDLLWriter<MG3ImageWriter>(&oImageReader); eStat = poMG3ImageWriter->initialize(); #endif if( LT_FAILURE( eStat ) ) { delete poMG3ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG3ImageWriter.initialize() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #if defined(LTI_SDK_MAJOR) && LTI_SDK_MAJOR >= 8 eStat = poMG3ImageWriter->setEncodingApplication("MrSID Driver", GDALVersionInfo("--version")); if( LT_FAILURE( eStat ) ) { delete poMG3ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG3ImageWriter.setEncodingApplication() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #endif // usage meter should only be disabled for debugging poMG3ImageWriter->setUsageMeterEnabled(bMeter); #if !defined(LTI_SDK_MAJOR) || LTI_SDK_MAJOR < 8 // Set 64-bit Interface for large files. poMG3ImageWriter->setFileStream64(true); #endif // set 2 pass optimizer option if( CSLFetchNameValue(papszOptions, "TWOPASS") != nullptr ) poMG3ImageWriter->params().setTwoPassOptimizer( true ); // set filesize in KB const char* pszValue = CSLFetchNameValue(papszOptions, "FILESIZE"); if( pszValue != nullptr ) poMG3ImageWriter->params().setTargetFilesize( atoi(pszValue) ); poImageWriter = poMG3ImageWriter; break; } #ifdef MRSID_HAVE_MG4WRITE case 4: { // Output Mrsid Version 4 file. LTIDLLDefault<MG4ImageWriter> *poMG4ImageWriter; poMG4ImageWriter = new LTIDLLDefault<MG4ImageWriter>; eStat = poMG4ImageWriter->initialize(&oImageReader, nullptr, nullptr); if( LT_FAILURE( eStat ) ) { delete poMG4ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG3ImageWriter.initialize() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } eStat = poMG4ImageWriter->setEncodingApplication("MrSID Driver", GDALVersionInfo("--version")); if( LT_FAILURE( eStat ) ) { delete poMG4ImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG3ImageWriter.setEncodingApplication() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } // usage meter should only be disabled for debugging poMG4ImageWriter->setUsageMeterEnabled(bMeter); // set 2 pass optimizer option if( CSLFetchNameValue(papszOptions, "TWOPASS") != nullptr ) poMG4ImageWriter->params().setTwoPassOptimizer( true ); // set filesize in KB const char* pszValue = CSLFetchNameValue(papszOptions, "FILESIZE"); if( pszValue != nullptr ) poMG4ImageWriter->params().setTargetFilesize( atoi(pszValue) ); poImageWriter = poMG4ImageWriter; break; } #endif /* MRSID_HAVE_MG4WRITE */ default: CPLError( CE_Failure, CPLE_AppDefined, "Invalid MrSID generation specified (VERSION=%s).", pszVersion ); return nullptr; } // set output filename poImageWriter->setOutputFileSpec( pszFilename ); // set progress delegate poImageWriter->setProgressDelegate(&oProgressDelegate); // set defaults poImageWriter->setStripHeight(poImageWriter->getStripHeight()); // set MrSID world file if( CSLFetchNameValue(papszOptions, "WORLDFILE") != nullptr ) poImageWriter->setWorldFileSupport( true ); // write the scene int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); const LTIScene oScene( 0, 0, nXSize, nYSize, 1.0 ); if( LT_FAILURE( eStat = poImageWriter->write( oScene ) ) ) { delete poImageWriter; CPLError( CE_Failure, CPLE_AppDefined, "MG2ImageWriter.write() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } delete poImageWriter; /* -------------------------------------------------------------------- */ /* Re-open dataset, and copy any auxiliary pam information. */ /* -------------------------------------------------------------------- */ GDALPamDataset *poDS = (GDALPamDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDS ) poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); return poDS; } #ifdef MRSID_J2K /************************************************************************/ /* JP2CreateCopy() */ /************************************************************************/ static GDALDataset * JP2CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { #ifdef DEBUG bool bMeter = false; #else bool bMeter = true; #endif int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); LT_STATUS eStat; if (poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr) { CPLError( (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported, "MrSID driver ignores color table. " "The source raster band will be considered as grey level.\n" "Consider using color table expansion (-expand option in gdal_translate)\n"); if (bStrict) return nullptr; } MrSIDProgress oProgressDelegate(pfnProgress, pProgressData); if( LT_FAILURE( eStat = oProgressDelegate.setProgressStatus(0) ) ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDProgress.setProgressStatus failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } // Create the file. MrSIDDummyImageReader oImageReader( poSrcDS ); eStat = oImageReader.initialize(); if( eStat != LT_STS_Success ) { CPLError( CE_Failure, CPLE_AppDefined, "MrSIDDummyImageReader.Initialize failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #if !defined(MRSID_POST5) J2KImageWriter oImageWriter(&oImageReader); eStat = oImageWriter.initialize(); #elif !defined(LTI_SDK_MAJOR) || LTI_SDK_MAJOR < 8 JP2WriterManager oImageWriter(&oImageReader); eStat = oImageWriter.initialize(); #else JP2WriterManager oImageWriter; eStat = oImageWriter.initialize(&oImageReader); #endif if( eStat != LT_STS_Success ) { CPLError( CE_Failure, CPLE_AppDefined, "J2KImageWriter.Initialize failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } #if !defined(LTI_SDK_MAJOR) || LTI_SDK_MAJOR < 8 // Set 64-bit Interface for large files. oImageWriter.setFileStream64(true); #endif oImageWriter.setUsageMeterEnabled(bMeter); // set output filename oImageWriter.setOutputFileSpec( pszFilename ); // set progress delegate oImageWriter.setProgressDelegate(&oProgressDelegate); // Set defaults //oImageWriter.setStripHeight(oImageWriter.getStripHeight()); // set MrSID world file if( CSLFetchNameValue(papszOptions, "WORLDFILE") != nullptr ) oImageWriter.setWorldFileSupport( true ); // check for compression option const char* pszValue = CSLFetchNameValue(papszOptions, "COMPRESSION"); if( pszValue != nullptr ) oImageWriter.params().setCompressionRatio( (float)CPLAtof(pszValue) ); pszValue = CSLFetchNameValue(papszOptions, "XMLPROFILE"); if( pszValue != nullptr ) { LTFileSpec xmlprofile(pszValue); eStat = oImageWriter.params().readProfile(xmlprofile); if( eStat != LT_STS_Success ) { CPLError( CE_Failure, CPLE_AppDefined, "JPCWriterParams.readProfile failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } } // write the scene const LTIScene oScene( 0, 0, nXSize, nYSize, 1.0 ); eStat = oImageWriter.write( oScene ); if( eStat != LT_STS_Success ) { CPLError( CE_Failure, CPLE_AppDefined, "J2KImageWriter.write() failed.\n%s", getLastStatusString( eStat ) ); return nullptr; } /* -------------------------------------------------------------------- */ /* Re-open dataset, and copy any auxiliary pam information. */ /* -------------------------------------------------------------------- */ GDALOpenInfo oOpenInfo(pszFilename, GA_ReadOnly); GDALPamDataset *poDS = (GDALPamDataset*) JP2Open(&oOpenInfo); if( poDS ) poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); return poDS; } #endif /* MRSID_J2K */ #endif /* MRSID_ESDK */ /************************************************************************/ /* GDALRegister_MrSID() */ /************************************************************************/ void GDALRegister_MrSID() { if( !GDAL_CHECK_VERSION( "MrSID driver" ) ) return; /* -------------------------------------------------------------------- */ /* MrSID driver. */ /* -------------------------------------------------------------------- */ if( GDALGetDriverByName( "MrSID" ) != nullptr ) return; GDALDriver *poDriver = new GDALDriver(); poDriver->SetDescription( "MrSID" ); poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Multi-resolution Seamless Image Database " "(MrSID)" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/mrsid.html" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "sid" ); #ifdef MRSID_ESDK poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte Int16 UInt16 Int32 UInt32 " "Float32 Float64" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" // Version 2 Options " <Option name='COMPRESSION' type='double' description='Set compression ratio (0.0 default is meant to be lossless)'/>" // Version 3 Options " <Option name='TWOPASS' type='int' description='Use twopass optimizer algorithm'/>" " <Option name='FILESIZE' type='int' description='Set target file size (0 implies lossless compression)'/>" // Version 2 and 3 Option " <Option name='WORLDFILE' type='boolean' description='Write out world file'/>" // Version Type " <Option name='VERSION' type='int' description='Valid versions are 2 and 3, default = 3'/>" "</CreationOptionList>" ); poDriver->pfnCreateCopy = MrSIDCreateCopy; #else // In read-only mode, we support VirtualIO. I don't think this is the case // for MrSIDCreateCopy(). poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); #endif poDriver->pfnIdentify = MrSIDIdentify; poDriver->pfnOpen = MrSIDOpen; GetGDALDriverManager()->RegisterDriver( poDriver ); /* -------------------------------------------------------------------- */ /* JP2MRSID driver. */ /* -------------------------------------------------------------------- */ #ifdef MRSID_J2K poDriver = new GDALDriver(); poDriver->SetDescription( "JP2MrSID" ); poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "MrSID JPEG2000" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/jp2mrsid.html" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "jp2" ); #ifdef MRSID_ESDK poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte Int16 UInt16" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" " <Option name='COMPRESSION' type='double' description='Set compression ratio (0.0 default is meant to be lossless)'/>" " <Option name='WORLDFILE' type='boolean' description='Write out world file'/>" " <Option name='XMLPROFILE' type='string' description='Use named xml profile file'/>" "</CreationOptionList>" ); poDriver->pfnCreateCopy = JP2CreateCopy; #else /* In read-only mode, we support VirtualIO. I don't think this is the case */ /* for JP2CreateCopy() */ poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); #endif poDriver->pfnIdentify = JP2Identify; poDriver->pfnOpen = JP2Open; GetGDALDriverManager()->RegisterDriver( poDriver ); #endif /* def MRSID_J2K */ } #if defined(MRSID_USE_TIFFSYMS_WORKAROUND) extern "C" { /* This is not pretty but I am not sure how else to get the plugin to build * against the ESDK. ESDK symbol dependencies bring in __TIFFmemcpy and * __gtiff_size, which are not exported from gdal.dll. Rather than link these * symbols from the ESDK distribution of GDAL, or link in the entire gdal.lib * statically, it seemed safer and smaller to bring in just the objects that * wouldsatisfy these symbols from the enclosing GDAL build. However, doing * so pulls in a few more dependencies. /Gy and /OPT:REF did not seem to help * things, so I have implemented no-op versions of these symbols since they * do not actually get called. If the MrSID ESDK ever comes to require the * actual versions of these functions, we'll hope duplicate symbol errors will * bring attention back to this problem. */ void TIFFClientOpen() {} void TIFFError() {} void TIFFGetField() {} void TIFFSetField() {} } #endif
65,480
1,145
<reponame>boralv/chatterino2 #pragma once #include <QDialog> namespace chatterino { class SelectChannelFiltersDialog : public QDialog { public: SelectChannelFiltersDialog(const QList<QUuid> &previousSelection, QWidget *parent = nullptr); const QList<QUuid> &getSelection() const; private: QList<QUuid> currentSelection_; }; } // namespace chatterino
161
5,169
{ "name": "Ololo", "platforms": { "ios": "9.0" }, "summary": "Testing ololo", "requires_arc": true, "version": "11", "license": "Apache 2.0", "authors": { "<NAME>": "<EMAIL>" }, "frameworks": [ "UIKit", "WebKit", "SafariServices", "CoreLocation", "CoreMotion" ], "homepage": "ololo.com", "swift_versions": "4.2", "source": { "git": "https://github.com/Appboxo/test_ios_binary_sdk.git", "tag": "11" }, "exclude_files": "Classes/Exclude", "ios": { "vendored_frameworks": "AppBoxoSDK.xcframework" }, "swift_version": "4.2" }
281
505
package de.rieckpil.blog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.List; @Component public class ApplicationUserInitializer implements CommandLineRunner { private final ApplicationUserRepository applicationUserRepository; private Logger logger = LoggerFactory.getLogger(ApplicationUser.class); public ApplicationUserInitializer(ApplicationUserRepository applicationUserRepository) { this.applicationUserRepository = applicationUserRepository; } @Override public void run(String... args) throws Exception { applicationUserRepository.saveAll( List.of( new ApplicationUser("duke"), new ApplicationUser("github"), new ApplicationUser("actions") )); logger.info("Successfully initialized default application user"); } }
267
1,179
<gh_stars>1000+ // SPDX-License-Identifier: BSD-2-Clause /* * Copyright (C) 2019, Theobroma Systems Design und Consulting GmbH */ #include <common.h> #include <io.h> #include <kernel/panic.h> #include <mm/core_memprot.h> #include <platform.h> #include <platform_config.h> #define FIREWALL_DDR_FW_DDR_RGN(i) ((i) * 0x4) #define FIREWALL_DDR_FW_DDR_MST(i) (0x20 + (i) * 0x4) #define FIREWALL_DDR_FW_DDR_CON_REG 0x40 #define FIREWALL_DDR_FW_DDR_RGN_NUM 8 #define FIREWALL_DDR_FW_DDR_MST_NUM 6 #define RG_MAP_SECURE(top, base) ((((top) - 1) << 16) | (base)) register_phys_mem_pgdir(MEM_AREA_IO_SEC, FIREWALL_DDR_BASE, FIREWALL_DDR_SIZE); int platform_secure_ddr_region(int rgn, paddr_t st, size_t sz) { vaddr_t fw_base = (vaddr_t)phys_to_virt_io(FIREWALL_DDR_BASE, FIREWALL_DDR_SIZE); paddr_t ed = st + sz; uint32_t st_mb = st / SIZE_M(1); uint32_t ed_mb = ed / SIZE_M(1); if (!fw_base) panic(); assert(rgn <= 7); assert(st < ed); /* Check aligned 1MB */ assert(st % SIZE_M(1) == 0); assert(ed % SIZE_M(1) == 0); DMSG("protecting region %d: 0x%lx-0x%lx\n", rgn, st, ed); /* Map top and base */ io_write32(fw_base + FIREWALL_DDR_FW_DDR_RGN(rgn), RG_MAP_SECURE(ed_mb, st_mb)); /* Enable secure setting */ io_setbits32(fw_base + FIREWALL_DDR_FW_DDR_CON_REG, BIT(rgn)); return 0; }
645
372
<gh_stars>100-1000 /* * Copyright © BeyondTrust Software 2004 - 2019 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Module Name: * * lookup.c * * Abstract: * Methods for looking up object attributes. * * * Authors: Author: CORP\slavam * * Created on: Mar 17, 2010 * */ #include "includes.h" /** * Actions initialization methods. */ DWORD InitAdtLookupObjectAction(IN AdtActionTP action) { return InitBaseAction(action); } /** * Actions validate methods. */ DWORD ValidateAdtLookupObjectAction(IN AdtActionTP action) { DWORD dwError = 0; AppContextTP appContext = (AppContextTP) ((AdtActionBaseTP) action)->opaque; PSTR cell = NULL; dwError = OpenADSearchConnectionDN(action, &(action->lookupObject.dn)); ADT_BAIL_ON_ERROR_NP(dwError); SwitchToSearchConnection(action); if (!action->lookupObject.dn) { dwError = ADT_ERR_ARG_MISSING_DN; ADT_BAIL_ON_ERROR_NP(dwError); } if (!action->lookupObject.attr) { action->lookupObject.isAll = 1; } dwError = ProcessDash(&(action->lookupObject.dn)); ADT_BAIL_ON_ERROR_NP(dwError); dwError = ResolveDN(appContext, ObjectClassAny, action->lookupObject.dn, &cell); ADT_BAIL_ON_ERROR_NP(dwError); LW_SAFE_FREE_MEMORY(action->lookupObject.dn); action->lookupObject.dn = cell; cleanup: return dwError; error: goto cleanup; } /** * Actions execute method. */ DWORD ExecuteAdtLookupObjectAction(IN AdtActionTP action) { DWORD dwError = 0; AppContextTP appContext = (AppContextTP) ((AdtActionBaseTP) action)->opaque; INT i, j; AttrValsT *avp = NULL; if(appContext->gopts.isPrintDN) { PrintResult(appContext, LogLevelNone, "%s\n", action->lookupObject.dn); goto cleanup; } PrintStderr(appContext, LogLevelVerbose, "%s: Looking up object attributes ...\n", appContext->actionName); if(action->lookupObject.attr) { dwError = LwAllocateMemory(2 * sizeof(AttrValsT), OUT_PPVOID(&avp)); ADT_BAIL_ON_ALLOC_FAILURE(!dwError); dwError = LwStrDupOrNull((PCSTR) action->lookupObject.attr, &(avp[0].attr)); ADT_BAIL_ON_ALLOC_FAILURE_NP(!dwError); dwError = GetObjectAttrs(appContext, action->lookupObject.dn, avp); ADT_BAIL_ON_ERROR_NP(dwError); } else { dwError = GetAllObjectAttrs(appContext, action->lookupObject.dn, &avp); ADT_BAIL_ON_ERROR_NP(dwError); } if (!appContext->gopts.isQuiet) { if (action->lookupObject.attr) { for (j = 0; avp && avp[0].vals && avp[0].vals[j]; ++j) { PrintResult(appContext, LogLevelNone, "%s\n", (PSTR) avp[0].vals[j]); } } else { for (i = 0; avp && avp[i].attr; ++i) { PrintResult(appContext, LogLevelNone, "%s: ", (PSTR) avp[i].attr); for (j = 0; avp[i].vals && avp[i].vals[j]; ++j) { PrintResult(appContext, LogLevelNone, j ? ";%s" : "%s", (PSTR) avp[i].vals[j]); } PrintResult(appContext, LogLevelNone, "\n"); } } } PrintStderr(appContext, LogLevelVerbose, "%s: Looking up object attributes - done\n", appContext->actionName); cleanup: if (avp) { for (i = 0; avp[i].attr; ++i) { LW_SAFE_FREE_MEMORY(avp[i].attr); if(avp[i].vals) { for (j = 0; avp[i].vals[j]; ++j) { LW_SAFE_FREE_MEMORY(avp[i].vals[j]); } LW_SAFE_FREE_MEMORY(avp[i].vals); } } LW_SAFE_FREE_MEMORY(avp); } return dwError; error: goto cleanup; } /** * Actions clean up methods. */ DWORD CleanUpAdtLookupObjectAction(IN AdtActionTP action) { return CleanUpBaseAction(action); }
2,296
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/files/file_path.h" #include "base/path_service.h" #include "base/values.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "extensions/browser/content_verifier/test_utils.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_test.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_paths.h" #include "extensions/common/extensions_client.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handlers/background_info.h" #include "extensions/common/manifest_handlers/content_scripts_handler.h" #include "extensions/common/scoped_testing_manifest_handler_registry.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { namespace { enum class BackgroundManifestType { kNone, kBackgroundScript, kBackgroundPage, }; base::FilePath kBackgroundScriptPath(FILE_PATH_LITERAL("foo/bg.txt")); base::FilePath kContentScriptPath(FILE_PATH_LITERAL("foo/content.txt")); base::FilePath kBackgroundPagePath(FILE_PATH_LITERAL("foo/page.txt")); base::FilePath kScriptFilePath(FILE_PATH_LITERAL("bar/code.js")); base::FilePath kUnknownTypeFilePath(FILE_PATH_LITERAL("bar/code.txt")); base::FilePath kHTMLFilePath(FILE_PATH_LITERAL("bar/page.html")); base::FilePath kHTMFilePath(FILE_PATH_LITERAL("bar/page.htm")); base::FilePath kIconPath(FILE_PATH_LITERAL("bar/16.png")); class TestContentVerifierDelegate : public MockContentVerifierDelegate { public: TestContentVerifierDelegate() = default; ~TestContentVerifierDelegate() override = default; std::set<base::FilePath> GetBrowserImagePaths( const extensions::Extension* extension) override; void SetBrowserImagePaths(std::set<base::FilePath> paths); private: std::set<base::FilePath> browser_images_paths_; DISALLOW_COPY_AND_ASSIGN(TestContentVerifierDelegate); }; std::set<base::FilePath> TestContentVerifierDelegate::GetBrowserImagePaths( const extensions::Extension* extension) { return std::set<base::FilePath>(browser_images_paths_); } void TestContentVerifierDelegate::SetBrowserImagePaths( std::set<base::FilePath> paths) { browser_images_paths_ = paths; } } // namespace class ContentVerifierTest : public ExtensionsTest, public testing::WithParamInterface<BackgroundManifestType> { public: ContentVerifierTest() {} void SetUp() override { ExtensionsTest::SetUp(); background_manifest_type_ = GetParam(); // Manually register handlers since the |ContentScriptsHandler| is not // usually registered in extensions_unittests. ScopedTestingManifestHandlerRegistry registry; (new BackgroundManifestHandler)->Register(); (new ContentScriptsHandler)->Register(); ManifestHandler::FinalizeRegistration(); extension_ = CreateTestExtension(); ExtensionRegistry::Get(browser_context())->AddEnabled(extension_); auto content_verifier_delegate = std::make_unique<TestContentVerifierDelegate>(); content_verifier_delegate_raw_ = content_verifier_delegate.get(); content_verifier_ = new ContentVerifier( browser_context(), std::move(content_verifier_delegate)); // |ContentVerifier::ShouldVerifyAnyPaths| always returns false if the // Content Verifier does not have |ContentVerifierIOData::ExtensionData| // for the extension. content_verifier_->ResetIODataForTesting(extension_.get()); } void TearDown() override { content_verifier_->Shutdown(); ExtensionsTest::TearDown(); } void UpdateBrowserImagePaths(const std::set<base::FilePath>& paths) { content_verifier_delegate_raw_->SetBrowserImagePaths(paths); content_verifier_->ResetIODataForTesting(extension_.get()); } bool ShouldVerifySinglePath(const base::FilePath& path) { std::set<base::FilePath> paths_to_verify; paths_to_verify.insert(path); return content_verifier_->ShouldVerifyAnyPaths( extension_->id(), extension_->path(), paths_to_verify); } BackgroundManifestType GetBackgroundManifestType() { return background_manifest_type_; } private: // Create a test extension with a content script and possibly a background // page or background script. scoped_refptr<Extension> CreateTestExtension() { base::DictionaryValue manifest; manifest.SetString("name", "Dummy Extension"); manifest.SetString("version", "1"); manifest.SetInteger("manifest_version", 2); if (background_manifest_type_ == BackgroundManifestType::kBackgroundScript) { auto background_scripts = std::make_unique<base::ListValue>(); background_scripts->AppendString("foo/bg.txt"); manifest.Set(manifest_keys::kBackgroundScripts, std::move(background_scripts)); } else if (background_manifest_type_ == BackgroundManifestType::kBackgroundPage) { manifest.SetString(manifest_keys::kBackgroundPage, "foo/page.txt"); } auto content_scripts = std::make_unique<base::ListValue>(); auto content_script = std::make_unique<base::DictionaryValue>(); auto js_files = std::make_unique<base::ListValue>(); auto matches = std::make_unique<base::ListValue>(); js_files->AppendString("foo/content.txt"); content_script->Set("js", std::move(js_files)); matches->AppendString("http://*/*"); content_script->Set("matches", std::move(matches)); content_scripts->Append(std::move(content_script)); manifest.Set(manifest_keys::kContentScripts, std::move(content_scripts)); base::FilePath path; EXPECT_TRUE(base::PathService::Get(DIR_TEST_DATA, &path)); std::string error; scoped_refptr<Extension> extension(Extension::Create( path, Manifest::INTERNAL, manifest, Extension::NO_FLAGS, &error)); EXPECT_TRUE(extension.get()) << error; return extension; } BackgroundManifestType background_manifest_type_; scoped_refptr<ContentVerifier> content_verifier_; scoped_refptr<Extension> extension_; TestContentVerifierDelegate* content_verifier_delegate_raw_; DISALLOW_COPY_AND_ASSIGN(ContentVerifierTest); }; // Verifies that |ContentVerifier::ShouldVerifyAnyPaths| returns true for // some file paths even if those paths are specified as browser images. TEST_P(ContentVerifierTest, BrowserImagesShouldBeVerified) { std::set<base::FilePath> files_to_be_verified = { kContentScriptPath, kScriptFilePath, kHTMLFilePath, kHTMFilePath}; std::set<base::FilePath> files_not_to_be_verified{kIconPath, kUnknownTypeFilePath}; if (GetBackgroundManifestType() == BackgroundManifestType::kBackgroundScript) { files_to_be_verified.insert(kBackgroundScriptPath); files_not_to_be_verified.insert(kBackgroundPagePath); } else if (GetBackgroundManifestType() == BackgroundManifestType::kBackgroundPage) { files_to_be_verified.insert(kBackgroundPagePath); files_not_to_be_verified.insert(kBackgroundScriptPath); } else { files_not_to_be_verified.insert(kBackgroundScriptPath); files_not_to_be_verified.insert(kBackgroundPagePath); } for (const base::FilePath& path : files_to_be_verified) { EXPECT_TRUE(ShouldVerifySinglePath(path)) << "for path " << path; UpdateBrowserImagePaths(std::set<base::FilePath>{path}); EXPECT_TRUE(ShouldVerifySinglePath(path)) << "for path " << path; } for (const base::FilePath& path : files_not_to_be_verified) { EXPECT_TRUE(ShouldVerifySinglePath(path)) << "for path " << path; UpdateBrowserImagePaths(std::set<base::FilePath>{path}); EXPECT_FALSE(ShouldVerifySinglePath(path)) << "for path " << path; } } INSTANTIATE_TEST_CASE_P( All, ContentVerifierTest, testing::Values(BackgroundManifestType::kNone, BackgroundManifestType::kBackgroundScript, BackgroundManifestType::kBackgroundPage)); } // namespace extensions
2,843
4,822
<gh_stars>1000+ /* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.search.aggregations.matrix.stats; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.ScoreMode; import org.opensearch.common.lease.Releasables; import org.opensearch.common.util.BigArrays; import org.opensearch.common.util.ObjectArray; import org.opensearch.index.fielddata.NumericDoubleValues; import org.opensearch.search.MultiValueMode; import org.opensearch.search.aggregations.Aggregator; import org.opensearch.search.aggregations.InternalAggregation; import org.opensearch.search.aggregations.LeafBucketCollector; import org.opensearch.search.aggregations.LeafBucketCollectorBase; import org.opensearch.search.aggregations.metrics.MetricsAggregator; import org.opensearch.search.aggregations.support.ValuesSource; import org.opensearch.search.internal.SearchContext; import org.opensearch.search.aggregations.support.ArrayValuesSource; import java.io.IOException; import java.util.Map; /** * Metric Aggregation for computing the pearson product correlation coefficient between multiple fields **/ final class MatrixStatsAggregator extends MetricsAggregator { /** Multiple ValuesSource with field names */ private final ArrayValuesSource.NumericArrayValuesSource valuesSources; /** array of descriptive stats, per shard, needed to compute the correlation */ ObjectArray<RunningStats> stats; MatrixStatsAggregator( String name, Map<String, ValuesSource.Numeric> valuesSources, SearchContext context, Aggregator parent, MultiValueMode multiValueMode, Map<String, Object> metadata ) throws IOException { super(name, context, parent, metadata); if (valuesSources != null && !valuesSources.isEmpty()) { this.valuesSources = new ArrayValuesSource.NumericArrayValuesSource(valuesSources, multiValueMode); stats = context.bigArrays().newObjectArray(1); } else { this.valuesSources = null; } } @Override public ScoreMode scoreMode() { return (valuesSources != null && valuesSources.needsScores()) ? ScoreMode.COMPLETE : ScoreMode.COMPLETE_NO_SCORES; } @Override public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, final LeafBucketCollector sub) throws IOException { if (valuesSources == null) { return LeafBucketCollector.NO_OP_COLLECTOR; } final BigArrays bigArrays = context.bigArrays(); final NumericDoubleValues[] values = new NumericDoubleValues[valuesSources.fieldNames().length]; for (int i = 0; i < values.length; ++i) { values[i] = valuesSources.getField(i, ctx); } return new LeafBucketCollectorBase(sub, values) { final String[] fieldNames = valuesSources.fieldNames(); final double[] fieldVals = new double[fieldNames.length]; @Override public void collect(int doc, long bucket) throws IOException { // get fields if (includeDocument(doc)) { stats = bigArrays.grow(stats, bucket + 1); RunningStats stat = stats.get(bucket); // add document fields to correlation stats if (stat == null) { stat = new RunningStats(fieldNames, fieldVals); stats.set(bucket, stat); } else { stat.add(fieldNames, fieldVals); } } } /** * return a map of field names and data */ private boolean includeDocument(int doc) throws IOException { // loop over fields for (int i = 0; i < fieldVals.length; ++i) { final NumericDoubleValues doubleValues = values[i]; if (doubleValues.advanceExact(doc)) { final double value = doubleValues.doubleValue(); if (value == Double.NEGATIVE_INFINITY) { // TODO: Fix matrix stats to treat neg inf as any other value return false; } fieldVals[i] = value; } else { return false; } } return true; } }; } @Override public InternalAggregation buildAggregation(long bucket) { if (valuesSources == null || bucket >= stats.size()) { return buildEmptyAggregation(); } return new InternalMatrixStats(name, stats.size(), stats.get(bucket), null, metadata()); } @Override public InternalAggregation buildEmptyAggregation() { return new InternalMatrixStats(name, 0, null, null, metadata()); } @Override public void doClose() { Releasables.close(stats); } }
2,384
2,535
import numpy as np from opensfm import geometry def test_rotaction_from_ptr_v2(): ptr = 0.1, 0.2, 0.3 rotation = geometry.rotation_from_ptr(*ptr) assert np.allclose(ptr, geometry.ptr_from_rotation(rotation)) def test_rotaction_from_ptr_v2(): ptr = 0.1, 0.2, 0.3 rotation = geometry.rotation_from_ptr_v2(*ptr) assert np.allclose(ptr, geometry.ptr_from_rotation_v2(rotation)) def test_rotation_from_ptr_compatibility(): """Check the two implementations yield the same rotation.""" ptr = 0.1, 0.2, 0.3 assert np.allclose( geometry.rotation_from_ptr(*ptr), geometry.rotation_from_ptr_v2(*ptr) )
259
454
{ "properties": { "connectionParameters": { "api_key": { "type": "securestring", "uiDefinition": { "displayName": "API Key", "description": "Get an API Key from HrFlow.ai", "tooltip": "Provide your API Key - learn more https://developers.hrflow.ai/getting-started/authentication", "constraints": { "tabIndex": 2, "clearText": false, "required": "true" } } } }, "iconBrandColor": "#34CBE6", "capabilities": [], "publisher": "HrFlow.ai", "stackOwner":"HrFlow.ai" } }
300
1,398
#include "rpc_server.h" #include "rpc_thread_factory.h" #include "rpc_handler_registry.h" using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using boost::shared_ptr; using namespace ::confluo; using namespace ::confluo::rpc; using namespace ::utils; namespace confluo { namespace rpc { rpc_service_handler::rpc_service_handler(confluo_store *store) : handler_id_(-1), store_(store), iterator_id_(0) { } void rpc_service_handler::register_handler() { handler_id_ = rpc_handler_registry::add(); } void rpc_service_handler::deregister_handler() { rpc_handler_registry::remove(handler_id_); } int64_t rpc_service_handler::create_atomic_multilog(const std::string &name, const rpc_schema &schema, const rpc_storage_mode mode) { int64_t ret; try { ret = store_->create_atomic_multilog(name, rpc_type_conversions::convert_schema(schema), rpc_type_conversions::convert_mode(mode)); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } return ret; } void rpc_service_handler::load_atomic_multilog(rpc_atomic_multilog_info &_return, const std::string &name) { try { _return.id = store_->load_atomic_multilog(name); auto dschema = store_->get_atomic_multilog(_return.id)->get_schema().columns(); _return.schema = rpc_type_conversions::convert_schema(dschema); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::get_atomic_multilog_info(rpc_atomic_multilog_info &_return, const std::string &name) { _return.id = store_->get_atomic_multilog_id(name); auto dschema = store_->get_atomic_multilog(_return.id)->get_schema().columns(); _return.schema = rpc_type_conversions::convert_schema(dschema); } void rpc_service_handler::remove_atomic_multilog(int64_t id) { try { store_->remove_atomic_multilog(id); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::add_index(int64_t id, const std::string &field_name, const double bucket_size) { try { store_->get_atomic_multilog(id)->add_index(field_name, bucket_size); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::remove_index(int64_t id, const std::string &field_name) { try { store_->get_atomic_multilog(id)->remove_index(field_name); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::add_filter(int64_t id, const std::string &filter_name, const std::string &filter_expr) { try { store_->get_atomic_multilog(id)->add_filter(filter_name, filter_expr); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } catch (parse_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::remove_filter(int64_t id, const std::string &filter_name) { try { store_->get_atomic_multilog(id)->remove_filter(filter_name); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::add_aggregate(int64_t id, const std::string &aggregate_name, const std::string &filter_name, const std::string &aggregate_expr) { try { store_->get_atomic_multilog(id)->add_aggregate(aggregate_name, filter_name, aggregate_expr); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } catch (parse_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::remove_aggregate(int64_t id, const std::string &aggregate_name) { try { store_->get_atomic_multilog(id)->remove_aggregate(aggregate_name); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::add_trigger(int64_t id, const std::string &trigger_name, const std::string &trigger_expr) { try { store_->get_atomic_multilog(id)->install_trigger(trigger_name, trigger_expr); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } catch (parse_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::remove_trigger(int64_t id, const std::string &trigger_name) { try { store_->get_atomic_multilog(id)->remove_trigger(trigger_name); } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } void rpc_service_handler::archive(int64_t id, int64_t offset) { try { if (offset >= 0) { store_->get_atomic_multilog(id)->archive(offset); } else { store_->get_atomic_multilog(id)->archive(); } } catch (management_exception &ex) { rpc_management_exception e; e.msg = ex.what(); throw e; } } int64_t rpc_service_handler::append(int64_t id, const std::string &data) { void *buf = (char *) &data[0]; // XXX: Fix return static_cast<int64_t>(store_->get_atomic_multilog(id)->append(buf)); } int64_t rpc_service_handler::append_batch(int64_t id, const rpc_record_batch &batch) { record_batch rbatch = rpc_type_conversions::convert_batch(batch); return static_cast<int64_t>(store_->get_atomic_multilog(id)->append_batch(rbatch)); } void rpc_service_handler::read(std::string &_return, int64_t id, const int64_t offset, const int64_t nrecords) { atomic_multilog *mlog = store_->get_atomic_multilog(id); uint64_t limit; read_only_data_log_ptr ptr; mlog->read((uint64_t) offset, limit, ptr); data_ptr dptr = ptr.decode(); char *data = reinterpret_cast<char *>(dptr.get()); size_t size = std::min(static_cast<size_t>(limit - offset), static_cast<size_t>(nrecords * mlog->record_size())); _return.assign(data, size); } void rpc_service_handler::query_aggregate(std::string &_return, int64_t id, const std::string &aggregate_name, const int64_t begin_ms, const int64_t end_ms) { atomic_multilog *m = store_->get_atomic_multilog(id); _return = m->get_aggregate(aggregate_name, (uint64_t) begin_ms, (uint64_t) end_ms).to_string(); } void rpc_service_handler::adhoc_aggregate(std::string &_return, int64_t id, const std::string &aggregate_expr, const std::string &filter_expr) { atomic_multilog *m = store_->get_atomic_multilog(id); _return = m->execute_aggregate(aggregate_expr, filter_expr).to_string(); } void rpc_service_handler::adhoc_filter(rpc_iterator_handle &_return, int64_t id, const std::string &filter_expr) { bool success; rpc_iterator_id it_id = new_iterator_id(); atomic_multilog *mlog = store_->get_atomic_multilog(id); try { adhoc_entry entry(it_id, mlog->execute_filter(filter_expr)); adhoc_status ret = adhoc_.insert(std::move(entry)); success = ret.second; } catch (parse_exception &ex) { rpc_invalid_operation e; e.msg = ex.what(); throw e; } if (!success) { rpc_invalid_operation e; e.msg = "Duplicate rpc_iterator_id assigned"; throw e; } adhoc_more(_return, mlog->record_size(), it_id); } void rpc_service_handler::predef_filter(rpc_iterator_handle &_return, int64_t id, const std::string &filter_name, const int64_t begin_ms, const int64_t end_ms) { rpc_iterator_id it_id = new_iterator_id(); atomic_multilog *mlog = store_->get_atomic_multilog(id); predef_entry entry(it_id, mlog->query_filter(filter_name, (uint64_t) begin_ms, (uint64_t) end_ms)); predef_status ret = predef_.insert(std::move(entry)); if (!ret.second) { rpc_invalid_operation e; e.msg = "Duplicate rpc_iterator_id assigned"; throw e; } predef_more(_return, mlog->record_size(), it_id); } void rpc_service_handler::combined_filter(rpc_iterator_handle &_return, int64_t id, const std::string &filter_name, const std::string &filter_expr, const int64_t begin_ms, const int64_t end_ms) { bool success; rpc_iterator_id it_id = new_iterator_id(); atomic_multilog *mlog = store_->get_atomic_multilog(id); try { combined_entry entry(it_id, mlog->query_filter(filter_name, (uint64_t) begin_ms, (uint64_t) end_ms, filter_expr)); combined_status ret = combined_.insert(std::move(entry)); success = ret.second; } catch (parse_exception &ex) { rpc_invalid_operation e; e.msg = ex.what(); throw e; } if (!success) { rpc_invalid_operation e; e.msg = "Duplicate rpc_iterator_id assigned"; throw e; } combined_more(_return, mlog->record_size(), it_id); } void rpc_service_handler::alerts_by_time(rpc_iterator_handle &_return, int64_t id, const int64_t begin_ms, const int64_t end_ms) { rpc_iterator_id it_id = new_iterator_id(); atomic_multilog *mlog = store_->get_atomic_multilog(id); alerts_entry entry(it_id, mlog->get_alerts((uint64_t) begin_ms, (uint64_t) end_ms)); alerts_status ret = alerts_.insert(std::move(entry)); if (!ret.second) { rpc_invalid_operation e; e.msg = "Duplicate rpc_iterator_id assigned"; throw e; } alerts_more(_return, it_id); } void rpc_service_handler::alerts_by_trigger_and_time(rpc_iterator_handle &_return, int64_t id, const std::string &trigger_name, const int64_t begin_ms, const int64_t end_ms) { rpc_iterator_id it_id = new_iterator_id(); atomic_multilog *mlog = store_->get_atomic_multilog(id); alerts_entry entry(it_id, mlog->get_alerts((uint64_t) begin_ms, (uint64_t) end_ms, trigger_name)); alerts_status ret = alerts_.insert(std::move(entry)); if (!ret.second) { rpc_invalid_operation e; e.msg = "Duplicate rpc_iterator_id assigned"; throw e; } alerts_more(_return, it_id); } void rpc_service_handler::get_more(rpc_iterator_handle &_return, int64_t id, const rpc_iterator_descriptor &desc) { if (desc.handler_id != handler_id_) { rpc_invalid_operation ex; ex.msg = "handler_id mismatch"; throw ex; } size_t record_size = store_->get_atomic_multilog(id)->record_size(); switch (desc.type) { case rpc_iterator_type::RPC_ADHOC: { adhoc_more(_return, record_size, desc.id); break; } case rpc_iterator_type::RPC_PREDEF: { predef_more(_return, record_size, desc.id); break; } case rpc_iterator_type::RPC_COMBINED: { combined_more(_return, record_size, desc.id); break; } case rpc_iterator_type::RPC_ALERTS: { alerts_more(_return, desc.id); break; } } } int64_t rpc_service_handler::num_records(int64_t id) { return static_cast<int64_t>(store_->get_atomic_multilog(id)->num_records()); } rpc_iterator_id rpc_service_handler::new_iterator_id() { return iterator_id_++; } void rpc_service_handler::adhoc_more(rpc_iterator_handle &_return, size_t record_size, rpc_iterator_id it_id) { // Initialize iterator descriptor _return.desc.data_type = rpc_data_type::RPC_RECORD; _return.desc.handler_id = handler_id_; _return.desc.id = it_id; _return.desc.type = rpc_iterator_type::RPC_ADHOC; // Read data from iterator try { auto &res = adhoc_.at(it_id); size_t to_read = rpc_configuration_params::ITERATOR_BATCH_SIZE(); _return.data.reserve(record_size * to_read); size_t i = 0; for (; res->has_more() && i < to_read; ++i, res->advance()) { record_t rec = res->get(); _return.data.append(reinterpret_cast<const char *>(rec.data()), rec.length()); } _return.num_entries = static_cast<int32_t>(i); _return.has_more = res->has_more(); } catch (std::out_of_range &ex) { rpc_invalid_operation e; e.msg = "No such iterator"; throw e; } } void rpc_service_handler::predef_more(rpc_iterator_handle &_return, size_t record_size, rpc_iterator_id it_id) { // Initialize iterator descriptor _return.desc.data_type = rpc_data_type::RPC_RECORD; _return.desc.handler_id = handler_id_; _return.desc.id = it_id; _return.desc.type = rpc_iterator_type::RPC_PREDEF; // Read data from iterator try { auto &res = predef_.at(it_id); size_t to_read = rpc_configuration_params::ITERATOR_BATCH_SIZE(); _return.data.reserve(record_size * to_read); size_t i = 0; for (; res->has_more() && i < to_read; ++i, res->advance()) { record_t rec = res->get(); _return.data.append(reinterpret_cast<const char *>(rec.data()), rec.length()); } _return.num_entries = static_cast<int32_t>(i); _return.has_more = res->has_more(); } catch (std::out_of_range &ex) { rpc_invalid_operation e; e.msg = "No such iterator"; throw e; } } void rpc_service_handler::combined_more(rpc_iterator_handle &_return, size_t record_size, rpc_iterator_id it_id) { // Initialize iterator descriptor _return.desc.data_type = rpc_data_type::RPC_RECORD; _return.desc.handler_id = handler_id_; _return.desc.id = it_id; _return.desc.type = rpc_iterator_type::RPC_COMBINED; // Read data from iterator try { auto &res = combined_.at(it_id); size_t to_read = rpc_configuration_params::ITERATOR_BATCH_SIZE(); _return.data.reserve(record_size * to_read); size_t i = 0; for (; res->has_more() && i < to_read; ++i, res->advance()) { record_t rec = res->get(); _return.data.append(reinterpret_cast<const char *>(rec.data()), rec.length()); } _return.num_entries = static_cast<int32_t>(i); _return.has_more = res->has_more(); } catch (std::out_of_range &ex) { rpc_invalid_operation e; e.msg = "No such iterator"; throw e; } } void rpc_service_handler::alerts_more(rpc_iterator_handle &_return, rpc_iterator_id it_id) { // Initialize iterator descriptor _return.desc.data_type = rpc_data_type::RPC_ALERT; _return.desc.handler_id = handler_id_; _return.desc.id = it_id; _return.desc.type = rpc_iterator_type::RPC_ALERTS; // Read data from iterator try { auto &res = alerts_.at(it_id); size_t to_read = rpc_configuration_params::ITERATOR_BATCH_SIZE(); size_t i = 0; for (; res->has_more() && i < to_read; ++i, res->advance()) { alert a = res->get(); _return.data.append(a.to_string()); _return.data.push_back('\n'); } _return.num_entries = static_cast<int32_t>(i); _return.has_more = res->has_more(); } catch (std::out_of_range &ex) { rpc_invalid_operation e; e.msg = "No such iterator"; throw e; } } rpc_clone_factory::rpc_clone_factory(confluo_store *store) : store_(store) { } rpc_clone_factory::~rpc_clone_factory() = default; rpc_serviceIf *rpc_clone_factory::getHandler(const TConnectionInfo &conn_info) { std::shared_ptr<TSocket> sock = std::dynamic_pointer_cast<TSocket>( conn_info.transport); LOG_INFO << "Incoming connection\n" << "\t\t\tSocketInfo: " << sock->getSocketInfo() << "\n" << "\t\t\tPeerHost: " << sock->getPeerHost() << "\n" << "\t\t\tPeerAddress: " << sock->getPeerAddress() << "\n" << "\t\t\tPeerPort: " << sock->getPeerPort(); return new rpc_service_handler(store_); } void rpc_clone_factory::releaseHandler(rpc_serviceIf *handler) { delete handler; } std::shared_ptr<TServer> rpc_server::create(confluo_store *store, const std::string &address, int port, int num_workers) { LOG_INFO << "Creating rpc server with a thread pool of size = " << num_workers; std::shared_ptr<ThreadManager> thread_manager = ThreadManager::newSimpleThreadManager(num_workers); thread_manager->threadFactory(std::make_shared<rpc_thread_factory>()); thread_manager->start(); auto clone_factory = std::make_shared<rpc_clone_factory>(store); auto proc_factory = std::make_shared<rpc_serviceProcessorFactory>(clone_factory); auto sock = std::make_shared<TServerSocket>(address, port); auto t_factory = std::make_shared<TBufferedTransportFactory>(); auto p_factory = std::make_shared<TBinaryProtocolFactory>(); return std::make_shared<TThreadPoolServer>(proc_factory, sock, t_factory, p_factory, thread_manager); } } }
7,877
423
// {{{ MIT License // Copyright 2017 <NAME> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // }}} #include "gringo/graph.hh" #include "gringo/utility.hh" #include "tests/tests.hh" namespace Gringo { namespace Test { using namespace Gringo::IO; namespace { typedef Graph<std::string> G; std::ostream &operator<<(std::ostream &out, G::SCCVec const &x) { auto f = [](std::ostream &out, G::NodeVec const x) { auto f = [](std::ostream &out, G::Node const *x) { out << x->data; }; out << "["; print_comma(out, x, ",", f); out << "]"; }; out << "["; print_comma(out, x, ",", f); out << "]"; return out; } std::string to_string(G::SCCVec const &x) { std::ostringstream out; out << x; return out.str(); } G graph(std::initializer_list<std::pair<std::string, std::string>> edges) { G g; std::map<std::string, G::Node*> map; for (auto &x : edges) { auto &a = map[x.first]; if (a == nullptr) { a = &g.insertNode(x.first); } auto &b = map[x.second]; if (b == nullptr) { b = &g.insertNode(x.second); } a->insertEdge(*b); } return g; } } // namespace TEST_CASE("graph", "[base]") { SECTION("test_tarjan") { REQUIRE("[[b,c],[d],[a]]" == to_string(graph({{"a","b"},{"a","d"},{"b","c"},{"c","b"},{"d","b"}}).tarjan())); REQUIRE("[[h,i],[f,g],[d,c,b,e],[a]]" == to_string(graph({{"a","b"},{"b","c"},{"c","h"},{"c","d"},{"d","e"},{"e","f"},{"e","b"},{"e","c"},{"f","g"},{"g","f"},{"h","i"},{"i","h"}}).tarjan())); REQUIRE("[[c,d],[a,b]]" == to_string(graph({{"a","b"},{"a","c"},{"a","d"},{"b","a"},{"c","d"},{"d","c"}}).tarjan())); REQUIRE("[[i],[n],[r3],[r4,e,r1,p,r2,s]]" == to_string(graph({{"r1","e"},{"r2","p"},{"r2","i"},{"r3","n"},{"r3","i"},{"r4","s"},{"p","r1"},{"s","r2"},{"s","r3"},{"e","r4"}}).tarjan())); G g{graph({{"a","b"},{"a","d"},{"b","c"},{"c","b"},{"d","b"}})}; REQUIRE("[[b,c],[d],[a]]" == to_string(g.tarjan())); REQUIRE("[[b,c],[d],[a]]" == to_string(g.tarjan())); REQUIRE("[[b,c],[d],[a]]" == to_string(g.tarjan())); } } } } // namespace Test Gringo
1,276
2,112
<reponame>laohubuzaijia/fbthrift<gh_stars>1000+ /* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/protocol/JSONProtocolCommon.h> #include <type_traits> #include <fmt/core.h> namespace { class WrappedIOBufQueueAppender { public: explicit WrappedIOBufQueueAppender(folly::io::QueueAppender& out) : out_(out) {} void append(const char* s, const size_t n) { if (n == 0) return; out_.push(reinterpret_cast<const uint8_t*>(CHECK_NOTNULL(s)), n); length_ += n; } void push_back(const char c) { append(&c, 1); } WrappedIOBufQueueAppender& operator+=(const char c) { push_back(c); return *this; } size_t size() const { return length_; } private: folly::io::QueueAppender& out_; size_t length_ = 0; }; } // namespace namespace folly { template <> struct IsSomeString<WrappedIOBufQueueAppender> : std::true_type {}; } // namespace folly namespace apache { namespace thrift { // This table describes the handling for the first 0x30 characters // 0 : escape using "\u00xx" notation // 1 : just output index // <other> : escape using "\<other>" notation const uint8_t JSONProtocolWriterCommon::kJSONCharTable[0x30] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 1, 1, '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 }; // The elements of this array must match up with the sequence of characters in // kEscapeChars const uint8_t JSONProtocolReaderCommon::kEscapeCharVals[8] = { '"', '\\', '/', '\b', '\f', '\n', '\r', '\t', }; uint32_t JSONProtocolWriterCommon::writeJSONDoubleInternal(double dbl) { WrappedIOBufQueueAppender appender(out_); folly::toAppend(dbl, &appender); return appender.size(); } uint32_t JSONProtocolWriterCommon::writeJSONDoubleInternal(float flt) { WrappedIOBufQueueAppender appender(out_); folly::toAppend( flt, &appender, double_conversion::DoubleToStringConverter::SHORTEST_SINGLE, 0); return appender.size(); } uint32_t JSONProtocolWriterCommon::writeJSONIntInternal(int64_t num) { WrappedIOBufQueueAppender appender(out_); if (!context.empty() && context.back().type == ContextType::MAP && context.back().meta % 2 == 1) { folly::toAppend('"', num, '"', &appender); } else { folly::toAppend(num, &appender); } return appender.size(); } static inline folly::StringPiece sp(char const& ch) { return {&ch, 1}; } [[noreturn]] void JSONProtocolReaderCommon::throwBadVersion() { throw TProtocolException( TProtocolException::BAD_VERSION, "Message contained bad version."); } [[noreturn]] void JSONProtocolReaderCommon::throwUnrecognizableAsBoolean( std::string const& s) { throw TProtocolException( TProtocolException::INVALID_DATA, s + " is not a valid bool"); } [[noreturn]] void JSONProtocolReaderCommon::throwUnrecognizableAsIntegral( folly::StringPiece s, folly::StringPiece typeName) { throw TProtocolException( TProtocolException::INVALID_DATA, folly::to<std::string>(s, " is not a valid ", typeName)); } [[noreturn]] void JSONProtocolReaderCommon::throwUnrecognizableAsFloatingPoint( std::string const& s) { throw TProtocolException( TProtocolException::INVALID_DATA, s + " is not a valid float/double"); } [[noreturn]] void JSONProtocolReaderCommon::throwUnrecognizableAsString( std::string const& s, std::exception const& e) { throw TProtocolException( TProtocolException::INVALID_DATA, s + " is not a valid JSON string: " + e.what()); } [[noreturn]] void JSONProtocolReaderCommon::throwUnrecognizableAsAny( std::string const& s) { throw TProtocolException( TProtocolException::INVALID_DATA, s + " is not valid JSON"); } [[noreturn]] void JSONProtocolReaderCommon::throwInvalidFieldStart( char const ch) { throw TProtocolException( TProtocolException::INVALID_DATA, std::string(1, ch) + " is not a valid start to a JSON field"); } [[noreturn]] void JSONProtocolReaderCommon::throwUnexpectedChar( char const ch, char const expected) { auto const msg = fmt::format( "expected '{0}' (hex {0:#02x}), read '{1}' (hex {1:#02x})", expected, ch); throw TProtocolException(TProtocolException::INVALID_DATA, msg); } [[noreturn]] void JSONProtocolReaderCommon::throwInvalidEscapeChar( char const ch) { throw TProtocolException( TProtocolException::INVALID_DATA, folly::to<std::string>("Expected control char, got '", sp(ch), "'.")); } [[noreturn]] void JSONProtocolReaderCommon::throwInvalidHexChar(char const ch) { throw TProtocolException( TProtocolException::INVALID_DATA, folly::to<std::string>( "Expected hex val ([0-9a-f]); got \'", sp(ch), "\'.")); } } // namespace thrift } // namespace apache
2,061
563
package com.gentics.mesh.search.index.tagfamily; import static com.gentics.mesh.search.index.MappingHelper.KEYWORD; import static com.gentics.mesh.search.index.MappingHelper.NAME_KEY; import static com.gentics.mesh.search.index.MappingHelper.OBJECT; import static com.gentics.mesh.search.index.MappingHelper.notAnalyzedType; import static com.gentics.mesh.search.index.MappingHelper.trigramTextType; import javax.inject.Inject; import javax.inject.Singleton; import com.gentics.mesh.etc.config.MeshOptions; import com.gentics.mesh.search.index.AbstractMappingProvider; import io.vertx.core.json.JsonObject; /** * Class which will generate the needed mapping for the tag family index. */ @Singleton public class TagFamilyMappingProvider extends AbstractMappingProvider { @Inject public TagFamilyMappingProvider(MeshOptions options) { super(options); } @Override public JsonObject getMappingProperties() { JsonObject props = new JsonObject(); props.put(NAME_KEY, trigramTextType()); // TODO tags // project JsonObject projectMapping = new JsonObject(); projectMapping.put("type", OBJECT); JsonObject projectMappingProps = new JsonObject(); projectMappingProps.put("name", trigramTextType()); projectMappingProps.put("uuid", notAnalyzedType(KEYWORD)); projectMapping.put("properties", projectMappingProps); props.put("project", projectMapping); return props; } }
468
6,215
/* * Copyright (c) 2021 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.source.postgres; import com.fasterxml.jackson.databind.JsonNode; import java.util.Properties; public class PostgresCdcProperties { static Properties getDebeziumProperties(final JsonNode config) { final Properties props = new Properties(); props.setProperty("plugin.name", PostgresUtils.getPluginValue(config.get("replication_method"))); props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); props.setProperty("snapshot.mode", "exported"); props.setProperty("slot.name", config.get("replication_method").get("replication_slot").asText()); props.setProperty("publication.name", config.get("replication_method").get("publication").asText()); props.setProperty("publication.autocreate.mode", "disabled"); return props; } }
286
1,702
<reponame>mhalbritter/spring-native /* * Copyright 2019-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.context.annotation; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase; import org.springframework.lang.Nullable; /** * Provide a complete state of the condition evaluation of a component. * * @author <NAME> */ public class ConditionEvaluationState { private final Conditions conditions; private final Map<ConfigurationPhase, ConditionEvaluation> recordedEvaluations = new LinkedHashMap<>(); ConditionEvaluationState(Conditions conditions) { this.conditions = conditions; } /** * Record the {@link ConditionEvaluation} for the specified {@link ConfigurationPhase phase}. * @param requiredPhase the required phase * @param conditionEvaluation the evaluation for that phase * @throws IllegalStateException if an evaluation already exists for that phase */ void recordConditionEvaluation(ConfigurationPhase requiredPhase, ConditionEvaluation conditionEvaluation) { ConditionEvaluation existing = this.recordedEvaluations.putIfAbsent(requiredPhase, conditionEvaluation); if (existing != null) { throw new IllegalStateException("Conditions evaluation for phase " + requiredPhase + " already recorded."); } } /** * Return the {@link Conditions conditions} of this instance * @return the conditions */ public Conditions getConditions() { return this.conditions; } /** * Return the {@link ConditionEvaluation} for the specified {@link ConfigurationPhase phase}. * @param phase the configuration phase of interest * @return the evaluation, or {@code null} if the evaluation for that phase has not been recorded yet */ @Nullable public ConditionEvaluation getConditionEvaluation(ConfigurationPhase phase) { return this.recordedEvaluations.get(phase); } }
662
410
{ "index": "What is considered the theme?", "breakpoints": "Breakpoints", "colors": "Colors", "space": "Space", "generator": "Generator" }
53
5,169
<filename>Specs/TomDoeTestLibrary/0.1.2/TomDoeTestLibrary.podspec.json { "name": "TomDoeTestLibrary", "version": "0.1.2", "summary": "A simple framework that does absolutly nothing.", "description": "This is just an attempt of creating a cocoapod. It does nothing and never will. Don't waist your time here", "homepage": "https://github.com/yotam-supersonic/TomDoeTestLibrary", "license": "MIT", "authors": { "yotam-supersonic": "<EMAIL>" }, "source": { "git": "https://github.com/yotam-supersonic/TomDoeTestLibrary.git", "tag": "0.1.2" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "resource_bundles": { "TomDoeTestLibrary": [ "Pod/Assets/*.png" ] } }
312
494
/******************************************************************************* * Copyright 2018 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shaded.org.apache.cassandra.db.marshal; import com.netflix.astyanax.shaded.org.apache.cassandra.exceptions.ConfigurationException; import com.netflix.astyanax.shaded.org.apache.cassandra.exceptions.SyntaxException; import com.netflix.astyanax.shaded.org.apache.cassandra.utils.FBUtilities; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** * Extend {@link TypeParser} to support shaded {@link AbstractType} from shaded package. * * This implementation uses some ugly reflection because {@link TypeParser#parse(String)} was apparently never meant * to be overridden -- too many references to private fields (e.g. {@link TypeParser#idx}, etc.) and private methods * ({@link TypeParser#getAbstractType}, etc.) which a derived method can't access. This ugliness could have been * avoided if TypeParser hadn't tried to restrict extension by setting everything private instead of protected. */ public class ShadedTypeParser extends TypeParser { private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(ShadedTypeParser.class); public static final String SHADED_PREFIX = "com.netflix.astyanax.shaded."; protected static TypeParser EMPTY_PARSER; static { try { EMPTY_PARSER = new ShadedTypeParser(""); } catch (ConfigurationException e) { Logger.error("ShadedTypeParser failed to create EMPTY_PARSER; message=" + e.getMessage(), e); } } /******************************************************************************************************************* * Begin ugly reflection required to work around TypeParser's lack of design for extension: ******************************************************************************************************************/ protected static Field strField; protected static Field idxField; protected static Field cacheField; protected static Map<String, AbstractType<?>> cache; protected static Method skipBlankMethod; protected static Method skipBlankMethod2; protected static Method isEOSMethod; protected static Method isEOSMethod2; protected static Method isIdentifierCharMethod; protected static void init() throws ConfigurationException { try { strField = ShadedTypeParser.class.getSuperclass().getDeclaredField("str"); strField.setAccessible(true); idxField = ShadedTypeParser.class.getSuperclass().getDeclaredField("idx"); idxField.setAccessible(true); cacheField = ShadedTypeParser.class.getSuperclass().getDeclaredField("cache"); cacheField.setAccessible(true); cache = (Map<String, AbstractType<?>>)cacheField.get(null); skipBlankMethod = ShadedTypeParser.class.getSuperclass().getDeclaredMethod("skipBlank"); skipBlankMethod.setAccessible(true); skipBlankMethod2 = ShadedTypeParser.class.getSuperclass().getDeclaredMethod("skipBlank", String.class, int.class); skipBlankMethod2.setAccessible(true); isEOSMethod = ShadedTypeParser.class.getSuperclass().getDeclaredMethod("isEOS"); isEOSMethod.setAccessible(true); isEOSMethod2 = ShadedTypeParser.class.getSuperclass().getDeclaredMethod("isEOS", String.class, int.class); isEOSMethod2.setAccessible(true); isIdentifierCharMethod = ShadedTypeParser.class.getSuperclass().getDeclaredMethod("isIdentifierChar", int.class); isIdentifierCharMethod.setAccessible(true); } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) { throw new ConfigurationException( "ShadedTypeParser init() failed for reflection; message=" + e.getMessage(), e); } } protected String getStr() throws IllegalAccessException { return (String)strField.get(this); } protected int getIdx() throws IllegalAccessException { return idxField.getInt(this); } protected void setIdx(int idx) throws IllegalAccessException { idxField.setInt(this, idx); } protected void skipBlank() throws InvocationTargetException, IllegalAccessException { skipBlankMethod.invoke(this); } protected static int skipBlank(String str, int i) throws InvocationTargetException, IllegalAccessException { return (Integer)skipBlankMethod2.invoke(null, str, i); } protected boolean isEOS() throws InvocationTargetException, IllegalAccessException { return (Boolean)isEOSMethod.invoke(this); } protected static boolean isEOS(String str, int i) throws InvocationTargetException, IllegalAccessException { return (Boolean)isEOSMethod2.invoke(null, str, i); } private static boolean isIdentifierChar(int c) throws InvocationTargetException, IllegalAccessException { return (Boolean)isIdentifierCharMethod.invoke(null, c); } protected static Method getRawAbstractTypeMethod(Class typeClass) throws NoSuchMethodException { return ShadedTypeParser.class.getSuperclass().getDeclaredMethod("getRawAbstractType", typeClass, EMPTY_PARSER.getClass()); } /******************************************************************************************************************* * End ugly reflection required to work around TypeParser's lack of design for extension ******************************************************************************************************************/ public static ShadedTypeParser buildTypeParser(String str, int idx) throws ConfigurationException { return new ShadedTypeParser(str, idx); } public ShadedTypeParser(String str) throws ConfigurationException { this(str, 0); } public ShadedTypeParser(String str, int idx) throws ConfigurationException { super(str); init(); try { setIdx(idx); } catch (IllegalAccessException e) { throw new ConfigurationException( "ShadedTypeParser constructor failed for reflection; message=" + e.getMessage(), e); } } public static String getShadedClassName(String className){ if(className.startsWith(SHADED_PREFIX)){ return className; } else if (className.contains(".")){ return SHADED_PREFIX + className; } else { return SHADED_PREFIX + "org.apache.cassandra.db.marshal." + className; } } public static String getShadedTypeName(String typeName){ if ( typeName.startsWith( "org.apache.cassandra.db.marshal." ) ) { return typeName.substring( "org.apache.cassandra.db.marshal.".length() ); } else if ( typeName.startsWith( SHADED_PREFIX + "org.apache.cassandra.db.marshal." ) ) { return typeName.substring( (SHADED_PREFIX + "org.apache.cassandra.db.marshal.").length() ); } return typeName; } /******************************************************************************************************************* * Begin methods very slightly modified from {@link TypeParser} to support shaded classes ******************************************************************************************************************/ public static AbstractType<?> parse(String str) throws SyntaxException, ConfigurationException { try{ if (str == null) { return BytesType.instance; } else { str = getShadedClassName(str); AbstractType<?> type = null; type = (AbstractType) cache.get(str); if (type != null) { return type; } else { int i = 0; i = skipBlank(str, i); int j; for (j = i; !isEOS(str, i) && isIdentifierChar(str.charAt(i)); ++i) { ; } if (i == j) { return BytesType.instance; } else { String name = str.substring(j, i); name = getShadedClassName(name); i = skipBlank(str, i); if (!isEOS(str, i) && str.charAt(i) == '(') { ShadedTypeParser typeParser = buildTypeParser(str, i); type = getAbstractType(name, typeParser); } else { type = getAbstractType(name); } cache.put(str, type); return type; } } } } catch (IllegalAccessException | InvocationTargetException e) { throw new ConfigurationException( "ShadedTypeParser parse(String) failed for reflection; message=" + e.getMessage(), e); } } public AbstractType<?> parse() throws SyntaxException, ConfigurationException { try { skipBlank(); String name = this.readNextIdentifier(); name = getShadedClassName(name); skipBlank(); return !isEOS() && this.getStr().charAt(getIdx()) == '(' ? getAbstractType(name, this) : getAbstractType(name); } catch (IllegalAccessException | InvocationTargetException e) { throw new ConfigurationException( "ShadedTypeParser parse() failed for reflection; message=" + e.getMessage(), e); } } protected static AbstractType<?> getAbstractType(String compareWith) throws ConfigurationException { String className = getShadedClassName(compareWith); Class typeClass = FBUtilities.classForName(className, "abstract-type"); try { Field field = typeClass.getDeclaredField("instance"); return (AbstractType)field.get((Object)null); } catch (NoSuchFieldException | IllegalAccessException var4) { try { Method getRawAbstractTypeMethod = getRawAbstractTypeMethod(typeClass); return (AbstractType<?>) getRawAbstractTypeMethod.invoke(null, typeClass, EMPTY_PARSER); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new ConfigurationException( "ShadedTypeParser getAbstractType failed for reflection; message=" + e.getMessage(), e); } } } protected static AbstractType<?> getAbstractType(String compareWith, TypeParser parser) throws SyntaxException, ConfigurationException { String className = getShadedClassName(compareWith); Class typeClass = FBUtilities.classForName(className, "abstract-type"); AbstractType type; try { Method method = typeClass.getDeclaredMethod("getInstance", TypeParser.class); return (AbstractType)method.invoke((Object)null, parser); } catch (NoSuchMethodException | IllegalAccessException var6) { try { Method getRawAbstractTypeMethod = getRawAbstractTypeMethod(typeClass); type = (AbstractType<?>) getRawAbstractTypeMethod.invoke(null, typeClass); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new ConfigurationException( "ShadedTypeParser getAbstractType() failed for reflection; message=" + e.getMessage(), e); } return AbstractType.parseDefaultParameters(type, parser); } catch (InvocationTargetException var8) { ConfigurationException ex = new ConfigurationException("Invalid definition for comparator " + typeClass.getName() + "."); ex.initCause(var8.getTargetException()); throw ex; } } /******************************************************************************************************************* * End methods copy-pasted from {@link TypeParser} and modified slightly to to work with shaded classes ******************************************************************************************************************/ }
4,833
743
{ "DATA_SOURCE_QUICKCONNECT" : { "NAME" : "QuickConnect" }, "QUICKCONNECT" : { "ACTION_CONNECT" : "Connecta’t", "ERROR_INVALID_URI" : "Especificació URI no vàlida", "ERROR_NO_HOST" : "No s'ha especificat l'amfitrió", "ERROR_NO_PROTOCOL" : "No s'ha especificat protocol", "ERROR_NOT_ABSOLUTE_URI" : "L'URI no és absolut", "FIELD_PLACEHOLDER_URI" : "Introduïu l'URI de connexió" } }
283
2,338
<reponame>mkinsner/llvm //===- ForceFunctionAttrs.cpp - Force function attrs for debugging --------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/InitializePasses.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "forceattrs" static cl::list<std::string> ForceAttributes("force-attribute", cl::Hidden, cl::desc("Add an attribute to a function. This should be a " "pair of 'function-name:attribute-name', for " "example -force-attribute=foo:noinline. This " "option can be specified multiple times.")); static cl::list<std::string> ForceRemoveAttributes( "force-remove-attribute", cl::Hidden, cl::desc("Remove an attribute from a function. This should be a " "pair of 'function-name:attribute-name', for " "example -force-remove-attribute=foo:noinline. This " "option can be specified multiple times.")); /// If F has any forced attributes given on the command line, add them. /// If F has any forced remove attributes given on the command line, remove /// them. When both force and force-remove are given to a function, the latter /// takes precedence. static void forceAttributes(Function &F) { auto ParseFunctionAndAttr = [&](StringRef S) { auto Kind = Attribute::None; auto KV = StringRef(S).split(':'); if (KV.first != F.getName()) return Kind; Kind = Attribute::getAttrKindFromName(KV.second); if (Kind == Attribute::None || !Attribute::canUseAsFnAttr(Kind)) { LLVM_DEBUG(dbgs() << "ForcedAttribute: " << KV.second << " unknown or not a function attribute!\n"); } return Kind; }; for (const auto &S : ForceAttributes) { auto Kind = ParseFunctionAndAttr(S); if (Kind == Attribute::None || F.hasFnAttribute(Kind)) continue; F.addFnAttr(Kind); } for (const auto &S : ForceRemoveAttributes) { auto Kind = ParseFunctionAndAttr(S); if (Kind == Attribute::None || !F.hasFnAttribute(Kind)) continue; F.removeFnAttr(Kind); } } static bool hasForceAttributes() { return !ForceAttributes.empty() || !ForceRemoveAttributes.empty(); } PreservedAnalyses ForceFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &) { if (!hasForceAttributes()) return PreservedAnalyses::all(); for (Function &F : M.functions()) forceAttributes(F); // Just conservatively invalidate analyses, this isn't likely to be important. return PreservedAnalyses::none(); } namespace { struct ForceFunctionAttrsLegacyPass : public ModulePass { static char ID; // Pass identification, replacement for typeid ForceFunctionAttrsLegacyPass() : ModulePass(ID) { initializeForceFunctionAttrsLegacyPassPass( *PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override { if (!hasForceAttributes()) return false; for (Function &F : M.functions()) forceAttributes(F); // Conservatively assume we changed something. return true; } }; } char ForceFunctionAttrsLegacyPass::ID = 0; INITIALIZE_PASS(ForceFunctionAttrsLegacyPass, "forceattrs", "Force set function attributes", false, false) Pass *llvm::createForceFunctionAttrsLegacyPass() { return new ForceFunctionAttrsLegacyPass(); }
1,410
458
<reponame>freebird-airlines/WhirlyGlobe package com.mousebird.maply; /** * A wrapper around the Proj4 general scheme for coordinate systems. * You set this up with a string that Proj4 recognizes and it will pass that directly through and * use it. * */ public class Proj4CoordSystem extends CoordSystem { /** * Construct with the proj4 string that defines your projection. */ public Proj4CoordSystem(String str) { initialise(str); } static { nativeInit(); } private static native void nativeInit(); native void initialise(String str); }
207
1,738
""" Contains information about the dateutil version. """ VERSION_MAJOR = 2 VERSION_MINOR = 6 VERSION_PATCH = 1 VERSION_TUPLE = (VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH) VERSION = '.'.join(map(str, VERSION_TUPLE))
83
26,127
package com.chad.baserecyclerviewadapterhelper.entity; /** * Created by luoxiongwen on 16/10/24. */ public class Movie { public String name; public int length; public int price; public String content; public Movie(String name, int length, int price, String content) { this.length = length; this.name = name; this.price = price; this.content=content; } }
162
435
<gh_stars>100-1000 /** * @file sgd.h * @brief The interface for a stochastic gradient descent solver * */ #pragma once #include "ps.h" #include "util/producer_consumer.h" #include "learner/proto/sgd.pb.h" #include "system/monitor.h" #include "system/assigner.h" #include "data/stream_reader.h" #include "util/localizer.h" #include "filter/frequency_filter.h" #include "learner/workload_pool.h" namespace PS { /** * @brief The base class of a scheduler node */ class ISGDScheduler : public App { public: ISGDScheduler() : App() { } virtual ~ISGDScheduler(); virtual void Run(); virtual void ProcessResponse(Message* response); virtual void ProcessRequest(Message* request); protected: // print the progress virtual void ShowProgress( double time, std::unordered_map<NodeID, SGDProgress>* progress); // merge the progress report from a computation node virtual void MergeProgress(const SGDProgress& src, SGDProgress* dst); void SendWorkload(const NodeID& recver); MonitorMaster<SGDProgress> monitor_; WorkloadPool *workload_pool_ = nullptr; // display size_t num_ex_processed_ = 0; bool show_prog_head_ = true; }; /** * @brief The base class of a computation node */ class ISGDCompNode : public App { public: ISGDCompNode() : App(), reporter_(SchedulerID()) { } virtual ~ISGDCompNode() { } protected: MonitorSlaver<SGDProgress> reporter_; }; /** * @brief A multithread minibatch reader * @tparam V the value type */ template <typename V> class MinibatchReader { public: MinibatchReader() { } ~MinibatchReader() { } /** * @brief set the text reader * * @param file data file * @param minibatch_size # of examples * @param data_buf in MB */ void InitReader(const DataConfig& file, int minibatch_size, int data_buf = 1000) { reader_.init(file); minibatch_size_ = minibatch_size; data_prefetcher_.setCapacity(data_buf); } /** * @brief tails features are filtered by the countmin sketch * * @param n countmin sketch parameter * @param k countmin sketch parameter * @param freq frequency threshold */ void InitFilter(size_t n, int k, int freq) { filter_.Resize(n, k); key_freq_ = freq; } /** * @brief Start the reader thread */ void Start() { data_prefetcher_.startProducer( [this](MatrixPtrList<V>* data, size_t* size)->bool { bool ret = reader_.readMatrices(minibatch_size_, data); for (const auto& mat : *data) { *size += mat->memSize(); } return ret; }); } /** * @brief Reads a minibatch * * @param Y the *minibatch_size* x 1 label vector * @param X the *minibatch_size* x p data matrix, all features are remapped to * continues id starting from 0 to p-1 * @param key p length array contains the original feature id in the data * * @return false if end of file */ bool Read(MatrixPtr<V>& Y, MatrixPtr<V>& X, SArray<Key>& key) { MatrixPtrList<V> data; if (!data_prefetcher_.pop(&data)) return false; CHECK_EQ(data.size(), 2); Y = data[0]; // localizer SArray<Key> uniq_key; SArray<uint8> key_cnt; Localizer<Key, V> localizer; localizer.CountUniqIndex(data[1], &uniq_key, &key_cnt); // filter keys filter_.InsertKeys(uniq_key, key_cnt); key = filter_.QueryKeys(uniq_key, key_freq_); // remap keys X = localizer.RemapIndex(key); return true; } private: int minibatch_size_ = 1000; StreamReader<V> reader_; FreqencyFilter<Key, uint8> filter_; int key_freq_ = 0; ProducerConsumer<MatrixPtrList<V>> data_prefetcher_; }; } // namespace PS
1,384
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.extexecution.base; import java.io.IOException; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.extexecution.base.Environment; import org.openide.util.Lookup; /** * The interface representing the implementation * of {@link org.netbeans.api.extexecution.base.ProcessBuilder}. * * @see org.netbeans.api.extexecution.base.ProcessBuilder * @author <NAME> */ public interface ProcessBuilderImplementation extends Lookup.Provider { /** * Returns the object for environment variables manipulation. * * @return the object for environment variables manipulation */ @NonNull Environment getEnvironment(); /** * Provides an extension point to the implementors. One may enhance the * functionality of {@link org.netbeans.api.extexecution.base.ProcessBuilder} * by this as the content of the {@link Lookup} is included in * {@link org.netbeans.api.extexecution.base.ProcessBuilder#getLookup()} * * @return a lookup providing an extension point */ @Override Lookup getLookup(); /** * Creates a process using the specified parameters. * <p> * The environment variables stored in parameters are acquired by call to * {@link Environment#values()}. So if the implementation does not aim to be * or can't be thread safe it may check or use the {@link Environment} * directly. * * @param parameters the instance describing the process parameters * @return a process created with specified parameters * @throws IOException if the process could not be created */ @NonNull Process createProcess(@NonNull ProcessParameters parameters) throws IOException; }
742
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "DrawDocShell.hxx" #include <tools/pstm.hxx> #include <vcl/svapp.hxx> #include <sfx2/docfac.hxx> #include <sfx2/objface.hxx> #ifndef _SVXIDS_HRC #include <svx/svxids.hrc> #endif #include <svl/srchitem.hxx> #include <svx/srchdlg.hxx> #include <editeng/flstitem.hxx> #include <svl/eitem.hxx> #include <svl/intitem.hxx> #include <sfx2/printer.hxx> #ifndef _SFX_DOCFILE_HXX //autogen #include <sfx2/docfile.hxx> #endif #include <svx/drawitem.hxx> #include <editeng/flstitem.hxx> #include <svx/drawitem.hxx> #include <svx/srchdlg.hxx> #include <sfx2/dispatch.hxx> #include <svl/whiter.hxx> #include <svl/itempool.hxx> #include <svtools/ctrltool.hxx> #include <svtools/filter.hxx> #ifndef _SO_CLSIDS_HXX #include <sot/clsids.hxx> #endif #include <svl/cjkoptions.hxx> #include <svl/visitem.hxx> #include <svx/svdoutl.hxx> #include <sfx2/fcontnr.hxx> #include "app.hrc" #include "app.hxx" #include "strmname.h" #include "stlpool.hxx" #include "strings.hrc" #include "View.hxx" #include "drawdoc.hxx" #include "sdpage.hxx" #include "glob.hrc" #include "res_bmp.hrc" #include "fupoor.hxx" #include "fusearch.hxx" #include "ViewShell.hxx" #include "sdresid.hxx" #ifndef SD_FU_SLIDE_SHOW_DLG_HXX #include "slideshow.hxx" #endif #include "drawview.hxx" #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #include "unomodel.hxx" #include "undo/undomanager.hxx" #include "undo/undofactory.hxx" #include "OutlineView.hxx" #include "ViewShellBase.hxx" using namespace sd; #define DrawDocShell #include "sdslots.hxx" SFX_IMPL_INTERFACE(DrawDocShell, SfxObjectShell, SdResId(0)) { SFX_CHILDWINDOW_REGISTRATION(SvxSearchDialogWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_INSERT); } namespace sd { #define POOL_BUFFER_SIZE (sal_uInt16)32768 #define BASIC_BUFFER_SIZE (sal_uInt16)8192 #define DOCUMENT_BUFFER_SIZE (sal_uInt16)32768 GraphicFilter* GetGrfFilter(); /************************************************************************* |* |* SFX-Slotmaps und -Definitionen |* \************************************************************************/ TYPEINIT1( DrawDocShell, SfxObjectShell ); SFX_IMPL_OBJECTFACTORY( DrawDocShell, SvGlobalName(SO3_SIMPRESS_CLASSID), SFXOBJECTSHELL_STD_NORMAL, "simpress" ) /************************************************************************* |* |* Construct |* \************************************************************************/ void DrawDocShell::Construct( bool bClipboard ) { mbInDestruction = sal_False; SetSlotFilter(); // setzt Filter zurueck mbOwnDocument = mpDoc == 0; if( mbOwnDocument ) mpDoc = new SdDrawDocument(meDocType, this); // The document has been created so we can call UpdateRefDevice() to set // the document's ref device. UpdateRefDevice(); SetBaseModel( new SdXImpressDocument( this, bClipboard ) ); SetPool( &mpDoc->GetItemPool() ); mpUndoManager = new sd::UndoManager; mpDoc->SetSdrUndoManager( mpUndoManager ); mpDoc->SetSdrUndoFactory( new sd::UndoFactory ); UpdateTablePointers(); SetStyleFamily(5); //CL: eigentlich SFX_STYLE_FAMILY_PSEUDO } /************************************************************************* |* |* Konstruktor 1 |* \************************************************************************/ DrawDocShell::DrawDocShell(SfxObjectCreateMode eMode, sal_Bool bDataObject, DocumentType eDocumentType) : SfxObjectShell( eMode == SFX_CREATE_MODE_INTERNAL ? SFX_CREATE_MODE_EMBEDDED : eMode), mpDoc(NULL), mpUndoManager(NULL), mpPrinter(NULL), mpViewShell(NULL), mpFontList(NULL), meDocType(eDocumentType), mpFilterSIDs(0), mbSdDataObj(bDataObject), mbOwnPrinter(sal_False), mbNewDocument( sal_True ) { Construct( eMode == SFX_CREATE_MODE_INTERNAL ); } /************************************************************************* |* |* Konstruktor 2 |* \************************************************************************/ DrawDocShell::DrawDocShell( const sal_uInt64 nModelCreationFlags, sal_Bool bDataObject, DocumentType eDocumentType ) : SfxObjectShell( nModelCreationFlags ), mpDoc(NULL), mpUndoManager(NULL), mpPrinter(NULL), mpViewShell(NULL), mpFontList(NULL), meDocType(eDocumentType), mpFilterSIDs(0), mbSdDataObj(bDataObject), mbOwnPrinter(sal_False), mbNewDocument( sal_True ) { Construct( sal_False ); } /************************************************************************* |* |* Konstruktor 3 |* \************************************************************************/ DrawDocShell::DrawDocShell(SdDrawDocument* pDoc, SfxObjectCreateMode eMode, sal_Bool bDataObject, DocumentType eDocumentType) : SfxObjectShell(eMode == SFX_CREATE_MODE_INTERNAL ? SFX_CREATE_MODE_EMBEDDED : eMode), mpDoc(pDoc), mpUndoManager(NULL), mpPrinter(NULL), mpViewShell(NULL), mpFontList(NULL), meDocType(eDocumentType), mpFilterSIDs(0), mbSdDataObj(bDataObject), mbOwnPrinter(sal_False), mbNewDocument( sal_True ) { Construct( eMode == SFX_CREATE_MODE_INTERNAL ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ DrawDocShell::~DrawDocShell() { // Tell all listeners that the doc shell is about to be // destroyed. This has been introduced for the PreviewRenderer to // free its view (that uses the item poll of the doc shell) but // may be useful in other places as well. Broadcast(SfxSimpleHint(SFX_HINT_DYING)); mbInDestruction = sal_True; SetDocShellFunction(0); delete mpFontList; if( mpDoc ) mpDoc->SetSdrUndoManager( 0 ); delete mpUndoManager; if (mbOwnPrinter) delete mpPrinter; if( mbOwnDocument ) delete mpDoc; // damit der Navigator das Verschwinden des Dokuments mitbekommt SfxBoolItem aItem(SID_NAVIGATOR_INIT, sal_True); SfxViewFrame* pFrame = mpViewShell ? mpViewShell->GetFrame() : GetFrame(); if( !pFrame ) pFrame = SfxViewFrame::GetFirst( this ); if( pFrame ) pFrame->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L); } /************************************************************************* |* |* Slot-Stati setzen |* \************************************************************************/ void DrawDocShell::GetState(SfxItemSet &rSet) { SfxWhichIter aIter( rSet ); sal_uInt16 nWhich = aIter.FirstWhich(); while ( nWhich ) { sal_uInt16 nSlotId = SfxItemPool::IsWhich(nWhich) ? GetPool().GetSlotId(nWhich) : nWhich; switch ( nSlotId ) { case SID_SEARCH_ITEM: { rSet.Put( *SD_MOD()->GetSearchItem() ); } break; case SID_CLOSEDOC: { sal_Bool bDisabled = sal_False; if (bDisabled) { rSet.DisableItem(SID_CLOSEDOC); } else { GetSlotState(SID_CLOSEDOC, SfxObjectShell::GetInterface(), &rSet); } } break; case SID_SEARCH_OPTIONS: { sal_uInt16 nOpt = SEARCH_OPTIONS_SEARCH | SEARCH_OPTIONS_WHOLE_WORDS | SEARCH_OPTIONS_BACKWARDS | SEARCH_OPTIONS_REG_EXP | SEARCH_OPTIONS_EXACT | SEARCH_OPTIONS_SIMILARITY | SEARCH_OPTIONS_SELECTION; if (!IsReadOnly()) { nOpt |= SEARCH_OPTIONS_REPLACE; nOpt |= SEARCH_OPTIONS_REPLACE_ALL; } rSet.Put(SfxUInt16Item(nWhich, nOpt)); } break; case SID_VERSION: { GetSlotState( SID_VERSION, SfxObjectShell::GetInterface(), &rSet ); } break; case SID_CHINESE_CONVERSION: case SID_HANGUL_HANJA_CONVERSION: { rSet.Put(SfxVisibilityItem(nWhich, SvtCJKOptions().IsAnyEnabled())); } break; default: break; } nWhich = aIter.NextWhich(); } SfxViewFrame* pFrame = SfxViewFrame::Current(); if (pFrame) { if (rSet.GetItemState(SID_RELOAD) != SFX_ITEM_UNKNOWN) { pFrame->GetSlotState(SID_RELOAD, pFrame->GetInterface(), &rSet); } } } void DrawDocShell::InPlaceActivate( sal_Bool bActive ) { if( !bActive ) { FrameView* pFrameView = NULL; List* pFrameViewList = mpDoc->GetFrameViewList(); DBG_ASSERT( pFrameViewList, "No FrameViewList?" ); if( pFrameViewList ) { sal_uInt32 i; for ( i = 0; i < pFrameViewList->Count(); i++) { // Ggf. FrameViews loeschen pFrameView = (FrameView*) pFrameViewList->GetObject(i); if (pFrameView) delete pFrameView; } pFrameViewList->Clear(); ViewShell* pViewSh = NULL; SfxViewShell* pSfxViewSh = NULL; SfxViewFrame* pSfxViewFrame = SfxViewFrame::GetFirst(this, false); while (pSfxViewFrame) { // Anzahl FrameViews ermitteln pSfxViewSh = pSfxViewFrame->GetViewShell(); pViewSh = PTR_CAST( ViewShell, pSfxViewSh ); if ( pViewSh && pViewSh->GetFrameView() ) { pViewSh->WriteFrameViewData(); pFrameViewList->Insert( new FrameView( mpDoc, pViewSh->GetFrameView() ) ); } pSfxViewFrame = SfxViewFrame::GetNext(*pSfxViewFrame, this, false); } } } SfxObjectShell::InPlaceActivate( bActive ); if( bActive ) { List* pFrameViewList = mpDoc->GetFrameViewList(); DBG_ASSERT( pFrameViewList, "No FrameViewList?" ); if( pFrameViewList ) { ViewShell* pViewSh = NULL; SfxViewShell* pSfxViewSh = NULL; SfxViewFrame* pSfxViewFrame = SfxViewFrame::GetFirst(this, false); sal_uInt32 i; for( i = 0; pSfxViewFrame && (i < pFrameViewList->Count()); i++ ) { // Anzahl FrameViews ermitteln pSfxViewSh = pSfxViewFrame->GetViewShell(); pViewSh = PTR_CAST( ViewShell, pSfxViewSh ); if ( pViewSh ) { pViewSh->ReadFrameViewData( (FrameView*)pFrameViewList->GetObject(i) ); } pSfxViewFrame = SfxViewFrame::GetNext(*pSfxViewFrame, this, false); } } } } /************************************************************************* |* |* SFX-Aktivierung |* \************************************************************************/ void DrawDocShell::Activate( sal_Bool bMDI) { if (bMDI) { ApplySlotFilter(); mpDoc->StartOnlineSpelling(); } } /************************************************************************* |* |* SFX-Deaktivierung |* \************************************************************************/ void DrawDocShell::Deactivate( sal_Bool ) { } /************************************************************************* |* |* SFX-Undomanager zurueckgeben |* \************************************************************************/ ::svl::IUndoManager* DrawDocShell::GetUndoManager() { return mpUndoManager; } /************************************************************************* |* |* Tabellenzeiger auffrischen |* \************************************************************************/ void DrawDocShell::UpdateTablePointers() { PutItem( SvxColorTableItem( mpDoc->GetColorTableFromSdrModel(), SID_COLOR_TABLE ) ); PutItem( SvxGradientListItem( mpDoc->GetGradientListFromSdrModel(), SID_GRADIENT_LIST ) ); PutItem( SvxHatchListItem( mpDoc->GetHatchListFromSdrModel(), SID_HATCH_LIST ) ); PutItem( SvxBitmapListItem( mpDoc->GetBitmapListFromSdrModel(), SID_BITMAP_LIST ) ); PutItem( SvxDashListItem( mpDoc->GetDashListFromSdrModel(), SID_DASH_LIST ) ); PutItem( SvxLineEndListItem( mpDoc->GetLineEndListFromSdrModel(), SID_LINEEND_LIST ) ); UpdateFontList(); } /************************************************************************* |* |* |* \************************************************************************/ void DrawDocShell::CancelSearching() { if( dynamic_cast<FuSearch*>( mxDocShellFunction.get() ) ) { SetDocShellFunction(0); } } /************************************************************************* |* |* den eingestellten SlotFilter anwenden |* \************************************************************************/ void DrawDocShell::ApplySlotFilter() const { SfxViewShell* pTestViewShell = SfxViewShell::GetFirst(); while( pTestViewShell ) { if( pTestViewShell->GetObjectShell() == const_cast<DrawDocShell*>( this ) && pTestViewShell->GetViewFrame() && pTestViewShell->GetViewFrame()->GetDispatcher() ) { SfxDispatcher* pDispatcher = pTestViewShell->GetViewFrame()->GetDispatcher(); if( mpFilterSIDs ) pDispatcher->SetSlotFilter( mbFilterEnable, mnFilterCount, mpFilterSIDs ); else pDispatcher->SetSlotFilter(); if( pDispatcher->GetBindings() ) pDispatcher->GetBindings()->InvalidateAll( sal_True ); } pTestViewShell = SfxViewShell::GetNext( *pTestViewShell ); } } void DrawDocShell::SetModified( sal_Bool bSet /* = sal_True */ ) { SfxObjectShell::SetModified( bSet ); // #100237# change model state, too // #103182# only set the changed state if modification is enabled if( IsEnableSetModified() ) { if ( mpDoc ) mpDoc->NbcSetChanged( bSet ); Broadcast( SfxSimpleHint( SFX_HINT_DOCCHANGED ) ); } } /************************************************************************* |* |* Callback fuer ExecuteSpellPopup() |* \************************************************************************/ // #91457# ExecuteSpellPopup now handled by DrawDocShell. This is necessary // to get hands on the outliner and the text object. IMPL_LINK(DrawDocShell, OnlineSpellCallback, SpellCallbackInfo*, pInfo) { SdrObject* pObj = NULL; SdrOutliner* pOutl = NULL; if(GetViewShell()) { pOutl = GetViewShell()->GetView()->GetTextEditOutliner(); pObj = GetViewShell()->GetView()->GetTextEditObject(); } mpDoc->ImpOnlineSpellCallback(pInfo, pObj, pOutl); return(0); } void DrawDocShell::ClearUndoBuffer() { // clear possible undo buffers of outliners SfxViewFrame* pSfxViewFrame = SfxViewFrame::GetFirst(this, false); while(pSfxViewFrame) { ViewShellBase* pViewShellBase = dynamic_cast< ViewShellBase* >( pSfxViewFrame->GetViewShell() ); if( pViewShellBase ) { ::boost::shared_ptr<ViewShell> pViewSh( pViewShellBase->GetMainViewShell() ); if( pViewSh.get() ) { ::sd::View* pView = pViewSh->GetView(); if( pView ) { pView->SdrEndTextEdit(); sd::OutlineView* pOutlView = dynamic_cast< sd::OutlineView* >( pView ); if( pOutlView ) { SdrOutliner* pOutliner = pOutlView->GetOutliner(); if( pOutliner ) pOutliner->GetUndoManager().Clear(); } } } } pSfxViewFrame = SfxViewFrame::GetNext(*pSfxViewFrame, this, false); } ::svl::IUndoManager* pUndoManager = GetUndoManager(); if(pUndoManager && pUndoManager->GetUndoActionCount()) pUndoManager->Clear(); } } // end of namespace sd
6,030
405
{ "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, "env": { "browser": true, "jquery": true }, "globals": { "sceditor": false }, "rules": { "no-bitwise": "error", "camelcase": "error", "curly": "error", "eqeqeq": "error", "guard-for-in": "error", "wrap-iife": ["error", "any"], "indent": ["error", "tab", { "SwitchCase": 1 }], "no-use-before-define": ["error", { "functions": false }], "new-cap": ["error", { "capIsNewExceptions": ["Event"] }], "no-caller": "error", "no-empty": ["error", { "allowEmptyCatch": true }], "no-new": "error", "no-plusplus": "off", "quotes": ["error", "single"], "no-undef": "error", "no-unused-vars": "error", "strict": "error", "max-params": ["error", 4], "max-depth": ["error", 4], "max-len": ["error", { "code": 80, "ignoreUrls": true, "ignoreRegExpLiterals": true }], "semi": ["error", "always"], "no-cond-assign": ["error", "except-parens"], "no-debugger": "error", "no-eq-null": "error", "no-eval": "error", "no-unused-expressions": "error", "block-scoped-var": "error", "no-iterator": "error", "linebreak-style": ["error", "unix"], "comma-style": ["error", "last"], "no-loop-func": "error", "no-multi-str": "error", "no-proto": "error", "no-script-url": "error", "no-shadow": "off", "dot-notation": "error", "no-new-func": "error", "no-new-wrappers": "error", "no-invalid-this": "off", "no-with": "error", "brace-style": ["error", "1tbs", { "allowSingleLine": false }], "no-mixed-spaces-and-tabs": "error", "key-spacing": ["error",{ "beforeColon": false, "afterColon": true }], "space-unary-ops": "error", "space-before-function-paren": ["error", { "anonymous": "always", "named": "never", "asyncArrow": "never" }], "no-spaced-func": "error", "array-bracket-spacing": ["error", "never"], "keyword-spacing": ["error", { "before": true, "after": true }], "space-in-parens": ["error", "never"], "comma-dangle": ["error", "never"], "no-trailing-spaces": "error", "eol-last": "error", "space-infix-ops": "error", "space-before-blocks": ["error", "always"] } }
1,090
359
/* * Copyright 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 * * 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 group.idealworld.dew.core.cluster.spi.mqtt; import group.idealworld.dew.core.cluster.Cluster; import org.eclipse.paho.mqttv5.client.MqttClient; import org.eclipse.paho.mqttv5.client.MqttClientPersistence; import org.eclipse.paho.mqttv5.client.MqttConnectionOptions; import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence; import org.eclipse.paho.mqttv5.client.persist.MqttDefaultFilePersistence; import org.eclipse.paho.mqttv5.common.MqttException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Mqtt adapter. * * @author gudaoxuri */ public class MqttAdapter { private static final Logger logger = LoggerFactory.getLogger(MqttAdapter.class); private MqttClient client; private final MqttConfig mqttConfig; MqttAdapter(MqttConfig mqttConfig) throws MqttException { this.mqttConfig = mqttConfig; init(); } private void init() throws MqttException { var clientId = mqttConfig.getClientId(); if (clientId == null || clientId.trim().isEmpty()) { clientId = "Dew_Cluster_" + Cluster.instanceId; } MqttClientPersistence persistence; if ("memory".equalsIgnoreCase(mqttConfig.getPersistence())) { persistence = new MemoryPersistence(); } else { persistence = new MqttDefaultFilePersistence(); } client = new MqttClient(mqttConfig.getBroker(), clientId, persistence); var connOpts = new MqttConnectionOptions(); if (mqttConfig.getUserName() != null) { connOpts.setUserName(mqttConfig.getUserName()); } if (mqttConfig.getPassword() != null) { connOpts.setPassword(mqttConfig.getPassword().getBytes()); } if (mqttConfig.getTimeoutSec() != null) { connOpts.setConnectionTimeout(mqttConfig.getTimeoutSec()); } if (mqttConfig.getKeepAliveIntervalSec() != null) { connOpts.setKeepAliveInterval(mqttConfig.getKeepAliveIntervalSec()); } connOpts.setAutomaticReconnect(true); logger.info("[" + clientId + "] Connecting to broker: " + mqttConfig.getBroker()); client.connect(connOpts); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { client.disconnect(); client.close(); } catch (MqttException e) { e.printStackTrace(); } })); } MqttClient getClient() { return client; } }
1,283
615
/* * Copyright (c) 2017-2019 superblaubeere27, <NAME>, MarcoMC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package me.superblaubeere27.jobf.utils; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import java.lang.reflect.Modifier; public class VariableProvider { private int max = 0; private int argumentSize; private VariableProvider() { } public VariableProvider(MethodNode method) { this(); if (!Modifier.isStatic(method.access)) registerExisting(0, Type.getType("Ljava/lang/Object;")); for (Type argumentType : Type.getArgumentTypes(method.desc)) { registerExisting(argumentType.getSize() + max - 1, argumentType); } argumentSize = max; for (AbstractInsnNode abstractInsnNode : method.instructions.toArray()) { if (abstractInsnNode instanceof VarInsnNode) { registerExisting(((VarInsnNode) abstractInsnNode).var, Utils.getType((VarInsnNode) abstractInsnNode)); } } } private void registerExisting(int var, Type type) { if (var >= max) max = var + type.getSize(); } public boolean isUnallocated(int var) { return var >= max; } public boolean isArgument(int var) { return var < argumentSize; } public int allocateVar() { return max++; } }
814
348
<filename>docs/data/leg-t2/077/07706343.json {"nom":"Ocquerre","circ":"6ème circonscription","dpt":"Seine-et-Marne","inscrits":255,"abs":172,"votants":83,"blancs":5,"nuls":1,"exp":77,"res":[{"nuance":"LR","nom":"<NAME>","voix":51},{"nuance":"REM","nom":"<NAME>","voix":26}]}
115
1,056
<filename>ide/editor.actions/src/org/netbeans/modules/editor/actions/ShowLinesAction.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.editor.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import org.netbeans.api.editor.EditorActionRegistration; @EditorActionRegistration(name="toggle-lines-view", menuPath="View", menuPosition=898, preferencesKey=ShowLinesAction.KEY_LINES, preferencesDefault=ShowLinesAction.DEF_LINES) public class ShowLinesAction extends AbstractAction { public static final String KEY_LINES = "enable.guide.lines"; public static final boolean DEF_LINES = true; @Override public void actionPerformed(ActionEvent e) { } }
512
14,793
package me.chanjar.weixin.common.service; import me.chanjar.weixin.common.bean.WxOAuth2UserInfo; import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken; import me.chanjar.weixin.common.error.WxErrorException; /** * oauth2 相关接口. * * @author <a href="https://github.com/binarywang"><NAME></a> * @date 2020-08-08 */ public interface WxOAuth2Service { /** * <pre> * 构造oauth2授权的url连接. * 详情请见: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html * </pre> * * @param redirectUri 用户授权完成后的重定向链接,无需urlencode, 方法内会进行encode * @param scope scope,静默:snsapi_base, 带信息授权:snsapi_userinfo * @param state state * @return url */ String buildAuthorizationUrl(String redirectUri, String scope, String state); /** * <pre> * 用code换取oauth2的access token. * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息 * </pre> * * @param code code * @return token对象 * @throws WxErrorException . */ WxOAuth2AccessToken getAccessToken(String code) throws WxErrorException; /** * 用code换取oauth2的access token. * * @param appId the appid * @param appSecret the secret * @param code code * @return token对象 * @throws WxErrorException . */ WxOAuth2AccessToken getAccessToken(String appId, String appSecret, String code) throws WxErrorException; /** * <pre> * 刷新oauth2的access token. * </pre> * * @param refreshToken 刷新token * @return 新的token对象 * @throws WxErrorException . */ WxOAuth2AccessToken refreshAccessToken(String refreshToken) throws WxErrorException; /** * <pre> * 用oauth2获取用户信息, 当前面引导授权时的scope是snsapi_userinfo的时候才可以. * </pre> * * @param oAuth2AccessToken token对象 * @param lang zh_CN, zh_TW, en * @return 用户对象 * @throws WxErrorException . */ WxOAuth2UserInfo getUserInfo(WxOAuth2AccessToken oAuth2AccessToken, String lang) throws WxErrorException; /** * <pre> * 验证oauth2的access token是否有效. * </pre> * * @param oAuth2AccessToken token对象 * @return 是否有效 */ boolean validateAccessToken(WxOAuth2AccessToken oAuth2AccessToken); }
1,100
417
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.janquadflieg.mrracer.opponents; import champ2011client.Controller.Stage; import java.awt.geom.Point2D; import de.janquadflieg.mrracer.classification.Situation; import de.janquadflieg.mrracer.telemetry.SensorData; import de.janquadflieg.mrracer.track.TrackModel; /** * * @author quad */ public class DummyObserver implements OpponentObserver/*, de.janquadflieg.mrracer.gui.GraphicDebugable*/{ SensorData data; TrackModel model; Point2D point = OpponentObserver.NO_RECOMMENDED_POINT; javax.swing.JLabel alibiDebugLabel = new javax.swing.JLabel("Isch mach nix"); public void setStage(Stage s){ } @Override public void update(SensorData data, Situation s){ this.data = data; if(model != null && model.initialized() && model.getLength()-data.getDistanceFromStartLine() < 4000.0 && point == OpponentObserver.NO_RECOMMENDED_POINT && model.getLength()-data.getDistanceFromStartLine() >= 1000.0 ){ double position = data.getDistanceRaced(); position += 150; //System.out.println("Setting test point."); point = new Point2D.Double(-0.75, position); } else if(point != OpponentObserver.NO_RECOMMENDED_POINT && model.getLength()-data.getDistanceFromStartLine() >= 1000.0){ double position = data.getDistanceRaced(); position += 150; point = new Point2D.Double(-0.75, position); //System.out.println("Updating test point."); } else { point = OpponentObserver.NO_RECOMMENDED_POINT; //System.out.println("Removing test point."); } } /** * Returns the recommended position on the track to avoid other cars. The * x-coordinate corresponds to the position on the track and the y-coordinate * to the race distance, at which the given x coordinate should be reached. * * Might return NO_RECOMMENDED_POINT if there is no recommendation. * * @return */ @Override public java.awt.geom.Point2D getRecommendedPosition(){ return point; } /** * Returns the recommended speed to avoid crashing into other cars. * Might return NO_RECOMMENDE_SPEED if there is no need to slow down. * * @return */ @Override public double getRecommendedSpeed(){ return OpponentObserver.NO_RECOMMENDED_SPEED; } @Override public boolean otherCars(){ return this.point != OpponentObserver.NO_RECOMMENDED_POINT; } @Override public void setTrackModel(TrackModel trackModel){ this.model = trackModel; } @Override public void reset(){ point = OpponentObserver.NO_RECOMMENDED_POINT; } public javax.swing.JComponent[] getComponent(){ return new javax.swing.JComponent[]{this.alibiDebugLabel}; } }
1,162
1,587
package io.reflectoring.solid.isp; class AdaptedBurgerOrder implements IAdapterOrderForBurger { private final IOrder burgerOrder; public AdaptedBurgerOrder(IOrder burgerOrder){ this.burgerOrder = burgerOrder; } @Override public void orderBurger(int quantity) { burgerOrder.orderBurger(quantity); } }
121
965
<gh_stars>100-1000 wprintf_s(L"Starting thread...\n"); // Create a thread that computes prime numbers. ComPtr<IAsyncAction> asyncAction; hr = threadPool->RunAsync(Callback<IWorkItemHandler>([&threadCompleted](IAsyncAction* asyncAction) -> HRESULT { // Print a message. const unsigned int start = 0; const unsigned int end = 100000; unsigned int primeCount = 0; for (int n = start; n < end; n++) { if (IsPrime(n)) { primeCount++; } } wprintf_s(L"There are %u prime numbers from %u to %u.\n", primeCount, start, end); // Set the completion event and return. SetEvent(threadCompleted.Get()); return S_OK; }).Get(), &asyncAction); if (FAILED(hr)) { return PrintError(__LINE__, hr); }
391