max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
609
<reponame>bytedance/CodeLocator<filename>CodeLocatorPlugin/src/main/java/com/bytedance/tools/codelocator/utils/ViewUtils.java package com.bytedance.tools.codelocator.utils; import com.bytedance.tools.codelocator.model.WView; import com.bytedance.tools.codelocator.panels.ScreenPanel; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Stack; import javax.annotation.Nullable; public class ViewUtils { public static @Nullable WView findClickedView(WView rootView, int clickX, int clickY, boolean justFindClickableView) { WView clickedView = null; ArrayList<WView> clickViews = new ArrayList<>(); findClickedView(rootView, clickX, clickY, clickViews, false); clickViews.sort((o1, o2) -> { if (justFindClickableView) { if (o2.getZIndex().equals(o1.getZIndex())) { return o2.getArea() - o1.getArea(); } return o2.getZIndex().compareTo(o1.getZIndex()); } else { return o1.getArea() - o2.getArea(); } }); if (justFindClickableView) { for (int i = 0; i < clickViews.size(); i++) { if (clickViews.get(i).isClickable()) { if (clickedView != null) { if (clickedView.getArea() < clickViews.get(i).getArea()) { break; } } clickedView = clickViews.get(i); break; } else if (clickedView == null || clickedView.getArea() > clickViews.get(i).getArea()) { clickedView = clickViews.get(i); } } } else { if (clickViews.size() > 0) { clickedView = clickViews.get(0); } } tryFindViewClickInfo(clickedView); return clickedView; } public static @Nullable List<WView> findClickedViewList(WView rootView, int clickX, int clickY) { ArrayList<WView> clickViews = new ArrayList<>(); findClickedView(rootView, clickX, clickY, clickViews, true); clickViews.sort(Comparator.comparing(WView::getZIndex)); return clickViews; } public static WView findViewUniqueIdParent(WView parentView, WView view) { if (view == null) { return null; } if (parentView == null) { parentView = view.getActivity().getDecorView(); } while (view != null) { if (viewIdIsUnique(parentView, view.getIdStr())) { return view; } if (view == parentView) { return null; } view = view.getParentView(); } return view; } public static boolean viewIdIsUnique(WView rootView, String viewIdStr) { if (rootView == null || viewIdStr == null || viewIdStr.isEmpty()) { return false; } int findCount = 0; LinkedList<WView> views = new LinkedList<>(); views.add(rootView); while (!views.isEmpty()) { int levelCount = views.size(); for (int i = 0; i < levelCount; i++) { final WView view = views.getFirst(); views.remove(view); if (viewIdStr.equals(view.getIdStr())) { findCount++; } for (int index = 0; index < view.getChildCount(); index++) { views.add(view.getChildAt(index)); } } if (findCount > 1) { return false; } } return true; } public static @Nullable List<WView> findViewList(@Nullable WView rootView, @Nullable List<String> viewIdList) { if (rootView == null || viewIdList == null || viewIdList.isEmpty()) { return null; } List<WView> clickViewList = new LinkedList<>(); Stack<WView> searchStack = new Stack<>(); searchStack.add(rootView); boolean find = false; for (int i = 0; i < viewIdList.size(); i++) { find = false; while (!searchStack.isEmpty()) { final WView pop = searchStack.pop(); if (pop.getMemAddr().equals(viewIdList.get(i))) { find = true; clickViewList.add(pop); searchStack.clear(); for (int j = 0; j < pop.getChildCount(); j++) { searchStack.push(pop.getChildAt(j)); } break; } } if (!find) { clickViewList.clear(); return clickViewList; } } return clickViewList; } public static void tryFindViewClickInfo(WView clickedView) { if (clickedView == null) { return; } int count = 0; WView parent = clickedView; String clickTag = clickedView.getClickTag(); while (clickTag == null && count < 10) { parent = parent.getParentView(); if (parent == null) { break; } clickTag = parent.getClickTag(); count++; if (clickTag != null && parent.getArea() - clickedView.getArea() < 300 * 300) { clickedView.setClickTag(clickTag); clickedView.setClickJumpInfo(parent.getClickJumpInfo()); break; } } tryFindViewTouchInfo(clickedView); } public static void tryFindViewTouchInfo(WView touchView) { if (touchView == null) { return; } int count = 0; WView parent = touchView; String touchTag = touchView.getTouchTag(); while (touchTag == null && count < 10) { parent = parent.getParentView(); if (parent == null) { break; } touchTag = parent.getTouchTag(); count++; if (touchTag != null && parent.getArea() - touchView.getArea() < 300 * 300) { touchView.setTouchTag(touchTag); touchView.setTouchJumpInfo(parent.getTouchJumpInfo()); break; } } } private static boolean findClickedView(WView view, int clickX, int clickY, ArrayList<WView> clickViews, boolean findJustClickView) { if (view == null) { return false; } if ('V' == view.getVisibility() && view.contains(clickX, clickY)) { boolean hasClickChild = false; for (int i = view.getChildCount() - 1; i > -1; i--) { hasClickChild = findClickedView(view.getChildAt(i), clickX, clickY, clickViews, findJustClickView) || hasClickChild; } if (!hasClickChild) { if (view.isClickable()) { clickViews.add(0, view); } else if (!findJustClickView) { clickViews.add(view); } } return hasClickChild; } return false; } public static List<WView> filterChildView(WView view, int filterMode) { if (view == null) { return null; } LinkedList<WView> filterViews = new LinkedList<>(); if (filterMode == ScreenPanel.FILTER_GONE) { filterChildViewByVisible(view, filterViews, 'G'); } else if (filterMode == ScreenPanel.FILTER_INVISIBLE) { filterChildViewByVisible(view, filterViews, 'I'); } else { filterChildViewByOverDraw(view, view, filterViews); } return filterViews; } private static void filterChildViewByVisible(WView view, List<WView> filterViews, char visibility) { if (view == null) { return; } if (view.getVisibility() == visibility) { filterViews.add(view); } for (int i = 0; i < view.getChildCount(); i++) { filterChildViewByVisible(view.getChildAt(i), filterViews, visibility); } } private static void filterChildViewByOverDraw(WView rootView, WView view, List<WView> filterViews) { if (view == null) { return; } boolean isOverDraw = false; if (view.getVisibility() == 'V' && view.getBackgroundColor() != null && !view.getBackgroundColor().isEmpty()) { WView tmpView = view.getParentView(); while (tmpView != null) { if (tmpView.getVisibility() != 'V') { break; } if (tmpView.getBackgroundColor() != null && !tmpView.getBackgroundColor().isEmpty()) { isOverDraw = true; break; } tmpView = tmpView.getParentView(); if (rootView == tmpView) { break; } } } if (isOverDraw) { filterViews.add(view); } for (int i = 0; i < view.getChildCount(); i++) { filterChildViewByOverDraw(rootView, view.getChildAt(i), filterViews); } } public static int getViewDeep(WView view) { int count = 0; while (view != null) { count++; if (view.getClassName().endsWith(".DecorView") || view.getClassName().endsWith("$PopupDecorView")) { break; } view = view.getParentView(); } return count; } }
4,943
1,199
<reponame>davidlrichmond/macports-ports --- Theme.h Thu Aug 21 02:20:20 2003 +++ Theme.h.new Tue Sep 7 12:03:55 2004 @@ -81,7 +81,7 @@ #ifndef WIN32 DIR *dir; if ((dir = opendir(ThemeDir.c_str())) == NULL) { - ThemeDir = "/usr/share/games/gav/" + ThemeDir; + ThemeDir = "__PREFIX__/share/games/gav/" + ThemeDir; if ((dir = opendir(ThemeDir.c_str())) == NULL) { std::cerr << "Cannot find themes directory\n"; exit(0);
199
3,807
package eu.davidea.flexibleadapter.livedata.models; import java.io.Serializable; import eu.davidea.flexibleadapter.items.IHolder; /** * This class is Pojo for the {@link IHolder} items. * It is used as base item for Item and Header model examples. * * By using Holder pattern, you can implement DB, XML & JSON (de)serialization libraries on this * item as usual. * * @author <NAME> * @since 07/10/2017 */ abstract class AbstractModel implements Serializable { private static final long serialVersionUID = -7385882749119849060L; private String id; AbstractModel(String id) { this.id = id; } @Override public boolean equals(Object inObject) { if (inObject instanceof AbstractModel) { AbstractModel inItem = (AbstractModel) inObject; return this.id.equals(inItem.id); } return false; } /** * Override this method too, when using functionalities like StableIds, Filter or CollapseAll. * FlexibleAdapter is making use of HashSet to improve performance, especially in big list. */ @Override public int hashCode() { return id.hashCode(); } public String getId() { return id; } public void setId(String id) { this.id = id; } }
480
2,059
import os, sys, zipfile from os.path import dirname, abspath, normpath, join from . import DATA_BASE_DIR ENCRYPTED_FILES_PASSWORD='<PASSWORD>' if sys.version_info[0] <= 2: # Python 2.x if sys.version_info[1] <= 6: # Python 2.6 # use is_zipfile backported from Python 2.7: from thirdparty.zipfile27 import is_zipfile else: # Python 2.7 from zipfile import is_zipfile else: # Python 3.x+ from zipfile import is_zipfile ENCRYPTED_FILES_PASSWORD = ENCRYPTED_FILES_PASSWORD.encode() def read(relative_path): with open(get_path_from_root(relative_path), 'rb') as file_handle: return file_handle.read() def read_encrypted(relative_path, filename=None): z = zipfile.ZipFile(get_path_from_root(relative_path)) if filename == None: contents = z.read(z.namelist()[0], pwd=ENCRYPTED_FILES_PASSWORD) else: contents = z.read(filename, pwd=ENCRYPTED_FILES_PASSWORD) z.close() return contents def get_path_from_root(relative_path): return join(DATA_BASE_DIR, relative_path)
463
315
package com.frogermcs.gactions.api; import java.util.HashMap; import java.util.Map; /** * Google Actions API config */ public class ActionsConfig { /** * Default tell-response for intent actions which aren't handled by user RequestHandler - Intent Action mapping */ public static final String ERROR_MESSAGE = "Sorry, I am unable to process your request."; /** * Header configurations for Google Actions API */ public static final String CONVERSATION_API_VERSION_HEADER = "Google-Assistant-API-Version"; public static final String CONVERSATION_API_VERSION = "v1"; public static final String HTTP_CONTENT_TYPE_JSON = "application/json"; public static final Map<String, String> RESPONSE_HEADERS; static { RESPONSE_HEADERS = new HashMap<>(); RESPONSE_HEADERS.put(CONVERSATION_API_VERSION_HEADER, CONVERSATION_API_VERSION); } /** * Permission granted argument. */ public static final String ARG_PERMISSION_GRANTED = "permission_granted"; }
344
375
<gh_stars>100-1000 /* Copyright (c) 2014, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tester/g_ult/unit_tests/cpu/naive_implementations.h" #include "device/api/nn_device_interface_0.h" #include "device/cpu/core/fixedpoint/layer_convolution_int16_fixedpoint_avx2.h" #include <gtest/gtest.h> const uint32_t C_simd_width = sizeof(__m256)/sizeof(int32_t); /////////////////////////////////////////////////////////////////////////////////////////////////// // Helper classs and functions. static void ult_nn_convolution_fp_initialize_work_item( nn_workload_item* &work_item, nn_workload_item* &input_item, int16_t *const input, int32_t*const biases, int16_t *const output, int16_t *const kernel, uint32_t num_output_feature_maps, uint32_t num_input_feature_maps, uint32_t output_feature_map_width, uint32_t output_feature_map_height, uint32_t input_feature_map_width, uint32_t input_feature_map_height, uint32_t kernel_width, uint32_t kernel_height, uint32_t kernel_stride_x, uint32_t kernel_stride_y, uint8_t accumulator_fraction, uint8_t output_fraction, uint_least32_t center_x, uint_least32_t center_y, NN_ACTIVATION_FUNCTION activation) { uint32_t IFMBlock = 16; uint32_t OFMBlock = 32; uint32_t OFMpBlock = 2; uint32_t OFMOutBlock = 16; if (num_input_feature_maps == 4) IFMBlock = 4; if (num_input_feature_maps == 1024 && num_output_feature_maps == 3072) { IFMBlock = 16; OFMBlock = 384; } nn_workload_data_layout_t in_layout = nn::layout_t<nn::layout_pxyznq_i16>::layout; nn_workload_data_layout_t out_layout = nn::layout_t<nn::layout_pxyznq_i16>::layout; nn_workload_data_layout_t bias_layout = nn::layout_t<nn::layout_zxynpq_i32>::layout; nn_workload_data_layout_t weight_layout = nn::layout_t<nn::layout_ypznxq_i16>::layout; nn_workload_data_coords_t input_coords = { 1, // batch size input_feature_map_width, input_feature_map_height, num_input_feature_maps / IFMBlock, IFMBlock, 1, }; nn_workload_data_coords_t output_coords = { 1, // batch size output_feature_map_width + 2 * center_x, output_feature_map_height + 2 * center_y, num_output_feature_maps / OFMOutBlock, OFMOutBlock, 1, }; nn_workload_data_coords_t nn_view_begin = { 0, center_x, center_y, 0, 0, 0 }; nn_workload_data_coords_t nn_view_end = { 0, output_feature_map_width + center_x - 1, output_feature_map_height + center_y - 1, num_output_feature_maps / OFMOutBlock - 1, OFMOutBlock - 1, 0 }; nn_workload_data_coords_t bias_coords = { 1, num_output_feature_maps, 1, 1, 1, 1 }; nn_workload_data_coords_t weight_coords = { kernel_width, kernel_height, OFMpBlock, num_input_feature_maps / OFMpBlock, OFMBlock, num_output_feature_maps / OFMBlock }; nn::workload_data<int16_t> *output_data = new nn::workload_data<int16_t>(output_coords, out_layout); nn::workload_data<int32_t> *bias_data = new nn::workload_data<int32_t>(bias_coords, bias_layout); nn::workload_data<int16_t> *weight_data = new nn::workload_data<int16_t>(weight_coords, weight_layout); work_item = new nn_workload_item(); work_item->type = NN_WORK_ITEM_TYPE_CONVOLUTION_INT16_FIXEDPOINT; nn::arguments_forward_convolution_fixedpoint &arguments = work_item->arguments.forward_convolution_fixedpoint; arguments.padding = NN_PADDING_MODE_NONE; arguments.stride[0] = kernel_stride_x; arguments.stride[1] = kernel_stride_y; arguments.center_offset[0] = center_x; arguments.center_offset[1] = center_y; arguments.activation.basic_arguments.function = activation; arguments.activation.fractions.accumulator = accumulator_fraction; arguments.activation.fractions.output = output_fraction; work_item->output.push_back(output_data); arguments.biases = bias_data; arguments.weights = weight_data; work_item->output.push_back(new nn::workload_data<int16_t>(*output_data, nn_view_begin, nn_view_end)); memcpy(work_item->output[0]->parent->data_buffer, output, work_item->output[0]->parent->buffer_size); memcpy(arguments.biases->parent->data_buffer, biases, arguments.biases->parent->buffer_size); memcpy(arguments.weights->parent->data_buffer, kernel, arguments.weights->parent->buffer_size); input_item = new nn_workload_item(); input_item->type = NN_WORK_ITEM_TYPE_INPUT; input_item->primitive = nullptr; nn::workload_data<int16_t> *input_data = new nn::workload_data<int16_t>(input_coords, in_layout); memcpy(input_data->parent->data_buffer, input, input_data->parent->buffer_size); input_item->output.push_back(input_data); work_item->input.push_back({ input_item, 0 }); // Create primitive nn_device_description_t device_description; nn_device_interface_0_t device_interface_0; nn_device_load(&device_description); nn_device_interface_open(0, &device_interface_0); work_item->primitive = new int16_fixedpoint::convolution_i16( kernel_width, kernel_height, num_input_feature_maps, num_output_feature_maps, output_feature_map_width, output_feature_map_height, center_x, center_y, kernel_stride_x, kernel_stride_y, arguments.activation, 1, 0, 0, 0, 0, reinterpret_cast<nn_device_internal*>(device_interface_0.device)); // Create primitive output delete work_item->output[0]; work_item->output[0] = static_cast<int16_fixedpoint::helper_z_block_xyz_i16::primitive_z_block_xyz_i16_base *>(work_item->primitive) ->create_outputs(false)[0]; } ////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_deinitialize_work_item(nn_workload_item* &work_item) { if(work_item->type != NN_WORK_ITEM_TYPE_INPUT) { auto &arguments = work_item->arguments.forward_convolution_fixedpoint; delete arguments.biases; delete arguments.weights; } for(auto& parameter : work_item->parameters) { delete parameter; parameter = nullptr; } for(auto& output : work_item->output) { delete output; output = nullptr; } delete work_item->primitive; work_item->primitive = nullptr; delete work_item; work_item = nullptr; } ////////////////////////////////////////////////////////////////////////////////////////////////// static bool ult_nn_convolution_fp_interface_run(nn_workload_item* &work_item) { bool retvalue = true; //int16_fixedpoint::run_multithreaded_convolve_fixedpoint_work_item(work_item); nn_device_description_t device_description; nn_device_interface_0_t device_interface_0; nn_device_load(&device_description); nn_device_interface_open(0, &device_interface_0); int16_fixedpoint::run_multithreaded_convolve_fixedpoint_work_item(work_item, reinterpret_cast<nn_device_internal*>(device_interface_0.device)); nn_device_interface_close(&device_interface_0); nn_device_unload(); return retvalue; } bool ult_nn_convolution_fp_interface_run(uint32_t nowitems, nn_workload_item* work_items[]) { bool retvalue = true; nn_device_description_t device_description; nn_device_interface_0_t device_interface_0; nn_device_load(&device_description); nn_device_interface_open(0, &device_interface_0); for (unsigned int item = 0; item < nowitems && retvalue; item++) { //int16_fixedpoint::run_multithreaded_convolve_fixedpoint_work_item(work_items[item]); int16_fixedpoint::run_multithreaded_convolve_fixedpoint_work_item(work_items[item], reinterpret_cast<nn_device_internal*>(device_interface_0.device)); } nn_device_interface_close(&device_interface_0); nn_device_unload(); return retvalue; } /////////////////////////////////////////////////////////////////////////////////////////////////// static int16_t ult_nn_convolution_fp_optimized_get_output_value( int16_t* output, uint_least32_t output_feature_map_width, uint_least32_t output_feature_map_height, uint_least32_t num_output_feature_maps, uint_least32_t output_column, uint_least32_t output_row, uint_least32_t output_map, uint_least32_t& offset) { offset = output_row*output_feature_map_width*num_output_feature_maps + output_column*num_output_feature_maps + output_map; return output[offset]; } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_optimized_set_output_value( int16_t* output, uint_least32_t output_feature_map_width, uint_least32_t output_feature_map_height, uint_least32_t num_output_feature_maps, uint_least32_t output_column, uint_least32_t output_row, uint_least32_t output_map, int16_t value, uint_least32_t& offset) { offset = output_row*output_feature_map_width*num_output_feature_maps + output_column*num_output_feature_maps + output_map; output[offset] = value; } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_optimized_set_input_value( int16_t* input, uint_least32_t input_feature_map_width, uint_least32_t num_input_feature_maps, uint_least32_t input_column, uint_least32_t input_row, uint_least32_t input_map, int16_t value, uint_least32_t& offset) { offset = input_column*num_input_feature_maps + input_row*num_input_feature_maps*input_feature_map_width + input_map; input[offset] = value; } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_optimized_set_kernel_value( int16_t* kernel, uint_least32_t kernel_width, uint_least32_t kernel_height, uint_least32_t num_input_feature_maps, uint_least32_t kernel_column, uint_least32_t kernel_row, uint_least32_t kernel_input_map, uint_least32_t kernel_output_map, int16_t value, uint_least32_t& offset) { uint_least32_t kernel_output_map_div = kernel_output_map / C_simd_width; uint_least32_t kernel_output_map_rem = kernel_output_map % C_simd_width; offset = kernel_row*C_simd_width*kernel_width*num_input_feature_maps + kernel_column*C_simd_width + kernel_input_map*C_simd_width*kernel_width + kernel_output_map_div*kernel_width*kernel_height*num_input_feature_maps*C_simd_width + kernel_output_map_rem; kernel[offset] = value; } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_both_initialize_matrices( int16_t* input, int16_t* output, int32_t* biases, int16_t* kernel, int16_t* input_ref, int16_t* output_ref, int32_t* biases_ref, int16_t* kernel_ref, uint_least32_t num_output_feature_maps, uint_least32_t num_input_feature_maps, uint_least32_t output_feature_map_width, uint_least32_t output_feature_map_height, uint_least32_t input_feature_map_width, uint_least32_t input_feature_map_height, uint_least32_t kernel_width, uint_least32_t kernel_height, uint_least32_t center_x, uint_least32_t center_y ) { uint_least32_t input_size = input_feature_map_width * input_feature_map_height * num_input_feature_maps * sizeof(int16_t); int16_t * inputT = (int16_t*)_mm_malloc(input_size, 64); uint_least32_t kernel_size = num_input_feature_maps * num_output_feature_maps * kernel_width * kernel_height * sizeof(int16_t); int16_t * weightT = (int16_t*)_mm_malloc(kernel_size, 64); uint32_t IFMBlock = 16; if (num_input_feature_maps == 4) IFMBlock = 4; uint32_t OFMBlock = 32; uint32_t OFMpBlock = 2; if (num_output_feature_maps == 3072 && num_input_feature_maps == 1024) { IFMBlock = 16; OFMBlock = 384; } for (uint_least32_t input_map = 0; input_map < num_input_feature_maps; input_map++) { uint_least32_t element = 0; int16_t value = input_map * 0x0100; for (uint_least32_t row = 0; row < input_feature_map_height; row++) { for (uint_least32_t column = 0; column < input_feature_map_width; column++) { uint_least32_t offset; //ult_nn_convolution_optimized_set_input_value(inputT, input_feature_map_width, num_input_feature_maps, column, row, input_map, value, offset); ult_nn_merge_convolution_fixedpoint_naive_set_input_value(inputT, input_feature_map_width, input_feature_map_height, column, row, input_map, value, offset); ult_nn_merge_convolution_fixedpoint_naive_set_input_value(input_ref, input_feature_map_width, input_feature_map_height, column, row, input_map, value, offset); value++; } } } int16_t value = 0; for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++) { for (uint_least32_t input_map = 0; input_map < num_input_feature_maps; input_map++) { //uint_least32_t element = 0; //int16_t value = input_map * 0x0100 + outmapa * 0x2000; for (uint_least32_t row = 0; row < kernel_height; row++) { for (uint_least32_t column = 0; column < kernel_width; column++) { //element++; uint_least32_t offset; //ult_nn_convolution_optimized_set_kernel_value ult_nn_merge_convolution_fixedpoint_naive_set_kernel_value(weightT, kernel_width, kernel_height, num_input_feature_maps, column, row, input_map, outmapa, value, offset); ult_nn_merge_convolution_fixedpoint_naive_set_kernel_value(kernel_ref, kernel_width, kernel_height, num_input_feature_maps, column, row, input_map, outmapa, value, offset); value++; } } } } for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++) { for (uint_least32_t row = 0; row < output_feature_map_height + 2 * center_y; row++) { for (uint_least32_t column = 0; column < output_feature_map_width + 2 * center_x; column++) { uint32_t index = column + row * (output_feature_map_width + 2 * center_x) + outmapa * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y); output[index] = 0; output_ref[index] = 0; } } } for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++) { biases[outmapa] = outmapa; biases_ref[outmapa] = outmapa; } //prepare right input layout for naive implementation for (uint32_t i = 0; i < num_input_feature_maps / IFMBlock; i++) for (uint32_t j = 0; j < input_feature_map_width * input_feature_map_height; j++) for (uint32_t n = 0; n < IFMBlock; n++) input[n + j * IFMBlock + i * input_feature_map_width * input_feature_map_height * IFMBlock] = inputT[n * input_feature_map_width * input_feature_map_height + j + i * input_feature_map_width * input_feature_map_height * IFMBlock]; const uint32_t ItrIn = num_input_feature_maps / 2; const uint32_t ItrOut = num_output_feature_maps / OFMBlock; for (uint32_t k = 0; k < ItrOut; k++) for (uint32_t i = 0; i < kernel_width * kernel_height; i++) for (uint32_t j = 0; j < ItrIn; j++) for (uint32_t n = 0; n < OFMBlock; n++) for (uint32_t m = 0; m < 2; m++) kernel[m + 2 * n + 2 * OFMBlock * j + i * 2 * OFMBlock * ItrIn + k * 2 * OFMBlock * ItrIn * kernel_width * kernel_height] = weightT[m * kernel_width * kernel_height + n * num_input_feature_maps * kernel_width * kernel_height + 2 * j * kernel_width * kernel_height + k * OFMBlock * num_input_feature_maps * kernel_width * kernel_height + i]; _mm_free(inputT); _mm_free(weightT); } /////////////////////////////////////////////////////////////////////////////////////////////////// bool ult_nn_convolution_fp_check_outputs( nn_workload_data_t* output, int16_t* output_ref, uint_least32_t num_output_feature_maps, uint_least32_t output_feature_map_width, uint_least32_t output_feature_map_height, uint_least32_t center_x, uint_least32_t center_y ) { uint32_t OFMOutBlock = 16; int16_t * outputOpt = (int16_t *)output->parent->data_buffer; uint_least32_t output_size = (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * num_output_feature_maps * sizeof(int16_t); int16_t* outputT = (int16_t*)_mm_malloc(output_size, 64); for (uint32_t i = 0; i < num_output_feature_maps / OFMOutBlock; i++) for (uint32_t j = 0; j < (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y); j++) for (uint32_t n = 0; n < OFMOutBlock; n++) { outputT[n + j * OFMOutBlock + i * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * OFMOutBlock] = output_ref[n * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) + j + i * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * OFMOutBlock]; } bool passed = true; for (uint_least32_t i = 0; i < (output_size / sizeof(int16_t)) && passed; i++) if (outputT[i] != outputOpt[i]) passed = false; _mm_free(outputT); return passed; } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_both_alloc( int16_t* &input, int16_t* &output, int32_t* &biases, int16_t* &kernel, int16_t* &input_ref, int16_t* &output_ref, int32_t* &biases_ref, int16_t* &kernel_ref, uint_least32_t num_output_feature_maps, uint_least32_t num_input_feature_maps, uint_least32_t output_width, uint_least32_t output_height, uint_least32_t input_width, uint_least32_t input_height, uint_least32_t kernel_width, uint_least32_t kernel_height, uint_least32_t center_x, uint_least32_t center_y ) { uint_least32_t input_size = input_width * input_height * num_input_feature_maps * sizeof(int16_t); uint_least32_t output_size = (output_width + 2 * center_x) * (output_height + 2 * center_y) * num_output_feature_maps * sizeof(int16_t); uint_least32_t bias_size = num_output_feature_maps * sizeof(int32_t); uint_least32_t kernel_size = num_input_feature_maps * num_output_feature_maps * kernel_width * kernel_height * sizeof(int16_t); input_ref = (int16_t*)_mm_malloc(input_size, 64); output_ref = (int16_t*)_mm_malloc(output_size, 64); biases_ref = (int32_t*)_mm_malloc(bias_size, 64); kernel_ref = (int16_t*)_mm_malloc(kernel_size, 64); input_size = input_width * input_height * num_input_feature_maps * sizeof(int16_t); output_size = (output_width + 2 * center_x) * (output_height + 2 * center_y) * num_output_feature_maps * sizeof(int16_t); kernel_size = num_input_feature_maps * num_output_feature_maps * kernel_width * kernel_height * sizeof(int32_t); input = (int16_t*)_mm_malloc(input_size, 64); output = (int16_t*)_mm_malloc(output_size, 64); biases = (int32_t*)_mm_malloc(bias_size, 64); kernel = (int16_t*)_mm_malloc(kernel_size, 64); } /////////////////////////////////////////////////////////////////////////////////////////////////// static void ult_nn_convolution_fp_both_dealloc( int16_t* &input, int16_t* &output, int32_t* &biases, int16_t* &kernel, int16_t* &input_ref, int16_t* &output_ref, int32_t* &biases_ref, int16_t* &kernel_ref) { if (input != 0) { _mm_free(input); input = 0; } if (output != 0) { _mm_free(output); output = 0; } if (biases != 0) { _mm_free(biases); biases = 0; } if (kernel != 0) { _mm_free(kernel); kernel = 0; } if (input_ref != 0) { _mm_free(input_ref); input_ref = 0; } if (output_ref != 0) { _mm_free(output_ref); output_ref = 0; } if (biases_ref != 0) { _mm_free(biases_ref); biases_ref = 0; } if (kernel_ref != 0) { _mm_free(kernel_ref); kernel_ref = 0; } } /////////////////////////////////////////////////////////////////////////////////////////////////// static bool ult_perform_test( uint_least32_t num_output_feature_maps, uint_least32_t num_input_feature_maps, uint_least32_t input_feature_map_width, uint_least32_t input_feature_map_height, uint_least32_t kernel_width, uint_least32_t kernel_height, uint_least32_t kernel_stride_x, uint_least32_t kernel_stride_y, uint8_t accumulator_fraction, uint8_t output_fraction, uint_least32_t center_x, uint_least32_t center_y, NN_ACTIVATION_FUNCTION activation ) { nn_workload_item* work_item = nullptr; nn_workload_item* work_items[12]; nn_workload_item* input_item = nullptr; nn_workload_item* input_items[12]; std::fill_n(work_items, 12, nullptr); bool passed = false; int16_t* input = 0; int16_t* output = 0; int32_t* biases = 0; int16_t* kernel = 0; int16_t* input_ref = 0; int16_t* output_ref = 0; int32_t* biases_ref = 0; int16_t* kernel_ref = 0; uint32_t NoWItems = 1; uint_least32_t output_feature_map_width = (input_feature_map_width - kernel_width) / kernel_stride_x + 1; uint_least32_t output_feature_map_height = (input_feature_map_height - kernel_height) / kernel_stride_y + 1; num_output_feature_maps += (C_simd_width - (num_output_feature_maps % C_simd_width)) % C_simd_width; // Allocate naive and optimized buffers. ult_nn_convolution_fp_both_alloc( input, output, biases, kernel, input_ref, output_ref, biases_ref, kernel_ref, num_output_feature_maps, num_input_feature_maps, output_feature_map_width, output_feature_map_height, input_feature_map_width, input_feature_map_height, kernel_width, kernel_height, center_x, center_y ); // Initialize both buffers. ult_nn_convolution_fp_both_initialize_matrices( input, output, biases, kernel, input_ref, output_ref, biases_ref, kernel_ref, num_output_feature_maps, num_input_feature_maps, output_feature_map_width, output_feature_map_height, input_feature_map_width, input_feature_map_height, kernel_width, kernel_height, center_x, center_y ); // Naive convolution ult_nn_convolve_fp_naive( input_ref, output_ref, biases_ref, kernel_ref, num_output_feature_maps, num_input_feature_maps, output_feature_map_width, output_feature_map_height, input_feature_map_width, input_feature_map_height, kernel_width, kernel_height, kernel_stride_x, kernel_stride_y, accumulator_fraction, output_fraction, center_x, center_y, activation); { // Perform data copy to interface test. ult_nn_convolution_fp_initialize_work_item( work_item, input_item, input, biases, output, kernel, num_output_feature_maps, num_input_feature_maps, output_feature_map_width, output_feature_map_height, input_feature_map_width, input_feature_map_height, kernel_width, kernel_height, kernel_stride_x, kernel_stride_y, accumulator_fraction, output_fraction, center_x, center_y, activation); //Optimized convolution. passed = ult_nn_convolution_fp_interface_run(work_item); } if (passed) { //Basic check between optimized and naive versions. passed = ult_nn_convolution_fp_check_outputs( work_item->output[0], output_ref, num_output_feature_maps, output_feature_map_width, output_feature_map_height, center_x, center_y); } // Cleanup. ult_nn_convolution_fp_deinitialize_work_item(work_item); ult_nn_convolution_fp_deinitialize_work_item(input_item); ult_nn_convolution_fp_both_dealloc( input, output, biases, kernel, input_ref, output_ref, biases_ref, kernel_ref); return passed; } /////////////////////////////////////////////////////////////////////////////////////////////////// TEST(cpu_int16_convolution_fixed_point, cpu_convolution_Overfeat) { //CX EXPECT_EQ(true, ult_perform_test(64, 64, 14, 14, 3, 3, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(64, 64, 14, 14, 3, 3, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); ////C1 EXPECT_EQ(true, ult_perform_test(96, 4, 231, 231, 11, 11, 4, 4, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(96, 4, 231, 231, 11, 11, 4, 4, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); //// C2 //EXPECT_EQ(true, ult_perform_test(256, 96, 28, 28, 5, 5, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(256, 96, 28, 28, 5, 5, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); //// C3 //EXPECT_EQ(true, ult_perform_test(512, 256, 14, 14, 3, 3, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(512, 256, 14, 14, 3, 3, 1, 1, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); //// C4 //EXPECT_EQ(true, ult_perform_test(1024, 512, 14, 14, 3, 3, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(1024, 512, 14, 14, 3, 3, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); // C5 //EXPECT_EQ(true, ult_perform_test(1024, 1024, 14, 14, 3, 3, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(1024, 1024, 14, 14, 3, 3, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); // C6 //EXPECT_EQ(true, ult_perform_test(3072, 1024, 6, 6, 6, 6, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_RELU)); //EXPECT_EQ(true, ult_perform_test(3072, 1024, 6, 6, 6, 6, 1, 1, false, 16, 0, 0, 0, NN_ACTIVATION_FUNCTION_NONE)); }
12,410
412
<reponame>tobireinhard/cbmc /******************************************************************\ Module: functions_harness_generator_options Author: Diffblue Ltd. \******************************************************************/ #ifndef CPROVER_GOTO_HARNESS_FUNCTION_HARNESS_GENERATOR_OPTIONS_H #define CPROVER_GOTO_HARNESS_FUNCTION_HARNESS_GENERATOR_OPTIONS_H #include "common_harness_generator_options.h" #define FUNCTION_HARNESS_GENERATOR_FUNCTION_OPT "function" #define FUNCTION_HARNESS_GENERATOR_NONDET_GLOBALS_OPT "nondet-globals" #define FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_ARRAY_OPT \ "treat-pointer-as-array" #define FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_OPT \ "treat-pointers-equal" #define FUNCTION_HARNESS_GENERATOR_ASSOCIATED_ARRAY_SIZE_OPT \ "associated-array-size" #define FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_CSTRING \ "treat-pointer-as-cstring" #define FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_MAYBE_OPT \ "treat-pointers-equal-maybe" // clang-format off #define FUNCTION_HARNESS_GENERATOR_OPTIONS \ "(" FUNCTION_HARNESS_GENERATOR_FUNCTION_OPT "):" \ "(" FUNCTION_HARNESS_GENERATOR_NONDET_GLOBALS_OPT ")" \ "(" FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_ARRAY_OPT "):" \ "(" FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_OPT "):" \ "(" FUNCTION_HARNESS_GENERATOR_ASSOCIATED_ARRAY_SIZE_OPT "):" \ "(" FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_CSTRING "):" \ "(" FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_MAYBE_OPT ")" \ // FUNCTION_HARNESS_GENERATOR_OPTIONS // clang-format on // clang-format off #define FUNCTION_HARNESS_GENERATOR_HELP \ "function harness generator (--harness-type call-function)\n\n" \ "--" FUNCTION_HARNESS_GENERATOR_FUNCTION_OPT \ " the function the harness should call\n" \ "--" FUNCTION_HARNESS_GENERATOR_NONDET_GLOBALS_OPT \ " set global variables to non-deterministic values\n" \ " in harness\n" \ COMMON_HARNESS_GENERATOR_HELP \ "--" FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_ARRAY_OPT \ " p treat the function parameter with the name `p' as\n" \ " an array\n" \ "--" FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_OPT \ " p,q,r[;s,t] treat the function parameters `q,r' equal\n" \ " to parameter `p'; `s` to `t` and so on\n" \ "--" FUNCTION_HARNESS_GENERATOR_TREAT_POINTERS_EQUAL_MAYBE_OPT \ " function parameters equality is non-deterministic\n" \ "--" FUNCTION_HARNESS_GENERATOR_ASSOCIATED_ARRAY_SIZE_OPT \ " array_name:size_name\n" \ " set the parameter <size_name> to the size" \ " of\n the array <array_name>\n" \ " (implies " \ "-- " FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_ARRAY_OPT \ " <array_name>)\n" \ "--" FUNCTION_HARNESS_GENERATOR_TREAT_POINTER_AS_CSTRING \ " p treat the function parameter with the name `p' as\n" \ " a string of characters\n" \ // FUNCTION_HARNESS_GENERATOR_HELP // clang-format on #endif // CPROVER_GOTO_HARNESS_FUNCTION_HARNESS_GENERATOR_OPTIONS_H
2,373
1,253
<gh_stars>1000+ from rnn import RNN from tokens import tokenize, detokenize model = RNN(61,200) model.load('uwv.pkl') # print(model.U.shape) # generate(start_token, num_of_chars, top_k random predictions) text = model.generate(tokenize('F'), 300, 3) for i in text: print(detokenize(i), end="")
119
558
<gh_stars>100-1000 /* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2015-2021 Micron Technology, Inc. All rights reserved. */ #include "framework_external.h" #include <hse_ut/conditions.h> #include <hse_util/hse_err.h> #include <hse_util/inttypes.h> #include <hse_test_support/mock_api.h> #include <cn/kblock_builder.h> #include <cn/vblock_builder.h> #include <mocks/mock_kbb_vbb.h> #include <mocks/mock_mpool.h> static merr_t _kbb_create(struct kblock_builder **bld_out, struct cn *cn, struct perfc_set *pc) { *bld_out = (struct kblock_builder *)0x1111; return 0; } static merr_t _vbb_create( struct vblock_builder **bld_out, struct cn * cn, struct perfc_set * pc, u64 vgroup) { *bld_out = (struct vblock_builder *)0x2222; return 0; } /* Prefer the mapi_inject_list method for mocking functions over the * MOCK_SET/MOCK_UNSET macros if the mock simply needs to return a * constant value. The advantage of the mapi_inject_list approach is * less code (no need to define a replacement function) and easier * maintenance (will not break when the mocked function signature * changes). */ static struct mapi_injection inject_list[] = { /* kblock builder */ { mapi_idx_kbb_destroy, MAPI_RC_SCALAR, 0}, { mapi_idx_kbb_add_entry, MAPI_RC_SCALAR, 0}, { mapi_idx_kbb_add_entry, MAPI_RC_SCALAR, 0}, { mapi_idx_kbb_add_ptomb, MAPI_RC_SCALAR, 0}, { mapi_idx_kbb_finish, MAPI_RC_SCALAR, 0}, /* vblock builder */ { mapi_idx_vbb_destroy, MAPI_RC_SCALAR, 0}, { mapi_idx_vbb_add_entry, MAPI_RC_SCALAR, 0}, { mapi_idx_vbb_finish, MAPI_RC_SCALAR, 0}, /* required termination */ { -1 }, }; void mock_kbb_vbb_set(void) { mock_mpool_set(); MOCK_SET(kblock_builder, _kbb_create); MOCK_SET(vblock_builder, _vbb_create); mapi_inject_list_set(inject_list); } void mock_kbb_vbb_unset(void) { mock_mpool_unset(); MOCK_UNSET(kblock_builder, _kbb_create); MOCK_UNSET(vblock_builder, _vbb_create); mapi_inject_list_unset(inject_list); }
945
5,169
<filename>Specs/b/e/5/Broadcast/1.3.2/Broadcast.podspec.json { "name": "Broadcast", "version": "1.3.2", "summary": "Lightweight instance syncing & property binding.", "description": "Broadcast is a quick-and-dirty solution for instance syncing and property binding.", "homepage": "https://github.com/mitchtreece/Broadcast", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/mitchtreece/Broadcast.git", "tag": "1.3.2" }, "social_media_url": "https://twitter.com/MitchTreece", "platforms": { "ios": "8.0" }, "source_files": "Broadcast/Classes/**/*", "pushed_with_swift_version": "3.0" }
290
1,602
<reponame>jhh67/chapel /* POWER7 gmp-mparam.h -- Compiler/machine parameter header file. Copyright 2019 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #define GMP_LIMB_BITS 64 #define GMP_LIMB_BYTES 8 /* 3720 MHz POWER7/SMT4 */ /* FFT tuning limit = 0.5 M */ /* Generated by tuneup.c, 2019-10-02, gcc 4.8 */ #define MOD_1_NORM_THRESHOLD 0 /* always */ #define MOD_1_UNNORM_THRESHOLD 0 /* always */ #define MOD_1N_TO_MOD_1_1_THRESHOLD 6 #define MOD_1U_TO_MOD_1_1_THRESHOLD 4 #define MOD_1_1_TO_MOD_1_2_THRESHOLD 8 #define MOD_1_2_TO_MOD_1_4_THRESHOLD 16 #define PREINV_MOD_1_TO_MOD_1_THRESHOLD 13 #define USE_PREINV_DIVREM_1 0 #define DIV_QR_1N_PI1_METHOD 1 /* 3.47% faster than 2 */ #define DIV_QR_1_NORM_THRESHOLD 1 #define DIV_QR_1_UNNORM_THRESHOLD 1 #define DIV_QR_2_PI2_THRESHOLD MP_SIZE_T_MAX /* never */ #define DIVEXACT_1_THRESHOLD 0 /* always (native) */ #define BMOD_1_TO_MOD_1_THRESHOLD 27 #define DIV_1_VS_MUL_1_PERCENT 341 #define MUL_TOOM22_THRESHOLD 22 #define MUL_TOOM33_THRESHOLD 71 #define MUL_TOOM44_THRESHOLD 196 #define MUL_TOOM6H_THRESHOLD 298 #define MUL_TOOM8H_THRESHOLD 406 #define MUL_TOOM32_TO_TOOM43_THRESHOLD 81 #define MUL_TOOM32_TO_TOOM53_THRESHOLD 140 #define MUL_TOOM42_TO_TOOM53_THRESHOLD 132 #define MUL_TOOM42_TO_TOOM63_THRESHOLD 139 #define MUL_TOOM43_TO_TOOM54_THRESHOLD 120 #define SQR_BASECASE_THRESHOLD 0 /* always (native) */ #define SQR_TOOM2_THRESHOLD 32 #define SQR_TOOM3_THRESHOLD 105 #define SQR_TOOM4_THRESHOLD 190 #define SQR_TOOM6_THRESHOLD 318 #define SQR_TOOM8_THRESHOLD 547 #define MULMID_TOOM42_THRESHOLD 56 #define MULMOD_BNM1_THRESHOLD 18 #define SQRMOD_BNM1_THRESHOLD 20 #define MUL_FFT_MODF_THRESHOLD 436 /* k = 5 */ #define MUL_FFT_TABLE3 \ { { 436, 5}, { 21, 6}, { 21, 7}, { 11, 6}, \ { 23, 7}, { 12, 6}, { 25, 7}, { 21, 8}, \ { 11, 7}, { 25, 8}, { 13, 7}, { 28, 8}, \ { 15, 7}, { 33, 8}, { 17, 7}, { 35, 8}, \ { 19, 7}, { 39, 8}, { 21, 9}, { 11, 8}, \ { 29, 9}, { 15, 8}, { 35, 9}, { 19, 8}, \ { 41, 9}, { 23, 8}, { 49, 9}, { 27,10}, \ { 15, 9}, { 31, 8}, { 63, 9}, { 43,10}, \ { 23, 9}, { 55,11}, { 15,10}, { 31, 9}, \ { 67,10}, { 39, 9}, { 79,10}, { 47, 9}, \ { 95,10}, { 55,11}, { 31,10}, { 63, 9}, \ { 127,10}, { 79,11}, { 47,10}, { 103,12}, \ { 31,11}, { 63,10}, { 135,11}, { 79,10}, \ { 159,11}, { 95,10}, { 191, 9}, { 383,11}, \ { 111,12}, { 63,11}, { 127,10}, { 255, 9}, \ { 511,11}, { 143,10}, { 287, 9}, { 575,11}, \ { 159,10}, { 319,12}, { 95,11}, { 191,10}, \ { 383, 9}, { 767,11}, { 207,10}, { 415,13}, \ { 8192,14}, { 16384,15}, { 32768,16}, { 65536,17}, \ { 131072,18}, { 262144,19}, { 524288,20}, {1048576,21}, \ {2097152,22}, {4194304,23}, {8388608,24} } #define MUL_FFT_TABLE3_SIZE 83 #define MUL_FFT_THRESHOLD 4736 #define SQR_FFT_MODF_THRESHOLD 368 /* k = 5 */ #define SQR_FFT_TABLE3 \ { { 368, 5}, { 19, 6}, { 10, 5}, { 21, 6}, \ { 21, 7}, { 11, 6}, { 23, 7}, { 12, 6}, \ { 25, 7}, { 13, 6}, { 27, 7}, { 25, 8}, \ { 13, 7}, { 28, 8}, { 15, 7}, { 32, 8}, \ { 17, 7}, { 35, 8}, { 19, 7}, { 39, 8}, \ { 21, 9}, { 11, 8}, { 29, 9}, { 15, 8}, \ { 35, 9}, { 19, 8}, { 41, 9}, { 23, 8}, \ { 47, 9}, { 27,10}, { 15, 9}, { 31, 8}, \ { 63, 9}, { 39,10}, { 23, 9}, { 51,11}, \ { 15,10}, { 31, 9}, { 67,10}, { 39, 9}, \ { 79,10}, { 47, 9}, { 95,10}, { 55,11}, \ { 31,10}, { 79,11}, { 47,10}, { 95,12}, \ { 31,11}, { 63,10}, { 135,11}, { 79,10}, \ { 159, 9}, { 319,11}, { 95,10}, { 191, 9}, \ { 383,11}, { 111,12}, { 63,11}, { 127,10}, \ { 255, 9}, { 511,11}, { 143,10}, { 287, 9}, \ { 575,10}, { 303,11}, { 159,10}, { 319, 9}, \ { 639,12}, { 95,11}, { 191,10}, { 383, 9}, \ { 767,13}, { 8192,14}, { 16384,15}, { 32768,16}, \ { 65536,17}, { 131072,18}, { 262144,19}, { 524288,20}, \ {1048576,21}, {2097152,22}, {4194304,23}, {8388608,24} } #define SQR_FFT_TABLE3_SIZE 84 #define SQR_FFT_THRESHOLD 3264 #define MULLO_BASECASE_THRESHOLD 3 #define MULLO_DC_THRESHOLD 35 #define MULLO_MUL_N_THRESHOLD 9449 #define SQRLO_BASECASE_THRESHOLD 3 #define SQRLO_DC_THRESHOLD 119 #define SQRLO_SQR_THRESHOLD 6440 #define DC_DIV_QR_THRESHOLD 33 #define DC_DIVAPPR_Q_THRESHOLD 124 #define DC_BDIV_QR_THRESHOLD 62 #define DC_BDIV_Q_THRESHOLD 144 #define INV_MULMOD_BNM1_THRESHOLD 67 #define INV_NEWTON_THRESHOLD 123 #define INV_APPR_THRESHOLD 123 #define BINV_NEWTON_THRESHOLD 284 #define REDC_1_TO_REDC_2_THRESHOLD 18 #define REDC_2_TO_REDC_N_THRESHOLD 109 #define MU_DIV_QR_THRESHOLD 1387 #define MU_DIVAPPR_Q_THRESHOLD 1334 #define MUPI_DIV_QR_THRESHOLD 50 #define MU_BDIV_QR_THRESHOLD 1308 #define MU_BDIV_Q_THRESHOLD 1499 #define POWM_SEC_TABLE 1,23,121,579,642 #define GET_STR_DC_THRESHOLD 11 #define GET_STR_PRECOMPUTE_THRESHOLD 18 #define SET_STR_DC_THRESHOLD 1562 #define SET_STR_PRECOMPUTE_THRESHOLD 3100 #define FAC_DSC_THRESHOLD 774 #define FAC_ODD_THRESHOLD 25 #define MATRIX22_STRASSEN_THRESHOLD 18 #define HGCD2_DIV1_METHOD 5 /* 3.27% faster than 3 */ #define HGCD_THRESHOLD 118 #define HGCD_APPR_THRESHOLD 150 #define HGCD_REDUCE_THRESHOLD 3014 #define GCD_DC_THRESHOLD 386 #define GCDEXT_DC_THRESHOLD 365 #define JACOBI_BASE_METHOD 4 /* 27.64% faster than 1 */
4,370
945
#include "vnl/vnl_sparse_matrix.hxx" template class VNL_EXPORT vnl_sparse_matrix<int>;
40
626
<reponame>VigneshwaranDev/zerocode<gh_stars>100-1000 package org.jsmart.zerocode.core.utils; import static java.lang.Integer.parseInt; import static java.lang.System.getProperty; import static java.lang.System.getenv; public class EnvUtils { public static Integer getEnvValueInt(String envKey) { String envValue = getProperty(envKey) == null ? getenv(envKey) : getProperty(envKey); return envValue == null ? null : parseInt(envValue); } public static String getEnvValueString(String envKey) { return getProperty(envKey) == null ? getenv(envKey) : getProperty(envKey); } }
221
317
<reponame>xcorail/OTB /* MIDWIN.f -- translated by f2c (version 19970805). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #ifdef __cplusplus extern "C" { #endif /* OTB patches: replace "f2c.h" by "otb_6S.h" */ /*#include "f2c.h"*/ #include "otb_6S.h" /* Common Block Declarations */ Extern struct { doublereal z__[34], p[34], t[34], wh[34], wo[34]; } sixs_atm__; #define sixs_atm__1 sixs_atm__ /*< subroutine midwin >*/ /* Subroutine */ int midwin_() { /* Initialized data */ static doublereal z3[34] = { 0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12., 13.,14.,15.,16.,17.,18.,19.,20.,21.,22.,23.,24.,25.,30.,35.,40., 45.,50.,70.,100.,99999. }; static doublereal p3[34] = { 1018.,897.3,789.7,693.8,608.1,531.3,462.7, 401.6,347.3,299.2,256.8,219.9,188.2,161.,137.8,117.8,100.7,86.1, 73.5,62.8,53.7,45.8,39.1,33.4,28.6,24.3,11.1,5.18,2.53,1.29,.682, .0467,3e-4,0. }; static doublereal t3[34] = { 272.2,268.7,265.2,261.7,255.7,249.7,243.7, 237.7,231.7,225.7,219.7,219.2,218.7,218.2,217.7,217.2,216.7,216.2, 215.7,215.2,215.2,215.2,215.2,215.2,215.2,215.2,217.4,227.8,243.2, 258.5,265.7,230.7,210.2,210. }; static doublereal wh3[34] = { 3.5,2.5,1.8,1.2,.66,.38,.21,.085,.035,.016, .0075,.0069,.006,.0018,.001,7.6e-4,6.4e-4,5.6e-4,5e-4,4.9e-4, 4.5e-4,5.1e-4,5.1e-4,5.4e-4,6e-4,6.7e-4,3.6e-4,1.1e-4,4.3e-5, 1.9e-5,6.3e-6,1.4e-7,1e-9,0. }; static doublereal wo3[34] = { 6e-5,5.4e-5,4.9e-5,4.9e-5,4.9e-5,5.8e-5, 6.4e-5,7.7e-5,9e-5,1.2e-4,1.6e-4,2.1e-4,2.6e-4,3e-4,3.2e-4,3.4e-4, 3.6e-4,3.9e-4,4.1e-4,4.3e-4,4.5e-4,4.3e-4,4.3e-4,3.9e-4,3.6e-4, 3.4e-4,1.9e-4,9.2e-5,4.1e-5,1.3e-5,4.3e-6,8.6e-8,4.3e-11,0. }; integer i__; /*< common /sixs_atm/z(34),p(34),t(34),wh(34),wo(34) >*/ /*< real z3(34),p3(34),t3(34),wh3(34),wo3(34) >*/ /*< real z,p,t,wh,wo >*/ /*< integer i >*/ /* model: midlatitude winter mc clatchey */ /*< >*/ /*< >*/ /*< >*/ /*< >*/ /*< >*/ /*< do 1 i=1,34 >*/ for (i__ = 1; i__ <= 34; ++i__) { /*< z(i)=z3(i) >*/ sixs_atm__1.z__[i__ - 1] = z3[i__ - 1]; /*< p(i)=p3(i) >*/ sixs_atm__1.p[i__ - 1] = p3[i__ - 1]; /*< t(i)=t3(i) >*/ sixs_atm__1.t[i__ - 1] = t3[i__ - 1]; /*< wh(i)=wh3(i) >*/ sixs_atm__1.wh[i__ - 1] = wh3[i__ - 1]; /*< wo(i)=wo3(i) >*/ sixs_atm__1.wo[i__ - 1] = wo3[i__ - 1]; /*< 1 continue >*/ /* L1: */ } /*< return >*/ return 0; /*< end >*/ } /* midwin_ */ #ifdef __cplusplus } #endif
1,633
52,316
"Test pathbrowser, coverage 95%." from idlelib import pathbrowser import unittest from test.support import requires from tkinter import Tk import os.path import pyclbr # for _modules import sys # for sys.path from idlelib.idle_test.mock_idle import Func import idlelib # for __file__ from idlelib import browser from idlelib.tree import TreeNode class PathBrowserTest(unittest.TestCase): @classmethod def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True) @classmethod def tearDownClass(cls): cls.pb.close() cls.root.update_idletasks() cls.root.destroy() del cls.root, cls.pb def test_init(self): pb = self.pb eq = self.assertEqual eq(pb.master, self.root) eq(pyclbr._modules, {}) self.assertIsInstance(pb.node, TreeNode) self.assertIsNotNone(browser.file_open) def test_settitle(self): pb = self.pb self.assertEqual(pb.top.title(), 'Path Browser') self.assertEqual(pb.top.iconname(), 'Path Browser') def test_rootnode(self): pb = self.pb rn = pb.rootnode() self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem) def test_close(self): pb = self.pb pb.top.destroy = Func() pb.node.destroy = Func() pb.close() self.assertTrue(pb.top.destroy.called) self.assertTrue(pb.node.destroy.called) del pb.top.destroy, pb.node.destroy class DirBrowserTreeItemTest(unittest.TestCase): def test_DirBrowserTreeItem(self): # Issue16226 - make sure that getting a sublist works d = pathbrowser.DirBrowserTreeItem('') d.GetSubList() self.assertEqual('', d.GetText()) dir = os.path.split(os.path.abspath(idlelib.__file__))[0] self.assertEqual(d.ispackagedir(dir), True) self.assertEqual(d.ispackagedir(dir + '/Icons'), False) class PathBrowserTreeItemTest(unittest.TestCase): def test_PathBrowserTreeItem(self): p = pathbrowser.PathBrowserTreeItem() self.assertEqual(p.GetText(), 'sys.path') sub = p.GetSubList() self.assertEqual(len(sub), len(sys.path)) self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem) if __name__ == '__main__': unittest.main(verbosity=2, exit=False)
1,063
408
from typing import Type class RLBotException(Exception): """Base class for exceptions in this module.""" def __init__(self, msg=None): if msg is None: # Set some default useful error message msg = "An error occurred attempting to set RLBot configuration on the dll side" super(RLBotException, self).__init__(msg) class BufferOverfilledError(RLBotException): def __init__(self): super(RLBotException, self).__init__("Buffer overfilled") class MessageLargerThanMaxError(RLBotException): def __init__(self): super(RLBotException, self).__init__("Message larger than max") class InvalidNumPlayerError(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid number of cars specified in configuration") class InvalidBotSkillError(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid bot skill specified in configuration") class InvalidHumanIndex(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid human index") class InvalidPlayerIndexError(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid player index") class InvalidName(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid name error. Python side was supposed to properly sanitize this!") class InvalidTeam(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid team specified in configuration") class InvalidTeamColor(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid team color specified") class InvalidCustomColor(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid custom color specified") class InvalidGameValues(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid game values") class InvalidThrottle(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid throttle input") class InvalidSteer(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid steer input") class InvalidPitch(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid pitch input") class InvalidYaw(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid yaw input") class InvalidRoll(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid roll input") class InvalidQuickChatPreset(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid quick chat preset") class InvalidRenderType(RLBotException): def __init__(self): super(RLBotException, self).__init__("Invalid render type") class EmptyDllResponse(RLBotException): def __init__(self): super(RLBotException, self).__init__("Response from dll was empty") error_dict = {1: BufferOverfilledError, 2: MessageLargerThanMaxError, 3: InvalidNumPlayerError, 4: InvalidBotSkillError, 5: InvalidHumanIndex, 6: InvalidName, 7: InvalidTeam, 8: InvalidTeamColor, 9: InvalidCustomColor, 10: InvalidGameValues, 11: InvalidThrottle, 12: InvalidSteer, 13: InvalidPitch, 14: InvalidYaw, 15: InvalidRoll, 16: InvalidPlayerIndexError, 17: InvalidQuickChatPreset, 18: InvalidRenderType} # https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel # https://docs.python.org/3/library/typing.html#classes-functions-and-decorators def get_exception_from_error_code(error_code) -> Type['RLBotException']: try: return error_dict[error_code] except KeyError: return RLBotException
1,370
1,431
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hwpf.usermodel; import org.apache.poi.common.Duplicatable; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; import org.apache.poi.util.LittleEndian; /** * This data structure is used by a paragraph to determine how it should drop * its first letter. I think its the visual effect that will show a giant first * letter to a paragraph. I've seen this used in the first paragraph of a book */ public final class DropCapSpecifier implements Duplicatable { private static final BitField _lines = BitFieldFactory.getInstance( 0xf8 ); private static final BitField _type = BitFieldFactory.getInstance( 0x07 ); private short _fdct; public DropCapSpecifier() { _fdct = 0; } public DropCapSpecifier(DropCapSpecifier other) { _fdct = other._fdct; } public DropCapSpecifier( byte[] buf, int offset ) { this( LittleEndian.getShort( buf, offset ) ); } public DropCapSpecifier( short fdct ) { this._fdct = fdct; } @Override public DropCapSpecifier copy() { return new DropCapSpecifier(this); } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; DropCapSpecifier other = (DropCapSpecifier) obj; if ( _fdct != other._fdct ) return false; return true; } public byte getCountOfLinesToDrop() { return (byte) _lines.getValue( _fdct ); } public byte getDropCapType() { return (byte) _type.getValue( _fdct ); } @Override public int hashCode() { return _fdct; } public boolean isEmpty() { return _fdct == 0; } public void setCountOfLinesToDrop( byte value ) { _fdct = (short) _lines.setValue( _fdct, value ); } public void setDropCapType( byte value ) { _fdct = (short) _type.setValue( _fdct, value ); } public short toShort() { return _fdct; } @Override public String toString() { if ( isEmpty() ) return "[DCS] EMPTY"; return "[DCS] (type: " + getDropCapType() + "; count: " + getCountOfLinesToDrop() + ")"; } }
1,199
348
{"nom":"Saint-Ferréol-d'Auroure","circ":"1ère circonscription","dpt":"Haute-Loire","inscrits":1907,"abs":916,"votants":991,"blancs":11,"nuls":2,"exp":978,"res":[{"nuance":"LR","nom":"Mme <NAME>","voix":321},{"nuance":"REM","nom":"Mme <NAME>","voix":276},{"nuance":"FN","nom":"<NAME>","voix":185},{"nuance":"FI","nom":"Mme <NAME>","voix":103},{"nuance":"SOC","nom":"M. <NAME>","voix":30},{"nuance":"ECO","nom":"Mme <NAME>","voix":26},{"nuance":"DLF","nom":"M. <NAME>","voix":16},{"nuance":"DVG","nom":"<NAME>","voix":8},{"nuance":"EXG","nom":"M. <NAME>","voix":6},{"nuance":"ECO","nom":"M. <NAME>","voix":6},{"nuance":"DIV","nom":"M. <NAME>","voix":1},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
288
347
/* * Copyright oVirt Authors * SPDX-License-Identifier: Apache-2.0 */ package org.ovirt.engine.api.restapi.resource; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import org.ovirt.engine.api.model.ClusterFeature; import org.ovirt.engine.api.resource.ClusterFeatureResource; import org.ovirt.engine.core.common.businessentities.AdditionalFeature; public class BackendClusterFeatureResource extends AbstractBackendSubResource<ClusterFeature, AdditionalFeature> implements ClusterFeatureResource { private String version; public BackendClusterFeatureResource(String version, String id) { super(id, ClusterFeature.class, AdditionalFeature.class); this.version = version; } @Override public ClusterFeature get() { AdditionalFeature feature = BackendClusterFeatureHelper.getClusterFeature(this, version, guid); if (feature == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return addLinks(map(feature, null)); } }
347
2,539
<filename>C/zstdmt/lz5-mt.h /** * Copyright (c) 2016 - 2017 <NAME> * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * You can contact the author at: * - zstdmt source repository: https://github.com/mcmilk/zstdmt */ /* *************************************** * Defines ****************************************/ #ifndef LZ5MT_H #define LZ5MT_H #if defined (__cplusplus) extern "C" { #endif #include <stddef.h> /* size_t */ /* current maximum the library will accept */ #define LZ5MT_THREAD_MAX 128 #define LZ5MT_LEVEL_MIN 1 #define LZ5MT_LEVEL_MAX 15 #define LZ5FMT_MAGICNUMBER 0x184D2205U #define LZ5FMT_MAGIC_SKIPPABLE 0x184D2A50U /* ************************************** * Error Handling ****************************************/ extern size_t lz5mt_errcode; typedef enum { LZ5MT_error_no_error, LZ5MT_error_memory_allocation, LZ5MT_error_read_fail, LZ5MT_error_write_fail, LZ5MT_error_data_error, LZ5MT_error_frame_compress, LZ5MT_error_frame_decompress, LZ5MT_error_compressionParameter_unsupported, LZ5MT_error_compression_library, LZ5MT_error_canceled, LZ5MT_error_maxCode } LZ5MT_ErrorCode; #ifdef ERROR # undef ERROR /* reported already defined on VS 2015 (Rich Geldreich) */ #endif #define PREFIX(name) LZ5MT_error_##name #define ERROR(name) ((size_t)-PREFIX(name)) extern unsigned LZ5MT_isError(size_t code); extern const char* LZ5MT_getErrorString(size_t code); /* ************************************** * Structures ****************************************/ typedef struct { void *buf; /* ptr to data */ size_t size; /* current filled in buf */ size_t allocated; /* length of buf */ } LZ5MT_Buffer; /** * reading and writing functions * - you can use stdio functions or plain read/write * - just write some wrapper on your own * - a sample is given in 7-Zip ZS or lz5mt.c * - the function should return -1 on error and zero on success * - the read or written bytes will go to in->size or out->size */ typedef int (fn_read) (void *args, LZ5MT_Buffer * in); typedef int (fn_write) (void *args, LZ5MT_Buffer * out); typedef struct { fn_read *fn_read; void *arg_read; fn_write *fn_write; void *arg_write; } LZ5MT_RdWr_t; /* ************************************** * Compression ****************************************/ typedef struct LZ5MT_CCtx_s LZ5MT_CCtx; /** * 1) allocate new cctx * - return cctx or zero on error * * @level - 1 .. 9 * @threads - 1 .. LZ5MT_THREAD_MAX * @inputsize - if zero, becomes some optimal value for the level * - if nonzero, the given value is taken */ LZ5MT_CCtx *LZ5MT_createCCtx(int threads, int level, int inputsize); /** * 2) threaded compression * - errorcheck via */ size_t LZ5MT_compressCCtx(LZ5MT_CCtx * ctx, LZ5MT_RdWr_t * rdwr); /** * 3) get some statistic */ size_t LZ5MT_GetFramesCCtx(LZ5MT_CCtx * ctx); size_t LZ5MT_GetInsizeCCtx(LZ5MT_CCtx * ctx); size_t LZ5MT_GetOutsizeCCtx(LZ5MT_CCtx * ctx); /** * 4) free cctx * - no special return value */ void LZ5MT_freeCCtx(LZ5MT_CCtx * ctx); /* ************************************** * Decompression ****************************************/ typedef struct LZ5MT_DCtx_s LZ5MT_DCtx; /** * 1) allocate new cctx * - return cctx or zero on error * * @threads - 1 .. LZ5MT_THREAD_MAX * @ inputsize - used for single threaded standard lz5 format without skippable frames */ LZ5MT_DCtx *LZ5MT_createDCtx(int threads, int inputsize); /** * 2) threaded compression * - return -1 on error */ size_t LZ5MT_decompressDCtx(LZ5MT_DCtx * ctx, LZ5MT_RdWr_t * rdwr); /** * 3) get some statistic */ size_t LZ5MT_GetFramesDCtx(LZ5MT_DCtx * ctx); size_t LZ5MT_GetInsizeDCtx(LZ5MT_DCtx * ctx); size_t LZ5MT_GetOutsizeDCtx(LZ5MT_DCtx * ctx); /** * 4) free cctx * - no special return value */ void LZ5MT_freeDCtx(LZ5MT_DCtx * ctx); #if defined (__cplusplus) } #endif #endif /* LZ5MT_H */
1,560
778
<filename>applications/SolidMechanicsApplication/custom_constitutive/custom_yield_criteria/yield_criterion.hpp // // Project Name: KratosSolidMechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: July 2013 $ // Revision: $Revision: 0.0 $ // // #if !defined(KRATOS_YIELD_CRITERION_H_INCLUDED) #define KRATOS_YIELD_CRITERION_H_INCLUDED // System includes // External includes // Project includes #include "includes/serializer.h" #include "custom_constitutive/custom_hardening_laws/hardening_law.hpp" namespace Kratos { ///@addtogroup ApplicationNameApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ class KRATOS_API(SOLID_MECHANICS_APPLICATION) YieldCriterion { public: struct Parameters { private: const double* mpStressNorm; HardeningLaw::Parameters HardeningParameters; public: //Set Parameters void SetStressNorm (const double& rStressNorm) { mpStressNorm = &rStressNorm; }; //Get Parameters const double& GetStressNorm () const { return *mpStressNorm; }; //Set Hardening Parameters void SetRateFactor (double rRateFactor) { HardeningParameters.SetRateFactor(rRateFactor); }; void SetDeltaGamma (const double& rDeltaGamma) { HardeningParameters.SetDeltaGamma(rDeltaGamma); }; void SetLameMu_bar (const double& rLameMu_bar) { HardeningParameters.SetLameMu_bar(rLameMu_bar); }; void SetDeltaTime (const double& rDeltaTime) { HardeningParameters.SetDeltaTime(rDeltaTime); }; void SetTemperature (const double& rTemperature) { HardeningParameters.SetTemperature(rTemperature); }; void SetEquivalentPlasticStrain (const double& rEquivalentPlasticStrain) { HardeningParameters.SetEquivalentPlasticStrain(rEquivalentPlasticStrain); }; void SetEquivalentPlasticStrainOld (const double& rEquivalentPlasticStrainOld) { HardeningParameters.SetEquivalentPlasticStrainOld(rEquivalentPlasticStrainOld); }; void SetCharacteristicSize (const double& rCharacteristicSize) {HardeningParameters.SetCharacteristicSize(rCharacteristicSize);} void SetStrainMatrix (const Matrix& rStrainMatrix) { HardeningParameters.SetStrainMatrix(rStrainMatrix); } void SetStressMatrix (const Matrix& rStressMatrix) { HardeningParameters.SetStressMatrix(rStressMatrix); } //Get Hardening Parameters const double& GetRateFactor () const { return HardeningParameters.GetRateFactor(); }; const double& GetDeltaGamma () const { return HardeningParameters.GetDeltaGamma(); }; const double& GetLameMu_bar () const { return HardeningParameters.GetLameMu_bar(); }; const double& GetDeltaTime () const { return HardeningParameters.GetDeltaTime(); }; const double& GetTemperature () const { return HardeningParameters.GetTemperature(); }; const double& GetEquivalentPlasticStrain () const { return HardeningParameters.GetEquivalentPlasticStrain(); }; const double& GetEquivalentPlasticStrainOld () const { return HardeningParameters.GetEquivalentPlasticStrainOld(); }; const HardeningLaw::Parameters& GetHardeningParameters () const { return HardeningParameters; }; const double& GetCharacteristicSize () const {return HardeningParameters.GetCharacteristicSize();} const Matrix& GetStrainMatrix () const { return HardeningParameters.GetStrainMatrix(); } const Matrix& GetStressMatrix () const { return HardeningParameters.GetStressMatrix(); } }; ///@name Type Definitions ///@{ typedef HardeningLaw::Pointer HardeningLawPointer; /// Pointer definition of YieldCriterion KRATOS_CLASS_POINTER_DEFINITION( YieldCriterion ); ///@} ///@name Life Cycle ///@{ /// Default constructor. YieldCriterion() { //KRATOS_THROW_ERROR( std::logic_error, "calling the default constructor in YieldCriterion ... illegal operation!!", "" ) }; /// Initialization constructor. YieldCriterion(HardeningLawPointer pHardeningLaw) :mpHardeningLaw(pHardeningLaw) { }; /// Copy constructor. YieldCriterion(YieldCriterion const& rOther) :mpHardeningLaw(rOther.mpHardeningLaw) { }; /// Assignment operator. YieldCriterion& operator=(YieldCriterion const& rOther) { mpHardeningLaw = rOther.mpHardeningLaw; return *this; } /// Destructor. virtual ~YieldCriterion() {}; ///@} ///@name Operators ///@{ /** * Clone function (has to be implemented by any derived class) * @return a pointer to a new instance of this yield criterion */ virtual YieldCriterion::Pointer Clone() const { return Kratos::make_shared<YieldCriterion>(*this); } ///@} ///@name Operations ///@{ void InitializeMaterial (HardeningLawPointer& pHardeningLaw, const Properties& rMaterialProperties) { mpHardeningLaw = pHardeningLaw; mpHardeningLaw->InitializeMaterial(rMaterialProperties); } void SetHardeningLaw(HardeningLaw& rHardeningLaw) { mpHardeningLaw = (HardeningLawPointer) (&rHardeningLaw); } void pSetHardeningLaw(HardeningLawPointer& pHardeningLaw) { mpHardeningLaw = pHardeningLaw; } HardeningLaw& GetHardeningLaw() { return *mpHardeningLaw; } HardeningLawPointer pGetHardeningLaw() { return mpHardeningLaw; } virtual double& CalculateYieldCondition(double & rStateFunction, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rStateFunction; }; virtual double& CalculateStateFunction(double & rStateFunction, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rStateFunction; }; virtual double& CalculateDeltaStateFunction(double & rDeltaStateFunction, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rDeltaStateFunction; }; virtual double& CalculatePlasticDissipation(double & rPlasticDissipation, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rPlasticDissipation; }; virtual double& CalculateDeltaPlasticDissipation(double & rDeltaPlasticDissipation, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rDeltaPlasticDissipation; }; virtual double& CalculateImplexPlasticDissipation(double & rPlasticDissipation, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rPlasticDissipation; }; virtual double& CalculateImplexDeltaPlasticDissipation(double & rDeltaPlasticDissipation, const Parameters& rVariables) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) return rDeltaPlasticDissipation; }; //Ll: virtual void CalculateYieldFunctionDerivative(const Vector& rPrincipalStress, Vector& rFirstDerivative) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; virtual void CalculateYieldFunctionDerivative(const Vector& rPrincipalStress, Vector& rFirstDerivative, const double& rAlpha) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; virtual void CalculateYieldFunctionDerivative(const Vector& rPrincipalStress, Vector& rFirstDerivative, const double& rAlpha, const double& rBeta) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; virtual void CalculateYieldFunctionSecondDerivative(const Vector& rPrincipalStress, Vector& rSecondDerivative) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; virtual double& CalculateYieldCondition(double& rStateFunction, const Vector& rPrincipalStress, const double& rAlpha) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; virtual double& CalculateYieldCondition(double& rStateFunction, const Vector& rPrincipalStress, const double& rAlpha, const double& rBeta) { KRATOS_THROW_ERROR( std::logic_error, "calling the base class function in YieldCriterion ... illegal operation!!", "" ) }; ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ // /// Turn back information as a string. // virtual std::string Info() const; // /// Print information about this object. // virtual void PrintInfo(std::ostream& rOStream) const; // /// Print object's data. // virtual void PrintData(std::ostream& rOStream) const; ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ HardeningLawPointer mpHardeningLaw; ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Serialization ///@{ friend class Serializer; // A private default constructor necessary for serialization virtual void save(Serializer& rSerializer) const { rSerializer.save("mpHardeningLaw",mpHardeningLaw); }; virtual void load(Serializer& rSerializer) { rSerializer.load("mpHardeningLaw",mpHardeningLaw); }; ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class YieldCriterion ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ // /// input stream function // inline std::istream& operator >> (std::istream& rIStream, // YieldCriterion& rThis); // /// output stream function // inline std::ostream& operator << (std::ostream& rOStream, // const YieldCriterion& rThis) // { // rThis.PrintInfo(rOStream); // rOStream << std::endl; // rThis.PrintData(rOStream); // return rOStream; // } ///@} ///@} addtogroup block } // namespace Kratos. #endif // KRATOS_YIELD_CRITERION_H_INCLUDED defined
4,597
488
<gh_stars>100-1000 PIrExpr PIrStatement_IrAssign_get_destAddr(PIrStatement NODE); int is_op_PIrStatement_IrAssign(PIrStatement NODE); PIrExpr PIrStatement_IrAssign_get_rightSide(PIrStatement NODE); LIST_PIrMultiAssign_Assign PIrStatement_IrMultiAssign_get_assigns(PIrStatement NODE); int is_op_PIrStatement_IrMultiAssign(PIrStatement NODE); int LIST_PIrMultiAssign_Assign_empty(LIST_PIrMultiAssign_Assign L); PIrMultiAssign_Assign LIST_PIrMultiAssign_Assign_hd(LIST_PIrMultiAssign_Assign L); LIST_PIrMultiAssign_Assign LIST_PIrMultiAssign_Assign_tl(LIST_PIrMultiAssign_Assign L); PIrExpr PIrStatement_IrMultiAssign_get_rightSide(PIrStatement NODE); PIrExpr PIrStatement_IrEvaluate_get_expression(PIrStatement NODE); int is_op_PIrStatement_IrEvaluate(PIrStatement NODE); PIrControlStatement PIrStatement_N_IrControlStatement_get_node(PIrStatement NODE); int is_op_PIrStatement_N_IrControlStatement(PIrStatement NODE); PIrExpr PIrStatement_IrModuloLimit_get_localUse(PIrStatement NODE); int is_op_PIrStatement_IrModuloLimit(PIrStatement NODE); Int64 PIrStatement_IrModuloLimit_get_modulo(PIrStatement NODE); PIrExpr PIrMultiAssign_Assign_Assign_get_destAddr(PIrMultiAssign_Assign NODE); int is_op_PIrMultiAssign_Assign_Assign(PIrMultiAssign_Assign NODE); CString PIrMultiAssign_Assign_Assign_get_constraint(PIrMultiAssign_Assign NODE); Int32 PIrMultiAssign_Assign_Assign_get_reg(PIrMultiAssign_Assign NODE); PIrExpr PIrControlStatement_IrJump_get_destBlock(PIrControlStatement NODE); int is_op_PIrControlStatement_IrJump(PIrControlStatement NODE); PIrExpr PIrControlStatement_IrReturnValue_get_returnExpr(PIrControlStatement NODE); int is_op_PIrControlStatement_IrReturnValue(PIrControlStatement NODE); Int32 PIrControlStatement_IrReturnValue_get_returnReg(PIrControlStatement NODE); PIrIf PIrControlStatement_N_IrIf_get_node(PIrControlStatement NODE); int is_op_PIrControlStatement_N_IrIf(PIrControlStatement NODE); PIrExpr PIrControlStatement_N_IrIf_get_condition(PIrControlStatement NODE); PIrExpr PIrControlStatement_N_IrIf_get_thenBlock(PIrControlStatement NODE); PIrExpr PIrControlStatement_N_IrIf_get_elseBlock(PIrControlStatement NODE); PIrExpr PIrControlStatement_IrLoopStart_get_iterationCount(PIrControlStatement NODE); int is_op_PIrControlStatement_IrLoopStart(PIrControlStatement NODE); PIrExpr PIrControlStatement_IrLoopStart_get_headBlockAddr(PIrControlStatement NODE); PIrExpr PIrControlStatement_IrLoopEnd_get_headBlockAddr(PIrControlStatement NODE); int is_op_PIrControlStatement_IrLoopEnd(PIrControlStatement NODE); PIrExpr PIrControlStatement_IrLoopEnd_get_exitBlockAddr(PIrControlStatement NODE); Int64 PIrExpr_IrConstant_get_constValue(PIrExpr NODE); int is_op_PIrExpr_IrConstant(PIrExpr NODE); PIrUnary PIrExpr_N_IrUnary_get_node(PIrExpr NODE); int is_op_PIrExpr_N_IrUnary(PIrExpr NODE); PIrExpr PIrExpr_N_IrUnary_get_child(PIrExpr NODE); PIrBinary PIrExpr_N_IrBinary_get_node(PIrExpr NODE); int is_op_PIrExpr_N_IrBinary(PIrExpr NODE); PIrExpr PIrExpr_N_IrBinary_get_left(PIrExpr NODE); PIrExpr PIrExpr_N_IrBinary_get_right(PIrExpr NODE); PIrExpr PIrExpr_IrCall_get_functionAddr(PIrExpr NODE); int is_op_PIrExpr_IrCall(PIrExpr NODE); LIST_PIrCall_Argument PIrExpr_IrCall_get_arguments(PIrExpr NODE); CString PIrExpr_IrAsm_get_asmPattern(PIrExpr NODE); int is_op_PIrExpr_IrAsm(PIrExpr NODE); CString PIrExpr_IrAsm_get_scratchPattern(PIrExpr NODE); Int32 PIrExpr_IrAsm_get_exeModes(PIrExpr NODE); LIST_PIrAsm_Info PIrExpr_IrAsm_get_infos(PIrExpr NODE); LIST_PIrAsm_Arg PIrExpr_IrAsm_get_args(PIrExpr NODE); PIrExpr PIrCall_Argument_Argument_get_argExpr(PIrCall_Argument NODE); int is_op_PIrCall_Argument_Argument(PIrCall_Argument NODE); Int32 PIrCall_Argument_Argument_get_reg(PIrCall_Argument NODE); PIrExpr PIrAsm_Arg_Arg_get_expr(PIrAsm_Arg NODE); int is_op_PIrAsm_Arg_Arg(PIrAsm_Arg NODE); CString PIrAsm_Arg_Arg_get_constraint(PIrAsm_Arg NODE); Int32 PIrAsm_Arg_Arg_get_reg(PIrAsm_Arg NODE); Int32 PIrAsm_Info_Info_get_argNr(PIrAsm_Info NODE); int is_op_PIrAsm_Info_Info(PIrAsm_Info NODE); Int32 PIrAsm_Info_Info_get_group(PIrAsm_Info NODE); Int32 PIrAsm_Info_Info_get_accu(PIrAsm_Info NODE); Int32 PIrAsm_Info_Info_get_addrModifier(PIrAsm_Info NODE); Int32 PIrAsm_Info_Info_get_cplNr(PIrAsm_Info NODE); Int32 PIrAsm_Info_Info_get_psr(PIrAsm_Info NODE); PIrExpr PIrBinary_IrModuloAdd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrModuloAdd(PIrBinary NODE); PIrExpr PIrBinary_IrModuloAdd_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrModuloAdd_get_lowerBound(PIrBinary NODE); PIrExpr PIrBinary_IrModuloAdd_get_moduloSize(PIrBinary NODE); PIrExpr PIrBinary_IrCircularAdd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrCircularAdd(PIrBinary NODE); PIrExpr PIrBinary_IrCircularAdd_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrCircularAdd_get_moduloSize(PIrBinary NODE); PIrExpr PIrBinary_IrRevInc_get_left(PIrBinary NODE); int is_op_PIrBinary_IrRevInc(PIrBinary NODE); PIrExpr PIrBinary_IrRevInc_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrSatAdd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSatAdd(PIrBinary NODE); PIrExpr PIrBinary_IrSatAdd_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrSatSub_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSatSub(PIrBinary NODE); PIrExpr PIrBinary_IrSatSub_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrSatMult_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSatMult(PIrBinary NODE); PIrExpr PIrBinary_IrSatMult_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrSatDiv_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSatDiv(PIrBinary NODE); PIrExpr PIrBinary_IrSatDiv_get_right(PIrBinary NODE); IrBoolField PIrBinary_IrSatDiv_get_roundToZero(PIrBinary NODE); PIrExpr PIrBinary_IrSatShiftLeft_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSatShiftLeft(PIrBinary NODE); PIrExpr PIrBinary_IrSatShiftLeft_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrRndShiftRight_get_left(PIrBinary NODE); int is_op_PIrBinary_IrRndShiftRight(PIrBinary NODE); PIrExpr PIrBinary_IrRndShiftRight_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrAdd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrAdd(PIrBinary NODE); PIrExpr PIrBinary_IrAdd_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrDimAdd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrDimAdd(PIrBinary NODE); PIrExpr PIrBinary_IrDimAdd_get_right(PIrBinary NODE); Int32 PIrBinary_IrDimAdd_get_dimension(PIrBinary NODE); PIrExpr PIrBinary_IrSub_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSub(PIrBinary NODE); PIrExpr PIrBinary_IrSub_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrMult_get_left(PIrBinary NODE); int is_op_PIrBinary_IrMult(PIrBinary NODE); PIrExpr PIrBinary_IrMult_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrDiv_get_left(PIrBinary NODE); int is_op_PIrBinary_IrDiv(PIrBinary NODE); PIrExpr PIrBinary_IrDiv_get_right(PIrBinary NODE); IrBoolField PIrBinary_IrDiv_get_roundToZero(PIrBinary NODE); PIrExpr PIrBinary_IrMod_get_left(PIrBinary NODE); int is_op_PIrBinary_IrMod(PIrBinary NODE); PIrExpr PIrBinary_IrMod_get_right(PIrBinary NODE); IrBoolField PIrBinary_IrMod_get_roundToZero(PIrBinary NODE); PIrExpr PIrBinary_IrShiftLeft_get_left(PIrBinary NODE); int is_op_PIrBinary_IrShiftLeft(PIrBinary NODE); PIrExpr PIrBinary_IrShiftLeft_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrShiftRight_get_left(PIrBinary NODE); int is_op_PIrBinary_IrShiftRight(PIrBinary NODE); PIrExpr PIrBinary_IrShiftRight_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrMax_get_left(PIrBinary NODE); int is_op_PIrBinary_IrMax(PIrBinary NODE); PIrExpr PIrBinary_IrMax_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrMin_get_left(PIrBinary NODE); int is_op_PIrBinary_IrMin(PIrBinary NODE); PIrExpr PIrBinary_IrMin_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrOr_get_left(PIrBinary NODE); int is_op_PIrBinary_IrOr(PIrBinary NODE); PIrExpr PIrBinary_IrOr_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrAnd_get_left(PIrBinary NODE); int is_op_PIrBinary_IrAnd(PIrBinary NODE); PIrExpr PIrBinary_IrAnd_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrXor_get_left(PIrBinary NODE); int is_op_PIrBinary_IrXor(PIrBinary NODE); PIrExpr PIrBinary_IrXor_get_right(PIrBinary NODE); PIrExpr PIrBinary_IrSetBits_get_left(PIrBinary NODE); int is_op_PIrBinary_IrSetBits(PIrBinary NODE); PIrExpr PIrBinary_IrSetBits_get_right(PIrBinary NODE); Int32 PIrBinary_IrSetBits_get_offset(PIrBinary NODE); Int32 PIrBinary_IrSetBits_get_width(PIrBinary NODE); PIrExpr PIrBinary_IrComma_get_left(PIrBinary NODE); int is_op_PIrBinary_IrComma(PIrBinary NODE); PIrExpr PIrBinary_IrComma_get_right(PIrBinary NODE); PIrRelation PIrBinary_N_IrRelation_get_node(PIrBinary NODE); int is_op_PIrBinary_N_IrRelation(PIrBinary NODE); PIrExpr PIrBinary_N_IrRelation_get_left(PIrBinary NODE); PIrExpr PIrBinary_N_IrRelation_get_right(PIrBinary NODE); PIrParallelBinary PIrBinary_N_IrParallelBinary_get_node(PIrBinary NODE); int is_op_PIrBinary_N_IrParallelBinary(PIrBinary NODE); PIrExpr PIrBinary_N_IrParallelBinary_get_left(PIrBinary NODE); PIrExpr PIrBinary_N_IrParallelBinary_get_right(PIrBinary NODE); Int32 PIrBinary_N_IrParallelBinary_get_sectionBits(PIrBinary NODE); PIrExpr PIrUnary_IrBitReverse_get_child(PIrUnary NODE); int is_op_PIrUnary_IrBitReverse(PIrUnary NODE); PIrExpr PIrUnary_IrSatNegate_get_child(PIrUnary NODE); int is_op_PIrUnary_IrSatNegate(PIrUnary NODE); PIrExpr PIrUnary_IrSatAbs_get_child(PIrUnary NODE); int is_op_PIrUnary_IrSatAbs(PIrUnary NODE); PIrExpr PIrUnary_IrSat_get_child(PIrUnary NODE); int is_op_PIrUnary_IrSat(PIrUnary NODE); PIrExpr PIrUnary_IrSatRound_get_child(PIrUnary NODE); int is_op_PIrUnary_IrSatRound(PIrUnary NODE); PIrExpr PIrUnary_IrNorm_get_child(PIrUnary NODE); int is_op_PIrUnary_IrNorm(PIrUnary NODE); PIrExpr PIrUnary_IrNegate_get_child(PIrUnary NODE); int is_op_PIrUnary_IrNegate(PIrUnary NODE); PIrExpr PIrUnary_IrInvert_get_child(PIrUnary NODE); int is_op_PIrUnary_IrInvert(PIrUnary NODE); PIrExpr PIrUnary_IrNot_get_child(PIrUnary NODE); int is_op_PIrUnary_IrNot(PIrUnary NODE); PIrExpr PIrUnary_IrRead_get_child(PIrUnary NODE); int is_op_PIrUnary_IrRead(PIrUnary NODE); PIrExpr PIrUnary_IrConvert_get_child(PIrUnary NODE); int is_op_PIrUnary_IrConvert(PIrUnary NODE); PIrExpr PIrUnary_IrBitLoyalConvert_get_child(PIrUnary NODE); int is_op_PIrUnary_IrBitLoyalConvert(PIrUnary NODE); PIrExpr PIrUnary_IrRound_get_child(PIrUnary NODE); int is_op_PIrUnary_IrRound(PIrUnary NODE); Int32 PIrUnary_IrRound_get_method(PIrUnary NODE); PIrExpr PIrUnary_IrAbs_get_child(PIrUnary NODE); int is_op_PIrUnary_IrAbs(PIrUnary NODE); PIrExpr PIrUnary_IrSquare_get_child(PIrUnary NODE); int is_op_PIrUnary_IrSquare(PIrUnary NODE); PIrExpr PIrUnary_IrGetBits_get_child(PIrUnary NODE); int is_op_PIrUnary_IrGetBits(PIrUnary NODE); IrBoolField PIrUnary_IrGetBits_get_sign(PIrUnary NODE); Int32 PIrUnary_IrGetBits_get_offset(PIrUnary NODE); Int32 PIrUnary_IrGetBits_get_width(PIrUnary NODE); PIrExpr PIrUnary_IrMatchNtrm_get_child(PIrUnary NODE); int is_op_PIrUnary_IrMatchNtrm(PIrUnary NODE); Int32 PIrUnary_IrMatchNtrm_get_ntrm(PIrUnary NODE); PIrExpr PIrRelation_IrEqual_get_left(PIrRelation NODE); int is_op_PIrRelation_IrEqual(PIrRelation NODE); PIrExpr PIrRelation_IrEqual_get_right(PIrRelation NODE); PIrExpr PIrRelation_IrUnequal_get_left(PIrRelation NODE); int is_op_PIrRelation_IrUnequal(PIrRelation NODE); PIrExpr PIrRelation_IrUnequal_get_right(PIrRelation NODE); PIrExpr PIrRelation_IrGreater_get_left(PIrRelation NODE); int is_op_PIrRelation_IrGreater(PIrRelation NODE); PIrExpr PIrRelation_IrGreater_get_right(PIrRelation NODE); PIrExpr PIrRelation_IrGreaterEqual_get_left(PIrRelation NODE); int is_op_PIrRelation_IrGreaterEqual(PIrRelation NODE); PIrExpr PIrRelation_IrGreaterEqual_get_right(PIrRelation NODE); PIrExpr PIrRelation_IrLess_get_left(PIrRelation NODE); int is_op_PIrRelation_IrLess(PIrRelation NODE); PIrExpr PIrRelation_IrLess_get_right(PIrRelation NODE); PIrExpr PIrRelation_IrLessEqual_get_left(PIrRelation NODE); int is_op_PIrRelation_IrLessEqual(PIrRelation NODE); PIrExpr PIrRelation_IrLessEqual_get_right(PIrRelation NODE); PIrExpr PIrParallelBinary_IrParallelAdd_get_left(PIrParallelBinary NODE); int is_op_PIrParallelBinary_IrParallelAdd(PIrParallelBinary NODE); PIrExpr PIrParallelBinary_IrParallelAdd_get_right(PIrParallelBinary NODE); Int32 PIrParallelBinary_IrParallelAdd_get_sectionBits(PIrParallelBinary NODE); PIrExpr PIrParallelBinary_IrParallelSub_get_left(PIrParallelBinary NODE); int is_op_PIrParallelBinary_IrParallelSub(PIrParallelBinary NODE); PIrExpr PIrParallelBinary_IrParallelSub_get_right(PIrParallelBinary NODE); Int32 PIrParallelBinary_IrParallelSub_get_sectionBits(PIrParallelBinary NODE);
5,569
738
<reponame>liufangqi/hudi /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hudi.utilities; import org.apache.hudi.HoodieTestCommitGenerator; import org.apache.hudi.client.HoodieReadClient; import org.apache.hudi.client.SparkRDDWriteClient; import org.apache.hudi.client.common.HoodieSparkEngineContext; import org.apache.hudi.common.engine.HoodieEngineContext; import org.apache.hudi.common.fs.FSUtils; import org.apache.hudi.common.testutils.HoodieCommonTestHarness; import org.apache.hudi.common.testutils.HoodieTestUtils; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.collection.Pair; import org.apache.hudi.exception.HoodieIOException; import org.apache.hudi.testutils.providers.SparkProvider; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SparkSession; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.provider.Arguments; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.hudi.HoodieTestCommitGenerator.getBaseFilename; import static org.apache.hudi.HoodieTestCommitGenerator.getLogFilename; import static org.apache.hudi.HoodieTestCommitGenerator.initCommitInfoForRepairTests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class TestHoodieRepairTool extends HoodieCommonTestHarness implements SparkProvider { private static final Logger LOG = LogManager.getLogger(TestHoodieRepairTool.class); // Instant time -> List<Pair<relativePartitionPath, fileId>> private static final Map<String, List<Pair<String, String>>> BASE_FILE_INFO = new HashMap<>(); private static final Map<String, List<Pair<String, String>>> LOG_FILE_INFO = new HashMap<>(); // Relative paths to base path for dangling files private static final List<String> DANGLING_DATA_FILE_LIST = new ArrayList<>(); private static transient SparkSession spark; private static transient SQLContext sqlContext; private static transient JavaSparkContext jsc; private static transient HoodieSparkEngineContext context; // instant time -> partitionPathToFileIdAndNameMap private final Map<String, Map<String, List<Pair<String, String>>>> instantInfoMap = new HashMap<>(); private final List<String> allFileAbsolutePathList = new ArrayList<>(); private java.nio.file.Path backupTempDir; @BeforeAll static void initFileInfo() { initCommitInfoForRepairTests(BASE_FILE_INFO, LOG_FILE_INFO); initDanglingDataFileList(); } @BeforeEach public void initWithCleanState() throws IOException { boolean initialized = spark != null; if (!initialized) { SparkConf sparkConf = conf(); SparkRDDWriteClient.registerClasses(sparkConf); HoodieReadClient.addHoodieSupport(sparkConf); spark = SparkSession.builder().config(sparkConf).getOrCreate(); sqlContext = spark.sqlContext(); jsc = new JavaSparkContext(spark.sparkContext()); context = new HoodieSparkEngineContext(jsc); } initPath(); metaClient = HoodieTestUtils.init(basePath, getTableType()); backupTempDir = tempDir.resolve("backup"); cleanUpDanglingDataFilesInFS(); cleanUpBackupTempDir(); HoodieTestCommitGenerator.setupTimelineInFS( basePath, BASE_FILE_INFO, LOG_FILE_INFO, instantInfoMap); allFileAbsolutePathList.clear(); allFileAbsolutePathList.addAll(instantInfoMap.entrySet().stream() .flatMap(e -> e.getValue().entrySet().stream() .flatMap(partition -> partition.getValue().stream() .map(fileInfo -> new Path( new Path(basePath, partition.getKey()), fileInfo.getValue()).toString()) .collect(Collectors.toList()) .stream()) .collect(Collectors.toList()) .stream() ) .collect(Collectors.toList())); } @AfterEach public void cleanUp() throws IOException { cleanUpDanglingDataFilesInFS(); cleanUpBackupTempDir(); } @AfterAll public static synchronized void resetSpark() { if (spark != null) { spark.close(); spark = null; } } private void cleanUpDanglingDataFilesInFS() { FileSystem fs = metaClient.getFs(); DANGLING_DATA_FILE_LIST.forEach( relativeFilePath -> { Path path = new Path(basePath, relativeFilePath); try { if (fs.exists(path)) { fs.delete(path, false); } } catch (IOException e) { throw new HoodieIOException("Unable to delete file: " + path); } } ); } private void cleanUpBackupTempDir() throws IOException { FileSystem fs = metaClient.getFs(); fs.delete(new Path(backupTempDir.toAbsolutePath().toString()), true); } private static void initDanglingDataFileList() { DANGLING_DATA_FILE_LIST.add( new Path("2022/01/01", getBaseFilename("000", UUID.randomUUID().toString())).toString()); DANGLING_DATA_FILE_LIST.add( new Path("2022/01/06", getLogFilename("001", UUID.randomUUID().toString())).toString()); } private Stream<Arguments> configPathParams() { Object[][] data = new Object[][] { {null, basePath, -1}, {basePath + "/backup", basePath, -1}, {"/tmp/backup", basePath, 0} }; return Stream.of(data).map(Arguments::of); } @Test public void testCheckBackupPathAgainstBasePath() { configPathParams().forEach(arguments -> { Object[] args = arguments.get(); String backupPath = (String) args[0]; String basePath = (String) args[1]; int expectedResult = (Integer) args[2]; HoodieRepairTool.Config config = new HoodieRepairTool.Config(); config.backupPath = backupPath; config.basePath = basePath; HoodieRepairTool tool = new HoodieRepairTool(jsc, config); assertEquals(expectedResult, tool.checkBackupPathAgainstBasePath()); }); } private Stream<Arguments> configPathParamsWithFS() throws IOException { SecureRandom random = new SecureRandom(); long randomLong = random.nextLong(); String emptyBackupPath = "/tmp/empty_backup_" + randomLong; FSUtils.createPathIfNotExists(metaClient.getFs(), new Path(emptyBackupPath)); String nonEmptyBackupPath = "/tmp/nonempty_backup_" + randomLong; FSUtils.createPathIfNotExists(metaClient.getFs(), new Path(nonEmptyBackupPath)); FSUtils.createPathIfNotExists(metaClient.getFs(), new Path(nonEmptyBackupPath, ".hoodie")); Object[][] data = new Object[][] { {null, basePath, 0}, {"/tmp/backup", basePath, 0}, {emptyBackupPath, basePath, 0}, {basePath + "/backup", basePath, -1}, {nonEmptyBackupPath, basePath, -1}, }; return Stream.of(data).map(Arguments::of); } @Test public void testCheckBackupPathForRepair() throws IOException { for (Arguments arguments: configPathParamsWithFS().collect(Collectors.toList())) { Object[] args = arguments.get(); String backupPath = (String) args[0]; String basePath = (String) args[1]; int expectedResult = (Integer) args[2]; HoodieRepairTool.Config config = new HoodieRepairTool.Config(); config.backupPath = backupPath; config.basePath = basePath; HoodieRepairTool tool = new HoodieRepairTool(jsc, config); assertEquals(expectedResult, tool.checkBackupPathForRepair()); if (backupPath == null) { // Backup path should be created if not provided assertNotNull(config.backupPath); } } } @Test public void testRepairWithIntactInstants() throws IOException { testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.REPAIR.toString(), backupTempDir.toAbsolutePath().toString(), true, allFileAbsolutePathList, Collections.emptyList()); } @Test public void testRepairWithBrokenInstants() throws IOException { List<String> tableDanglingFileList = createDanglingDataFilesInFS(basePath); String backupPath = backupTempDir.toAbsolutePath().toString(); List<String> backupDanglingFileList = DANGLING_DATA_FILE_LIST.stream() .map(filePath -> new Path(backupPath, filePath).toString()) .collect(Collectors.toList()); List<String> existingFileList = new ArrayList<>(allFileAbsolutePathList); existingFileList.addAll(backupDanglingFileList); testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.REPAIR.toString(), backupPath, true, existingFileList, tableDanglingFileList); } @Test public void testRepairWithOneBrokenInstant() throws IOException { List<String> tableDanglingFileList = createDanglingDataFilesInFS(basePath); String backupPath = backupTempDir.toAbsolutePath().toString(); List<String> backupDanglingFileList = DANGLING_DATA_FILE_LIST .subList(1, 2).stream() .map(filePath -> new Path(backupPath, filePath).toString()) .collect(Collectors.toList()); List<String> existingFileList = new ArrayList<>(allFileAbsolutePathList); existingFileList.addAll(backupDanglingFileList); existingFileList.addAll(tableDanglingFileList.subList(0, 1)); testRepairToolWithMode( Option.of("001"), Option.empty(), HoodieRepairTool.Mode.REPAIR.toString(), backupPath, true, existingFileList, tableDanglingFileList.subList(1, 2)); } @Test public void testDryRunWithBrokenInstants() throws IOException { List<String> tableDanglingFileList = createDanglingDataFilesInFS(basePath); String backupPath = backupTempDir.toAbsolutePath().toString(); List<String> backupDanglingFileList = DANGLING_DATA_FILE_LIST.stream() .map(filePath -> new Path(backupPath, filePath).toString()) .collect(Collectors.toList()); List<String> existingFileList = new ArrayList<>(allFileAbsolutePathList); existingFileList.addAll(tableDanglingFileList); testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.DRY_RUN.toString(), backupPath, true, existingFileList, backupDanglingFileList); } @Test public void testDryRunWithOneBrokenInstant() throws IOException { List<String> tableDanglingFileList = createDanglingDataFilesInFS(basePath); String backupPath = backupTempDir.toAbsolutePath().toString(); List<String> backupDanglingFileList = DANGLING_DATA_FILE_LIST.stream() .map(filePath -> new Path(backupPath, filePath).toString()) .collect(Collectors.toList()); List<String> existingFileList = new ArrayList<>(allFileAbsolutePathList); existingFileList.addAll(tableDanglingFileList); testRepairToolWithMode( Option.of("001"), Option.empty(), HoodieRepairTool.Mode.DRY_RUN.toString(), backupPath, true, existingFileList, backupDanglingFileList); } @Test public void testUndoWithNonExistentBackupPath() throws IOException { String backupPath = backupTempDir.toAbsolutePath().toString(); metaClient.getFs().delete(new Path(backupPath), true); testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.UNDO.toString(), backupPath, false, allFileAbsolutePathList, Collections.emptyList()); } @Test public void testUndoWithExistingBackupPath() throws IOException { String backupPath = backupTempDir.toAbsolutePath().toString(); List<String> backupDanglingFileList = createDanglingDataFilesInFS(backupPath); List<String> restoreDanglingFileList = DANGLING_DATA_FILE_LIST.stream() .map(filePath -> new Path(basePath, filePath).toString()) .collect(Collectors.toList()); List<String> existingFileList = new ArrayList<>(allFileAbsolutePathList); existingFileList.addAll(backupDanglingFileList); existingFileList.addAll(restoreDanglingFileList); verifyFilesInFS(allFileAbsolutePathList, restoreDanglingFileList); verifyFilesInFS(backupDanglingFileList, Collections.emptyList()); testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.UNDO.toString(), backupPath, true, existingFileList, Collections.emptyList()); // Second run should fail testRepairToolWithMode( Option.empty(), Option.empty(), HoodieRepairTool.Mode.UNDO.toString(), backupPath, false, existingFileList, Collections.emptyList()); } private void testRepairToolWithMode( Option<String> startingInstantOption, Option<String> endingInstantOption, String runningMode, String backupPath, boolean isRunSuccessful, List<String> existFilePathList, List<String> nonExistFilePathList) throws IOException { HoodieRepairTool.Config config = new HoodieRepairTool.Config(); config.backupPath = backupPath; config.basePath = basePath; config.assumeDatePartitioning = true; if (startingInstantOption.isPresent()) { config.startingInstantTime = startingInstantOption.get(); } if (endingInstantOption.isPresent()) { config.endingInstantTime = endingInstantOption.get(); } config.runningMode = runningMode; HoodieRepairTool tool = new HoodieRepairTool(jsc, config); assertEquals(isRunSuccessful, tool.run()); verifyFilesInFS(existFilePathList, nonExistFilePathList); } private void verifyFilesInFS( List<String> existFilePathList, List<String> nonExistFilePathList) throws IOException { FileSystem fs = metaClient.getFs(); for (String filePath : existFilePathList) { assertTrue(fs.exists(new Path(filePath)), String.format("File %s should exist but it's not in the file system", filePath)); } for (String filePath : nonExistFilePathList) { assertFalse(fs.exists(new Path(filePath)), String.format("File %s should not exist but it's in the file system", filePath)); } } private List<String> createDanglingDataFilesInFS(String parentPath) { FileSystem fs = metaClient.getFs(); return DANGLING_DATA_FILE_LIST.stream().map(relativeFilePath -> { Path path = new Path(parentPath, relativeFilePath); try { fs.mkdirs(path.getParent()); if (!fs.exists(path)) { fs.create(path, false); } } catch (IOException e) { LOG.error("Error creating file: " + path); } return path.toString(); }) .collect(Collectors.toList()); } @Override public HoodieEngineContext context() { return context; } @Override public SparkSession spark() { return spark; } @Override public SQLContext sqlContext() { return sqlContext; } @Override public JavaSparkContext jsc() { return jsc; } }
5,784
1,490
# This code is supporting material for the book # Building Machine Learning Systems with Python # by <NAME> and <NAME> # published by PACKT Publishing # # It is made available under the MIT License # This script generates web traffic data for our hypothetical # web startup "MLASS" in chapter 01 import os import scipy as sp from scipy.stats import gamma import matplotlib.pyplot as plt from utils import DATA_DIR, CHART_DIR sp.random.seed(3) # to reproduce the data later on x = sp.arange(1, 31*24) y = sp.array(200*(sp.sin(2*sp.pi*x/(7*24))), dtype=int) y += gamma.rvs(15, loc=0, scale=100, size=len(x)) y += 2 * sp.exp(x/100.0) y = sp.ma.array(y, mask=[y<0]) print(sum(y), sum(y<0)) plt.scatter(x, y) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks([w*7*24 for w in range(5)], ['week %i' %(w+1) for w in range(5)]) plt.autoscale(tight=True) plt.grid() plt.savefig(os.path.join(CHART_DIR, "1400_01_01.png")) sp.savetxt(os.path.join(DATA_DIR, "web_traffic.tsv"), list(zip(x, y)), delimiter="\t", fmt="%s")
449
709
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 <NAME> // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "IEmpty.hpp" namespace s3d { class CEmpty final : public ISiv3DEmpty { private: public: }; }
131
348
{"nom":"Saint-Aubin-d'Aubigné","circ":"6ème circonscription","dpt":"Ille-et-Vilaine","inscrits":2693,"abs":1286,"votants":1407,"blancs":17,"nuls":11,"exp":1379,"res":[{"nuance":"REM","nom":"<NAME>","voix":666},{"nuance":"UDI","nom":"M. <NAME>","voix":254},{"nuance":"FI","nom":"<NAME>","voix":175},{"nuance":"COM","nom":"M. <NAME>","voix":133},{"nuance":"FN","nom":"<NAME>","voix":105},{"nuance":"ECO","nom":"Mme <NAME>","voix":11},{"nuance":"REG","nom":"Mme <NAME>","voix":11},{"nuance":"DVD","nom":"Mme <NAME>","voix":10},{"nuance":"DIV","nom":"<NAME>","voix":7},{"nuance":"EXG","nom":"<NAME>","voix":7},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
266
385
<reponame>3096/starlight /** * @file stream.h * @brief Binary/Text I/O Streaming */ #pragma once #include "types.h" namespace sead { class StreamFormat; class StreamSrc; class Endian { public: enum Types { BIG = 0, LITTLE = 1 }; }; class Stream { public: enum Modes { BINARY = 0, TEXT = 1 }; Stream(); Stream(sead::StreamSrc *, sead::Stream::Modes); Stream(sead::StreamSrc *, sead::StreamFormat *); virtual ~Stream(); void setMode(sead::Stream::Modes); void setUserFormat(sead::StreamFormat *); void setBinaryEndian(sead::Endian::Types); void skip(u32 howMany); void skip(u32, u32); void rewind(); bool isEOF(); sead::StreamFormat* mStreamFormat; // _8 sead::StreamSrc* mSrc; // _10 sead::Endian::Types mEndianess; // _18 }; class ReadStream { }; class WriteStream { }; };
521
2,999
<gh_stars>1000+ /* Copyright 2017 - 2021 <NAME> * Copyright 2017 - 2021 Quarkslab * * 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 "DosHeader.hpp" namespace LIEF { namespace PE { void init_c_dos_header(Pe_Binary_t* c_binary, Binary* binary) { const DosHeader& dos_header = binary->dos_header(); c_binary->dos_header.magic = dos_header.magic(); c_binary->dos_header.used_bytes_in_the_last_page = dos_header.used_bytes_in_the_last_page(); c_binary->dos_header.file_size_in_pages = dos_header.file_size_in_pages(); c_binary->dos_header.numberof_relocation = dos_header.numberof_relocation(); c_binary->dos_header.header_size_in_paragraphs = dos_header.header_size_in_paragraphs(); c_binary->dos_header.minimum_extra_paragraphs = dos_header.minimum_extra_paragraphs(); c_binary->dos_header.maximum_extra_paragraphs = dos_header.maximum_extra_paragraphs(); c_binary->dos_header.initial_relative_ss = dos_header.initial_relative_ss(); c_binary->dos_header.initial_sp = dos_header.initial_sp(); c_binary->dos_header.checksum = dos_header.checksum(); c_binary->dos_header.initial_ip = dos_header.initial_ip(); c_binary->dos_header.initial_relative_cs = dos_header.initial_relative_cs(); c_binary->dos_header.addressof_relocation_table = dos_header.addressof_relocation_table(); c_binary->dos_header.overlay_number = dos_header.overlay_number(); c_binary->dos_header.oem_id = dos_header.oem_id(); c_binary->dos_header.oem_info = dos_header.oem_info(); c_binary->dos_header.addressof_new_exeheader = dos_header.addressof_new_exeheader(); const DosHeader::reserved_t& reserved = dos_header.reserved(); std::copy( std::begin(reserved), std::end(reserved), c_binary->dos_header.reserved); const DosHeader::reserved2_t& reserved2 = dos_header.reserved2(); std::copy( std::begin(reserved2), std::end(reserved2), c_binary->dos_header.reserved2); } } }
1,035
679
/************************************************************** * * 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_cui.hxx" #include <memory> #include <sfx2/objsh.hxx> #include <vcl/svapp.hxx> #include <vcl/msgbox.hxx> #include <vos/mutex.hxx> #include <cuires.hrc> #include "scriptdlg.hrc" #include "scriptdlg.hxx" #include <dialmgr.hxx> #include "selector.hxx" #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/frame/XDesktop.hpp> #include <com/sun/star/script/XInvocation.hpp> #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp> #include <com/sun/star/script/provider/XScriptProvider.hpp> #include <com/sun/star/script/browse/BrowseNodeTypes.hpp> #include <com/sun/star/script/browse/XBrowseNodeFactory.hpp> #include <com/sun/star/script/browse/BrowseNodeFactoryViewTypes.hpp> #include <com/sun/star/script/provider/ScriptErrorRaisedException.hpp> #include <com/sun/star/script/provider/ScriptExceptionRaisedException.hpp> #include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp> #include <com/sun/star/frame/XModuleManager.hpp> #include <com/sun/star/script/XInvocation.hpp> #include <com/sun/star/document/XEmbeddedScripts.hpp> #include <cppuhelper/implbase1.hxx> #include <comphelper/documentinfo.hxx> #include <comphelper/uno3.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/propertycontainer.hxx> #include <comphelper/proparrhlp.hxx> #include <basic/sbx.hxx> #include <svtools/imagemgr.hxx> #include <tools/urlobj.hxx> #include <vector> #include <algorithm> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::script; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::document; void ShowErrorDialog( const Any& aException ) { SvxScriptErrorDialog* pDlg = new SvxScriptErrorDialog( NULL, aException ); pDlg->Execute(); delete pDlg; } SFTreeListBox::SFTreeListBox( Window* pParent, const ResId& rResId ) : SvTreeListBox( pParent, ResId( rResId.GetId(),*rResId.GetResMgr() ) ), m_hdImage(ResId(IMG_HARDDISK,*rResId.GetResMgr())), m_hdImage_hc(ResId(IMG_HARDDISK_HC,*rResId.GetResMgr())), m_libImage(ResId(IMG_LIB,*rResId.GetResMgr())), m_libImage_hc(ResId(IMG_LIB_HC,*rResId.GetResMgr())), m_macImage(ResId(IMG_MACRO,*rResId.GetResMgr())), m_macImage_hc(ResId(IMG_MACRO_HC,*rResId.GetResMgr())), m_docImage(ResId(IMG_DOCUMENT,*rResId.GetResMgr())), m_docImage_hc(ResId(IMG_DOCUMENT_HC,*rResId.GetResMgr())), m_sMyMacros(String(ResId(STR_MYMACROS,*rResId.GetResMgr()))), m_sProdMacros(String(ResId(STR_PRODMACROS,*rResId.GetResMgr()))) { FreeResource(); SetSelectionMode( SINGLE_SELECTION ); SetStyle( GetStyle() | WB_CLIPCHILDREN | WB_HSCROLL | WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HIDESELECTION | WB_HASLINES | WB_HASLINESATROOT ); SetNodeDefaultImages(); nMode = 0xFF; // Alles } SFTreeListBox::~SFTreeListBox() { deleteAllTree(); } void SFTreeListBox::delUserData( SvLBoxEntry* pEntry ) { if ( pEntry ) { String text = GetEntryText( pEntry ); SFEntry* pUserData = (SFEntry*)pEntry->GetUserData(); if ( pUserData ) { delete pUserData; // TBD seem to get a Select event on node that is remove ( below ) // so need to be able to detect that this node is not to be // processed in order to do this, setting userData to NULL ( must // be a better way to do this ) pUserData = 0; pEntry->SetUserData( pUserData ); } } } void SFTreeListBox::deleteTree( SvLBoxEntry* pEntry ) { delUserData( pEntry ); pEntry = FirstChild( pEntry ); while ( pEntry ) { SvLBoxEntry* pNextEntry = NextSibling( pEntry ); deleteTree( pEntry ); GetModel()->Remove( pEntry ); pEntry = pNextEntry; } } void SFTreeListBox::deleteAllTree() { SvLBoxEntry* pEntry = GetEntry( 0 ); // TBD - below is a candidate for a destroyAllTrees method if ( pEntry ) { while ( pEntry ) { String text = GetEntryText( pEntry ); SvLBoxEntry* pNextEntry = NextSibling( pEntry ) ; deleteTree( pEntry ); GetModel()->Remove( pEntry ); pEntry = pNextEntry; } } } void SFTreeListBox::Init( const ::rtl::OUString& language ) { SetUpdateMode( sal_False ); deleteAllTree(); Reference< browse::XBrowseNode > rootNode; Reference< XComponentContext > xCtx; Sequence< Reference< browse::XBrowseNode > > children; ::rtl::OUString userStr = ::rtl::OUString::createFromAscii("user"); ::rtl::OUString shareStr = ::rtl::OUString::createFromAscii("share"); ::rtl::OUString singleton = ::rtl::OUString::createFromAscii( "/singletons/com.sun.star.script.browse.theBrowseNodeFactory" ); try { Reference < beans::XPropertySet > xProps( ::comphelper::getProcessServiceFactory(), UNO_QUERY_THROW ); xCtx.set( xProps->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext" ))), UNO_QUERY_THROW ); Reference< browse::XBrowseNodeFactory > xFac( xCtx->getValueByName( singleton ), UNO_QUERY_THROW ); rootNode.set( xFac->createView( browse::BrowseNodeFactoryViewTypes::MACROORGANIZER ) ); if ( rootNode.is() && rootNode->hasChildNodes() == sal_True ) { children = rootNode->getChildNodes(); } } catch( Exception& e ) { OSL_TRACE("Exception getting root browse node from factory: %s", ::rtl::OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).pData->buffer ); // TODO exception handling } Reference<XModel> xDocumentModel; for ( sal_Int32 n = 0; n < children.getLength(); n++ ) { bool app = false; ::rtl::OUString uiName = children[ n ]->getName(); ::rtl::OUString factoryURL; if ( uiName.equals( userStr ) || uiName.equals( shareStr ) ) { app = true; if ( uiName.equals( userStr ) ) { uiName = m_sMyMacros; } else { uiName = m_sProdMacros; } } else { xDocumentModel.set(getDocumentModel(xCtx, uiName ), UNO_QUERY); if ( xDocumentModel.is() ) { Reference< ::com::sun::star::frame::XModuleManager > xModuleManager( xCtx->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager"), xCtx ), UNO_QUERY_THROW ); Reference<container::XNameAccess> xModuleConfig( xModuleManager, UNO_QUERY_THROW ); // get the long name of the document: Sequence<beans::PropertyValue> moduleDescr; try{ ::rtl::OUString appModule = xModuleManager->identify( xDocumentModel ); xModuleConfig->getByName(appModule) >>= moduleDescr; } catch(const uno::Exception&) {} beans::PropertyValue const * pmoduleDescr = moduleDescr.getConstArray(); for ( sal_Int32 pos = moduleDescr.getLength(); pos--; ) { if (pmoduleDescr[ pos ].Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ooSetupFactoryEmptyDocumentURL") )) { pmoduleDescr[ pos ].Value >>= factoryURL; break; } } } } ::rtl::OUString lang( language ); Reference< browse::XBrowseNode > langEntries = getLangNodeFromRootNode( children[ n ], lang ); /*SvLBoxEntry* pBasicManagerRootEntry =*/ insertEntry( uiName, app ? IMG_HARDDISK : IMG_DOCUMENT, 0, true, std::auto_ptr< SFEntry >(new SFEntry( OBJTYPE_SFROOT, langEntries, xDocumentModel )), factoryURL ); } SetUpdateMode( sal_True ); } Reference< XInterface > SFTreeListBox::getDocumentModel( Reference< XComponentContext >& xCtx, ::rtl::OUString& docName ) { Reference< XInterface > xModel; Reference< lang::XMultiComponentFactory > mcf = xCtx->getServiceManager(); Reference< frame::XDesktop > desktop ( mcf->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop"), xCtx ), UNO_QUERY ); Reference< container::XEnumerationAccess > componentsAccess = desktop->getComponents(); Reference< container::XEnumeration > components = componentsAccess->createEnumeration(); while (components->hasMoreElements()) { Reference< frame::XModel > model( components->nextElement(), UNO_QUERY ); if ( model.is() ) { ::rtl::OUString sTdocUrl = ::comphelper::DocumentInfo::getDocumentTitle( model ); if( sTdocUrl.equals( docName ) ) { xModel = model; break; } } } return xModel; } Reference< browse::XBrowseNode > SFTreeListBox::getLangNodeFromRootNode( Reference< browse::XBrowseNode >& rootNode, ::rtl::OUString& language ) { Reference< browse::XBrowseNode > langNode; try { Sequence < Reference< browse::XBrowseNode > > children = rootNode->getChildNodes(); for ( sal_Int32 n = 0; n < children.getLength(); n++ ) { if ( children[ n ]->getName().equals( language ) ) { langNode = children[ n ]; break; } } } catch ( Exception& ) { // if getChildNodes() throws an exception we just return // the empty Reference } return langNode; } void SFTreeListBox:: RequestSubEntries( SvLBoxEntry* pRootEntry, Reference< ::com::sun::star::script::browse::XBrowseNode >& node, Reference< XModel >& model ) { if (! node.is() ) { return; } Sequence< Reference< browse::XBrowseNode > > children; try { children = node->getChildNodes(); } catch ( Exception& ) { // if we catch an exception in getChildNodes then no entries are added } for ( sal_Int32 n = 0; n < children.getLength(); n++ ) { ::rtl::OUString name( children[ n ]->getName() ); if ( children[ n ]->getType() != browse::BrowseNodeTypes::SCRIPT) { insertEntry( name, IMG_LIB, pRootEntry, true, std::auto_ptr< SFEntry >(new SFEntry( OBJTYPE_SCRIPTCONTAINER, children[ n ],model ))); } else { if ( children[ n ]->getType() == browse::BrowseNodeTypes::SCRIPT ) { insertEntry( name, IMG_MACRO, pRootEntry, false, std::auto_ptr< SFEntry >(new SFEntry( OBJTYPE_METHOD, children[ n ],model ))); } } } } long SFTreeListBox::ExpandingHdl() { return sal_True; } void SFTreeListBox::ExpandAllTrees() { } SvLBoxEntry * SFTreeListBox::insertEntry( String const & rText, sal_uInt16 nBitmap, SvLBoxEntry * pParent, bool bChildrenOnDemand, std::auto_ptr< SFEntry > aUserData, ::rtl::OUString factoryURL ) { SvLBoxEntry * p; if( nBitmap == IMG_DOCUMENT && factoryURL.getLength() > 0 ) { Image aImage = SvFileInformationManager::GetFileImage( INetURLObject(factoryURL), false, BMP_COLOR_NORMAL ); Image aHCImage = SvFileInformationManager::GetFileImage( INetURLObject(factoryURL), false, BMP_COLOR_HIGHCONTRAST ); p = InsertEntry( rText, aImage, aImage, pParent, bChildrenOnDemand, LIST_APPEND, aUserData.release()); // XXX possible leak SetExpandedEntryBmp(p, aHCImage, BMP_COLOR_HIGHCONTRAST); SetCollapsedEntryBmp(p, aHCImage, BMP_COLOR_HIGHCONTRAST); } else { p = insertEntry( rText, nBitmap, pParent, bChildrenOnDemand, aUserData ); } return p; } SvLBoxEntry * SFTreeListBox::insertEntry( String const & rText, sal_uInt16 nBitmap, SvLBoxEntry * pParent, bool bChildrenOnDemand, std::auto_ptr< SFEntry > aUserData ) { Image aHCImage, aImage; if( nBitmap == IMG_HARDDISK ) { aImage = m_hdImage; aHCImage = m_hdImage_hc; } else if( nBitmap == IMG_LIB ) { aImage = m_libImage; aHCImage = m_libImage_hc; } else if( nBitmap == IMG_MACRO ) { aImage = m_macImage; aHCImage = m_macImage_hc; } else if( nBitmap == IMG_DOCUMENT ) { aImage = m_docImage; aHCImage = m_docImage_hc; } SvLBoxEntry * p = InsertEntry( rText, aImage, aImage, pParent, bChildrenOnDemand, LIST_APPEND, aUserData.release()); // XXX possible leak SetExpandedEntryBmp(p, aHCImage, BMP_COLOR_HIGHCONTRAST); SetCollapsedEntryBmp(p, aHCImage, BMP_COLOR_HIGHCONTRAST); return p; } void __EXPORT SFTreeListBox::RequestingChilds( SvLBoxEntry* pEntry ) { SFEntry* userData = 0; if ( !pEntry ) { return; } userData = (SFEntry*)pEntry->GetUserData(); Reference< browse::XBrowseNode > node; Reference< XModel > model; if ( userData && !userData->isLoaded() ) { node = userData->GetNode(); model = userData->GetModel(); RequestSubEntries( pEntry, node, model ); userData->setLoaded(); } } void __EXPORT SFTreeListBox::ExpandedHdl() { /* SvLBoxEntry* pEntry = GetHdlEntry(); DBG_ASSERT( pEntry, "Was wurde zugeklappt?" ); if ( !IsExpanded( pEntry ) && pEntry->HasChildsOnDemand() ) { SvLBoxEntry* pChild = FirstChild( pEntry ); while ( pChild ) { GetModel()->Remove( pChild ); // Ruft auch den DTOR pChild = FirstChild( pEntry ); } }*/ } // ---------------------------------------------------------------------------- // InputDialog ------------------------------------------------------------ // ---------------------------------------------------------------------------- InputDialog::InputDialog(Window * pParent, sal_uInt16 nMode ) : ModalDialog( pParent, CUI_RES( RID_DLG_NEWLIB ) ), aText( this, CUI_RES( FT_NEWLIB ) ), aEdit( this, CUI_RES( ED_LIBNAME ) ), aOKButton( this, CUI_RES( PB_OK ) ), aCancelButton( this, CUI_RES( PB_CANCEL ) ) { aEdit.GrabFocus(); if ( nMode == INPUTMODE_NEWLIB ) { SetText( String( CUI_RES( STR_NEWLIB ) ) ); } else if ( nMode == INPUTMODE_NEWMACRO ) { SetText( String( CUI_RES( STR_NEWMACRO ) ) ); aText.SetText( String( CUI_RES( STR_FT_NEWMACRO ) ) ); } else if ( nMode == INPUTMODE_RENAME ) { SetText( String( CUI_RES( STR_RENAME ) ) ); aText.SetText( String( CUI_RES( STR_FT_RENAME ) ) ); } FreeResource(); // some resizing so that the text fits Point point, newPoint; Size siz, newSiz; long gap; sal_uInt16 style = TEXT_DRAW_MULTILINE | TEXT_DRAW_TOP | TEXT_DRAW_LEFT | TEXT_DRAW_WORDBREAK; // get dimensions of dialog instructions control point = aText.GetPosPixel(); siz = aText.GetSizePixel(); // get dimensions occupied by text in the control Rectangle rect = GetTextRect( Rectangle( point, siz ), aText.GetText(), style ); newSiz = rect.GetSize(); // the gap is the difference between the text width and its control width gap = siz.Height() - newSiz.Height(); //resize the text field newSiz = Size( siz.Width(), siz.Height() - gap ); aText.SetSizePixel( newSiz ); //move the OK & cancel buttons point = aEdit.GetPosPixel(); newPoint = Point( point.X(), point.Y() - gap ); aEdit.SetPosPixel( newPoint ); } InputDialog::~InputDialog() { } // ---------------------------------------------------------------------------- // ScriptOrgDialog ------------------------------------------------------------ // ---------------------------------------------------------------------------- SvxScriptOrgDialog::SvxScriptOrgDialog( Window* pParent, ::rtl::OUString language ) : SfxModalDialog( pParent, CUI_RES( RID_DLG_SCRIPTORGANIZER ) ), aScriptsTxt( this, CUI_RES( SF_TXT_SCRIPTS ) ), aScriptsBox( this, CUI_RES( SF_CTRL_SCRIPTSBOX ) ), aRunButton( this, CUI_RES( SF_PB_RUN ) ), aCloseButton( this, CUI_RES( SF_PB_CLOSE ) ), aCreateButton( this, CUI_RES( SF_PB_CREATE ) ), aEditButton( this, CUI_RES( SF_PB_EDIT ) ), aRenameButton(this, CUI_RES( SF_PB_RENAME ) ), aDelButton( this, CUI_RES( SF_PB_DEL ) ), aHelpButton( this, CUI_RES( SF_PB_HELP ) ), m_sLanguage( language ), m_delErrStr( CUI_RES( RID_SVXSTR_DELFAILED ) ), m_delErrTitleStr( CUI_RES( RID_SVXSTR_DELFAILED_TITLE ) ), m_delQueryStr( CUI_RES( RID_SVXSTR_DELQUERY ) ), m_delQueryTitleStr( CUI_RES( RID_SVXSTR_DELQUERY_TITLE ) ) , m_createErrStr( CUI_RES ( RID_SVXSTR_CREATEFAILED ) ), m_createDupStr( CUI_RES ( RID_SVXSTR_CREATEFAILEDDUP ) ), m_createErrTitleStr( CUI_RES( RID_SVXSTR_CREATEFAILED_TITLE ) ), m_renameErrStr( CUI_RES ( RID_SVXSTR_RENAMEFAILED ) ), m_renameErrTitleStr( CUI_RES( RID_SVXSTR_RENAMEFAILED_TITLE ) ) { // must be a neater way to deal with the strings than as above // append the language to the dialog title String winTitle( GetText() ); winTitle.SearchAndReplace( String::CreateFromAscii( "%MACROLANG" ), language.pData->buffer ); SetText( winTitle ); aScriptsBox.SetSelectHdl( LINK( this, SvxScriptOrgDialog, ScriptSelectHdl ) ); aRunButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aCloseButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aRenameButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aEditButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aDelButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aCreateButton.SetClickHdl( LINK( this, SvxScriptOrgDialog, ButtonHdl ) ); aRunButton.Disable(); aRenameButton.Disable(); aEditButton.Disable(); aDelButton.Disable(); aCreateButton.Disable(); aScriptsBox.Init( m_sLanguage ); RestorePreviousSelection(); FreeResource(); } __EXPORT SvxScriptOrgDialog::~SvxScriptOrgDialog() { // clear the SelectHdl so that it isn't called during the dtor aScriptsBox.SetSelectHdl( Link() ); }; short SvxScriptOrgDialog::Execute() { SfxObjectShell *pDoc = SfxObjectShell::GetFirst(); // force load of MSPs for all documents while ( pDoc ) { Reference< provider::XScriptProviderSupplier > xSPS = Reference< provider::XScriptProviderSupplier > ( pDoc->GetModel(), UNO_QUERY ); if ( xSPS.is() ) { Reference< provider::XScriptProvider > ScriptProvider = xSPS->getScriptProvider(); } pDoc = SfxObjectShell::GetNext(*pDoc); } aScriptsBox.ExpandAllTrees(); Window* pPrevDlgParent = Application::GetDefDialogParent(); Application::SetDefDialogParent( this ); short nRet = ModalDialog::Execute(); Application::SetDefDialogParent( pPrevDlgParent ); return nRet; } void SvxScriptOrgDialog::CheckButtons( Reference< browse::XBrowseNode >& node ) { if ( node.is() ) { if ( node->getType() == browse::BrowseNodeTypes::SCRIPT) { aRunButton.Enable(); } else { aRunButton.Disable(); } Reference< beans::XPropertySet > xProps( node, UNO_QUERY ); if ( !xProps.is() ) { aEditButton.Disable(); aDelButton.Disable(); aCreateButton.Disable(); aRunButton.Disable(); return; } ::rtl::OUString sName; sName = String::CreateFromAscii("Editable") ; if ( getBoolProperty( xProps, sName ) ) { aEditButton.Enable(); } else { aEditButton.Disable(); } sName = String::CreateFromAscii("Deletable") ; if ( getBoolProperty( xProps, sName ) ) { aDelButton.Enable(); } else { aDelButton.Disable(); } sName = String::CreateFromAscii("Creatable") ; if ( getBoolProperty( xProps, sName ) ) { aCreateButton.Enable(); } else { aCreateButton.Disable(); } sName = String::CreateFromAscii("Renamable") ; if ( getBoolProperty( xProps, sName ) ) { aRenameButton.Enable(); } else { aRenameButton.Disable(); } } else { // no node info available, disable all configurable actions aDelButton.Disable(); aCreateButton.Disable(); aEditButton.Disable(); aRunButton.Disable(); aRenameButton.Disable(); } } IMPL_LINK_INLINE_START( SvxScriptOrgDialog, MacroDoubleClickHdl, SvTreeListBox *, EMPTYARG ) { return 0; } IMPL_LINK_INLINE_END( SvxScriptOrgDialog, MacroDoubleClickHdl, SvTreeListBox *, EMPTYARG ) IMPL_LINK( SvxScriptOrgDialog, ScriptSelectHdl, SvTreeListBox *, pBox ) { if ( !pBox->IsSelected( pBox->GetHdlEntry() ) ) { return 0; } SvLBoxEntry* pEntry = pBox->GetHdlEntry(); SFEntry* userData = 0; if ( !pEntry ) { return 0; } userData = (SFEntry*)pEntry->GetUserData(); Reference< browse::XBrowseNode > node; if ( userData ) { node = userData->GetNode(); CheckButtons( node ); } return 0; } IMPL_LINK( SvxScriptOrgDialog, ButtonHdl, Button *, pButton ) { if ( pButton == &aCloseButton ) { StoreCurrentSelection(); EndDialog( 0 ); } if ( pButton == &aEditButton || pButton == &aCreateButton || pButton == &aDelButton || pButton == &aRunButton || pButton == &aRenameButton ) { if ( aScriptsBox.IsSelected( aScriptsBox.GetHdlEntry() ) ) { SvLBoxEntry* pEntry = aScriptsBox.GetHdlEntry(); SFEntry* userData = 0; if ( !pEntry ) { return 0; } userData = (SFEntry*)pEntry->GetUserData(); if ( userData ) { Reference< browse::XBrowseNode > node; Reference< XModel > xModel; node = userData->GetNode(); xModel = userData->GetModel(); if ( !node.is() ) { return 0; } if ( pButton == &aRunButton ) { ::rtl::OUString tmpString; Reference< beans::XPropertySet > xProp( node, UNO_QUERY ); Reference< provider::XScriptProvider > mspNode; if( !xProp.is() ) { return 0; } if ( xModel.is() ) { Reference< XEmbeddedScripts > xEmbeddedScripts( xModel, UNO_QUERY); if( !xEmbeddedScripts.is() ) { return 0; } if (!xEmbeddedScripts->getAllowMacroExecution()) { // Please FIXME: Show a message box if AllowMacroExecution is false return 0; } } SvLBoxEntry* pParent = aScriptsBox.GetParent( pEntry ); while ( pParent && !mspNode.is() ) { SFEntry* mspUserData = (SFEntry*)pParent->GetUserData(); mspNode.set( mspUserData->GetNode() , UNO_QUERY ); pParent = aScriptsBox.GetParent( pParent ); } xProp->getPropertyValue( String::CreateFromAscii("URI" ) ) >>= tmpString; const String scriptURL( tmpString ); if ( mspNode.is() ) { try { Reference< provider::XScript > xScript( mspNode->getScript( scriptURL ), UNO_QUERY_THROW ); const Sequence< Any > args(0); Any aRet; Sequence< sal_Int16 > outIndex; Sequence< Any > outArgs( 0 ); aRet = xScript->invoke( args, outIndex, outArgs ); } catch ( reflection::InvocationTargetException& ite ) { ::com::sun::star::uno::Any a = makeAny(ite); ShowErrorDialog(a); } catch ( provider::ScriptFrameworkErrorException& ite ) { ::com::sun::star::uno::Any a = makeAny(ite); ShowErrorDialog(a); } catch ( RuntimeException& re ) { ::com::sun::star::uno::Any a = makeAny(re); ShowErrorDialog(a); } catch ( Exception& e ) { ::com::sun::star::uno::Any a = makeAny(e); ShowErrorDialog(a); } } StoreCurrentSelection(); EndDialog( 0 ); } else if ( pButton == &aEditButton ) { Reference< script::XInvocation > xInv( node, UNO_QUERY ); if ( xInv.is() ) { StoreCurrentSelection(); EndDialog( 0 ); Sequence< Any > args(0); Sequence< Any > outArgs( 0 ); Sequence< sal_Int16 > outIndex; try { // ISSUE need code to run script here xInv->invoke( ::rtl::OUString::createFromAscii( "Editable" ), args, outIndex, outArgs ); } catch( Exception& e ) { OSL_TRACE("Caught exception trying to invoke %s", ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer ); } } } else if ( pButton == &aCreateButton ) { createEntry( pEntry ); } else if ( pButton == &aDelButton ) { deleteEntry( pEntry ); } else if ( pButton == &aRenameButton ) { renameEntry( pEntry ); } } } } return 0; } Reference< browse::XBrowseNode > SvxScriptOrgDialog::getBrowseNode( SvLBoxEntry* pEntry ) { Reference< browse::XBrowseNode > node; if ( pEntry ) { SFEntry* userData = (SFEntry*)pEntry->GetUserData(); if ( userData ) { node = userData->GetNode(); } } return node; } Reference< XModel > SvxScriptOrgDialog::getModel( SvLBoxEntry* pEntry ) { Reference< XModel > model; if ( pEntry ) { SFEntry* userData = (SFEntry*)pEntry->GetUserData(); if ( userData ) { model = userData->GetModel(); } } return model; } void SvxScriptOrgDialog::createEntry( SvLBoxEntry* pEntry ) { Reference< browse::XBrowseNode > aChildNode; Reference< browse::XBrowseNode > node = getBrowseNode( pEntry ); Reference< script::XInvocation > xInv( node, UNO_QUERY ); if ( xInv.is() ) { ::rtl::OUString aNewName; ::rtl::OUString aNewStdName; sal_uInt16 nMode = INPUTMODE_NEWLIB; if( aScriptsBox.GetModel()->GetDepth( pEntry ) == 0 ) { aNewStdName = ::rtl::OUString::createFromAscii( "Library" ) ; } else { aNewStdName = ::rtl::OUString::createFromAscii( "Macro" ) ; nMode = INPUTMODE_NEWMACRO; } //do we need L10N for this? ie somethng like: //String aNewStdName( ResId( STR_STDMODULENAME ) ); sal_Bool bValid = sal_False; sal_uInt16 i = 1; Sequence< Reference< browse::XBrowseNode > > childNodes; // no children => ok to create Parcel1 or Script1 without checking try { if( node->hasChildNodes() == sal_False ) { aNewName = aNewStdName; aNewName += String::CreateFromInt32( i ); bValid = sal_True; } else { childNodes = node->getChildNodes(); } } catch ( Exception& ) { // ignore, will continue on with empty sequence } ::rtl::OUString extn; while ( !bValid ) { aNewName = aNewStdName; aNewName += String::CreateFromInt32( i ); sal_Bool bFound = sal_False; if(childNodes.getLength() > 0 ) { ::rtl::OUString nodeName = childNodes[0]->getName(); sal_Int32 extnPos = nodeName.lastIndexOf( '.' ); if(extnPos>0) extn = nodeName.copy(extnPos); } for( sal_Int32 index = 0; index < childNodes.getLength(); index++ ) { if ( (aNewName+extn).equals( childNodes[index]->getName() ) ) { bFound = sal_True; break; } } if( bFound ) { i++; } else { bValid = sal_True; } } std::auto_ptr< InputDialog > xNewDlg( new InputDialog( static_cast<Window*>(this), nMode ) ); xNewDlg->SetObjectName( aNewName ); do { if ( xNewDlg->Execute() && xNewDlg->GetObjectName().Len() ) { ::rtl::OUString aUserSuppliedName = xNewDlg->GetObjectName(); bValid = sal_True; for( sal_Int32 index = 0; index < childNodes.getLength(); index++ ) { if ( (aUserSuppliedName+extn).equals( childNodes[index]->getName() ) ) { bValid = sal_False; String aError( m_createErrStr ); aError.Append( m_createDupStr ); ErrorBox aErrorBox( static_cast<Window*>(this), WB_OK | RET_OK, aError ); aErrorBox.SetText( m_createErrTitleStr ); aErrorBox.Execute(); xNewDlg->SetObjectName( aNewName ); break; } } if( bValid ) aNewName = aUserSuppliedName; } else { // user hit cancel or hit OK with nothing in the editbox return; } } while ( !bValid ); // open up parent node (which ensures it's loaded) aScriptsBox.RequestingChilds( pEntry ); Sequence< Any > args( 1 ); args[ 0 ] <<= aNewName; Sequence< Any > outArgs( 0 ); Sequence< sal_Int16 > outIndex; try { Any aResult; aResult = xInv->invoke( ::rtl::OUString::createFromAscii( "Creatable" ), args, outIndex, outArgs ); Reference< browse::XBrowseNode > newNode( aResult, UNO_QUERY ); aChildNode = newNode; } catch( Exception& e ) { OSL_TRACE("Caught exception trying to Create %s", ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer ); } } if ( aChildNode.is() ) { String aChildName = aChildNode->getName(); SvLBoxEntry* pNewEntry = NULL; ::rtl::OUString name( aChildName ); Reference<XModel> xDocumentModel = getModel( pEntry ); // ISSUE do we need to remove all entries for parent // to achieve sort? Just need to determine position // SvTreeListBox::InsertEntry can take position arg // -- Basic doesn't do this on create. // Suppose we could avoid this too. -> created nodes are // not in alphabetical order if ( aChildNode->getType() == browse::BrowseNodeTypes::SCRIPT ) { pNewEntry = aScriptsBox.insertEntry( aChildName, IMG_MACRO, pEntry, false, std::auto_ptr< SFEntry >(new SFEntry( OBJTYPE_METHOD, aChildNode,xDocumentModel ) ) ); } else { pNewEntry = aScriptsBox.insertEntry( aChildName, IMG_LIB, pEntry, false, std::auto_ptr< SFEntry >(new SFEntry( OBJTYPE_SCRIPTCONTAINER, aChildNode,xDocumentModel ) ) ); // If the Parent is not loaded then set to // loaded, this will prevent RequestingChilds ( called // from vcl via RequestingChilds ) from // creating new ( duplicate ) children SFEntry* userData = (SFEntry*)pEntry->GetUserData(); if ( userData && !userData->isLoaded() ) { userData->setLoaded(); } } aScriptsBox.SetCurEntry( pNewEntry ); aScriptsBox.Select( aScriptsBox.GetCurEntry() ); } else { //ISSUE L10N & message from exception? String aError( m_createErrStr ); ErrorBox aErrorBox( static_cast<Window*>(this), WB_OK | RET_OK, aError ); aErrorBox.SetText( m_createErrTitleStr ); aErrorBox.Execute(); } } void SvxScriptOrgDialog::renameEntry( SvLBoxEntry* pEntry ) { Reference< browse::XBrowseNode > aChildNode; Reference< browse::XBrowseNode > node = getBrowseNode( pEntry ); Reference< script::XInvocation > xInv( node, UNO_QUERY ); if ( xInv.is() ) { ::rtl::OUString aNewName = node->getName(); sal_Int32 extnPos = aNewName.lastIndexOf( '.' ); ::rtl::OUString extn; if(extnPos>0) { extn = aNewName.copy(extnPos); aNewName = aNewName.copy(0,extnPos); } sal_uInt16 nMode = INPUTMODE_RENAME; std::auto_ptr< InputDialog > xNewDlg( new InputDialog( static_cast<Window*>(this), nMode ) ); xNewDlg->SetObjectName( aNewName ); sal_Bool bValid; do { if ( xNewDlg->Execute() && xNewDlg->GetObjectName().Len() ) { ::rtl::OUString aUserSuppliedName = xNewDlg->GetObjectName(); bValid = sal_True; /* for( sal_Int32 index = 0; index < childNodes.getLength(); index++ ) { if ( (aUserSuppliedName+extn).equals( childNodes[index]->getName() ) ) { bValid = sal_False; String aError( m_createErrStr ); aError.Append( m_createDupStr ); ErrorBox aErrorBox( static_cast<Window*>(this), WB_OK | RET_OK, aError ); aErrorBox.SetText( m_createErrTitleStr ); aErrorBox.Execute(); xNewDlg->SetObjectName( aNewName ); break; } } */ if( bValid ) aNewName = aUserSuppliedName; } else { // user hit cancel or hit OK with nothing in the editbox return; } } while ( !bValid ); Sequence< Any > args( 1 ); args[ 0 ] <<= aNewName; Sequence< Any > outArgs( 0 ); Sequence< sal_Int16 > outIndex; try { Any aResult; aResult = xInv->invoke( ::rtl::OUString::createFromAscii( "Renamable" ), args, outIndex, outArgs ); Reference< browse::XBrowseNode > newNode( aResult, UNO_QUERY ); aChildNode = newNode; } catch( Exception& e ) { OSL_TRACE("Caught exception trying to Rename %s", ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer ); } } if ( aChildNode.is() ) { aScriptsBox.SetEntryText( pEntry, aChildNode->getName() ); aScriptsBox.SetCurEntry( pEntry ); aScriptsBox.Select( aScriptsBox.GetCurEntry() ); } else { //ISSUE L10N & message from exception? String aError( m_renameErrStr ); ErrorBox aErrorBox( static_cast<Window*>(this), WB_OK | RET_OK, aError ); aErrorBox.SetText( m_renameErrTitleStr ); aErrorBox.Execute(); } } void SvxScriptOrgDialog::deleteEntry( SvLBoxEntry* pEntry ) { sal_Bool result = sal_False; Reference< browse::XBrowseNode > node = getBrowseNode( pEntry ); // ISSUE L10N string & can we centre list? String aQuery( m_delQueryStr ); aQuery.Append( getListOfChildren( node, 0 ) ); QueryBox aQueryBox( static_cast<Window*>(this), WB_YES_NO | WB_DEF_YES, aQuery ); aQueryBox.SetText( m_delQueryTitleStr ); if ( aQueryBox.Execute() == RET_NO ) { return; } Reference< script::XInvocation > xInv( node, UNO_QUERY ); if ( xInv.is() ) { Sequence< Any > args( 0 ); Sequence< Any > outArgs( 0 ); Sequence< sal_Int16 > outIndex; try { Any aResult; aResult = xInv->invoke( ::rtl::OUString::createFromAscii( "Deletable" ), args, outIndex, outArgs ); aResult >>= result; // or do we just assume true if no exception ? } catch( Exception& e ) { OSL_TRACE("Caught exception trying to delete %s", ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer ); } } if ( result == sal_True ) { aScriptsBox.deleteTree( pEntry ); aScriptsBox.GetModel()->Remove( pEntry ); } else { //ISSUE L10N & message from exception? ErrorBox aErrorBox( static_cast<Window*>(this), WB_OK | RET_OK, m_delErrStr ); aErrorBox.SetText( m_delErrTitleStr ); aErrorBox.Execute(); } } sal_Bool SvxScriptOrgDialog::getBoolProperty( Reference< beans::XPropertySet >& xProps, ::rtl::OUString& propName ) { sal_Bool result = false; try { sal_Bool bTemp = sal_False; xProps->getPropertyValue( propName ) >>= bTemp; result = ( bTemp == sal_True ); } catch ( Exception& ) { return result; } return result; } String SvxScriptOrgDialog::getListOfChildren( Reference< browse::XBrowseNode > node, int depth ) { String result; result.Append( String::CreateFromAscii( "\n" ) ); for( int i=0;i<=depth;i++ ) { result.Append( String::CreateFromAscii( "\t" ) ); } result.Append( String( node->getName() ) ); try { if ( node->hasChildNodes() == sal_True ) { Sequence< Reference< browse::XBrowseNode > > children = node->getChildNodes(); for ( sal_Int32 n = 0; n < children.getLength(); n++ ) { result.Append( getListOfChildren( children[ n ] , depth+1 ) ); } } } catch ( Exception& ) { // ignore, will return an empty string } return result; } Selection_hash SvxScriptOrgDialog::m_lastSelection; void SvxScriptOrgDialog::StoreCurrentSelection() { String aDescription; if ( aScriptsBox.IsSelected( aScriptsBox.GetHdlEntry() ) ) { SvLBoxEntry* pEntry = aScriptsBox.GetHdlEntry(); while( pEntry ) { aDescription.Insert( aScriptsBox.GetEntryText( pEntry ), 0 ); pEntry = aScriptsBox.GetParent( pEntry ); if ( pEntry ) aDescription.Insert( ';', 0 ); } ::rtl::OUString sDesc( aDescription ); m_lastSelection[ m_sLanguage ] = sDesc; } } void SvxScriptOrgDialog::RestorePreviousSelection() { String aStoredEntry = String( m_lastSelection[ m_sLanguage ] ); if( aStoredEntry.Len() <= 0 ) return; SvLBoxEntry* pEntry = 0; sal_uInt16 nIndex = 0; while ( nIndex != STRING_NOTFOUND ) { String aTmp( aStoredEntry.GetToken( 0, ';', nIndex ) ); SvLBoxEntry* pTmpEntry = aScriptsBox.FirstChild( pEntry ); ::rtl::OUString debugStr(aTmp); while ( pTmpEntry ) { debugStr = ::rtl::OUString(aScriptsBox.GetEntryText( pTmpEntry )); if ( aScriptsBox.GetEntryText( pTmpEntry ) == aTmp ) { pEntry = pTmpEntry; break; } pTmpEntry = aScriptsBox.NextSibling( pTmpEntry ); } if ( !pTmpEntry ) break; aScriptsBox.RequestingChilds( pEntry ); } aScriptsBox.SetCurEntry( pEntry ); } ::rtl::OUString ReplaceString( const ::rtl::OUString& source, const ::rtl::OUString& token, const ::rtl::OUString& value ) { sal_Int32 pos = source.indexOf( token ); if ( pos != -1 && value.getLength() != 0 ) { return source.replaceAt( pos, token.getLength(), value ); } else { return source; } } ::rtl::OUString FormatErrorString( const ::rtl::OUString& unformatted, const ::rtl::OUString& language, const ::rtl::OUString& script, const ::rtl::OUString& line, const ::rtl::OUString& type, const ::rtl::OUString& message ) { ::rtl::OUString result = unformatted.copy( 0 ); result = ReplaceString( result, ::rtl::OUString::createFromAscii( "%LANGUAGENAME" ), language ); result = ReplaceString( result, ::rtl::OUString::createFromAscii( "%SCRIPTNAME" ), script ); result = ReplaceString( result, ::rtl::OUString::createFromAscii( "%LINENUMBER" ), line ); if ( type.getLength() != 0 ) { result += ::rtl::OUString::createFromAscii( "\n\n" ); result += ::rtl::OUString(String(CUI_RES(RID_SVXSTR_ERROR_TYPE_LABEL))); result += ::rtl::OUString::createFromAscii( " " ); result += type; } if ( message.getLength() != 0 ) { result += ::rtl::OUString::createFromAscii( "\n\n" ); result += ::rtl::OUString(String(CUI_RES(RID_SVXSTR_ERROR_MESSAGE_LABEL))); result += ::rtl::OUString::createFromAscii( " " ); result += message; } return result; } ::rtl::OUString GetErrorMessage( const provider::ScriptErrorRaisedException& eScriptError ) { ::rtl::OUString unformatted = String( CUI_RES( RID_SVXSTR_ERROR_AT_LINE ) ); ::rtl::OUString unknown = ::rtl::OUString::createFromAscii( "UNKNOWN" ); ::rtl::OUString language = unknown; ::rtl::OUString script = unknown; ::rtl::OUString line = unknown; ::rtl::OUString type = ::rtl::OUString(); ::rtl::OUString message = eScriptError.Message; if ( eScriptError.language.getLength() != 0 ) { language = eScriptError.language; } if ( eScriptError.scriptName.getLength() != 0 ) { script = eScriptError.scriptName; } if ( eScriptError.Message.getLength() != 0 ) { message = eScriptError.Message; } if ( eScriptError.lineNum != -1 ) { line = ::rtl::OUString::valueOf( eScriptError.lineNum ); unformatted = String( CUI_RES( RID_SVXSTR_ERROR_AT_LINE ) ); } else { unformatted = String( CUI_RES( RID_SVXSTR_ERROR_RUNNING ) ); } return FormatErrorString( unformatted, language, script, line, type, message ); } ::rtl::OUString GetErrorMessage( const provider::ScriptExceptionRaisedException& eScriptException ) { ::rtl::OUString unformatted = String( CUI_RES( RID_SVXSTR_EXCEPTION_AT_LINE ) ); ::rtl::OUString unknown = ::rtl::OUString::createFromAscii( "UNKNOWN" ); ::rtl::OUString language = unknown; ::rtl::OUString script = unknown; ::rtl::OUString line = unknown; ::rtl::OUString type = unknown; ::rtl::OUString message = eScriptException.Message; if ( eScriptException.language.getLength() != 0 ) { language = eScriptException.language; } if ( eScriptException.scriptName.getLength() != 0 ) { script = eScriptException.scriptName; } if ( eScriptException.Message.getLength() != 0 ) { message = eScriptException.Message; } if ( eScriptException.lineNum != -1 ) { line = ::rtl::OUString::valueOf( eScriptException.lineNum ); unformatted = String( CUI_RES( RID_SVXSTR_EXCEPTION_AT_LINE ) ); } else { unformatted = String( CUI_RES( RID_SVXSTR_EXCEPTION_RUNNING ) ); } if ( eScriptException.exceptionType.getLength() != 0 ) { type = eScriptException.exceptionType; } return FormatErrorString( unformatted, language, script, line, type, message ); } ::rtl::OUString GetErrorMessage( const provider::ScriptFrameworkErrorException& sError ) { ::rtl::OUString unformatted = String( CUI_RES( RID_SVXSTR_FRAMEWORK_ERROR_RUNNING ) ); ::rtl::OUString language = ::rtl::OUString::createFromAscii( "UNKNOWN" ); ::rtl::OUString script = ::rtl::OUString::createFromAscii( "UNKNOWN" ); ::rtl::OUString message; if ( sError.scriptName.getLength() > 0 ) { script = sError.scriptName; } if ( sError.language.getLength() > 0 ) { language = sError.language; } if ( sError.errorType == provider::ScriptFrameworkErrorType::NOTSUPPORTED ) { message = String( CUI_RES( RID_SVXSTR_ERROR_LANG_NOT_SUPPORTED ) ); message = ReplaceString( message, ::rtl::OUString::createFromAscii( "%LANGUAGENAME" ), language ); } else { message = sError.Message; } return FormatErrorString( unformatted, language, script, ::rtl::OUString(), ::rtl::OUString(), message ); } ::rtl::OUString GetErrorMessage( const RuntimeException& re ) { Type t = ::getCppuType( &re ); ::rtl::OUString message = t.getTypeName(); message += re.Message; return message; } ::rtl::OUString GetErrorMessage( const Exception& e ) { Type t = ::getCppuType( &e ); ::rtl::OUString message = t.getTypeName(); message += e.Message; return message; } ::rtl::OUString GetErrorMessage( const com::sun::star::uno::Any& aException ) { ::rtl::OUString exType; if ( aException.getValueType() == ::getCppuType( (const reflection::InvocationTargetException* ) NULL ) ) { reflection::InvocationTargetException ite; aException >>= ite; if ( ite.TargetException.getValueType() == ::getCppuType( ( const provider::ScriptErrorRaisedException* ) NULL ) ) { // Error raised by script provider::ScriptErrorRaisedException scriptError; ite.TargetException >>= scriptError; return GetErrorMessage( scriptError ); } else if ( ite.TargetException.getValueType() == ::getCppuType( ( const provider::ScriptExceptionRaisedException* ) NULL ) ) { // Exception raised by script provider::ScriptExceptionRaisedException scriptException; ite.TargetException >>= scriptException; return GetErrorMessage( scriptException ); } else { // Unknown error, shouldn't happen // OSL_ASSERT(...) } } else if ( aException.getValueType() == ::getCppuType( ( const provider::ScriptFrameworkErrorException* ) NULL ) ) { // A Script Framework error has occurred provider::ScriptFrameworkErrorException sfe; aException >>= sfe; return GetErrorMessage( sfe ); } // unknown exception Exception e; RuntimeException rte; if ( aException >>= rte ) { return GetErrorMessage( rte ); } aException >>= e; return GetErrorMessage( e ); } SvxScriptErrorDialog::SvxScriptErrorDialog( Window* , ::com::sun::star::uno::Any aException ) : m_sMessage() { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_sMessage = GetErrorMessage( aException ); } SvxScriptErrorDialog::~SvxScriptErrorDialog() { } short SvxScriptErrorDialog::Execute() { // Show Error dialog asynchronously // // Pass a copy of the message to the ShowDialog method as the // SvxScriptErrorDialog may be deleted before ShowDialog is called Application::PostUserEvent( LINK( this, SvxScriptErrorDialog, ShowDialog ), new rtl::OUString( m_sMessage ) ); return 0; } IMPL_LINK( SvxScriptErrorDialog, ShowDialog, ::rtl::OUString*, pMessage ) { ::rtl::OUString message; if ( pMessage && pMessage->getLength() != 0 ) { message = *pMessage; } else { message = String( CUI_RES( RID_SVXSTR_ERROR_TITLE ) ); } MessBox* pBox = new WarningBox( NULL, WB_OK, message ); pBox->SetText( CUI_RES( RID_SVXSTR_ERROR_TITLE ) ); pBox->Execute(); if ( pBox ) delete pBox; if ( pMessage ) delete pMessage; return 0; }
25,118
348
<filename>docs/data/leg-t2/040/04003070.json {"nom":"Castandet","circ":"3ème circonscription","dpt":"Landes","inscrits":302,"abs":112,"votants":190,"blancs":17,"nuls":1,"exp":172,"res":[{"nuance":"REM","nom":"<NAME>","voix":93},{"nuance":"SOC","nom":"<NAME>","voix":79}]}
110
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_SIGNIN_PROFILE_OAUTH2_TOKEN_SERVICE_IOS_PROVIDER_IMPL_H_ #define IOS_CHROME_BROWSER_SIGNIN_PROFILE_OAUTH2_TOKEN_SERVICE_IOS_PROVIDER_IMPL_H_ #include <string> #include <vector> #include "base/macros.h" #include "components/signin/ios/browser/profile_oauth2_token_service_ios_provider.h" // Implementation of ProfileOAuth2TokenServiceIOSProvider. class ProfileOAuth2TokenServiceIOSProviderImpl : public ProfileOAuth2TokenServiceIOSProvider { public: ProfileOAuth2TokenServiceIOSProviderImpl(); ~ProfileOAuth2TokenServiceIOSProviderImpl() override; // ios::ProfileOAuth2TokenServiceIOSProvider void GetAccessToken(const std::string& gaia_id, const std::string& client_id, const std::set<std::string>& scopes, const AccessTokenCallback& callback) override; std::vector<AccountInfo> GetAllAccounts() const override; AuthenticationErrorCategory GetAuthenticationErrorCategory( const std::string& gaia_id, NSError* error) const override; private: DISALLOW_COPY_AND_ASSIGN(ProfileOAuth2TokenServiceIOSProviderImpl); }; #endif // IOS_CHROME_BROWSER_SIGNIN_PROFILE_OAUTH2_TOKEN_SERVICE_IOS_PROVIDER_IMPL_H_
518
13,885
<reponame>N500/filament<filename>filament/src/fg2/FrameGraphTexture.cpp /* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fg2/FrameGraphTexture.h" #include "ResourceAllocator.h" #include <algorithm> namespace filament { void FrameGraphTexture::create(ResourceAllocatorInterface& resourceAllocator, const char* name, FrameGraphTexture::Descriptor const& descriptor, FrameGraphTexture::Usage usage) noexcept { std::array<backend::TextureSwizzle, 4> swizzle = { descriptor.swizzle.r, descriptor.swizzle.g, descriptor.swizzle.b, descriptor.swizzle.a }; handle = resourceAllocator.createTexture(name, descriptor.type, descriptor.levels, descriptor.format, descriptor.samples, descriptor.width, descriptor.height, descriptor.depth, swizzle, usage); } void FrameGraphTexture::destroy(ResourceAllocatorInterface& resourceAllocator) noexcept { if (handle) { resourceAllocator.destroyTexture(handle); handle.clear(); } } FrameGraphTexture::Descriptor FrameGraphTexture::generateSubResourceDescriptor( Descriptor descriptor, SubResourceDescriptor const& srd) noexcept { descriptor.levels = 1; descriptor.width = std::max(1u, descriptor.width >> srd.level); descriptor.height = std::max(1u, descriptor.height >> srd.level); return descriptor; } } // namespace filament
663
326
package com.rarepebble.colorpickerdemo; import android.app.Activity; import android.os.Bundle; import com.rarepebble.colorpicker.ColorPickerView; public class ViewDemoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_demo); ColorPickerView picker = (ColorPickerView)findViewById(R.id.colorPicker); picker.setColor(0xffff0000); } }
157
1,103
/* * Copyright 2021 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.hollow.core.read; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.HollowConsumer.DoubleSnapshotConfig; import com.netflix.hollow.api.consumer.InMemoryBlobStore; import com.netflix.hollow.api.consumer.fs.HollowFilesystemBlobRetriever; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig; import com.netflix.hollow.api.producer.fs.HollowFilesystemPublisher; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.filter.TypeFilter; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.TypeA; import com.netflix.hollow.core.write.objectmapper.TypeB; import com.netflix.hollow.core.write.objectmapper.TypeC; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import org.junit.Assert; import org.junit.Test; public class HollowBlobOptionalPartTest { @Test public void optionalPartsAreAvailableInLowLevelAPI() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); // HollowBlobInput cPartInput = HollowBlobInput.serial(new ByteArrayInputStream(cPart.toByteArray())); OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); GenericHollowObject obj = new GenericHollowObject(readEngine, "TypeA", 1); Assert.assertEquals("2", obj.getObject("a1").getString("value")); Assert.assertEquals(2, obj.getInt("a2")); Assert.assertEquals(2L, obj.getObject("b").getLong("b2")); Assert.assertNull(readEngine.getTypeState("TypeC")); } @Test public void optionalPartsAreAvailableInHighLevelAPI() throws IOException { InMemoryBlobStore blobStore = new InMemoryBlobStore(Collections.singleton("B")); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer .withPublisher(blobStore) .withNumStatesBetweenSnapshots(2) .withBlobStager(stager) .build(); producer.initializeDataModel(TypeA.class); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); // state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); state.add(new TypeA("4", 4, new TypeB((short)4, 4L, 4f, new char[] {'4'}, new byte[] { 4 }), Collections.singleton(new TypeC('4', null)))); }); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(blobStore) .build(); consumer.triggerRefresh(); GenericHollowObject obj = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 3); Assert.assertEquals("4", obj.getObject("a1").getString("value")); Assert.assertEquals(4, obj.getInt("a2")); Assert.assertEquals(4L, obj.getObject("b").getLong("b2")); Assert.assertFalse(consumer.getStateEngine().getTypeState("TypeB").getPopulatedOrdinals().get(1)); Assert.assertNull(consumer.getStateEngine().getTypeState("TypeC")); } @Test public void refusesToApplyIncorrectPartSnapshot() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); ByteArrayOutputStream mainPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart2 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart2); partStreams.addOutputStream("C", cPart2); writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart2, partStreams); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); InputStream cPartInput = new ByteArrayInputStream(cPart2.toByteArray()); /// wrong part state OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); try { reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); Assert.fail("Should have thrown Exception"); } catch(IllegalArgumentException ex) { Assert.assertEquals("Optional blob part C does not appear to be matched with the main input", ex.getMessage()); } } @Test public void testFilesystemBlobRetriever() throws IOException { File localBlobStore = createLocalDir(); HollowFilesystemPublisher publisher = new HollowFilesystemPublisher(localBlobStore.toPath()); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer.withPublisher(publisher).withBlobStager(stager).build(); producer.initializeDataModel(TypeA.class); long v1 = producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); long v2 = producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); state.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); }); HollowFilesystemBlobRetriever blobRetriever = new HollowFilesystemBlobRetriever(localBlobStore.toPath(), new HashSet<>(Arrays.asList("B", "C"))); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(blobRetriever) .withDoubleSnapshotConfig(new DoubleSnapshotConfig() { @Override public int maxDeltasBeforeDoubleSnapshot() { return Integer.MAX_VALUE; } @Override public boolean allowDoubleSnapshot() { return false; } }).build(); consumer.triggerRefreshTo(v1); consumer.triggerRefreshTo(v2); consumer.triggerRefreshTo(v1); } @Test public void refusesToApplyIncorrectPartDelta() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); ByteArrayOutputStream mainPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart2 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart2); partStreams.addOutputStream("C", cPart2); writer = new HollowBlobWriter(writeEngine); writer.writeDelta(mainPart2, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("5", 5, new TypeB((short)5, 5L, 5f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('5', null)))); ByteArrayOutputStream mainPart3 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart3 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart3 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart3); partStreams.addOutputStream("C", cPart3); writer = new HollowBlobWriter(writeEngine); writer.writeDelta(mainPart3, partStreams); /// read snapshot HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); InputStream cPartInput = new ByteArrayInputStream(cPart.toByteArray()); OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); /// apply delta mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart2.toByteArray())); bPartInput = new ByteArrayInputStream(bPart3.toByteArray()); /// wrong part state cPartInput = new ByteArrayInputStream(cPart2.toByteArray()); optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); try { reader.applyDelta(mainPartInput, optionalPartInput); Assert.fail("Should have thrown Exception"); } catch(IllegalArgumentException ex) { Assert.assertEquals("Optional blob part B does not appear to be matched with the main input", ex.getMessage()); } } @Test public void optionalPartsWithSharedMemoryLazy() throws IOException { File localBlobStore = createLocalDir(); HollowFilesystemPublisher publisher = new HollowFilesystemPublisher(localBlobStore.toPath()); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer .withPublisher(publisher) .withNumStatesBetweenSnapshots(2) .withBlobStager(stager) .build(); producer.initializeDataModel(TypeA.class); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(new HollowFilesystemBlobRetriever(localBlobStore.toPath(), Collections.singleton("B"))) .withMemoryMode(MemoryMode.SHARED_MEMORY_LAZY) .build(); consumer.triggerRefresh(); GenericHollowObject obj = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 1); Assert.assertEquals("2", obj.getObject("a1").getString("value")); Assert.assertEquals(2, obj.getInt("a2")); Assert.assertEquals(2L, obj.getObject("b").getLong("b2")); Assert.assertNull(consumer.getStateEngine().getTypeState("TypeC")); } private ProducerOptionalBlobPartConfig newPartConfig() { ProducerOptionalBlobPartConfig partConfig = new ProducerOptionalBlobPartConfig(); partConfig.addTypesToPart("B", "TypeB"); partConfig.addTypesToPart("C", "SetOfTypeC", "TypeC", "MapOfStringToListOfInteger", "ListOfInteger", "Integer"); return partConfig; } static File createLocalDir() throws IOException { File localDir = Files.createTempDirectory("hollow").toFile(); localDir.deleteOnExit(); return localDir; } }
7,569
348
<filename>docs/data/leg-t1/003/00301309.json<gh_stars>100-1000 {"nom":"<NAME>","circ":"1ère circonscription","dpt":"Allier","inscrits":378,"abs":163,"votants":215,"blancs":3,"nuls":2,"exp":210,"res":[{"nuance":"REM","nom":"<NAME>","voix":54},{"nuance":"COM","nom":"<NAME>","voix":48},{"nuance":"LR","nom":"<NAME>-<NAME>","voix":47},{"nuance":"FN","nom":"Mme <NAME>","voix":29},{"nuance":"SOC","nom":"<NAME>","voix":14},{"nuance":"DVG","nom":"<NAME>","voix":5},{"nuance":"ECO","nom":"<NAME>","voix":4},{"nuance":"EXG","nom":"M. <NAME>","voix":3},{"nuance":"DIV","nom":"<NAME>","voix":3},{"nuance":"DLF","nom":"M. <NAME>","voix":2},{"nuance":"DIV","nom":"Mme <NAME>","voix":1},{"nuance":"DVG","nom":"Mme <NAME>","voix":0}]}
295
2,268
//========= Copyright Valve Corporation, All rights reserved. ============// #ifndef EYE_REFRACT_HELPER_H #define EYE_REFRACT_HELPER_H #ifdef _WIN32 #pragma once #endif #include <string.h> //----------------------------------------------------------------------------- // Forward declarations //----------------------------------------------------------------------------- class CBaseVSShader; class IMaterialVar; class IShaderDynamicAPI; class IShaderShadow; //----------------------------------------------------------------------------- // Init params/ init/ draw methods //----------------------------------------------------------------------------- struct Eye_Refract_Vars_t { Eye_Refract_Vars_t() { memset( this, 0xFF, sizeof(Eye_Refract_Vars_t) ); } int m_nFrame; int m_nIris; int m_nIrisFrame; int m_nEyeOrigin; int m_nIrisU; int m_nIrisV; int m_nDilation; int m_nGlossiness; int m_nIntro; int m_nEntityOrigin; // Needed for intro int m_nWarpParam; int m_nCorneaTexture; int m_nAmbientOcclTexture; int m_nEnvmap; int m_nSphereTexKillCombo; int m_nRaytraceSphere; int m_nParallaxStrength; int m_nCorneaBumpStrength; int m_nAmbientOcclColor; int m_nEyeballRadius; int m_nDiffuseWarpTexture; }; // Default values (Arrays should only be vec[4]) static const int kDefaultIntro = 0; static const float kDefaultEyeOrigin[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const float kDefaultIrisU[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const float kDefaultIrisV[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const float kDefaultDilation = 0.5f; static const float kDefaultGlossiness = 1.0f; static const float kDefaultWarpParam = 0.0f; static const int kDefaultSphereTexKillCombo = 0; static const int kDefaultRaytraceSphere = 0; static const float kDefaultParallaxStrength = 0.25f; static const float kDefaultCorneaBumpStrength = 1.0f; static const float kDefaultAmbientOcclColor[4] = { 0.33f, 0.33f, 0.33f, 0.0f }; static const float kDefaultEyeballRadius = 0.5f; void InitParams_Eyes_Refract( CBaseVSShader *pShader, IMaterialVar** params, const char *pMaterialName, Eye_Refract_Vars_t &info ); void Init_Eyes_Refract( CBaseVSShader *pShader, IMaterialVar** params, Eye_Refract_Vars_t &info ); void Draw_Eyes_Refract( CBaseVSShader *pShader, IMaterialVar** params, IShaderDynamicAPI *pShaderAPI, IShaderShadow* pShaderShadow, Eye_Refract_Vars_t &info, VertexCompressionType_t vertexCompression ); #endif // EYES_DX8_DX9_HELPER_H
876
1,127
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino.tools.mo.ops.unique import Unique from openvino.tools.mo.front.extractor import FrontExtractorOp class UniqueFrontExtractor(FrontExtractorOp): op = 'Unique' enabled = True @classmethod def extract(cls, node): # TensorFlow Unique operation always returns two outputs: unique elements and indices # The unique elements in the output are not sorted attrs = { 'sorted': 'false', 'return_inverse': 'true', 'return_counts': 'false' } Unique.update_node_stat(node, attrs) return cls.enabled
267
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/password_manager/password_manager_uitest_util.h" #include "testing/gtest/include/gtest/gtest.h" void TestGenerationPopupObserver::OnPopupShown( PasswordGenerationPopupController::GenerationUIState state) { popup_showing_ = GenerationPopup::kShown; state_ = state; MaybeQuitRunLoop(); } void TestGenerationPopupObserver::OnPopupHidden() { popup_showing_ = GenerationPopup::kHidden; MaybeQuitRunLoop(); } bool TestGenerationPopupObserver::popup_showing() const { return popup_showing_ == GenerationPopup::kShown; } GenerationUIState TestGenerationPopupObserver::state() const { return state_; } // Waits until the popup is in specified status. void TestGenerationPopupObserver::WaitForStatus(GenerationPopup status) { if (status == popup_showing_) return; SCOPED_TRACE(::testing::Message() << "WaitForStatus " << static_cast<int>(status)); base::RunLoop run_loop; run_loop_ = &run_loop; run_loop_->Run(); EXPECT_EQ(popup_showing_, status); } // Waits until the popup is either shown or hidden. void TestGenerationPopupObserver::WaitForStatusChange() { SCOPED_TRACE(::testing::Message() << "WaitForStatusChange"); base::RunLoop run_loop; run_loop_ = &run_loop; run_loop_->Run(); } void TestGenerationPopupObserver::MaybeQuitRunLoop() { if (run_loop_) { run_loop_->Quit(); run_loop_ = nullptr; } }
545
643
<filename>java/ql/test/stubs/jboss-logging-3.4.2/org/jboss/logging/Logger.java /* * JBoss, Home of Professional Open Source. * * Copyright 2011 Red Hat, 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 org.jboss.logging; import java.io.Serializable; import java.util.Locale; public abstract class Logger implements Serializable, BasicLogger { public enum Level { } public String getName() { return null; } public boolean isTraceEnabled() { return false; } public void trace(Object message) { } public void trace(Object message, Throwable t) { } public void trace(String loggerFqcn, Object message, Throwable t) { } public void trace(Object message, Object[] params) { } public void trace(Object message, Object[] params, Throwable t) { } public void trace(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void tracev(String format, Object... params) { } public void tracev(String format, Object param1) { } public void tracev(String format, Object param1, Object param2) { } public void tracev(String format, Object param1, Object param2, Object param3) { } public void tracev(Throwable t, String format, Object... params) { } public void tracev(Throwable t, String format, Object param1) { } public void tracev(Throwable t, String format, Object param1, Object param2) { } public void tracev(Throwable t, String format, Object param1, Object param2, Object param3) { } public void tracef(String format, Object... params) { } public void tracef(String format, Object param1) { } public void tracef(String format, Object param1, Object param2) { } public void tracef(String format, Object param1, Object param2, Object param3) { } public void tracef(Throwable t, String format, Object... params) { } public void tracef(Throwable t, String format, Object param1) { } public void tracef(Throwable t, String format, Object param1, Object param2) { } public void tracef(Throwable t, String format, Object param1, Object param2, Object param3) { } public void tracef(final String format, final int arg) { } public void tracef(final String format, final int arg1, final int arg2) { } public void tracef(final String format, final int arg1, final Object arg2) { } public void tracef(final String format, final int arg1, final int arg2, final int arg3) { } public void tracef(final String format, final int arg1, final int arg2, final Object arg3) { } public void tracef(final String format, final int arg1, final Object arg2, final Object arg3) { } public void tracef(final Throwable t, final String format, final int arg) { } public void tracef(final Throwable t, final String format, final int arg1, final int arg2) { } public void tracef(final Throwable t, final String format, final int arg1, final Object arg2) { } public void tracef(final Throwable t, final String format, final int arg1, final int arg2, final int arg3) { } public void tracef(final Throwable t, final String format, final int arg1, final int arg2, final Object arg3) { } public void tracef(final Throwable t, final String format, final int arg1, final Object arg2, final Object arg3) { } public void tracef(final String format, final long arg) { } public void tracef(final String format, final long arg1, final long arg2) { } public void tracef(final String format, final long arg1, final Object arg2) { } public void tracef(final String format, final long arg1, final long arg2, final long arg3) { } public void tracef(final String format, final long arg1, final long arg2, final Object arg3) { } public void tracef(final String format, final long arg1, final Object arg2, final Object arg3) { } public void tracef(final Throwable t, final String format, final long arg) { } public void tracef(final Throwable t, final String format, final long arg1, final long arg2) { } public void tracef(final Throwable t, final String format, final long arg1, final Object arg2) { } public void tracef(final Throwable t, final String format, final long arg1, final long arg2, final long arg3) { } public void tracef(final Throwable t, final String format, final long arg1, final long arg2, final Object arg3) { } public void tracef(final Throwable t, final String format, final long arg1, final Object arg2, final Object arg3) { } public boolean isDebugEnabled() { return false; } public void debug(Object message) { } public void debug(Object message, Throwable t) { } public void debug(String loggerFqcn, Object message, Throwable t) { } public void debug(Object message, Object[] params) { } public void debug(Object message, Object[] params, Throwable t) { } public void debug(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void debugv(String format, Object... params) { } public void debugv(String format, Object param1) { } public void debugv(String format, Object param1, Object param2) { } public void debugv(String format, Object param1, Object param2, Object param3) { } public void debugv(Throwable t, String format, Object... params) { } public void debugv(Throwable t, String format, Object param1) { } public void debugv(Throwable t, String format, Object param1, Object param2) { } public void debugv(Throwable t, String format, Object param1, Object param2, Object param3) { } public void debugf(String format, Object... params) { } public void debugf(String format, Object param1) { } public void debugf(String format, Object param1, Object param2) { } public void debugf(String format, Object param1, Object param2, Object param3) { } public void debugf(Throwable t, String format, Object... params) { } public void debugf(Throwable t, String format, Object param1) { } public void debugf(Throwable t, String format, Object param1, Object param2) { } public void debugf(Throwable t, String format, Object param1, Object param2, Object param3) { } public void debugf(final String format, final int arg) { } public void debugf(final String format, final int arg1, final int arg2) { } public void debugf(final String format, final int arg1, final Object arg2) { } public void debugf(final String format, final int arg1, final int arg2, final int arg3) { } public void debugf(final String format, final int arg1, final int arg2, final Object arg3) { } public void debugf(final String format, final int arg1, final Object arg2, final Object arg3) { } public void debugf(final Throwable t, final String format, final int arg) { } public void debugf(final Throwable t, final String format, final int arg1, final int arg2) { } public void debugf(final Throwable t, final String format, final int arg1, final Object arg2) { } public void debugf(final Throwable t, final String format, final int arg1, final int arg2, final int arg3) { } public void debugf(final Throwable t, final String format, final int arg1, final int arg2, final Object arg3) { } public void debugf(final Throwable t, final String format, final int arg1, final Object arg2, final Object arg3) { } public void debugf(final String format, final long arg) { } public void debugf(final String format, final long arg1, final long arg2) { } public void debugf(final String format, final long arg1, final Object arg2) { } public void debugf(final String format, final long arg1, final long arg2, final long arg3) { } public void debugf(final String format, final long arg1, final long arg2, final Object arg3) { } public void debugf(final String format, final long arg1, final Object arg2, final Object arg3) { } public void debugf(final Throwable t, final String format, final long arg) { } public void debugf(final Throwable t, final String format, final long arg1, final long arg2) { } public void debugf(final Throwable t, final String format, final long arg1, final Object arg2) { } public void debugf(final Throwable t, final String format, final long arg1, final long arg2, final long arg3) { } public void debugf(final Throwable t, final String format, final long arg1, final long arg2, final Object arg3) { } public void debugf(final Throwable t, final String format, final long arg1, final Object arg2, final Object arg3) { } public boolean isInfoEnabled() { return false; } public void info(Object message) { } public void info(Object message, Throwable t) { } public void info(String loggerFqcn, Object message, Throwable t) { } public void info(Object message, Object[] params) { } public void info(Object message, Object[] params, Throwable t) { } public void info(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void infov(String format, Object... params) { } public void infov(String format, Object param1) { } public void infov(String format, Object param1, Object param2) { } public void infov(String format, Object param1, Object param2, Object param3) { } public void infov(Throwable t, String format, Object... params) { } public void infov(Throwable t, String format, Object param1) { } public void infov(Throwable t, String format, Object param1, Object param2) { } public void infov(Throwable t, String format, Object param1, Object param2, Object param3) { } public void infof(String format, Object... params) { } public void infof(String format, Object param1) { } public void infof(String format, Object param1, Object param2) { } public void infof(String format, Object param1, Object param2, Object param3) { } public void infof(Throwable t, String format, Object... params) { } public void infof(Throwable t, String format, Object param1) { } public void infof(Throwable t, String format, Object param1, Object param2) { } public void infof(Throwable t, String format, Object param1, Object param2, Object param3) { } public void warn(Object message) { } public void warn(Object message, Throwable t) { } public void warn(String loggerFqcn, Object message, Throwable t) { } public void warn(Object message, Object[] params) { } public void warn(Object message, Object[] params, Throwable t) { } public void warn(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void warnv(String format, Object... params) { } public void warnv(String format, Object param1) { } public void warnv(String format, Object param1, Object param2) { } public void warnv(String format, Object param1, Object param2, Object param3) { } public void warnv(Throwable t, String format, Object... params) { } public void warnv(Throwable t, String format, Object param1) { } public void warnv(Throwable t, String format, Object param1, Object param2) { } public void warnv(Throwable t, String format, Object param1, Object param2, Object param3) { } public void warnf(String format, Object... params) { } public void warnf(String format, Object param1) { } public void warnf(String format, Object param1, Object param2) { } public void warnf(String format, Object param1, Object param2, Object param3) { } public void warnf(Throwable t, String format, Object... params) { } public void warnf(Throwable t, String format, Object param1) { } public void warnf(Throwable t, String format, Object param1, Object param2) { } public void warnf(Throwable t, String format, Object param1, Object param2, Object param3) { } public void error(Object message) { } public void error(Object message, Throwable t) { } public void error(String loggerFqcn, Object message, Throwable t) { } public void error(Object message, Object[] params) { } public void error(Object message, Object[] params, Throwable t) { } public void error(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void errorv(String format, Object... params) { } public void errorv(String format, Object param1) { } public void errorv(String format, Object param1, Object param2) { } public void errorv(String format, Object param1, Object param2, Object param3) { } public void errorv(Throwable t, String format, Object... params) { } public void errorv(Throwable t, String format, Object param1) { } public void errorv(Throwable t, String format, Object param1, Object param2) { } public void errorv(Throwable t, String format, Object param1, Object param2, Object param3) { } public void errorf(String format, Object... params) { } public void errorf(String format, Object param1) { } public void errorf(String format, Object param1, Object param2) { } public void errorf(String format, Object param1, Object param2, Object param3) { } public void errorf(Throwable t, String format, Object... params) { } public void errorf(Throwable t, String format, Object param1) { } public void errorf(Throwable t, String format, Object param1, Object param2) { } public void errorf(Throwable t, String format, Object param1, Object param2, Object param3) { } public void fatal(Object message) { } public void fatal(Object message, Throwable t) { } public void fatal(String loggerFqcn, Object message, Throwable t) { } public void fatal(Object message, Object[] params) { } public void fatal(Object message, Object[] params, Throwable t) { } public void fatal(String loggerFqcn, Object message, Object[] params, Throwable t) { } public void fatalv(String format, Object... params) { } public void fatalv(String format, Object param1) { } public void fatalv(String format, Object param1, Object param2) { } public void fatalv(String format, Object param1, Object param2, Object param3) { } public void fatalv(Throwable t, String format, Object... params) { } public void fatalv(Throwable t, String format, Object param1) { } public void fatalv(Throwable t, String format, Object param1, Object param2) { } public void fatalv(Throwable t, String format, Object param1, Object param2, Object param3) { } public void fatalf(String format, Object... params) { } public void fatalf(String format, Object param1) { } public void fatalf(String format, Object param1, Object param2) { } public void fatalf(String format, Object param1, Object param2, Object param3) { } public void fatalf(Throwable t, String format, Object... params) { } public void fatalf(Throwable t, String format, Object param1) { } public void fatalf(Throwable t, String format, Object param1, Object param2) { } public void fatalf(Throwable t, String format, Object param1, Object param2, Object param3) { } public void log(Level level, Object message) { } public void log(Level level, Object message, Throwable t) { } public void log(Level level, String loggerFqcn, Object message, Throwable t) { } public void log(Level level, Object message, Object[] params) { } public void log(Level level, Object message, Object[] params, Throwable t) { } public void log(String loggerFqcn, Level level, Object message, Object[] params, Throwable t) { } public void logv(Level level, String format, Object... params) { } public void logv(Level level, String format, Object param1) { } public void logv(Level level, String format, Object param1, Object param2) { } public void logv(Level level, String format, Object param1, Object param2, Object param3) { } public void logv(Level level, Throwable t, String format, Object... params) { } public void logv(Level level, Throwable t, String format, Object param1) { } public void logv(Level level, Throwable t, String format, Object param1, Object param2) { } public void logv(Level level, Throwable t, String format, Object param1, Object param2, Object param3) { } public void logv(String loggerFqcn, Level level, Throwable t, String format, Object... params) { } public void logv(String loggerFqcn, Level level, Throwable t, String format, Object param1) { } public void logv(String loggerFqcn, Level level, Throwable t, String format, Object param1, Object param2) { } public void logv(String loggerFqcn, Level level, Throwable t, String format, Object param1, Object param2, Object param3) { } public void logf(Level level, String format, Object... params) { } public void logf(Level level, String format, Object param1) { } public void logf(Level level, String format, Object param1, Object param2) { } public void logf(Level level, String format, Object param1, Object param2, Object param3) { } public void logf(Level level, Throwable t, String format, Object... params) { } public void logf(Level level, Throwable t, String format, Object param1) { } public void logf(Level level, Throwable t, String format, Object param1, Object param2) { } public void logf(Level level, Throwable t, String format, Object param1, Object param2, Object param3) { } public void logf(String loggerFqcn, Level level, Throwable t, String format, Object param1) { } public void logf(String loggerFqcn, Level level, Throwable t, String format, Object param1, Object param2) { } public void logf(String loggerFqcn, Level level, Throwable t, String format, Object param1, Object param2, Object param3) { } public void logf(String loggerFqcn, Level level, Throwable t, String format, Object... params) { } public static Logger getLogger(String name) { return null; } public static Logger getLogger(String name, String suffix) { return null; } public static Logger getLogger(Class<?> clazz) { return null; } public static Logger getLogger(Class<?> clazz, String suffix) { return null; } public static <T> T getMessageLogger(Class<T> type, String category) { return null; } public static <T> T getMessageLogger(final Class<T> type, final String category, final Locale locale) { return null; } }
6,554
778
package org.aion.p2p.impl; import java.io.IOException; import java.net.ServerSocket; public class TestUtilities { private TestUtilities() {} /** * Tries to return a free port thats currently not used * * @return */ public static int getFreePort() { try { ServerSocket socket = new ServerSocket(0); socket.setReuseAddress(true); int port = socket.getLocalPort(); socket.close(); return port; } catch (IOException e) { throw new IllegalStateException("could not find free TCP/IP port"); } } static String formatAddr(String id, String ip, int port) { return id + "@" + ip + ":" + port; } }
314
576
#pragma once #include "../../databags/databag.h" #include "core/templates/paged_allocator.h" #include "shape_base.h" #include <BulletCollision/CollisionShapes/btConeShape.h> struct BtCone : public BtRigidShape { COMPONENT_CUSTOM_CONSTRUCTOR(BtCone, SharedSteadyStorage) static void _bind_methods(); static void _get_storage_config(Dictionary &r_config); real_t radius = 1.0; real_t height = 1.0; real_t margin = 0.004; BtCone() : BtRigidShape(TYPE_CONE) {} void set_radius(real_t p_radius); real_t get_radius() const; void set_height(real_t p_height); real_t get_height() const; void set_margin(real_t p_margin); real_t get_margin() const; ShapeInfo *add_shape(btConeShape *p_shape, const Vector3 &p_scale); private: void update_shapes(); }; struct BtShapeStorageCone : public godex::Databag { DATABAG(BtShapeStorageCone); PagedAllocator<btConeShape, false> allocator; btCollisionShape *construct_shape(BtCone *p_shape_owner, const Vector3 &p_scale); };
394
527
<gh_stars>100-1000 #include "VariableCollection.h" #include <iostream> #include "FetlangException.h" bool VariableCollection::has(const std::string& variable_name) const { return variables.find(variable_name) != variables.end(); } Variable& VariableCollection::get(const std::string& variable_name) { if (!has(variable_name)) { throw FetlangException("No such variable with name " + variable_name); } return variables[variable_name]; } Variable& VariableCollection::access(const std::string& variable_name) { Variable& return_value = get(variable_name); if (variable_access_list.empty() || variable_access_list.back() != &return_value) { variable_access_list.push_back(&return_value); } return return_value; } Variable& VariableCollection::getLastAdded() { if (variable_added_list.empty()) { throw FetlangException( "Can't retrieve last variable added because the variable list is empty"); } return *(variable_added_list.back()); } Variable& VariableCollection::getLastAccessed() { if (variable_added_list.empty()) { throw FetlangException( "Can't retrieve last variable accessed because the access list is empty"); } return *(variable_access_list.back()); } void VariableCollection::add(const Variable& variable) { if (has(variable.getName())) { throw FetlangException("Variable with " + variable.getName() + " already exists"); } variables[variable.getName()] = variable; variable_added_list.push_back(&(variables[variable.getName()])); } Variable& VariableCollection::getLastOfGender(Gender gender, bool exclude_last) { for (auto it = variable_access_list.rbegin() + (exclude_last ? 1 : 0); it != variable_access_list.rend(); it++) { if ((*it)->getGender() == gender) { return **it; } if ((*it)->getGender() == UNASSIGNED_GENDER) { (*it)->setGender(gender); return **it; } } throw FetlangException("No variable with the appropriate gender"); } Variable& VariableCollection::getLastOfGenderExcludingLast(Gender gender) { return getLastOfGender(gender, true); } bool VariableCollection::hasLastOfGender(Gender gender, bool exclude_last) { for (auto it = variable_access_list.rbegin() + (exclude_last ? 1 : 0); it != variable_access_list.rend(); it++) { if ((*it)->getGender() == gender) { return true; } if ((*it)->getGender() == UNASSIGNED_GENDER) { return true; } } return false; } bool VariableCollection::hasLastOfGenderExcludingLast(Gender gender) { return hasLastOfGender(gender, true); } void VariableCollection::display() { for (const auto& varpair : variables) { Variable var = varpair.second; std::cout << var.getName() << "(" << var.getCode() << "): " << var.getType() << "\n"; } }
888
3,371
<gh_stars>1000+ package com.beloo.widget.chipslayoutmanager.gravity; import android.graphics.Rect; import com.beloo.widget.chipslayoutmanager.layouter.AbstractLayouter; import com.beloo.widget.chipslayoutmanager.layouter.Item; import java.util.List; class RTLRowFillSpaceStrategy implements IRowStrategy { @Override public void applyStrategy(AbstractLayouter abstractLayouter, List<Item> row) { if (abstractLayouter.getRowSize() == 1) return; int difference = GravityUtil.getHorizontalDifference(abstractLayouter) / (abstractLayouter.getRowSize() - 1); int offsetDifference = 0; for (Item item : row) { Rect childRect = item.getViewRect(); if (childRect.right == abstractLayouter.getCanvasRightBorder()) { //right view of row int rightDif = abstractLayouter.getCanvasRightBorder() - childRect.right; //press view to right border childRect.left += rightDif; childRect.right = abstractLayouter.getCanvasRightBorder(); continue; } offsetDifference += difference; childRect.right -= offsetDifference; childRect.left -= offsetDifference; } } }
520
1,133
<gh_stars>1000+ #include <iostream> #include <fstream> #include "byteswap.h" #include "Cosar.hh" #include <stdlib.h> // Cosar files are big-endian // thus, we need to determine the endianness of the machine we are on // and decide whether we need to swap bytes Cosar::Cosar(std::string input, std::string output) { // Check the endianness if (is_big_endian() == 1) { std::cout << "Machine is Big Endian" << std::endl; this->isBigEndian = true; } else { std::cout << "Machine is Little Endian" << std::endl; this->isBigEndian = false; } this->fin.open(input.c_str(), std::ios::binary | std::ios::in); if (fin.fail()) { std::cout << "Error in file " << __FILE__ << " at line " << __LINE__ << std::endl; std::cout << "Cannot open file " << input << std::endl ; exit(1); } this->fout.open(output.c_str(), std::ios::binary | std::ios::out); if (fout.fail()) { std::cout << "Error in file " << __FILE__ << " at line " << __LINE__ << std::endl; std::cout << "Cannot open file " << input << std::endl ; exit(1); } try { this->header = new Header(this->isBigEndian); } catch(const char *ex) { throw; } } Cosar::~Cosar() { this->fin.close(); this->fout.close(); } void Cosar::parse() { this->header->parse(this->fin); this->header->print(); int byteTotal = this->header->getRangelineTotalNumberOfBytes(); int numLines = this->header->getTotalNumberOfLines(); int burstSize = this->header->getBytesInBurst(); int rangeSamples = this->header->getRangeSamples(); int azimuthSamples = this->header->getAzimuthSamples(); std::cout << "Image is " << azimuthSamples << " x " << rangeSamples << std::endl; this->numberOfBursts = (int)(byteTotal*numLines)/burstSize; this->bursts = new Burst*[this->numberOfBursts]; for(int i=0;i<this->numberOfBursts;i++) { std::cout << "Extracting Burst " << (i+1) << " of " << this->numberOfBursts << std::endl; this->bursts[i] = new Burst(rangeSamples,azimuthSamples,this->isBigEndian); this->bursts[i]->parse(this->fin,this->fout); } }
945
2,443
// Copyright (c) 2015-2019 The HomeKit ADK Contributors // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors. #include "HAP+Internal.h" static const HAPLogObject logObject = { .subsystem = kHAP_LogSubsystem, .category = "BLEPDU" }; /** * Checks whether a value represents a valid PDU type. * * @param value Value to check. * * @return true If the value is valid. * @return false Otherwise. */ HAP_RESULT_USE_CHECK static bool HAPBLEPDUIsValidType(uint8_t value) { switch (value) { case kHAPBLEPDUType_Request: case kHAPBLEPDUType_Response: { return true; } default: { return false; } } } /** * Returns description of a PDU type. * * @param type Value of which to get description. * * @return Description of the type. */ HAP_RESULT_USE_CHECK static const char* HAPBLEPDUTypeDescription(HAPBLEPDUType type) { HAPPrecondition(HAPBLEPDUIsValidType(type)); switch (type) { case kHAPBLEPDUType_Request: { return "Request"; } case kHAPBLEPDUType_Response: { return "Response"; } } HAPFatalError(); } /** * Returns description of a HAP Opcode. * * @param opcode Value of which to get description. * * @return Description of the opcode. */ HAP_RESULT_USE_CHECK static const char* HAPBLEPDUOpcodeDescription(HAPPDUOpcode opcode) { HAPPrecondition(HAPPDUIsValidOpcode(opcode)); switch (opcode) { case kHAPPDUOpcode_CharacteristicSignatureRead: { return "HAP-Characteristic-Signature-Read"; } case kHAPPDUOpcode_CharacteristicWrite: { return "HAP-Characteristic-Write"; } case kHAPPDUOpcode_CharacteristicRead: { return "HAP-Characteristic-Read"; } case kHAPPDUOpcode_CharacteristicTimedWrite: { return "HAP-Characteristic-Timed-Write"; } case kHAPPDUOpcode_CharacteristicExecuteWrite: { return "HAP-Characteristic-Execute-Write"; } case kHAPPDUOpcode_ServiceSignatureRead: { return "HAP-Service-Signature-Read"; } case kHAPPDUOpcode_CharacteristicConfiguration: { return "HAP-Characteristic-Configuration"; } case kHAPPDUOpcode_ProtocolConfiguration: { return "HAP-Protocol-Configuration"; } case kHAPPDUOpcode_Token: { return "HAP-Token"; } case kHAPPDUOpcode_TokenUpdate: { return "HAP-Token-Update"; } case kHAPPDUOpcode_Info: { return "HAP-Info"; } } HAPFatalError(); } HAP_RESULT_USE_CHECK bool HAPBLEPDUOpcodeIsServiceOperation(HAPPDUOpcode opcode) { HAPPrecondition(HAPPDUIsValidOpcode(opcode)); switch (opcode) { case kHAPPDUOpcode_ServiceSignatureRead: case kHAPPDUOpcode_ProtocolConfiguration: { return true; } case kHAPPDUOpcode_CharacteristicSignatureRead: case kHAPPDUOpcode_CharacteristicWrite: case kHAPPDUOpcode_CharacteristicRead: case kHAPPDUOpcode_CharacteristicTimedWrite: case kHAPPDUOpcode_CharacteristicExecuteWrite: case kHAPPDUOpcode_CharacteristicConfiguration: case kHAPPDUOpcode_Token: case kHAPPDUOpcode_TokenUpdate: case kHAPPDUOpcode_Info: { return false; } } HAPFatalError(); } /** * Checks whether a value represents a valid HAP Status Code. * * @param value Value to check. * * @return true If the value is valid. * @return false Otherwise. */ HAP_RESULT_USE_CHECK static bool HAPBLEPDUIsValidStatus(uint8_t value) { switch (value) { case kHAPBLEPDUStatus_Success: case kHAPBLEPDUStatus_UnsupportedPDU: case kHAPBLEPDUStatus_MaxProcedures: case kHAPBLEPDUStatus_InsufficientAuthorization: case kHAPBLEPDUStatus_InvalidInstanceID: case kHAPBLEPDUStatus_InsufficientAuthentication: case kHAPBLEPDUStatus_InvalidRequest: { return true; } default: { return false; } } } /** * Returns description of a HAP Status Code. * * @param status Value of which to get description. * * @return Description of the status. */ HAP_RESULT_USE_CHECK static const char* HAPBLEPDUStatusDescription(HAPBLEPDUStatus status) { HAPPrecondition(HAPBLEPDUIsValidStatus(status)); switch (status) { case kHAPBLEPDUStatus_Success: { return "Success"; } case kHAPBLEPDUStatus_UnsupportedPDU: { return "Unsupported-PDU"; } case kHAPBLEPDUStatus_MaxProcedures: { return "Max-Procedures"; } case kHAPBLEPDUStatus_InsufficientAuthorization: { return "Insufficient Authorization"; } case kHAPBLEPDUStatus_InvalidInstanceID: { return "Invalid Instance ID"; } case kHAPBLEPDUStatus_InsufficientAuthentication: { return "Insufficient Authentication"; } case kHAPBLEPDUStatus_InvalidRequest: { return "Invalid Request"; } } HAPFatalError(); } /** * Logs a HAP-BLE PDU. * * @param pdu PDU to log. */ static void LogPDU(const HAPBLEPDU* pdu) { HAPPrecondition(pdu); HAPBLEPDUType type = pdu->controlField.type; HAPPrecondition(HAPBLEPDUIsValidType(type)); switch (pdu->controlField.fragmentationStatus) { case kHAPBLEPDUFragmentationStatus_FirstFragment: { switch (type) { case kHAPBLEPDUType_Request: { HAPPDUOpcode opcode = pdu->fixedParams.request.opcode; HAPLogBufferDebug( &logObject, pdu->body.bytes, pdu->body.numBytes, "%s-%s (0x%02x):\n" " TID: 0x%02x\n" " IID: %u", HAPPDUIsValidOpcode(opcode) ? HAPBLEPDUOpcodeDescription(opcode) : "Unknown", HAPBLEPDUTypeDescription(type), opcode, pdu->fixedParams.request.tid, pdu->fixedParams.request.iid); } break; case kHAPBLEPDUType_Response: { HAPBLEPDUStatus status = pdu->fixedParams.response.status; HAPLogBufferDebug( &logObject, pdu->body.bytes, pdu->body.numBytes, "%s:\n" " TID: 0x%02x\n" " Status: %s (0x%02x)", HAPBLEPDUTypeDescription(type), pdu->fixedParams.response.tid, HAPBLEPDUIsValidStatus(status) ? HAPBLEPDUStatusDescription(status) : "Unknown", pdu->fixedParams.response.status); } break; } } break; case kHAPBLEPDUFragmentationStatus_Continuation: { HAPLogBufferDebug( &logObject, pdu->body.bytes, pdu->body.numBytes, "%s (Continuation):\n" " TID: 0x%02x", HAPBLEPDUTypeDescription(type), pdu->fixedParams.response.tid); } break; } } /** * Attempts to deserialize the Control Field into a PDU structure. * * @param[out] pdu PDU. * @param controlField Serialized Control Field. * * @return kHAPError_None If successful. * @return kHAPError_InvalidData If the controller sent a malformed request. */ HAP_RESULT_USE_CHECK static HAPError DeserializeControlField(HAPBLEPDU* pdu, const uint8_t* controlField) { HAPPrecondition(pdu); HAPPrecondition(controlField); // Check that reserved bits are 0. if (controlField[0] & (1 << 6 | 1 << 5 | 1 << 4)) { HAPLog(&logObject, "Invalid reserved bits in Control Field 0x%02x.", controlField[0]); return kHAPError_InvalidData; } // Fragmentation status. switch (controlField[0] & 1 << 7) { case 0 << 7: { pdu->controlField.fragmentationStatus = kHAPBLEPDUFragmentationStatus_FirstFragment; } break; case 1 << 7: { pdu->controlField.fragmentationStatus = kHAPBLEPDUFragmentationStatus_Continuation; } break; default: { HAPLog(&logObject, "Invalid fragmentation status in Control Field 0x%02x.", controlField[0]); return kHAPError_InvalidData; } } // PDU Type. switch (controlField[0] & (1 << 3 | 1 << 2 | 1 << 1)) { case 0 << 3 | 0 << 2 | 0 << 1: { pdu->controlField.type = kHAPBLEPDUType_Request; } break; case 0 << 3 | 0 << 2 | 1 << 1: { pdu->controlField.type = kHAPBLEPDUType_Response; } break; default: { HAPLog(&logObject, "Invalid PDU Type in Control Field 0x%02x.", controlField[0]); return kHAPError_InvalidData; } } // Length. switch (controlField[0] & 1 << 0) { case 0 << 0: { pdu->controlField.length = kHAPBLEPDUControlFieldLength_1Byte; } break; default: { HAPLog(&logObject, "Invalid length in Control Field 0x%02x.", controlField[0]); return kHAPError_InvalidData; } } return kHAPError_None; } HAP_RESULT_USE_CHECK HAPError HAPBLEPDUDeserialize(HAPBLEPDU* pdu, const void* bytes, size_t numBytes) { HAPPrecondition(pdu); HAPPrecondition(bytes); HAPError err; const uint8_t* b = bytes; size_t remainingBytes = numBytes; // PDU Header - Control Field. if (remainingBytes < 1) { HAPLog(&logObject, "PDU not long enough to contain Control Field."); return kHAPError_InvalidData; } err = DeserializeControlField(pdu, b); if (err) { HAPAssert(err == kHAPError_InvalidData); return err; } if (pdu->controlField.fragmentationStatus != kHAPBLEPDUFragmentationStatus_FirstFragment) { HAPLog(&logObject, "Unexpected PDU fragmentation status (expected: First fragment (or no fragmentation))."); return kHAPError_InvalidData; } b += 1; remainingBytes -= 1; // PDU Fixed Params. switch (pdu->controlField.type) { case kHAPBLEPDUType_Request: { if (remainingBytes < 4) { HAPLog(&logObject, "Request PDU not long enough to contain Fixed Params."); return kHAPError_InvalidData; } pdu->fixedParams.request.opcode = (HAPPDUOpcode) b[0]; pdu->fixedParams.request.tid = b[1]; pdu->fixedParams.request.iid = HAPReadLittleUInt16(&b[2]); b += 4; remainingBytes -= 4; } goto deserialize_body; case kHAPBLEPDUType_Response: { if (remainingBytes < 2) { HAPLog(&logObject, "Response PDU not long enough to contain Fixed Params."); return kHAPError_InvalidData; } pdu->fixedParams.response.tid = b[0]; pdu->fixedParams.response.status = (HAPBLEPDUStatus) b[1]; b += 2; remainingBytes -= 2; } goto deserialize_body; } HAPFatalError(); deserialize_body: // PDU Body (Optional). if (!remainingBytes) { pdu->body.totalBodyBytes = 0; pdu->body.bytes = NULL; pdu->body.numBytes = 0; } else { if (remainingBytes < 2) { HAPLog(&logObject, "PDU not long enough to contain body length."); return kHAPError_InvalidData; } pdu->body.totalBodyBytes = HAPReadLittleUInt16(b); b += 2; remainingBytes -= 2; if (remainingBytes < pdu->body.totalBodyBytes) { // First fragment. pdu->body.numBytes = (uint16_t) remainingBytes; } else { // Complete body available. pdu->body.numBytes = pdu->body.totalBodyBytes; } pdu->body.bytes = b; b += pdu->body.numBytes; remainingBytes -= pdu->body.numBytes; } // All data read. if (remainingBytes) { HAPLog(&logObject, "Excess data after PDU."); return kHAPError_InvalidData; } (void) b; LogPDU(pdu); return kHAPError_None; } HAP_RESULT_USE_CHECK HAPError HAPBLEPDUDeserializeContinuation( HAPBLEPDU* pdu, const void* bytes, size_t numBytes, HAPBLEPDUType typeOfFirstFragment, size_t remainingBodyBytes, size_t totalBodyBytesSoFar) { HAPPrecondition(pdu); HAPPrecondition(bytes); HAPPrecondition(remainingBodyBytes >= totalBodyBytesSoFar); HAPPrecondition(remainingBodyBytes <= UINT16_MAX); HAPError err; const uint8_t* b = bytes; size_t remainingBytes = numBytes; // PDU Header - Control Field. if (remainingBytes < 1) { HAPLog(&logObject, "PDU not long enough to contain Control Field."); return kHAPError_InvalidData; } err = DeserializeControlField(pdu, b); if (err) { HAPAssert(err == kHAPError_InvalidData); return err; } if (pdu->controlField.fragmentationStatus != kHAPBLEPDUFragmentationStatus_Continuation) { HAPLog(&logObject, "Unexpected PDU fragmentation status (expected: Continuation of fragmented PDU)."); return kHAPError_InvalidData; } if (pdu->controlField.type != typeOfFirstFragment) { HAPLog(&logObject, "Unexpected PDU type (Continuation type: 0x%02x, First Fragment type: 0x%02x).", pdu->controlField.type, typeOfFirstFragment); return kHAPError_InvalidData; } b += 1; remainingBytes -= 1; // PDU Fixed Params. if (remainingBytes < 1) { HAPLog(&logObject, "Continuation PDU not long enough to contain Fixed Params."); return kHAPError_InvalidData; } pdu->fixedParams.continuation.tid = b[0]; b += 1; remainingBytes -= 1; // PDU Body (Optional). pdu->body.totalBodyBytes = (uint16_t) remainingBodyBytes; if (!remainingBytes) { pdu->body.bytes = NULL; pdu->body.numBytes = 0; } else if (remainingBytes <= remainingBodyBytes - totalBodyBytesSoFar) { pdu->body.numBytes = (uint16_t) remainingBytes; pdu->body.bytes = b; b += pdu->body.numBytes; remainingBytes -= pdu->body.numBytes; } // All data read. if (remainingBytes) { HAPLog(&logObject, "Excess data after PDU."); return kHAPError_InvalidData; } (void) b; LogPDU(pdu); return kHAPError_None; } /** * Checks whether a value represents a valid fragmentation status. * * @param value Value to check. * * @return true If the value is valid. * @return false Otherwise. */ HAP_RESULT_USE_CHECK static bool HAPBLEPDUIsValidFragmentStatus(uint8_t value) { switch (value) { case kHAPBLEPDUFragmentationStatus_FirstFragment: case kHAPBLEPDUFragmentationStatus_Continuation: { return true; } default: { return false; } } } /** * Checks whether a value represents a valid Control Field length. * * @param value Value to check. * * @return true If the value is valid. * @return false Otherwise. */ HAP_RESULT_USE_CHECK static bool HAPBLEPDUIsValidControlFieldLength(uint8_t value) { switch (value) { case kHAPBLEPDUControlFieldLength_1Byte: { return true; } default: { return false; } } } /** * Checks whether the Control Field of a PDU structure is valid. * * @param pdu PDU with Control Field to check. * * @return true If the Control Field is valid. * @return false Otherwise. */ HAP_RESULT_USE_CHECK static bool HAPBLEPDUHasValidControlField(const HAPBLEPDU* pdu) { HAPPrecondition(pdu); return HAPBLEPDUIsValidFragmentStatus(pdu->controlField.fragmentationStatus) && HAPBLEPDUIsValidType(pdu->controlField.type) && HAPBLEPDUIsValidControlFieldLength(pdu->controlField.length); } /** * Serializes the Control Field of a PDU structure. * * @param pdu PDU with Control Field to serialize. * @param[out] controlFieldByte Serialized Control Field. */ static void SerializeControlField(const HAPBLEPDU* pdu, uint8_t* controlFieldByte) { HAPPrecondition(pdu); HAPPrecondition(HAPBLEPDUHasValidControlField(pdu)); HAPPrecondition(controlFieldByte); // Clear all bits. controlFieldByte[0] = 0; // Fragmentation status. switch (pdu->controlField.fragmentationStatus) { case kHAPBLEPDUFragmentationStatus_FirstFragment: { controlFieldByte[0] |= 0 << 7; } goto serialize_pdu_type; case kHAPBLEPDUFragmentationStatus_Continuation: { controlFieldByte[0] |= 1 << 7; } goto serialize_pdu_type; } HAPFatalError(); serialize_pdu_type: // PDU Type. switch (pdu->controlField.type) { case kHAPBLEPDUType_Request: { controlFieldByte[0] |= 0 << 3 | 0 << 2 | 0 << 1; } goto serialize_length; case kHAPBLEPDUType_Response: { controlFieldByte[0] |= 0 << 3 | 0 << 2 | 1 << 1; } goto serialize_length; } HAPFatalError(); serialize_length: // Length. switch (pdu->controlField.length) { case kHAPBLEPDUControlFieldLength_1Byte: { controlFieldByte[0] |= 0 << 0; return; } } HAPFatalError(); } HAP_RESULT_USE_CHECK HAPError HAPBLEPDUSerialize(const HAPBLEPDU* pdu, void* bytes, size_t maxBytes, size_t* numBytes) { HAPPrecondition(pdu); HAPPrecondition(HAPBLEPDUHasValidControlField(pdu)); HAPPrecondition(pdu->body.numBytes <= pdu->body.totalBodyBytes); HAPPrecondition(bytes); HAPPrecondition(numBytes); LogPDU(pdu); uint8_t* b = bytes; size_t remainingBytes = maxBytes; // PDU Header - Control Field. if (remainingBytes < 1) { HAPLog(&logObject, "Not enough capacity to serialize Control Field."); return kHAPError_OutOfResources; } SerializeControlField(pdu, b); b += 1; remainingBytes -= 1; // PDU Header - PDU Fixed Params. switch (pdu->controlField.fragmentationStatus) { case kHAPBLEPDUFragmentationStatus_FirstFragment: { switch (pdu->controlField.type) { case kHAPBLEPDUType_Request: { if (remainingBytes < 4) { HAPLog(&logObject, "Not enough capacity to serialize Request PDU Fixed Params."); return kHAPError_OutOfResources; } b[0] = pdu->fixedParams.request.opcode; b[1] = pdu->fixedParams.request.tid; HAPWriteLittleUInt16(&b[2], pdu->fixedParams.request.iid); b += 4; remainingBytes -= 4; goto serialize_body; } case kHAPBLEPDUType_Response: { if (remainingBytes < 2) { HAPLog(&logObject, "Not enough capacity to serialize Response PDU Fixed Params."); return kHAPError_OutOfResources; } b[0] = pdu->fixedParams.response.tid; b[1] = pdu->fixedParams.response.status; b += 2; remainingBytes -= 2; goto serialize_body; } } HAPFatalError(); serialize_body: // PDU Body (Optional). if (pdu->body.bytes) { if (remainingBytes < 2) { HAPLog(&logObject, "Not enough capacity to serialize PDU Body length."); return kHAPError_OutOfResources; } HAPWriteLittleUInt16(&b[0], pdu->body.totalBodyBytes); b += 2; remainingBytes -= 2; if (remainingBytes < pdu->body.numBytes) { HAPLog(&logObject, "Not enough capacity to serialize PDU Body."); return kHAPError_OutOfResources; } HAPRawBufferCopyBytes(b, HAPNonnullVoid(pdu->body.bytes), pdu->body.numBytes); b += pdu->body.numBytes; remainingBytes -= pdu->body.numBytes; } goto done; } case kHAPBLEPDUFragmentationStatus_Continuation: { if (remainingBytes < 1) { HAPLog(&logObject, "Not enough capacity to serialize Continuation PDU Fixed Params."); return kHAPError_OutOfResources; } b[0] = pdu->fixedParams.continuation.tid; b += 1; remainingBytes -= 1; if (remainingBytes < pdu->body.numBytes) { HAPLog(&logObject, "Not enough capacity to serialize PDU Body."); return kHAPError_OutOfResources; } if (!pdu->body.numBytes) { HAPLog(&logObject, "Received empty continuation fragment."); } else { HAPAssert(pdu->body.bytes); HAPRawBufferCopyBytes(b, HAPNonnullVoid(pdu->body.bytes), pdu->body.numBytes); b += pdu->body.numBytes; remainingBytes -= pdu->body.numBytes; } goto done; } } HAPAssertionFailure(); done: // All data written. *numBytes = maxBytes - remainingBytes; (void) b; return kHAPError_None; }
11,026
2,770
<gh_stars>1000+ """Alert on the OneLogin event that a user has assumed the role of someone else.""" from streamalert.shared.rule import rule @rule(logs=['onelogin:events']) def onelogin_events_assumed_role(rec): """ author: @javutin description: Alert on OneLogin users assuming a different role. reference_1: https://support.onelogin.com/hc/en-us/articles/202123164-Assuming-Users reference_2: https://developers.onelogin.com/api-docs/1/events/event-types """ return rec['event_type_id'] == 3
195
700
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib SKIDL_lib_version = '0.0.1' pspice = SchLib(tool=SKIDL).add_parts(*[ Part(name='0',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='CAP',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['C']), Part(name='DIODE',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='INDUCTOR',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='ISOURCE',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='QNPN',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='QPNP',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='R',dest=TEMPLATE,tool=SKIDL,keywords='R DEV',description='Resistance',ref_prefix='R',num_units=1,do_erc=True,pins=[ Pin(num='1',name='~',func=Pin.PASSIVE,do_erc=True), Pin(num='2',name='~',func=Pin.PASSIVE,do_erc=True)]), Part(name='VSOURCE',dest=TEMPLATE,tool=SKIDL,do_erc=True)])
469
453
<filename>libc/libgloss/m32c/sample.c /* Copyright (c) 2008 Red Hat Incorporated. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. The name of Red Hat Incorporated may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT INCORPORATED BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This is a sample program that shows how to use a few of the features of the M32C port of GCC, Binutils, and Newlib. */ #include <varvects.h> typedef unsigned char byte; typedef unsigned short word; #define prcr (*(volatile byte *)0x000a) #define cm0 (*(volatile byte *)0x0006) #define cm1 (*(volatile byte *)0x0007) #define ocd (*(volatile byte *)0x000c) #ifdef __r8c_cpu__ /* These are for the R8C/20 with LEDs on port P2 */ #define tracr (*(volatile byte *)0x0100) #define traioc (*(volatile byte *)0x0101) #define tramr (*(volatile byte *)0x0102) #define trapre (*(volatile byte *)0x0103) #define tra (*(volatile byte *)0x0104) #define traic (*(volatile byte *)0x0056) #define pd2 (*(volatile byte *)0x00e6) #define p2 (*(volatile byte *)0x00e4) #define ivec_timer_ra 22 #endif #ifdef __m32c_cpu__ /* These are for the M32C/83 with LEDs on port P0 and P1 */ #define ta0 (*(volatile word *)0x0346) #define ta0mr (*(volatile byte *)0x0356) #define tabsr (*(volatile byte *)0x0340) #define ta0ic (*(volatile byte *)0x006c) #define pd0 (*(volatile byte *)0x03e2) #define pd1 (*(volatile byte *)0x03e3) #define p0 (*(volatile byte *)0x03e0) #define p1 (*(volatile byte *)0x03e1) #define ivec_timer_a0 12 #endif /* Newlib's exit() pulls in lots of other things. Main() should never exit, but if it did, you could hard-reset the chip here. */ void exit(int rv) { while (1) asm volatile (""); } #ifdef __r8c_cpu__ /* The "constructor" attribute causes the startup code to call this sometime before main() is called. */ __attribute__((constructor)) void fast_clock(void) { asm("fclr I"); prcr = 1; cm0 = 0x08; cm1 = 0x38; asm("nop"); asm("nop"); asm("nop"); asm("nop"); ocd = 0; prcr = 0; asm("fset I"); } #endif /* We mark this volatile in case a non-interrupt function wants to read it, else gcc may optimize away extra reads. */ static volatile int tc = 1; /* The "interrupt" attribute changes the function entry/exit to properly preserve any changed registers. */ static void __attribute__((interrupt)) timer_ra_interrupt() { tc ++; #ifdef __r8c_cpu__ p2 = tc >> 4; #else p1 = tc; p0 = tc >> 8; #endif } main() { #ifdef __r8c_cpu__ pd2 = 0xff; /* TIMER RA */ tracr = 0x00; traioc = 0x00; tramr = 0x00; /* timer mode, f1 */ trapre = 255; /* prescaler */ tra = 255; /* cycle count */ _set_var_vect (timer_ra_interrupt, ivec_timer_ra); traic = 5; tracr = 1; #endif #ifdef __m32c_cpu__ pd0 = 0xff; pd1 = 0xff; /* TIMER A0 */ ta0mr = 0x00; /* Timer A0 mode register */ ta0 = 65535; /* Timer A0 register */ _set_var_vect (timer_ra_interrupt, ivec_timer_a0); ta0ic = 5; tabsr = 0xff; #endif /* main() must never return. */ while (1) ; }
1,594
348
<filename>docs/data/leg-t1/077/07709377.json {"nom":"Presles-en-Brie","circ":"9ème circonscription","dpt":"Seine-et-Marne","inscrits":1525,"abs":832,"votants":693,"blancs":7,"nuls":1,"exp":685,"res":[{"nuance":"REM","nom":"M<NAME>","voix":238},{"nuance":"LR","nom":"<NAME>","voix":146},{"nuance":"FN","nom":"M. <NAME>","voix":103},{"nuance":"FI","nom":"Mme <NAME>","voix":98},{"nuance":"SOC","nom":"Mme <NAME>","voix":31},{"nuance":"DLF","nom":"<NAME>","voix":18},{"nuance":"COM","nom":"Mme <NAME>","voix":17},{"nuance":"ECO","nom":"Mme <NAME>","voix":17},{"nuance":"ECO","nom":"Mme <NAME>","voix":7},{"nuance":"REG","nom":"<NAME>","voix":6},{"nuance":"DIV","nom":"Mme <NAME>","voix":2},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"EXG","nom":"M. <NAME>","voix":0}]}
321
713
<gh_stars>100-1000 # Solution 01: class TrieNode(object): def __init__(self): self.children = {} self.isEnd = False self.data = None self.rank = 0 class AutocompleteSystem(object): def __init__(self, sentences, times): """ :type sentences: List[str] :type times: List[int] """ self.root = TrieNode() self.inputKeyword = "" for i, sentence in enumerate(sentences): self.addRecord(sentence, times[i]) def addRecord(self, sentence, hotness): currentNode = self.root for char in sentence: if char not in currentNode.children: currentNode.children[char] = TrieNode() currentNode = currentNode.children[char] currentNode.isEnd = True currentNode.data = sentence currentNode.rank -= hotness # The reason for making it negative is, becasue 'rank' later uses sorted() on the tuples. But we need to sort assending for senetce and descending for rank. So by negating the rank, it can easily just sort assending as the default for sorted is. def dfs(self, root): results = [] if root: if root.isEnd: results.append((root.rank, root.data)) for child in root.children: results.extend(self.dfs(root.children[child])) return results def search(self, sentence): currentNode = self.root for char in sentence: if char not in currentNode.children: return [] currentNode = currentNode.children[char] return self.dfs(currentNode) def input(self, c): """ :type c: str :rtype: List[str] """ results = [] if c != "#": self.inputKeyword += c results = self.search(self.inputKeyword) else: self.addRecord(self.inputKeyword, 1) self.inputKeyword = "" return [item[1] for item in sorted(results)[:3]] # First 3 items which is sentence, sorted by rank # Your AutocompleteSystem object will be instantiated and called as such: # obj = AutocompleteSystem(sentences, times) # param_1 = obj.input(c) # Your AutocompleteSystem object will be instantiated and called as such: # obj = AutocompleteSystem(sentences, times) # param_1 = obj.input(c)
1,019
1,682
<reponame>haroldl/rest.li /* Copyright (c) 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.linkedin.pegasus.generator; import com.linkedin.data.schema.DataSchemaLocation; import com.linkedin.pegasus.generator.spec.ClassTemplateSpec; import com.sun.codemodel.JDefinedClass; import java.io.File; import java.util.Set; /** * Implements the checker interface to decide if a template class should be persisted. */ public class DataTemplatePersistentClassChecker implements JavaCodeUtil.PersistentClassChecker { private final boolean _generateImported; private final TemplateSpecGenerator _specGenerator; private final JavaDataTemplateGenerator _dataTemplateGenerator; private final Set<File> _sourceFiles; public DataTemplatePersistentClassChecker(boolean generateImported, TemplateSpecGenerator specGenerator, JavaDataTemplateGenerator dataTemplateGenerator, Set<File> sourceFiles) { _generateImported = generateImported; _specGenerator = specGenerator; _dataTemplateGenerator = dataTemplateGenerator; _sourceFiles = sourceFiles; } @Override public boolean isPersistent(JDefinedClass clazz) { if (_generateImported) { return true; } else { final ClassTemplateSpec spec = _dataTemplateGenerator.getGeneratedClasses().get(clazz); final DataSchemaLocation location = _specGenerator.getClassLocation(spec); return location == null // assume local || _sourceFiles.contains(location.getSourceFile()); } } }
622
922
package me.zbl.fullstack.mapper; import me.zbl.fullstack.entity.Article; import me.zbl.fullstack.entity.dto.form.ArticleSearchForm; import me.zbl.fullstack.framework.mapper.IMyMapper; import me.zbl.fullstack.mapper.provider.ArticleSqlProvider; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectProvider; import java.util.List; /** * @author James */ public interface ArticleMapper extends IMyMapper<Article> { String COLUMN_LIST = "article.id,title,introduction,article.gmt_create AS gmtCreate,article.gmt_modified AS gmtModified"; @Select({ "SELECT", COLUMN_LIST, "FROM", "article", "ORDER BY article.gmt_create DESC" }) List<Article> getPostViewAllArticles(); /** * 通过 tag id 查找文章 * * @param id tag id * * @return 符合条件的文章 */ @Select({ "SELECT", COLUMN_LIST, "FROM article", "INNER JOIN tag_article", "ON tag_article.article_id = article.id", "AND tag_article.tag_id=#{id}", "ORDER BY article.gmt_create DESC" }) List<Article> getArticleListByTagId(Integer id); /** * 通过条件查找文章 * * @param form 条件表单 * * @return 符合条件的文章 */ @SelectProvider(type = ArticleSqlProvider.class, method = "getArticleByCondition") List<Article> getArticleListByCondition(ArticleSearchForm form); }
742
2,703
<filename>tests/visual/test_widget_radioselect.py from selenium.webdriver.common.keys import Keys from django.test.utils import override_settings from .. import test_widget_radioselect as test from . import VisualTest @override_settings(ROOT_URLCONF='tests.test_widget_radioselect') class Test(VisualTest): def test_test_default_usecase(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_default_usecase.url)) self.assertScreenshot('form', 'radioselect_default_usecase') def test_missing_value_error(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_missing_value_error.url)) self.driver.find_element_by_css_selector("button").send_keys(Keys.RETURN) self.driver.find_element_by_css_selector("label[for=id_test_field_1]").click() self.assertScreenshot('form', 'radioselect_missing_value_error') def test_part_group_class(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_group_class.url)) self.assertScreenshot('form', 'radioselect_part_group_class') def test_part_add_group_class(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_add_group_class.url)) self.assertScreenshot('form', 'radioselect_part_add_group_class') def test_part_prefix(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_prefix.url)) self.assertScreenshot('form', 'radioselect_part_prefix') def test_part_add_control_class(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_add_control_class.url)) self.driver.find_element_by_css_selector("label[for=id_test_field_1]").click() self.assertScreenshot('form', 'radioselect_part_add_control_class') def test_part_label(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_label.url)) self.assertScreenshot('form', 'radioselect_part_label') def test_part_add_label_class(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_add_label_class.url)) self.assertScreenshot('form', 'radioselect_part_add_label_class') def test_part_help_text(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_help_text.url)) self.assertScreenshot('form', 'radioselect_part_help_text') def test_part_errors(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_part_errors.url)) self.assertScreenshot('form', 'radioselect_part_errors')
1,066
3,428
{"id":"00418","group":"spam-1","checksum":{"type":"MD5","value":"6321175c76411371c109eafc99563d2c"},"text":"From <EMAIL> Sun Sep 22 14:13:25 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby zzzzason.org (Postfix) with ESMTP id EE16616F16\n\tfor <zzzz@localhost>; Sun, 22 Sep 2002 14:13:24 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Sun, 22 Sep 2002 14:13:24 +0100 (IST)\nReceived: from tony.reimersinc.local ([65.210.112.2]) by\n dogma.slashnull.org (8.11.6/8.11.6) with SMTP id g8MBRdC32691 for\n <<EMAIL>>; Sun, 22 Sep 2002 12:27:40 +0100\nReceived: from mx1.eudoramail.com ([192.168.3.11]) by\n tony.reimersinc.local (Mail-Gear 2.0.0) with SMTP id M2002092207110412848 ;\n Sun, 22 Sep 2002 07:11:57 -0400\nMessage-Id: <<EMAIL>>\nTo: <<EMAIL>>\nFrom: [email protected]\nSubject: Have you planned for your family's future? ZBM\nDate: Sun, 22 Sep 2002 16:33:38 -0700\nMIME-Version: 1.0\nContent-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: quoted-printable\n\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<HTML><HEAD><TITLE></TITLE>\n<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Diso-8859-1=\n\"></HEAD>\n<BODY>\n<CENTER><A href=3D\"http://61.145.116.189/user0203/627216/index.htm\">\n<IMG src=3D\"http://192.168.127.12/life-ad.gif\" border=3D0></A> </CENTER><BR>=\n<BR>\n<TABLE width=3D450 align=3Dcenter><TBODY><TR>\n<TD align=3Dmiddle><FONT face=3DArial,Helvetica color=3D#000000 size=3D1>=FF=\nFFFFA9\nCopyright 2002 - All rights reserved<BR><BR>If you would no longer like us\nto contact you or feel that you have<BR>received this email in error,\nplease <A href=3D\"http://172.16.17.32/light/first.asp\">click here to\nunsubscribe</A>.</FONT></TD></TR></TBODY></TABLE></BODY></HTML>\n\n\n\n\n"}
852
302
// // ARViewController.h // Renaissance // // Created by <NAME> on 15/12/21. // Copyright © 2015年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "ARFrontView.h" #import "GeoJSON_Root.h" @interface ARViewController : UIViewController @property (nonatomic,strong) ARFrontView *ARView; @property (nonatomic,strong) GeoJSON_Root *ARdata; @property (nonatomic,strong) CLLocation * playerLocation; @end
150
348
{"nom":"Domèvre-en-Haye","circ":"5ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":276,"abs":149,"votants":127,"blancs":9,"nuls":2,"exp":116,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":64},{"nuance":"REM","nom":"<NAME>","voix":52}]}
104
488
<reponame>chauffer/BulletSharpUnity3d #include "main.h" extern "C" { EXPORT btMultiBodyJointLimitConstraint* btMultiBodyJointLimitConstraint_new(btMultiBody* body, int link, btScalar lower, btScalar upper); }
86
725
<reponame>mb64/swipl-devel<filename>src/win32/console/history.c /* Part of SWI-Prolog Author: <NAME> E-mail: <EMAIL> WWW: http://www.swi-prolog.org Copyright (c) 1999-2012, University of Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include <tchar.h> #define _MAKE_DLL 1 #undef _export #include "console.h" /* public stuff */ #include "console_i.h" /* internal stuff */ #include <string.h> #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif static __inline int next(RlcData b, int i) { if ( ++i == b->history.size ) return 0; return i; } static __inline int prev(RlcData b, int i) { if ( --i < 0 ) return b->history.size-1; return i; } void rlc_init_history(rlc_console c, int size) { RlcData b = rlc_get_data(c); int oldsize; int i; if ( b->history.lines ) { b->history.lines = rlc_realloc(b->history.lines, sizeof(TCHAR *) * size); oldsize = b->history.size; } else { b->history.lines = rlc_malloc(sizeof(TCHAR *) * size); oldsize = 0; } for(i=oldsize; i<size; i++) b->history.lines[i] = NULL; b->history.size = size; b->history.current = -1; } void rlc_add_history(rlc_console c, const TCHAR *line) { RlcData b = rlc_get_data(c); if ( b->history.size ) { int i = next(b, b->history.head); size_t len = _tcslen(line); while(*line && *line <= ' ') /* strip leading white-space */ line++; len = _tcslen(line); /* strip trailing white-space */ while ( len > 0 && line[len-1] <= ' ' ) len--; if ( len == 0 ) { b->history.current = -1; return; } if ( b->history.lines[b->history.head] && _tcsncmp(b->history.lines[b->history.head], line, len) == 0 ) { b->history.current = -1; return; /* same as last line added */ } if ( i == b->history.tail ) /* this one is lost */ b->history.tail = next(b, b->history.tail); b->history.head = i; b->history.current = -1; if ( b->history.lines[i] ) b->history.lines[i] = rlc_realloc(b->history.lines[i], (len+1)*sizeof(TCHAR)); else b->history.lines[i] = rlc_malloc((len+1)*sizeof(TCHAR)); if ( b->history.lines[i] ) { _tcsncpy(b->history.lines[i], line, len); b->history.lines[i][len] = '\0'; } } } int rlc_for_history(rlc_console c, int (*handler)(void *ctx, int no, const TCHAR *line), void *ctx) { RlcData b = rlc_get_data(c); int here = b->history.head; int no = 1; for( ; here != b->history.tail; here = prev(b, here)) { int rc; if ( (rc=(*handler)(ctx, no++, b->history.lines[here])) != 0 ) return rc; } return 0; } int rlc_at_head_history(RlcData b) { return b->history.current == -1 ? TRUE : FALSE; } const TCHAR * rlc_bwd_history(RlcData b) { if ( b->history.size ) { if ( b->history.current == -1 ) b->history.current = b->history.head; else if ( b->history.current == b->history.tail ) return NULL; else b->history.current = prev(b, b->history.current); return b->history.lines[b->history.current]; } return NULL; } const TCHAR * rlc_fwd_history(RlcData b) { if ( b->history.size && b->history.current != -1 ) { const TCHAR *s; b->history.current = next(b, b->history.current); s = b->history.lines[b->history.current]; if ( b->history.current == b->history.head ) b->history.current = -1; return s; } return NULL; }
1,909
348
{"nom":"Gaillères","circ":"1ère circonscription","dpt":"Landes","inscrits":467,"abs":221,"votants":246,"blancs":12,"nuls":8,"exp":226,"res":[{"nuance":"MDM","nom":"<NAME>","voix":136},{"nuance":"SOC","nom":"<NAME>","voix":90}]}
90
8,599
<reponame>dolphin57/Activiti /* * Copyright 2010-2020 Alfresco Software, 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 org.activiti.engine.impl.persistence.entity.data.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.impl.EventSubscriptionQueryImpl; import org.activiti.engine.impl.Page; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.activiti.engine.impl.persistence.CachedEntityMatcher; import org.activiti.engine.impl.persistence.entity.CompensateEventSubscriptionEntity; import org.activiti.engine.impl.persistence.entity.CompensateEventSubscriptionEntityImpl; import org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity; import org.activiti.engine.impl.persistence.entity.EventSubscriptionEntityImpl; import org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity; import org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntityImpl; import org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity; import org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntityImpl; import org.activiti.engine.impl.persistence.entity.data.AbstractDataManager; import org.activiti.engine.impl.persistence.entity.data.EventSubscriptionDataManager; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.EventSubscriptionsByExecutionAndTypeMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.EventSubscriptionsByExecutionIdMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.EventSubscriptionsByNameMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.EventSubscriptionsByProcInstTypeAndActivityMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.MessageEventSubscriptionsByProcInstAndEventNameMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.SignalEventSubscriptionByEventNameMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.SignalEventSubscriptionByNameAndExecutionMatcher; import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.SignalEventSubscriptionByProcInstAndEventNameMatcher; /** */ public class MybatisEventSubscriptionDataManager extends AbstractDataManager<EventSubscriptionEntity> implements EventSubscriptionDataManager { private static List<Class<? extends EventSubscriptionEntity>> ENTITY_SUBCLASSES = new ArrayList<Class<? extends EventSubscriptionEntity>>(); static { ENTITY_SUBCLASSES.add(MessageEventSubscriptionEntityImpl.class); ENTITY_SUBCLASSES.add(SignalEventSubscriptionEntityImpl.class); ENTITY_SUBCLASSES.add(CompensateEventSubscriptionEntityImpl.class); } protected CachedEntityMatcher<EventSubscriptionEntity> eventSubscriptionsByNameMatcher = new EventSubscriptionsByNameMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> eventSubscritionsByExecutionIdMatcher = new EventSubscriptionsByExecutionIdMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> eventSubscriptionsByProcInstTypeAndActivityMatcher = new EventSubscriptionsByProcInstTypeAndActivityMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> eventSubscriptionsByExecutionAndTypeMatcher = new EventSubscriptionsByExecutionAndTypeMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> signalEventSubscriptionByNameAndExecutionMatcher = new SignalEventSubscriptionByNameAndExecutionMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> signalEventSubscriptionByProcInstAndEventNameMatcher = new SignalEventSubscriptionByProcInstAndEventNameMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> signalEventSubscriptionByEventNameMatcher = new SignalEventSubscriptionByEventNameMatcher(); protected CachedEntityMatcher<EventSubscriptionEntity> messageEventSubscriptionsByProcInstAndEventNameMatcher = new MessageEventSubscriptionsByProcInstAndEventNameMatcher(); public MybatisEventSubscriptionDataManager(ProcessEngineConfigurationImpl processEngineConfiguration) { super(processEngineConfiguration); } @Override public Class<? extends EventSubscriptionEntity> getManagedEntityClass() { return EventSubscriptionEntityImpl.class; } @Override public List<Class<? extends EventSubscriptionEntity>> getManagedEntitySubClasses() { return ENTITY_SUBCLASSES; } @Override public EventSubscriptionEntity create() { // only allowed to create subclasses throw new UnsupportedOperationException(); } @Override public CompensateEventSubscriptionEntity createCompensateEventSubscription() { return new CompensateEventSubscriptionEntityImpl(); } @Override public MessageEventSubscriptionEntity createMessageEventSubscription() { return new MessageEventSubscriptionEntityImpl(); } @Override public SignalEventSubscriptionEntity createSignalEventSubscription() { return new SignalEventSubscriptionEntityImpl(); } @Override public long findEventSubscriptionCountByQueryCriteria(EventSubscriptionQueryImpl eventSubscriptionQueryImpl) { final String query = "selectEventSubscriptionCountByQueryCriteria"; return (Long) getDbSqlSession().selectOne(query, eventSubscriptionQueryImpl); } @Override @SuppressWarnings("unchecked") public List<EventSubscriptionEntity> findEventSubscriptionsByQueryCriteria(EventSubscriptionQueryImpl eventSubscriptionQueryImpl, Page page) { final String query = "selectEventSubscriptionByQueryCriteria"; return getDbSqlSession().selectList(query, eventSubscriptionQueryImpl, page); } @Override public List<MessageEventSubscriptionEntity> findMessageEventSubscriptionsByProcessInstanceAndEventName(final String processInstanceId, final String eventName) { Map<String, String> params = new HashMap<String, String>(); params.put("processInstanceId", processInstanceId); params.put("eventName", eventName); return toMessageEventSubscriptionEntityList(getList("selectMessageEventSubscriptionsByProcessInstanceAndEventName", params, messageEventSubscriptionsByProcInstAndEventNameMatcher, true)); } @Override public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByEventName(final String eventName, final String tenantId) { final String query = "selectSignalEventSubscriptionsByEventName"; final Map<String, String> params = new HashMap<String, String>(); params.put("eventName", eventName); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } List<EventSubscriptionEntity> result = getList(query, params, signalEventSubscriptionByEventNameMatcher, true); return toSignalEventSubscriptionEntityList(result); } @Override public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByProcessInstanceAndEventName(final String processInstanceId, final String eventName) { final String query = "selectSignalEventSubscriptionsByProcessInstanceAndEventName"; Map<String, String> params = new HashMap<String, String>(); params.put("processInstanceId", processInstanceId); params.put("eventName", eventName); return toSignalEventSubscriptionEntityList(getList(query, params, signalEventSubscriptionByProcInstAndEventNameMatcher, true)); } @Override public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByNameAndExecution(final String name, final String executionId) { Map<String, String> params = new HashMap<String, String>(); params.put("executionId", executionId); params.put("eventName", name); return toSignalEventSubscriptionEntityList(getList("selectSignalEventSubscriptionsByNameAndExecution", params, signalEventSubscriptionByNameAndExecutionMatcher, true)); } @Override public List<EventSubscriptionEntity> findEventSubscriptionsByExecutionAndType(final String executionId, final String type) { Map<String, String> params = new HashMap<String, String>(); params.put("executionId", executionId); params.put("eventType", type); return getList("selectEventSubscriptionsByExecutionAndType", params, eventSubscriptionsByExecutionAndTypeMatcher, true); } @Override public List<EventSubscriptionEntity> findEventSubscriptionsByProcessInstanceAndActivityId(final String processInstanceId, final String activityId, final String type) { Map<String, String> params = new HashMap<String, String>(); params.put("processInstanceId", processInstanceId); params.put("eventType", type); params.put("activityId", activityId); return getList("selectEventSubscriptionsByProcessInstanceTypeAndActivity", params, eventSubscriptionsByProcInstTypeAndActivityMatcher, true); } @Override public List<EventSubscriptionEntity> findEventSubscriptionsByExecution(final String executionId) { return getList("selectEventSubscriptionsByExecution", executionId, eventSubscritionsByExecutionIdMatcher, true); } @Override @SuppressWarnings("unchecked") public List<EventSubscriptionEntity> findEventSubscriptionsByTypeAndProcessDefinitionId(String type, String processDefinitionId, String tenantId) { final String query = "selectEventSubscriptionsByTypeAndProcessDefinitionId"; Map<String,String> params = new HashMap<String, String>(); if (type != null) { params.put("eventType", type); } params.put("processDefinitionId", processDefinitionId); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } return getDbSqlSession().selectList(query, params); } @Override public List<EventSubscriptionEntity> findEventSubscriptionsByName(final String type, final String eventName, final String tenantId) { Map<String, String> params = new HashMap<String, String>(); params.put("eventType", type); params.put("eventName", eventName); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } return getList("selectEventSubscriptionsByName", params, eventSubscriptionsByNameMatcher, true); } @Override @SuppressWarnings("unchecked") public List<EventSubscriptionEntity> findEventSubscriptionsByNameAndExecution(String type, String eventName, String executionId) { final String query = "selectEventSubscriptionsByNameAndExecution"; Map<String, String> params = new HashMap<String, String>(); params.put("eventType", type); params.put("eventName", eventName); params.put("executionId", executionId); return getDbSqlSession().selectList(query, params); } @Override public MessageEventSubscriptionEntity findMessageStartEventSubscriptionByName(String messageName, String tenantId) { Map<String, String> params = new HashMap<String, String>(); params.put("eventName", messageName); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } MessageEventSubscriptionEntity entity = (MessageEventSubscriptionEntity) getDbSqlSession().selectOne("selectMessageStartEventSubscriptionByName", params); return entity; } @Override public void updateEventSubscriptionTenantId(String oldTenantId, String newTenantId) { Map<String, String> params = new HashMap<String, String>(); params.put("oldTenantId", oldTenantId); params.put("newTenantId", newTenantId); getDbSqlSession().update("updateTenantIdOfEventSubscriptions", params); } @Override public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) { getDbSqlSession().delete("deleteEventSubscriptionsForProcessDefinition", processDefinitionId, EventSubscriptionEntityImpl.class); } protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList(List<EventSubscriptionEntity> result) { List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList<SignalEventSubscriptionEntity>(result.size()); for (EventSubscriptionEntity eventSubscriptionEntity : result ) { signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity); } return signalEventSubscriptionEntities; } protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList(List<EventSubscriptionEntity> result) { List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList<MessageEventSubscriptionEntity>(result.size()); for (EventSubscriptionEntity eventSubscriptionEntity : result ) { messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity); } return messageEventSubscriptionEntities; } }
3,897
1,056
<filename>ide/db.sql.editor/src/org/netbeans/modules/db/sql/analyzer/InsertStatementAnalyzer.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.db.sql.analyzer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.netbeans.api.db.sql.support.SQLIdentifiers.Quoter; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.modules.db.sql.analyzer.SQLStatement.Context; import org.netbeans.modules.db.sql.lexer.SQLTokenId; /** * * @author <NAME> */ class InsertStatementAnalyzer extends SQLStatementAnalyzer { private final List<String> columns = new ArrayList<String> (); private final List<String> values = new ArrayList<String> (); private QualIdent table = null; public static InsertStatement analyze (TokenSequence<SQLTokenId> seq, Quoter quoter) { seq.moveStart(); if (!seq.moveNext()) { return null; } InsertStatementAnalyzer sa = new InsertStatementAnalyzer(seq, quoter); sa.parse(); TableIdent ti = new TableIdent(sa.table, null); TablesClause tablesClause = sa.context.isAfter(Context.FROM) ? sa.createTablesClause(Collections.singletonList(ti)) : null; return new InsertStatement( sa.startOffset, seq.offset() + seq.token().length(), sa.getTable(), Collections.unmodifiableList(sa.columns), Collections.unmodifiableList(sa.values), sa.offset2Context, tablesClause, Collections.unmodifiableList(sa.subqueries) ); } private InsertStatementAnalyzer (TokenSequence<SQLTokenId> seq, Quoter quoter) { super(seq, quoter); } private void parse () { startOffset = seq.offset (); do { switch (context) { case START: if (SQLStatementAnalyzer.isKeyword ("INSERT", seq)) { // NOI18N moveToContext(Context.INSERT); } break; case INSERT: if (SQLStatementAnalyzer.isKeyword("INTO", seq)) { // NOI18N moveToContext(Context.INSERT_INTO); } break; case INSERT_INTO: switch (seq.token ().id ()) { case IDENTIFIER: table = parseIdentifier(); break; case LPAREN: moveToContext(Context.COLUMNS); break; case KEYWORD: if (SQLStatementAnalyzer.isKeyword ("VALUES", seq)) { //NOI18N moveToContext(Context.VALUES); } else if (SQLStatementAnalyzer.isKeyword ("SET", seq)) { //NOI18N moveToContext(Context.SET); } break; } break; case COLUMNS: switch (seq.token ().id ()) { case IDENTIFIER: List<String> chosenColumns = analyzeChosenColumns (); if ( ! chosenColumns.isEmpty ()) { columns.addAll (chosenColumns); } break; case KEYWORD: if (SQLStatementAnalyzer.isKeyword ("VALUES", seq)) { //NOI18N moveToContext(Context.VALUES); } break; case RPAREN: moveToContext(Context.VALUES); break; } break; case VALUES: switch (seq.token ().id ()) { case IDENTIFIER: List<String> newValues = analyzeChosenColumns (); if ( ! newValues.isEmpty ()) { values.addAll (newValues); } break; } break; default: } } while (nextToken ()); } private List<String> analyzeChosenColumns () { List<String> parts = new ArrayList<String> (); parts.add (getUnquotedIdentifier ()); while (seq.moveNext ()) { switch (seq.token ().id ()) { case WHITESPACE: continue; case COMMA: continue; case RPAREN: return parts; default: parts.add (getUnquotedIdentifier ()); } } return parts; } private QualIdent getTable () { return table; } }
3,030
1,545
<gh_stars>1000+ /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.bookkeeper.auth; import java.io.IOException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.proto.BookieConnectionPeer; /** * Bookie authentication provider interface. * * <p>This must be implemented by any party wishing to implement * an authentication mechanism for bookkeeper connections. */ public interface BookieAuthProvider { /** * A factory to create the bookie authentication provider. */ interface Factory { /** * Initialize the factory with the server configuration * and protobuf message registry. Implementors must * add any extention messages which contain the auth * payload, so that the server can decode auth messages * it receives from the client. */ void init(ServerConfiguration conf) throws IOException; /** * Create a new instance of a bookie auth provider. * Each connection should get its own instance, as they * can hold connection specific state. * The completeCb is used to notify the server that * the authentication handshake is complete. * CompleteCb should be called only once. * If the authentication was successful, BKException.Code.OK * should be passed as the return code. Otherwise, another * error code should be passed. * If authentication fails, the server will close the * connection. * @param connection an handle to the connection * @param completeCb callback to be notified when authentication * is complete. */ BookieAuthProvider newProvider(BookieConnectionPeer connection, AuthCallbacks.GenericCallback<Void> completeCb); /** * Get Auth provider plugin name. * Used as a sanity check to ensure that the bookie and the client. * are using the same auth provider. */ String getPluginName(); /** * Release resources. */ default void close() {} } /** * Callback to let the provider know that the underlying protocol is changed. * For instance this will happen when a START_TLS operation succeeds */ default void onProtocolUpgrade() { } /** * Process a request from the client. cb will receive the next * message to be sent to the client. If there are no more messages * to send to the client, cb should not be called, and completeCb * must be called instead. */ void process(AuthToken m, AuthCallbacks.GenericCallback<AuthToken> cb); /** * Release resources. */ default void close() {} }
1,186
8,664
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once namespace Js { class RemoteSourceContextInfo; class SourceDynamicProfileManager; }; // // This object is created per script source file or dynamic script buffer. // class SourceContextInfo { public: Field(uint) sourceContextId; Field(Js::LocalFunctionId) nextLocalFunctionId; // Count of functions seen so far #if DBG Field(bool) closed; #endif Field(DWORD_PTR) dwHostSourceContext; // Context passed in to ParseScriptText Field(bool) isHostDynamicDocument; // will be set to true when current doc is treated dynamic from the host side. (IActiveScriptContext::IsDynamicDocument) union { struct { FieldNoBarrier(char16 const *) url; // The url of the file FieldNoBarrier(char16 const *) sourceMapUrl; // The url of the source map, such as actual non-minified source of JS on the server. }; Field(uint) hash; // hash for dynamic scripts }; #if ENABLE_PROFILE_INFO Field(Js::SourceDynamicProfileManager *) sourceDynamicProfileManager; #endif void EnsureInitialized(); bool IsDynamic() const { return dwHostSourceContext == Js::Constants::NoHostSourceContext || isHostDynamicDocument; } bool IsSourceProfileLoaded() const; SourceContextInfo* Clone(Js::ScriptContext* scriptContext) const; };
529
578
/* * 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 <gtest/gtest.h> #include "cachelib/navy/common/Utils.h" namespace facebook { namespace cachelib { namespace navy { namespace tests { TEST(Utils, PowTwoAlign) { EXPECT_EQ(0, powTwoAlign(0, 16)); EXPECT_EQ(16, powTwoAlign(1, 16)); EXPECT_EQ(16, powTwoAlign(2, 16)); EXPECT_EQ(16, powTwoAlign(15, 16)); EXPECT_EQ(16, powTwoAlign(16, 16)); EXPECT_EQ(32, powTwoAlign(17, 16)); } TEST(Utils, Between) { EXPECT_TRUE(between(0.4, 0, 1)); EXPECT_TRUE(between(1.0, 0, 1)); EXPECT_TRUE(between(0.0, 0, 1)); EXPECT_TRUE(betweenStrict(0.4, 0, 1)); EXPECT_FALSE(betweenStrict(1.0, 0, 1)); EXPECT_FALSE(betweenStrict(0.0, 0, 1)); } } // namespace tests } // namespace navy } // namespace cachelib } // namespace facebook
493
1,673
/* bug #250 - Array size compile-time optimization stops halfway */ #include <stdlib.h> #define LZO_MAX(a,b) ((a) >= (b) ? (a) : (b)) unsigned char c[2*4]; unsigned char b[2*LZO_MAX(8,sizeof(int))]; // this will not compile int main(void) { /* FIXME: add some runtime check */ return EXIT_SUCCESS; }
133
376
<filename>vapory/helpers.py WIKIREF = "http://wiki.povray.org/content/Reference:" def vectorize(arr): """ transforms [a, b, c] into string "<a, b, c>"" """ return "<%s>" % ",".join([str(e) for e in arr]) def format_if_necessary(e): """ If necessary, replaces -3 by (-3), and [a, b, c] by <a, b, c> """ if isinstance(e, (int, float)) and e<0: # This format because POVray interprets -3 as a substraction return "( %s )"%str(e) if hasattr(e, '__iter__') and not isinstance(e, str): # lists, tuples, numpy arrays, become '<a,b,c,d >' return vectorize(e) else: return e
277
17,318
/* * Copyright (c) 2011-2018, <NAME>. All Rights Reserved. * * 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.dianping.cat.report.page.state.task; import java.util.Date; import java.util.Set; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import com.dianping.cat.Cat; import com.dianping.cat.Constants; import com.dianping.cat.config.server.ServerConfigManager; import com.dianping.cat.config.server.ServerFilterConfigManager; import com.dianping.cat.configuration.NetworkInterfaceManager; import com.dianping.cat.consumer.state.StateAnalyzer; import com.dianping.cat.consumer.state.model.entity.ProcessDomain; import com.dianping.cat.consumer.state.model.entity.StateReport; import com.dianping.cat.consumer.state.model.transform.BaseVisitor; import com.dianping.cat.consumer.state.model.transform.DefaultNativeBuilder; import com.dianping.cat.core.dal.DailyReport; import com.dianping.cat.core.dal.Hostinfo; import com.dianping.cat.core.dal.MonthlyReport; import com.dianping.cat.core.dal.WeeklyReport; import com.dianping.cat.helper.TimeHelper; import com.dianping.cat.report.page.state.service.StateReportService; import com.dianping.cat.report.task.TaskBuilder; import com.dianping.cat.report.task.TaskHelper; import com.dianping.cat.report.task.current.CurrentWeeklyMonthlyReportTask; import com.dianping.cat.report.task.current.CurrentWeeklyMonthlyReportTask.CurrentWeeklyMonthlyTask; import com.dianping.cat.service.HostinfoService; import com.dianping.cat.service.ProjectService; @Named(type = TaskBuilder.class, value = StateReportBuilder.ID) public class StateReportBuilder implements TaskBuilder, Initializable { public static final String ID = StateAnalyzer.ID; @Inject protected StateReportService m_reportService; @Inject protected ServerConfigManager m_serverConfigManager; @Inject protected ServerFilterConfigManager m_serverFilterConfigManager; @Inject private ProjectService m_projectService; @Inject private HostinfoService m_hostinfoService; @Override public boolean buildDailyTask(String name, String domain, Date period) { StateReport stateReport = queryHourlyReportsByDuration(domain, period, TaskHelper.tomorrowZero(period)); DailyReport report = new DailyReport(); report.setCreationDate(new Date()); report.setDomain(domain); report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress()); report.setName(name); report.setPeriod(period); report.setType(1); byte[] binaryContent = DefaultNativeBuilder.build(stateReport); return m_reportService.insertDailyReport(report, binaryContent); } @Override public boolean buildHourlyTask(String name, String domain, Date period) { StateReport stateReport = m_reportService .queryReport(domain, period, new Date(period.getTime() + TimeHelper.ONE_HOUR)); new StateReportVisitor().visitStateReport(stateReport); return true; } @Override public boolean buildMonthlyTask(String name, String domain, Date period) { StateReport stateReport = queryDailyReportsByDuration(domain, period, TaskHelper.nextMonthStart(period)); MonthlyReport report = new MonthlyReport(); report.setCreationDate(new Date()); report.setDomain(domain); report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress()); report.setName(name); report.setPeriod(period); report.setType(1); byte[] binaryContent = DefaultNativeBuilder.build(stateReport); return m_reportService.insertMonthlyReport(report, binaryContent); } @Override public boolean buildWeeklyTask(String name, String domain, Date period) { Date start = period; Date end = new Date(start.getTime() + TimeHelper.ONE_DAY * 7); StateReport stateReport = queryDailyReportsByDuration(domain, start, end); WeeklyReport report = new WeeklyReport(); report.setCreationDate(new Date()); report.setDomain(domain); report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress()); report.setName(name); report.setPeriod(period); report.setType(1); byte[] binaryContent = DefaultNativeBuilder.build(stateReport); return m_reportService.insertWeeklyReport(report, binaryContent); } @Override public void initialize() throws InitializationException { CurrentWeeklyMonthlyReportTask.getInstance().register(new CurrentWeeklyMonthlyTask() { @Override public void buildCurrentMonthlyTask(String name, String domain, Date start) { if (Constants.CAT.equals(domain)) { buildMonthlyTask(name, domain, start); } } @Override public void buildCurrentWeeklyTask(String name, String domain, Date start) { if (Constants.CAT.equals(domain)) { buildWeeklyTask(name, domain, start); } } @Override public String getReportName() { return ID; } }); } private StateReport queryDailyReportsByDuration(String domain, Date start, Date end) { long startTime = start.getTime(); long endTime = end.getTime(); HistoryStateReportMerger merger = new HistoryStateReportMerger(new StateReport(domain)); for (; startTime < endTime; startTime += TimeHelper.ONE_DAY) { try { StateReport reportModel = m_reportService .queryReport(domain, new Date(startTime), new Date(startTime + TimeHelper.ONE_DAY)); reportModel.accept(merger); } catch (Exception e) { Cat.logError(e); } } StateReport stateReport = merger.getStateReport(); new ClearDetailInfo().visitStateReport(stateReport); stateReport.setStartTime(start); stateReport.setEndTime(end); return stateReport; } private StateReport queryHourlyReportsByDuration(String domain, Date period, Date endDate) { long startTime = period.getTime(); long endTime = endDate.getTime(); HistoryStateReportMerger merger = new HistoryStateReportMerger(new StateReport(domain)); for (; startTime < endTime; startTime = startTime + TimeHelper.ONE_HOUR) { Date date = new Date(startTime); StateReport reportModel = m_reportService.queryReport(domain, date, new Date(date.getTime() + TimeHelper.ONE_HOUR)); reportModel.accept(merger); } StateReport stateReport = merger.getStateReport(); new ClearDetailInfo().visitStateReport(stateReport); stateReport.setStartTime(period); stateReport.setEndTime(endDate); return stateReport; } private void updateProjectAndHost(String domain, String ip) { if (m_serverFilterConfigManager.validateDomain(domain)) { if (!m_projectService.contains(domain)) { m_projectService.insert(domain); } Hostinfo info = m_hostinfoService.findByIp(ip); if (info == null) { m_hostinfoService.insert(domain, ip); } else { String oldDomain = info.getDomain(); if (!domain.equals(oldDomain) && !Constants.CAT.equals(oldDomain)) { m_hostinfoService.update(info.getId(), domain, ip); } } } } public static class ClearDetailInfo extends BaseVisitor { @Override public void visitProcessDomain(ProcessDomain processDomain) { processDomain.getDetails().clear(); } } public class StateReportVisitor extends BaseVisitor { @Override public void visitProcessDomain(ProcessDomain processDomain) { String domain = processDomain.getName(); Set<String> ips = processDomain.getIps(); for (String ip : ips) { if (m_serverFilterConfigManager.validateDomain(domain) && m_serverConfigManager.validateIp(ip)) { updateProjectAndHost(domain, ip); } } } } }
2,646
1,080
<gh_stars>1000+ /* * ccommon - a cache common library. * Copyright (C) 2013 Twitter, 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. */ #include <cc_event.h> #include <cc_debug.h> #include <cc_define.h> #include <cc_mm.h> #include <inttypes.h> #include <string.h> #include <sys/event.h> #include <sys/errno.h> #include <unistd.h> #include "cc_shared.h" struct event_base { int kq; /* kernel event queue descriptor */ struct kevent *change; /* change[] - events we want to monitor */ int nchange; /* # change */ struct kevent *event; /* event[] - events that were triggered */ int nevent; /* # events */ int nreturned; /* # events placed in event[] */ int nprocessed; /* # events processed from event[] */ event_cb_fn cb; /* event callback */ }; struct event_base * event_base_create(int nevent, event_cb_fn cb) { struct event_base *evb; int status, kq; struct kevent *change, *event; ASSERT(nevent > 0); kq = kqueue(); if (kq < 0) { log_error("kqueue failed: %s", strerror(errno)); return NULL; } change = (struct kevent *)cc_calloc(nevent, sizeof(*change)); if (change == NULL) { status = close(kq); if (status < 0) { log_warn("close kqueue fd %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } event = (struct kevent *)cc_calloc(nevent, sizeof(*event)); if (event == NULL) { cc_free(change); status = close(kq); if (status < 0) { log_warn("close kqueue fd %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } evb = (struct event_base *)cc_alloc(sizeof(*evb)); if (evb == NULL) { cc_free(change); cc_free(event); status = close(kq); if (status < 0) { log_warn("close kqueue fd %d failed, ignored: %s", kq, strerror(errno)); } return NULL; } evb->kq = kq; evb->change = change; evb->nchange = 0; evb->event = event; evb->nevent = nevent; evb->nreturned = 0; evb->nprocessed = 0; evb->cb = cb; log_info("kqueue fd %d with nevent %d", evb->kq, evb->nevent); return evb; } void event_base_destroy(struct event_base **evb) { ASSERT(evb != NULL); int status; struct event_base *e = *evb; if (e == NULL) { return; } ASSERT(e->kq > 0); cc_free(e->change); cc_free(e->event); status = close(e->kq); if (status < 0) { log_warn("close kq %d failed, ignored: %s", e->kq, strerror(errno)); } e->kq = -1; cc_free(e); *evb = NULL; } static void _event_update(struct event_base *evb, int fd, uint16_t flags, uint32_t fflags, void *data) { struct kevent *event; ASSERT(evb != NULL && evb->kq > 0); ASSERT(fd > 0); ASSERT(evb->nchange < evb->nevent); event = &evb->change[evb->nchange++]; EV_SET(event, fd, flags, fflags, 0, 0, data); kevent(evb->kq, evb->change, evb->nchange, NULL, 0, NULL); evb->nchange = 0; } int event_add_read(struct event_base *evb, int fd, void *data) { _event_update(evb, fd, EVFILT_READ, EV_ADD, data); INCR(event_metrics, event_read); log_verb("adding read event to fd %d", fd); return 0; } int event_add_write(struct event_base *evb, int fd, void *data) { _event_update(evb, fd, EVFILT_WRITE, EV_ADD, data); INCR(event_metrics, event_write); log_verb("adding read event to fd %d", fd); return 0; } int event_del(struct event_base *evb, int fd) { _event_update(evb, fd, EVFILT_READ, EV_DELETE, NULL); _event_update(evb, fd, EVFILT_WRITE, EV_DELETE, NULL); return 0; } int event_wait(struct event_base *evb, int timeout) { int kq; struct timespec ts, *tsp; ASSERT(evb != NULL); kq = evb->kq; ASSERT(kq > 0); /* kevent should block indefinitely if timeout < 0 */ if (timeout < 0) { tsp = NULL; } else { tsp = &ts; tsp->tv_sec = timeout / 1000LL; tsp->tv_nsec = (timeout % 1000LL) * 1000000LL; } for (;;) { /* * kevent() is used both to register new events with kqueue, and to * retrieve any pending events. Changes that should be applied to the * kqueue are given in the change[] and any returned events are placed * in event[], up to the maximum sized allowed by nevent. The number * of entries actually placed in event[] is returned by the kevent() * call and saved in nreturned. * * Events are registered with the system by the application via a * struct kevent, and an event is uniquely identified with the system * by a (kq, ident, filter) tuple. This means that there can be only * one (ident, filter) pair for a given kqueue. */ evb->nreturned = kevent(kq, evb->change, evb->nchange, evb->event, evb->nevent, tsp); INCR(event_metrics, event_loop); evb->nchange = 0; if (evb->nreturned > 0) { INCR_N(event_metrics, event_total, evb->nreturned); for (evb->nprocessed = 0; evb->nprocessed < evb->nreturned; evb->nprocessed++) { struct kevent *ev = &evb->event[evb->nprocessed]; uint32_t events = 0; log_verb("kevent %04"PRIX32" with filter %"PRIX16" triggered " "on ident %d", ev->flags, ev->filter, ev->ident); /* * If an error occurs while processing an element of the * change[] and there is enough room in the event[], then the * event event will be placed in the eventlist with EV_ERROR * set in flags and the system error(errno) in data. */ if (ev->flags & EV_ERROR) { /* * Error messages that can happen, when a delete fails. * EBADF happens when the file descriptor has been closed * ENOENT when the file descriptor was closed and then * reopened. * EINVAL for some reasons not understood; EINVAL * should not be returned ever; but FreeBSD does :-\ * An error is also indicated when a callback deletes an * event we are still processing. In that case the data * field is set to ENOENT. */ if (ev->data != ENOMEM && ev->data != EFAULT && ev->data != EACCES && ev->data != EINVAL) { continue; } events |= EVENT_ERR; } if (ev->filter == EVFILT_READ) { events |= EVENT_READ; } if (ev->filter == EVFILT_WRITE) { events |= EVENT_WRITE; } if (evb->cb != NULL && events != 0) { evb->cb(ev->udata, events); } } log_verb("returned %d events from kqueue fd %d", evb->nreturned, kq); return evb->nreturned; } if (evb->nreturned == 0) { if (timeout == -1) { log_error("indefinite wait on kqueue fd %d with %d events " "returned no events", kq, evb->nevent); return -1; } log_vverb("wait on kqueue fd %d with nevent %d timeout " "%d returned no events", kq, evb->nevent, timeout); return 0; } if (errno == EINTR) { continue; } log_error("wait on kqueue fd %d with nevent %d and timeout %d failed: " "%s", kq, evb->nevent, timeout, strerror(errno)); return -1; } NOT_REACHED(); }
4,195
1,875
/* * Copyright 2020 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 2007-present, <NAME> & <NAME> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.threeten.bp.chrono; import static org.threeten.bp.temporal.ChronoField.EPOCH_DAY; import java.io.Serializable; import java.util.Objects; import org.threeten.bp.LocalTime; import org.threeten.bp.ZoneId; import org.threeten.bp.jdk8.Jdk8Methods; import org.threeten.bp.temporal.ChronoField; import org.threeten.bp.temporal.ChronoUnit; import org.threeten.bp.temporal.Temporal; import org.threeten.bp.temporal.TemporalAdjuster; import org.threeten.bp.temporal.TemporalField; import org.threeten.bp.temporal.TemporalUnit; import org.threeten.bp.temporal.ValueRange; /** * A date-time without a time-zone for the calendar neutral API. * <p> * {@code ChronoLocalDateTime} is an immutable date-time object that represents a date-time, often * viewed as year-month-day-hour-minute-second. This object can also access other * fields such as day-of-year, day-of-week and week-of-year. * <p> * This class stores all date and time fields, to a precision of nanoseconds. * It does not store or represent a time-zone. For example, the value * "2nd October 2007 at 13:45.30.123456789" can be stored in an {@code ChronoLocalDateTime}. * * <h3>Specification for implementors</h3> * This class is immutable and thread-safe. * * @param <D> the date type */ final class ChronoLocalDateTimeImpl<D extends ChronoLocalDate> extends ChronoLocalDateTime<D> implements Temporal, TemporalAdjuster, Serializable { /** * Hours per minute. */ private static final int HOURS_PER_DAY = 24; /** * Minutes per hour. */ private static final int MINUTES_PER_HOUR = 60; /** * Minutes per day. */ private static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY; /** * Seconds per minute. */ private static final int SECONDS_PER_MINUTE = 60; /** * Seconds per hour. */ private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; /** * Seconds per day. */ private static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; /** * Milliseconds per day. */ private static final long MILLIS_PER_DAY = SECONDS_PER_DAY * 1000L; /** * Microseconds per day. */ private static final long MICROS_PER_DAY = SECONDS_PER_DAY * 1000000L; /** * Nanos per second. */ private static final long NANOS_PER_SECOND = 1000000000L; /** * Nanos per minute. */ private static final long NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE; /** * Nanos per hour. */ private static final long NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR; /** * Nanos per day. */ private static final long NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY; /** * The date part. */ private final D date; /** * The time part. */ private final LocalTime time; //----------------------------------------------------------------------- /** * Obtains an instance of {@code ChronoLocalDateTime} from a date and time. * * @param date the local date, not null * @param time the local time, not null * @return the local date-time, not null */ static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> of(R date, LocalTime time) { return new ChronoLocalDateTimeImpl<R>(date, time); } /** * Constructor. * * @param date the date part of the date-time, not null * @param time the time part of the date-time, not null */ private ChronoLocalDateTimeImpl(D date, LocalTime time) { Objects.requireNonNull(date, "date"); Objects.requireNonNull(time, "time"); this.date = date; this.time = time; } /** * Returns a copy of this date-time with the new date and time, checking * to see if a new object is in fact required. * * @param newDate the date of the new date-time, not null * @param newTime the time of the new date-time, not null * @return the date-time, not null */ private ChronoLocalDateTimeImpl<D> with(Temporal newDate, LocalTime newTime) { if (date == newDate && time == newTime) { return this; } // Validate that the new DateTime is a ChronoLocalDate (and not something else) D cd = date.getChronology().ensureChronoLocalDate(newDate); return new ChronoLocalDateTimeImpl<D>(cd, newTime); } //----------------------------------------------------------------------- @Override public D toLocalDate() { return date; } @Override public LocalTime toLocalTime() { return time; } //----------------------------------------------------------------------- @Override public boolean isSupported(TemporalField field) { if (field instanceof ChronoField) { return field.isDateBased() || field.isTimeBased(); } return field != null && field.isSupportedBy(this); } @Override public boolean isSupported(TemporalUnit unit) { if (unit instanceof ChronoUnit) { return unit.isDateBased() || unit.isTimeBased(); } return unit != null && unit.isSupportedBy(this); } @Override public ValueRange range(TemporalField field) { if (field instanceof ChronoField) { return field.isTimeBased() ? time.range(field) : date.range(field); } return field.rangeRefinedBy(this); } @Override public int get(TemporalField field) { if (field instanceof ChronoField) { return field.isTimeBased() ? time.get(field) : date.get(field); } return range(field).checkValidIntValue(getLong(field), field); } @Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { return field.isTimeBased() ? time.getLong(field) : date.getLong(field); } return field.getFrom(this); } //----------------------------------------------------------------------- @Override public ChronoLocalDateTimeImpl<D> with(TemporalAdjuster adjuster) { if (adjuster instanceof ChronoLocalDate) { // The Chrono is checked in with(date,time) return with((ChronoLocalDate) adjuster, time); } else if (adjuster instanceof LocalTime) { return with(date, (LocalTime) adjuster); } else if (adjuster instanceof ChronoLocalDateTimeImpl) { return date.getChronology().ensureChronoLocalDateTime((ChronoLocalDateTimeImpl<?>) adjuster); } return date.getChronology().ensureChronoLocalDateTime((ChronoLocalDateTimeImpl<?>) adjuster.adjustInto(this)); } @Override public ChronoLocalDateTimeImpl<D> with(TemporalField field, long newValue) { if (field instanceof ChronoField) { if (field.isTimeBased()) { return with(date, time.with(field, newValue)); } else { return with(date.with(field, newValue), time); } } return date.getChronology().ensureChronoLocalDateTime(field.adjustInto(this, newValue)); } //----------------------------------------------------------------------- @Override public ChronoLocalDateTimeImpl<D> plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit) { ChronoUnit f = (ChronoUnit) unit; switch (f) { case NANOS: return plusNanos(amountToAdd); case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY) .plusNanos((amountToAdd % MICROS_PER_DAY) * 1000); case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY) .plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000000); case SECONDS: return plusSeconds(amountToAdd); case MINUTES: return plusMinutes(amountToAdd); case HOURS: return plusHours(amountToAdd); case HALF_DAYS: // no overflow (256 is multiple of 2) return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); } return with(date.plus(amountToAdd, unit), time); } return date.getChronology().ensureChronoLocalDateTime(unit.addTo(this, amountToAdd)); } private ChronoLocalDateTimeImpl<D> plusDays(long days) { return with(date.plus(days, ChronoUnit.DAYS), time); } private ChronoLocalDateTimeImpl<D> plusHours(long hours) { return plusWithOverflow(date, hours, 0, 0, 0); } private ChronoLocalDateTimeImpl<D> plusMinutes(long minutes) { return plusWithOverflow(date, 0, minutes, 0, 0); } ChronoLocalDateTimeImpl<D> plusSeconds(long seconds) { return plusWithOverflow(date, 0, 0, seconds, 0); } private ChronoLocalDateTimeImpl<D> plusNanos(long nanos) { return plusWithOverflow(date, 0, 0, 0, nanos); } //----------------------------------------------------------------------- private ChronoLocalDateTimeImpl<D> plusWithOverflow(D newDate, long hours, long minutes, long seconds, long nanos) { // 9223372036854775808 long, 2147483648 int if ((hours | minutes | seconds | nanos) == 0) { return with(newDate, time); } long totDays = nanos / NANOS_PER_DAY // max/24*60*60*1B + seconds / SECONDS_PER_DAY // max/24*60*60 + minutes / MINUTES_PER_DAY // max/24*60 + hours / HOURS_PER_DAY; // max/24 long totNanos = nanos % NANOS_PER_DAY // max 86400000000000 + (seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND // max 86400000000000 + (minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE // max 86400000000000 + (hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 86400000000000 long curNoD = time.toNanoOfDay(); // max 86400000000000 totNanos = totNanos + curNoD; // total 432000000000000 totDays += Jdk8Methods.floorDiv(totNanos, NANOS_PER_DAY); long newNoD = Jdk8Methods.floorMod(totNanos, NANOS_PER_DAY); LocalTime newTime = newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD); return with(newDate.plus(totDays, ChronoUnit.DAYS), newTime); } //----------------------------------------------------------------------- @Override public ChronoZonedDateTime<D> atZone(ZoneId zoneId) { return ChronoZonedDateTimeImpl.ofBest(this, zoneId, null); } //----------------------------------------------------------------------- @Override public long until(Temporal endExclusive, TemporalUnit unit) { @SuppressWarnings("unchecked") ChronoLocalDateTime<D> end = (ChronoLocalDateTime<D>) toLocalDate().getChronology().localDateTime(endExclusive); if (unit instanceof ChronoUnit) { ChronoUnit f = (ChronoUnit) unit; if (f.isTimeBased()) { long amount = end.getLong(EPOCH_DAY) - date.getLong(EPOCH_DAY); switch (f) { case NANOS: amount = Jdk8Methods.safeMultiply(amount, NANOS_PER_DAY); break; case MICROS: amount = Jdk8Methods.safeMultiply(amount, MICROS_PER_DAY); break; case MILLIS: amount = Jdk8Methods.safeMultiply(amount, MILLIS_PER_DAY); break; case SECONDS: amount = Jdk8Methods.safeMultiply(amount, SECONDS_PER_DAY); break; case MINUTES: amount = Jdk8Methods.safeMultiply(amount, MINUTES_PER_DAY); break; case HOURS: amount = Jdk8Methods.safeMultiply(amount, HOURS_PER_DAY); break; case HALF_DAYS: amount = Jdk8Methods.safeMultiply(amount, 2); break; } return Jdk8Methods.safeAdd(amount, time.until(end.toLocalTime(), unit)); } ChronoLocalDate endDate = end.toLocalDate(); if (end.toLocalTime().isBefore(time)) { endDate = endDate.minus(1, ChronoUnit.DAYS); } return date.until(endDate, unit); } return unit.between(this, end); } }
5,861
1,609
// $Id$ // // Copyright (c) 2008, Novartis Institutes for BioMedical Research Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Novartis Institutes for BioMedical Research Inc. // nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Created by <NAME>, 2006 // #include <RDGeneral/test.h> #include <iostream> #include <GraphMol/RDKitBase.h> #include <GraphMol/SLNParse/SLNParse.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/Substruct/SubstructMatch.h> #include <RDGeneral/RDLog.h> using namespace std; void test1() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test1 " << std::endl; sln = "CH4"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); delete mol; sln = "CH3CH3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); TEST_ASSERT(mol->getRingInfo()->numRings() == 0); delete mol; sln = "C[1]H2CH2CH2@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); delete mol; sln = "C[2]H2CH2CH2@2"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); delete mol; sln = "C[200]H2CH2CH2@200"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); delete mol; sln = "C[1:foo]H2CH2CH2@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); delete mol; sln = "C[foo;bar=1;baz=bletch]H4"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getRingInfo()->numRings() == 0); delete mol; sln = "CH3CH(CH3)OCH3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 5); TEST_ASSERT(mol->getRingInfo()->numRings() == 0); TEST_ASSERT(mol->getAtomWithIdx(0)->getDegree() == 1); TEST_ASSERT(mol->getAtomWithIdx(1)->getDegree() == 3); TEST_ASSERT(mol->getAtomWithIdx(2)->getDegree() == 1); TEST_ASSERT(mol->getAtomWithIdx(3)->getDegree() == 2); delete mol; sln = "CH3CH(CH3)OCH3.Cl"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 0); TEST_ASSERT(mol->getAtomWithIdx(0)->getDegree() == 1); TEST_ASSERT(mol->getAtomWithIdx(1)->getDegree() == 3); TEST_ASSERT(mol->getAtomWithIdx(2)->getDegree() == 1); TEST_ASSERT(mol->getAtomWithIdx(3)->getDegree() == 2); TEST_ASSERT(mol->getAtomWithIdx(4)->getDegree() == 1); TEST_ASSERT(mol->getAtomWithIdx(5)->getDegree() == 0); delete mol; sln = "H-O-H"; mol = RDKit::SLNToMol(sln, false); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getAtomWithIdx(0)->getAtomicNum() == 1); TEST_ASSERT(mol->getAtomWithIdx(1)->getAtomicNum() == 8); TEST_ASSERT(mol->getAtomWithIdx(2)->getAtomicNum() == 1); delete mol; sln = "HC(F)(Cl)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); delete mol; sln = "CH3C(=O)H"; mol = RDKit::SLNToMol(sln, false); //,1); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 7); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test2() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test2: bond orders " << std::endl; sln = "CH3CH3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); delete mol; sln = "CH2-CH2"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); delete mol; sln = "CH2=CH2"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::DOUBLE); delete mol; sln = "CH#CH"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::TRIPLE); delete mol; sln = "C[1]H-CH2-CH2-CH2-CH2-CH=@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(3, 4)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(4, 5)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(5, 0)->getBondType() == RDKit::Bond::DOUBLE); delete mol; sln = "C[1]H:CH:CH:CH:CH:CH:@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::AROMATIC); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::AROMATIC); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::AROMATIC); TEST_ASSERT(mol->getBondBetweenAtoms(3, 4)->getBondType() == RDKit::Bond::AROMATIC); TEST_ASSERT(mol->getBondBetweenAtoms(4, 5)->getBondType() == RDKit::Bond::AROMATIC); TEST_ASSERT(mol->getBondBetweenAtoms(5, 0)->getBondType() == RDKit::Bond::AROMATIC); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test3() { std::string pval; RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test3: atom properties " << std::endl; sln = "C[-]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -1); delete mol; sln = "C[charge=-]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -1); delete mol; sln = "C[charge=-1]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -1); delete mol; sln = "C[CHARGE=-1]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -1); delete mol; sln = "C[chARgE=-1]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -1); delete mol; sln = "C[1:-2]H2"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == -2); delete mol; sln = "C[1:+]H5"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == 1); delete mol; sln = "C[1:+2]H6"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getFormalCharge() == 2); delete mol; sln = "C[1:foo;bar=baz]H4"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasProp("foo")); mol->getAtomWithIdx(0)->getProp("foo", pval); TEST_ASSERT(pval == ""); TEST_ASSERT(mol->getAtomWithIdx(0)->hasProp("bar")); mol->getAtomWithIdx(0)->getProp("bar", pval); TEST_ASSERT(pval == "baz"); TEST_ASSERT(!mol->getAtomWithIdx(0)->hasProp("baz")); delete mol; sln = "H[I=2]-C(-H[I=2])(F)F"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 5); TEST_ASSERT(mol->getAtomWithIdx(0)->getIsotope() == 2); TEST_ASSERT(mol->getAtomWithIdx(2)->getIsotope() == 2); delete mol; sln = "C[*]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumExplicitHs() == 3); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumImplicitHs() == 0); TEST_ASSERT(mol->getAtomWithIdx(0)->getNoImplicit()); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumRadicalElectrons() == 1); #if 1 // FIX: this should be accepted delete mol; sln = "CH[I=2]"; mol = RDKit::SLNToMol(sln); //,true,1); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 2); #endif // but this should not be accepted: delete mol; sln = "CH4[I=13]"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test4() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test4: hydrogen handling " << std::endl; sln = "CH4"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumExplicitHs() == 4); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumImplicitHs() == 0); TEST_ASSERT(mol->getAtomWithIdx(0)->getNoImplicit()); delete mol; sln = "C[-]H3"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumExplicitHs() == 3); TEST_ASSERT(mol->getAtomWithIdx(0)->getNumImplicitHs() == 0); TEST_ASSERT(mol->getAtomWithIdx(0)->getNoImplicit()); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test5() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test5: basic queries " << std::endl; #if 1 sln = "C[charge=+1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(patt->getAtomWithIdx(0)->getNumExplicitHs() == 0); TEST_ASSERT(patt->getAtomWithIdx(0)->getNoImplicit()); TEST_ASSERT(patt->getAtomWithIdx(0)->getNumImplicitHs() == 0); smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); delete patt; sln = "AnyAny"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete patt; sln = "Any-Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete patt; sln = "Any=Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "Any#Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "Any:Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "Any~Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "C[charge=+1|charge=+2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C[CH2+](C)[CH+2]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete mol; smi = "C[CH2+](C)[N+2]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C[N+](C)[CH+2]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "C[charge=+1;HC=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C[CH2+](CC)[NH+]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0][0].second == 1); delete patt; sln = "Any[charge=+1;HC=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C[CH2+](CC)[NH+]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0][0].second == 1); delete patt; sln = "Any[charge=+1;!HC=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C[CH2+](CC)[NH+]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0][0].second == 4); delete mol; smi = "[H]CC[H]"; mol = RDKit::SmilesToMol(smi, 0, false); TEST_ASSERT(mol); RDKit::MolOps::sanitizeMol(*mol); TEST_ASSERT(mol->getNumAtoms() == 4); delete patt; sln = "AnyAny"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "HevHev"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "AnyHev"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; delete mol; smi = "FC(Cl)(Br)CI"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); RDKit::MolOps::sanitizeMol(*mol); TEST_ASSERT(mol->getNumAtoms() == 6); sln = "HalC"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete patt; #endif delete mol; smi = "CO[2H]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); RDKit::MolOps::sanitizeMol(*mol); TEST_ASSERT(mol->getNumAtoms() == 3); sln = "H"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "H[i=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "H[i=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "Het"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test6() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test6: ring queries " << std::endl; sln = "C[rbc=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(!patt->getAtomWithIdx(0)->hasProp("rbc")); smi = "C1CC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete mol; smi = "C1C2C1C2"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete mol; smi = "CCC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete patt; sln = "C[rbc=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C1CC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; smi = "CCC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete patt; sln = "C[rbc=3]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C1CC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; smi = "C1C2C1C2"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); // test case sensitivity, just because we should: delete patt; sln = "C[rBC=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(!patt->getAtomWithIdx(0)->hasProp("rbc")); delete mol; smi = "C1CC1C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "C[r]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C1CC1C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "C[1:rbc=f]CCC@1"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 4); delete mol; smi = "C1CCC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C1CC2C1CC2"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete patt; sln = "C[1:rbc=f]C[rbc=f]CC@1"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 4); delete mol; smi = "C1CCC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; smi = "C1CC2C1CC2"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete patt; sln = "C[1:rbc=f]C[rbc=f]C[rbc=f]C@1"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 4); delete mol; smi = "C1CCC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C1CC2C1CC2"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete mol; delete patt; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test7() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test7: qualified queries " << std::endl; sln = "C[charge=+1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "C[charge<1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "C[charge<=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete patt; sln = "C[charge>=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "C[charge>1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "C[charge!=0]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; sln = "C[charge!=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); delete mol; smi = "C[CH2+](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); delete mol; smi = "C[CH](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete mol; smi = "C[CH3+2](C)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); delete mol; delete patt; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test8() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test8: more complex atom properties " << std::endl; sln = "Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 4); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[2][0].second == 2); TEST_ASSERT(mV[3][0].second == 3); delete patt; sln = "CO[F]C"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 3); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 2); delete patt; sln = "Any[TBO=4]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); // CHECK: should TBO really match both Cs here or only atom 3 (i.e. should it // be degree or valence)? TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1][0].second == 3); delete patt; sln = "Any[TAC=2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0][0].second == 2); delete patt; sln = "Any[TAC>2]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1][0].second == 3); delete patt; sln = "Any[HC=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete patt; sln = "Any[HC=0]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 1); TEST_ASSERT(mV[1][0].second == 2); delete patt; sln = "Any[HC=F]H3"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0][0].second == 3); delete patt; sln = "Any[HAC>1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1][0].second == 2); delete patt; sln = "Any[HAC=1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 1); TEST_ASSERT(mV[1][0].second == 3); delete patt; sln = "Any[HAC=F]~Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0][0].second == 1); TEST_ASSERT(mV[1][0].second == 3); delete patt; sln = "AnyAny[TAC=F]Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 3); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0][1].second == 2); delete mol; smi = "CCC=C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "CC"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); delete patt; sln = "CC[F]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "CC[F]H3"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); delete patt; delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test9() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test9: recursive SLNs " << std::endl; sln = "Any[is=Cl,Br,I]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); smi = "C(=O)Cl"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 2); delete mol; smi = "C(=O)Br"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 2); delete mol; smi = "C(=O)I"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 2); delete mol; smi = "C(=O)C"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete patt; sln = "C[is=C=O]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete patt; sln = "Any[is=C,O;charge=-1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 0); delete mol; smi = "C(=O)[O-]"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 2); delete patt; // make sure we aren't case sensitive: sln = "Any[Is=C,O;charge=-1]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "[C-](=O)O"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete patt; // check handling of 'not': sln = "Any[not=N,O]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C(=O)OCN"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV.size() == 2); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1].size() == 1); TEST_ASSERT(mV[1][0].second == 3); delete patt; delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test10() { std::string pval; RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test10: nested recursive SLNs " << std::endl; // do recursions in the 'is': sln = "Any[is=C[is=Any=O],O]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 3); TEST_ASSERT(mV.size() == 3); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[1].size() == 1); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[2].size() == 1); TEST_ASSERT(mV[2][0].second == 2); // do recursions in the 'not': delete patt; sln = "Any[not=C[is=Any=O],O]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 3); delete patt; // move the anchor: sln = "C[is=C=O]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); delete mol; smi = "C(=O)OC"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete patt; sln = "C[is=O=C*]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete patt; sln = "C[is=O=C]"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(!RDKit::SubstructMatch(*mol, *patt, mV)); delete patt; delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test11() { std::string pval, cip; RDKit::RWMol *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test11: chiral SLNs " << std::endl; sln = "CH(Cl)(F)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getAtomWithIdx(0)->getChiralTag() == RDKit::Atom::CHI_UNSPECIFIED); delete mol; sln = "C[s=N]H(Cl)(F)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; smi = MolToSmiles(*mol, true); // TEST_ASSERT(smi=="F[C@@H](Cl)Br"); delete mol; sln = "ClC[s=i]H(F)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); // mol->debugMol(std::cerr); #if 0 RDKit::MolOps::assignAtomChiralCodes(*mol); TEST_ASSERT(mol->getAtomWithIdx(1)->hasProp(RDKit::common_properties::_CIPCode)); mol->getAtomWithIdx(1)->getProp(RDKit::common_properties::_CIPCode,cip); TEST_ASSERT(cip=="R"); #endif std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; smi = MolToSmiles(*mol, true); // TEST_ASSERT(smi=="F[C@@H](Cl)Br"); delete mol; sln = "FC[s=N]H(Cl)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; smi = MolToSmiles(*mol, true); // TEST_ASSERT(smi=="F[C@@H](Cl)Br"); delete mol; sln = "FC[s=N]H(Br)Cl"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; smi = MolToSmiles(*mol, true); // TEST_ASSERT(smi=="F[C@H](Cl)Br"); delete mol; sln = "HC[s=N](Cl)(F)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; smi = MolToSmiles(*mol, true); // TEST_ASSERT(smi=="F[C@@H](Cl)Br"); delete mol; sln = "C[s=i]H(Cl)(F)Br"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); smi = MolToSmiles(*mol, true); std::cerr << sln << " -> " << MolToSmiles(*mol, true) << " " << mol->getNumAtoms() << std::endl; // TEST_ASSERT(smi=="F[C@H](Cl)Br"); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test12() { RDKit::RWMol *patt, *mol; std::vector<RDKit::MatchVectType> mV; std::string sln, smi; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test12: bond queries and properties " << std::endl; sln = "Any-Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); smi = "C=CN"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 1); TEST_ASSERT(mV[0][1].second == 2); delete patt; sln = "Any~Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 1); TEST_ASSERT(mV[1].size() == 2); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[1][1].second == 2); delete patt; sln = "Any-=Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 1); TEST_ASSERT(mV[1].size() == 2); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[1][1].second == 2); delete patt; sln = "Any=-Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 1); TEST_ASSERT(mV[1].size() == 2); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[1][1].second == 2); delete patt; sln = "Any-:Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 1); TEST_ASSERT(mV[0][1].second == 2); sln = "Any-[type=2]Any"; delete patt; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 1); delete patt; sln = "Any-[type=2|type=1]Any"; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); TEST_ASSERT(mV[0][1].second == 1); TEST_ASSERT(mV[1].size() == 2); TEST_ASSERT(mV[1][0].second == 1); TEST_ASSERT(mV[1][1].second == 2); sln = "O~[r]C"; delete patt; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); delete mol; smi = "O=CC1COC1"; mol = RDKit::SmilesToMol(smi); TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 2); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 4); TEST_ASSERT(mV[1][0].second == 4); sln = "O~[!r]C"; delete patt; patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 2); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV[0].size() == 2); TEST_ASSERT(mV[0][0].second == 0); delete mol; delete patt; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test13() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test13: ring closure details " << std::endl; sln = "C[1]H2CH2CH2CH2CH2CH2@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); delete mol; sln = "C[1]H2CH2(CH2CH2CH2CH2@1)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); delete mol; sln = "CH2(C[1]H2)CH2(CH2CH2CH2@1)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 6); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); delete mol; sln = "C[1]H2CH2CH2CH2C[2]HCH@1CH2CH2@2"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 8); TEST_ASSERT(mol->getRingInfo()->numRings() == 2); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); TEST_ASSERT(mol->getRingInfo()->atomRings()[1].size() == 4); delete mol; sln = "C[1]H2(CH2(CH2(CH2(C[2]H(CH@1(CH2(CH2@2)))))))"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 8); TEST_ASSERT(mol->getRingInfo()->numRings() == 2); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); TEST_ASSERT(mol->getRingInfo()->atomRings()[1].size() == 4); delete mol; sln = "C[1](CH2CH2CH(CH2CH2@1)CH2CH2@1)Cl"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 9); TEST_ASSERT(mol->getRingInfo()->numRings() == 3); TEST_ASSERT(mol->getRingInfo()->atomRings()[0].size() == 6); TEST_ASSERT(mol->getRingInfo()->atomRings()[1].size() == 6); TEST_ASSERT(mol->getRingInfo()->atomRings()[2].size() == 6); delete mol; sln = "CH2(CH2@1)CH2(C[1]H2)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; sln = "CH2(CH2@1)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; sln = "C[1]H-CH2-C(@1)=O"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 0)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::DOUBLE); delete mol; sln = "C[1]H-CH2-CH(@1)O"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 0)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::SINGLE); delete mol; sln = "C[1]H-CH2-C(=@1)O"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 0)->getBondType() == RDKit::Bond::DOUBLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::SINGLE); delete mol; sln = "C[1]H-CH2-C(O)=@1"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 0)->getBondType() == RDKit::Bond::DOUBLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::SINGLE); delete mol; sln = "C[1]H-CH2-C(O)(=@1)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getRingInfo()->numRings() == 1); TEST_ASSERT(mol->getBondBetweenAtoms(0, 1)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(1, 2)->getBondType() == RDKit::Bond::SINGLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 0)->getBondType() == RDKit::Bond::DOUBLE); TEST_ASSERT(mol->getBondBetweenAtoms(2, 3)->getBondType() == RDKit::Bond::SINGLE); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test14() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test14: error catching " << std::endl; sln = "CH2(C@1H2)CH2(CH2CH2C[1]H2)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; sln = "CH2(CH2[1])CH2(CH2CH2CH2@1)"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test15() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test15: CTAB properties " << std::endl; { sln = "CH4<blah>"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp("blah")); delete mol; } { sln = "CH4<name=methane>"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp(RDKit::common_properties::_Name)); std::string sval; mol->getProp(RDKit::common_properties::_Name, sval); TEST_ASSERT(sval == "methane"); delete mol; } { sln = "CH4<blah;foo=\"1\">"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp("blah")); TEST_ASSERT(mol->hasProp("foo")); std::string sval; mol->getProp("foo", sval); TEST_ASSERT(sval == "1"); delete mol; } { sln = "CH4<blah;foo=1>"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp("blah")); TEST_ASSERT(mol->hasProp("foo")); std::string sval; mol->getProp("foo", sval); TEST_ASSERT(sval == "1"); delete mol; } { sln = "CH4<name=\"methane\";blah;coord2d=(1,0);too.small;test=lots and-lots " "of special,characters all at once.>"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp("blah")); std::string sval; mol->getProp(RDKit::common_properties::_Name, sval); TEST_ASSERT(sval == "methane"); mol->getProp("coord2d", sval); TEST_ASSERT(sval == "(1,0)"); TEST_ASSERT(mol->hasProp("too.small")); TEST_ASSERT(mol->hasProp("test")); mol->getProp("test", sval); TEST_ASSERT(sval == "lots and-lots of special,characters all at once."); delete mol; } { // Though it isn't part of the spec, // sometimes we have multiple ctab property blocks: sln = "CH4<foo=1><bar=2>"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->hasProp("foo")); TEST_ASSERT(mol->hasProp("bar")); std::string sval; mol->getProp("foo", sval); TEST_ASSERT(sval == "1"); mol->getProp("bar", sval); TEST_ASSERT(sval == "2"); delete mol; } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test16() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test16: simple macro atoms " << std::endl; { sln = "CH3ZCH3{Z:O}"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 3); TEST_ASSERT(mol->getAtomWithIdx(1)->getAtomicNum() == 8); delete mol; } { sln = "CH3ZGCH3{Z:O}{G:N}"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 4); TEST_ASSERT(mol->getAtomWithIdx(1)->getAtomicNum() == 8); TEST_ASSERT(mol->getAtomWithIdx(2)->getAtomicNum() == 7); delete mol; } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void testIssue278() { BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test issue278: handling of 'not' and 'is' queries on Any" << std::endl; { std::string sln = "Any[IS=C(=O)]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[NOT=C(=O)]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[IS=C(=O)]"; RDKit::RWMol *mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[NOT=C(=O)]"; RDKit::RWMol *mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void testIssue277() { BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test issue277: parse error with & " << std::endl; { std::string sln = "Any[NOT=C,IS=O]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[NOT=C;IS=O]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[NOT=C&IS=O]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Any[NOT=C,N&IS=O,S]"; RDKit::RWMol *mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); TEST_ASSERT(mol->getAtomWithIdx(0)->hasQuery()); delete mol; } { std::string sln = "Hev[!r;NOT=N]"; RDKit::RWMol *patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(patt->getAtomWithIdx(0)->hasQuery()); std::string smi = "CC1CC1N"; RDKit::RWMol *mol = RDKit::SmilesToMol(smi); std::vector<RDKit::MatchVectType> mV; TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete mol; delete patt; } { std::string sln = "Hev[!r&NOT=N]"; RDKit::RWMol *patt = RDKit::SLNQueryToMol(sln); TEST_ASSERT(patt); TEST_ASSERT(patt->getNumAtoms() == 1); TEST_ASSERT(patt->getAtomWithIdx(0)->hasQuery()); std::string smi = "CC1CC1N"; RDKit::RWMol *mol = RDKit::SmilesToMol(smi); std::vector<RDKit::MatchVectType> mV; TEST_ASSERT(mol); TEST_ASSERT(RDKit::SubstructMatch(*mol, *patt, mV) == 1); TEST_ASSERT(mV.size() == 1); TEST_ASSERT(mV[0].size() == 1); TEST_ASSERT(mV[0][0].second == 0); delete mol; delete patt; } { // examples from <NAME>, taken from // http://pubs.acs.org/doi/abs/10.1021/ci300461a std::string slns[] = { "HetC(=O)O-[!R]C[8]:Hev(Any[NOT=O,S[TAC=2],C[TAC=4],N[TAC=3]]):Hev:Hev(" "Any[IS=Hal,C#N,C(F)(F)F,S(=O)=O,C(=O)&NOT=C(=O)OH]):Hev:Hev(Any[NOT=O," "S[TAC=2],C[TAC=4],N[TAC=3]]):@8", "HetC(=O)O-[!R]C[8]:Hev(Any[IS=Hal,C#N,C(F)(F)F,S(=O)=O,C(=O)&NOT=C(=O)" "OH]):Hev:Hev(Any[NOT=O,S[TAC=2],C[TAC=4],N[TAC=3]]):Hev:Hev(Any[NOT=O," "S[TAC=2],C[TAC=4],N[TAC=3]]):@8", "CCH=[!R]C(Any[IS=H,C])Any[IS=C#N,C(=O)&NOT=C(=O)Any[IS=N,O]]", "Any[IS=C,O]CH=[!R]C(Any[IS=C(=O),S(=O),C#N,Hal,C(Hal)(Hal)Hal&NOT=C(=" "O)OH])Any[IS=C(=O),S(=O),C#N&NOT=C(=O)OH]", "C[1](C(=O)OC[5]:C:C:C:C:C:@5CH=@1)Any[IS=C(=O),C(=S),S(=O),C#N,Hal,C(" "Hal)(Hal)Hal&NOT=C(=O)OH]", "C[1](=CHOC[5]:C:C:C:C:C:@5C@1=O)Any[IS=C(=O),C(=S),S(=O),C#N,Hal,C(" "Hal)(Hal)Hal&NOT=C(=O)OH]", "C[1]:N:Any(Any[IS=Hal,S(=O)(=O)C]):Any:Any(Any[IS=Hal,C(C)=NO,C#N,C(=" "O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH]):Any:@1", "C[1]:N:Any(Any[IS=Hal,C(C)=NO,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH])" ":Any:Any(Any[IS=Hal,S(=O)(=O)C]):Any:@1", "C[1]:N:Any(Any[IS=Hal,S(=O)(=O)C]):Any(Any[IS=Hal,C(C)=NO,C#N,C(=O),C(" "F)(F)F,S(=O)=O&NOT=C(=O)OH]):Any:Any:@1", "C[1]:N:Any(Any[IS=Hal,S(=O)(=O)C]):Any:Any:Any(Any[IS=Hal,C(C)=NO,C#N," "C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH]):@1", "C[1](Any[IS=Hal,C(C)=NO,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH]):N:" "Any(Any[IS=Hal,S(=O)(=O)C]):Any(Any[NOT=N]):Any(Any[NOT=N]):Any:@1", "C[1]:N:Any:Any(Any[IS=Hal,C(C)=NO,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)" "OH]):Any(Any[IS=Hal,S(=O)(=O)C]):Any:@1", "C[1](Any[NOT=N,O]):C(Any[IS=Hal,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)" "OH]):C(Any[IS=Hal,S(=O)(=O)C,C[r](=O)NC]):C(Any[NOT=N,O]):C(Any[NOT=N," "O]):C(Any[IS=Hal,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH]):@1", "C[1](Any[IS=Hal,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(=O)OH]):C(Any[IS=Hal," "S(=O)(=O)C,C[r](=O)NC]):C(Any[IS=Hal,C#N,C(=O),C(F)(F)F,S(=O)=O&NOT=C(" "=O)OH]):C(Any[NOT=N,O]):C(Any[NOT=N,O]):C(Any[NOT=N,O]):@1", "N(Any[IS=H,C[TAC=4]&NOT=C[TAC=4]-[R]C[TAC=4]N])(Any[IS=H,C[TAC=4]&NOT=" "C[TAC=4]-[R]C[TAC=4]N])(Any[IS=H,C[TAC=4]&NOT=C[TAC=4]-[R]C[TAC=4]N])<" "max=1>", "Any[IS=H,C&NOT=C=O]N[!r](Any[IS=H,C&NOT=C=O])C(=O)C<max=2>", "Hev[!r&NOT=NC(=O)NC(=O)]Hev[!r&NOT=NC(=O)NC(=O)]Hev[!r&NOT=NC(=O)NC(=" "O)]Hev[!r&NOT=NC(=O)NC(=O)]Hev[!r&NOT=NC(=O)NC(=O)]Hev[!r&NOT=NC(=O)" "NC(=O)]Hev[!r&NOT=NC(=O)NC(=O)]Hev[!r&NOT=NC(=O)NC(=O)]", "Hev[!r&NOT=C=O,S(=O)(=O),N*S(=O),N*(C=O)]Hev[!r&NOT=C=O,S(=O)(=O),N*S(" "=O),N*(C=O)]Hev[!r&NOT=C=O,S(=O)(=O),N*S(=O),N*(C=O)]Hev[!r&NOT=C=O,S(" "=O)(=O),N*S(=O),N*(C=O)]Hev[!r&NOT=C=O,S(=O)(=O)]Any[IS=CH3,OH,NH2,N(" "CH3)CH3]", "EOF"}; unsigned int i = 0; while (slns[i] != "EOF") { RDKit::RWMol *mol = RDKit::SLNQueryToMol(slns[i++]); TEST_ASSERT(mol); delete mol; } } BOOST_LOG(rdInfoLog) << "\tdone" << std::endl; } void test17() { RDKit::RWMol *mol; std::string sln; BOOST_LOG(rdInfoLog) << "-------------------------------------" << std::endl; BOOST_LOG(rdInfoLog) << "Test1 " << std::endl; // test whitespace at end sln = "CH4 \t"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); delete mol; sln = "CH4\t"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(mol); TEST_ASSERT(mol->getNumAtoms() == 1); delete mol; sln = "CH4\tfff"; mol = RDKit::SLNToMol(sln); TEST_ASSERT(!mol); delete mol; sln = "C[charge=+1] \t"; mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(mol); delete mol; sln = "C[charge=+1] \tfoo"; mol = RDKit::SLNQueryToMol(sln); TEST_ASSERT(!mol); delete mol; } int main(int argc, char *argv[]) { (void)argc; (void)argv; RDLog::InitLogs(); // FIX: need a test for handling Hs in the SLN itself. This should be done for // both normal and query SLNs and must be done after the SLN parser handles // that case (errr, duh) #if 1 test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); // test11(); test12(); test13(); test14(); test15(); test16(); test17(); #endif testIssue277(); testIssue278(); }
28,104
2,338
<gh_stars>1000+ // RUN: %clang_cc1 -triple i386-pc-linux-gnu -DBITCODE -emit-llvm-bc -o %t.bc %s // RUN: %clang_cc1 -triple i386-pc-linux-gnu -DBITCODE2 -emit-llvm-bc -o %t-2.bc %s // RUN: %clang_cc1 -triple i386-pc-linux-gnu -mlink-bitcode-file %t.bc \ // RUN: -O3 -emit-llvm -o - %s | FileCheck -check-prefix=CHECK-NO-BC %s // RUN: %clang_cc1 -triple i386-pc-linux-gnu -O3 -emit-llvm -o - \ // RUN: -mlink-bitcode-file %t.bc -mlink-bitcode-file %t-2.bc %s \ // RUN: | FileCheck -check-prefix=CHECK-NO-BC -check-prefix=CHECK-NO-BC2 %s // RUN: not %clang_cc1 -triple i386-pc-linux-gnu -DBITCODE -O3 -emit-llvm -o - \ // RUN: -mlink-bitcode-file %t.bc %s 2>&1 | FileCheck -check-prefix=CHECK-BC %s // Make sure we deal with failure to load the file. // RUN: not %clang_cc1 -triple i386-pc-linux-gnu -mlink-bitcode-file no-such-file.bc \ // RUN: -emit-llvm -o - %s 2>&1 | FileCheck -check-prefix=CHECK-NO-FILE %s int f(void); #ifdef BITCODE extern int f2(void); // CHECK-BC: fatal error: cannot link module {{.*}}'f': symbol multiply defined int f(void) { f2(); return 42; } #elif BITCODE2 int f2(void) { return 43; } #else // CHECK-NO-BC-LABEL: define{{.*}} i32 @g // CHECK-NO-BC: ret i32 42 int g(void) { return f(); } // CHECK-NO-BC-LABEL: define{{.*}} i32 @f // CHECK-NO-BC2-LABEL: define{{.*}} i32 @f2 #endif // CHECK-NO-FILE: fatal error: cannot open file 'no-such-file.bc'
648
518
package io.sdb.controller; import com.alibaba.fastjson.JSON; import com.jfinal.kit.JsonKit; import com.jfinal.kit.LogKit; import io.sdb.common.entity.kuaidi100.NoticeRequest; import io.sdb.common.entity.kuaidi100.NoticeResponse; import io.sdb.common.entity.kuaidi100.Result; import io.sdb.model.Logistics; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController @Slf4j @RequestMapping("/sys/logistics") public class SysLogisticsController { @RequestMapping("notify") public NoticeResponse kuaidi100Notify(@RequestParam String param){ NoticeResponse resp = new NoticeResponse(); resp.setResult(false); resp.setReturnCode("500"); resp.setMessage("保存失败"); try { NoticeRequest nReq = JSON.parseObject(param, NoticeRequest.class); Result result = nReq.getLastResult(); // 处理快递结果 Logistics logistics = Logistics.dao.findById(result.getNu()); resp.setResult(true); resp.setReturnCode("200"); resp.setMessage("提交成功"); if(logistics != null){ logistics.setUpdateDate(new Date()); logistics.setOrderState(Integer.parseInt(result.getState())); logistics.setData(JSON.toJSONString(result.getData())); logistics.update(); return resp; }else { logistics = new Logistics(); logistics.setUpdateDate(new Date()); logistics.setOrderState(Integer.parseInt(result.getState())); logistics.setData(JSON.toJSONString(result.getData())); logistics.setTrackingNo(result.getNu()); logistics.save(); return resp; } //response.getWriter().print(JsonKit.toJson(resp)); //这里必须返回,否则认为失败,过30分钟又会重复推送。 } catch (Exception e) { e.printStackTrace(); log.error("kuaidi100Notify 保存失败 error = ", e); resp.setMessage("保存失败"); return resp; //response.getWriter().print(JsonKit.toJson(resp));//保存失败,服务端等30分钟会重复推送。 } } }
1,199
332
/** * Package for DIRT JDBC util classes. */ package org.springframework.xd.dirt.jdbc.util;
34
1,374
package def.dom; import def.js.Object; public class SVGAnimatedInteger extends def.js.Object { public double animVal; public double baseVal; public static SVGAnimatedInteger prototype; public SVGAnimatedInteger(){} }
73
312
<gh_stars>100-1000 /******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.query.parser; import org.eclipse.rdf4j.common.lang.service.ServiceRegistry; import org.eclipse.rdf4j.query.QueryLanguage; /** * A registry that keeps track of the available {@link QueryParserFactory}s. * * @author <NAME> */ public class QueryParserRegistry extends ServiceRegistry<QueryLanguage, QueryParserFactory> { /** * Internal helper class to avoid continuous synchronized checking. */ private static class QueryParserRegistryHolder { public static final QueryParserRegistry instance = new QueryParserRegistry(); } /** * Gets the default QueryParserRegistry. * * @return The default registry. */ public static QueryParserRegistry getInstance() { return QueryParserRegistryHolder.instance; } public QueryParserRegistry() { super(QueryParserFactory.class); } @Override protected QueryLanguage getKey(QueryParserFactory factory) { return factory.getQueryLanguage(); } }
378
361
package li.cil.oc2.common.item; import net.minecraft.item.IDyeableArmorItem; public final class FloppyItem extends AbstractStorageItem implements IDyeableArmorItem { public FloppyItem(final int capacity) { super(capacity); } }
80
2,783
from stompest.config import StompConfig from stompest.protocol import StompSpec from stompest.sync import Stomp CONFIG = StompConfig('tcp://localhost:61613', version=StompSpec.VERSION_1_1) QUEUE = '/queue/test' if __name__ == '__main__': client = Stomp(CONFIG) client.connect(heartBeats=(0, 10000)) client.subscribe(QUEUE, {StompSpec.ID_HEADER: 1, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}) client.send(QUEUE, 'test message 1') client.send(QUEUE, 'test message 2') while True: frame = client.receiveFrame() print 'Got %s' % frame.info() client.ack(frame) client.disconnect()
230
330
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 INSTALLED_HANDLERS = None EXCLUDED_HANDLERS = [] RAPIDSMS_HANDLERS_EXCLUDE_APPS = []
70
377
//------------------------------------------------------------------------------ // vkstreamtexturepool.cc // (C) 2016-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "vkstreamtexturepool.h" #include "coregraphics/texture.h" #include "io/ioserver.h" #include "coregraphics/vk/vktypes.h" #include "IL/il.h" #include "coregraphics/load/glimltypes.h" #include "vkloader.h" #include "vkgraphicsdevice.h" #include "vkutilities.h" #include "math/scalar.h" #include "vkshaderserver.h" #include "coregraphics/memorytexturepool.h" #include "vksubmissioncontext.h" #include "profiling/profiling.h" #include "threading/interlocked.h" namespace Vulkan { __ImplementClass(Vulkan::VkStreamTexturePool, 'VKTL', Resources::ResourceStreamPool); using namespace CoreGraphics; using namespace Resources; using namespace IO; //------------------------------------------------------------------------------ /** */ VkStreamTexturePool::VkStreamTexturePool() { this->async = true; this->placeholderResourceName = "tex:system/white.dds"; this->failResourceName = "tex:system/error.dds"; this->streamerThreadName = "Texture Pool Streamer Thread"; } //------------------------------------------------------------------------------ /** */ VkStreamTexturePool::~VkStreamTexturePool() { // empty } //------------------------------------------------------------------------------ /** */ inline Resources::ResourceUnknownId VkStreamTexturePool::AllocObject() { return texturePool->AllocObject(); } //------------------------------------------------------------------------------ /** */ inline void VkStreamTexturePool::DeallocObject(const Resources::ResourceUnknownId id) { texturePool->DeallocObject(id); } //------------------------------------------------------------------------------ /** */ ResourcePool::LoadStatus VkStreamTexturePool::LoadFromStream(const Resources::ResourceId res, const Util::StringAtom& tag, const Ptr<IO::Stream>& stream, bool immediate) { N_SCOPE_ACCUM(CreateAndLoad, TextureStream); n_assert(stream.isvalid()); n_assert(stream->CanBeMapped()); n_assert(this->GetState(res) == Resources::Resource::Pending); void* srcData = stream->MemoryMap(); uint srcDataSize = stream->GetSize(); const int NumBasicLods = immediate ? 1000 : 5; // load using gliml gliml::context ctx; if (ctx.load_dds(srcData, srcDataSize)) { // during the load-phase, we can safetly get the structs __LockName(texturePool->Allocator(), lock); VkTextureRuntimeInfo& runtimeInfo = texturePool->Get<Texture_RuntimeInfo>(res.resourceId); VkTextureLoadInfo& loadInfo = texturePool->Get<Texture_LoadInfo>(res.resourceId); VkTextureStreamInfo& streamInfo = texturePool->Get<Texture_StreamInfo>(res.resourceId); streamInfo.mappedBuffer = srcData; streamInfo.bufferSize = srcDataSize; streamInfo.stream = stream; streamInfo.ctx = ctx; loadInfo.dev = Vulkan::GetCurrentDevice(); VkPhysicalDevice physicalDev = Vulkan::GetCurrentPhysicalDevice(); VkDevice dev = Vulkan::GetCurrentDevice(); int numMips = ctx.num_mipmaps(0); int mips = Math::max(0, numMips - NumBasicLods); int depth = ctx.image_depth(0, 0); int width = ctx.image_width(0, 0); int height = ctx.image_height(0, 0); bool isCube = ctx.num_faces() > 1; streamInfo.lowestLod = Math::max(0, mips); CoreGraphics::PixelFormat::Code nebulaFormat = CoreGraphics::Gliml::ToPixelFormat(ctx); VkFormat vkformat = VkTypes::AsVkFormat(nebulaFormat); VkTypes::VkBlockDimensions block = VkTypes::AsVkBlockSize(vkformat); runtimeInfo.type = isCube ? CoreGraphics::TextureCube : ctx.is_3d() ? CoreGraphics::Texture3D : CoreGraphics::Texture2D; // use linear if we really have to VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(physicalDev, vkformat, &formatProps); bool forceLinear = false; if (!(formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { forceLinear = true; } // create image VkExtent3D extents; extents.width = width; extents.height = height; extents.depth = depth; VkImageCreateInfo info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, NULL, isCube ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : VkImageCreateFlags(0), VkTypes::AsVkImageType(runtimeInfo.type), vkformat, extents, (uint32_t)numMips, (uint32_t)ctx.num_faces(), VK_SAMPLE_COUNT_1_BIT, forceLinear ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_SHARING_MODE_EXCLUSIVE, 0, nullptr, VK_IMAGE_LAYOUT_UNDEFINED }; VkResult stat = vkCreateImage(dev, &info, NULL, &loadInfo.img); n_assert(stat == VK_SUCCESS); CoreGraphics::Alloc alloc = AllocateMemory(loadInfo.dev, loadInfo.img, CoreGraphics::MemoryPool_DeviceLocal); stat = vkBindImageMemory(loadInfo.dev, loadInfo.img, alloc.mem, alloc.offset); n_assert(stat == VK_SUCCESS); loadInfo.mem = alloc; // create image view VkImageSubresourceRange subres; subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subres.baseArrayLayer = 0; subres.baseMipLevel = Math::max(mips, 0); subres.layerCount = info.arrayLayers; subres.levelCount = Math::min(numMips, NumBasicLods); VkImageViewCreateInfo viewCreate = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, nullptr, 0, loadInfo.img, VkTypes::AsVkImageViewType(runtimeInfo.type), vkformat, VkTypes::AsVkMapping(nebulaFormat), subres }; stat = vkCreateImageView(dev, &viewCreate, NULL, &runtimeInfo.view); n_assert(stat == VK_SUCCESS); // use resource submission CoreGraphics::LockResourceSubmission(); CoreGraphics::SubmissionContextId sub = CoreGraphics::GetResourceSubmissionContext(); // transition to transfer VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(sub), CoreGraphics::BarrierStage::Top, CoreGraphics::BarrierStage::Transfer, VkUtilities::ImageMemoryBarrier(loadInfo.img, subres, VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)); // now load texture by walking through all images and mips for (int i = 0; i < ctx.num_faces(); i++) { for (int j = subres.baseMipLevel; j < ctx.num_mipmaps(i); j++) { extents.width = ctx.image_width(i, j); extents.height = ctx.image_height(i, j); extents.depth = ctx.image_depth(i, j); VkImageSubresourceRange res = subres; res.layerCount = 1; res.levelCount = 1; res.baseMipLevel = j; res.baseArrayLayer = subres.baseArrayLayer + i; VkBuffer outBuf; CoreGraphics::Alloc outMem; VkUtilities::ImageUpdate( dev, CoreGraphics::SubmissionContextGetCmdBuffer(sub), TransferQueueType, loadInfo.img, extents, res.baseMipLevel, res.baseArrayLayer, ctx.image_size(i, j), (uint32_t*)ctx.image_data(i, j), outBuf, outMem); // add host memory buffer, intermediate device memory, and intermediate device buffer to delete queue SubmissionContextFreeMemory(sub, outMem); SubmissionContextFreeVkBuffer(sub, dev, outBuf); } } // transition image to be used for rendering VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(sub), CoreGraphics::BarrierStage::Transfer, CoreGraphics::BarrierStage::AllGraphicsShaders, VkUtilities::ImageMemoryBarrier(loadInfo.img, subres, TransferQueueType, GraphicsQueueType, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); // perform final transition on graphics queue CoreGraphics::SubmissionContextId gfxSub = CoreGraphics::GetHandoverSubmissionContext(); VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(gfxSub), CoreGraphics::BarrierStage::Transfer, CoreGraphics::BarrierStage::AllGraphicsShaders, VkUtilities::ImageMemoryBarrier(loadInfo.img, subres, TransferQueueType, GraphicsQueueType, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); CoreGraphics::UnlockResourceSubmission(); loadInfo.dims.width = width; loadInfo.dims.height = height; loadInfo.dims.depth = depth; loadInfo.layers = info.arrayLayers; loadInfo.mips = Math::max(numMips, 1); loadInfo.format = nebulaFormat;// VkTypes::AsNebulaPixelFormat(vkformat); loadInfo.dev = dev; loadInfo.swapExtension = Ids::InvalidId32; loadInfo.stencilExtension = Ids::InvalidId32; loadInfo.sparseExtension = Ids::InvalidId32; runtimeInfo.bind = VkShaderServer::Instance()->RegisterTexture(TextureId(res), runtimeInfo.type); //stream->MemoryUnmap(); #if NEBULA_GRAPHICS_DEBUG ObjectSetName((TextureId)res, stream->GetURI().LocalPath().AsCharPtr()); #endif return ResourcePool::Success; } stream->MemoryUnmap(); return ResourcePool::Failed; } //------------------------------------------------------------------------------ /** */ inline void VkStreamTexturePool::Unload(const Resources::ResourceId id) { __LockName(texturePool->Allocator(), lock); VkTextureStreamInfo& streamInfo = texturePool->Get<Texture_StreamInfo>(id.resourceId); streamInfo.stream->MemoryUnmap(); texturePool->Unload(id); } //------------------------------------------------------------------------------ /** */ void VkStreamTexturePool::StreamMaxLOD(const Resources::ResourceId& id, const float lod, bool immediate) { N_SCOPE_ACCUM(StreamMaxLOD, TextureStream); __LockName(texturePool->Allocator(), lock); VkTextureStreamInfo& streamInfo = texturePool->Get<Texture_StreamInfo>(id.resourceId); const VkTextureLoadInfo& loadInfo = texturePool->Get<Texture_LoadInfo>(id.resourceId); VkTextureRuntimeInfo& runtimeInfo = texturePool->Get<Texture_RuntimeInfo>(id.resourceId); // if the lod is undefined, just add 1 mip IndexT adjustedLod = Math::max(0.0f, Math::ceil(loadInfo.mips * lod)); // abort if the lod is already higher if (streamInfo.lowestLod <= (uint32_t)adjustedLod) return; // bump lod adjustedLod = Math::min(adjustedLod, (IndexT)loadInfo.mips); IndexT maxLod = loadInfo.mips - streamInfo.lowestLod; VkDevice dev = Vulkan::GetCurrentDevice(); const gliml::context& ctx = streamInfo.ctx; VkImageSubresourceRange subres; subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subres.baseArrayLayer = 0; subres.baseMipLevel = adjustedLod; subres.layerCount = loadInfo.layers; subres.levelCount = 1; // create image VkExtent3D extents; extents.width = ctx.image_width(0, 0); extents.height = ctx.image_height(0, 0); extents.depth = ctx.image_depth(0, 0); // create image view VkImageSubresourceRange viewSubres; viewSubres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; viewSubres.baseArrayLayer = 0; viewSubres.baseMipLevel = adjustedLod; viewSubres.layerCount = loadInfo.layers; viewSubres.levelCount = loadInfo.mips - viewSubres.baseMipLevel; VkImageViewCreateInfo viewCreate = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, nullptr, 0, loadInfo.img, VkTypes::AsVkImageViewType(runtimeInfo.type), VkTypes::AsVkFormat(loadInfo.format), VkTypes::AsVkMapping(loadInfo.format), viewSubres }; // use resource submission CoreGraphics::LockResourceSubmission(); CoreGraphics::SubmissionContextId sub = CoreGraphics::GetResourceSubmissionContext(); CoreGraphics::SubmissionContextId gfxSub = CoreGraphics::GetHandoverSubmissionContext(); // transition to transfer VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(gfxSub), CoreGraphics::BarrierStage::AllGraphicsShaders, CoreGraphics::BarrierStage::Transfer, VkUtilities::ImageMemoryBarrier(loadInfo.img, viewSubres, GraphicsQueueType, TransferQueueType, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)); // now load texture by walking through all images and mips for (int i = 0; i < ctx.num_faces(); i++) { for (int j = adjustedLod; j < (IndexT)streamInfo.lowestLod; j++) { extents.width = ctx.image_width(i, j); extents.height = ctx.image_height(i, j); extents.depth = ctx.image_depth(i, j); VkImageSubresourceRange res = subres; res.layerCount = 1; res.levelCount = 1; res.baseMipLevel = j; res.baseArrayLayer = subres.baseArrayLayer + i; VkBuffer outBuf; CoreGraphics::Alloc outMem; VkUtilities::ImageUpdate( dev, CoreGraphics::SubmissionContextGetCmdBuffer(sub), TransferQueueType, loadInfo.img, extents, res.baseMipLevel, res.baseArrayLayer, ctx.image_size(i, j), (uint32_t*)ctx.image_data(i, j), outBuf, outMem); // add host memory buffer, intermediate device memory, and intermediate device buffer to delete queue SubmissionContextFreeMemory(sub, outMem); SubmissionContextFreeVkBuffer(sub, dev, outBuf); } } // transition image to be used for rendering VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(sub), CoreGraphics::BarrierStage::Transfer, CoreGraphics::BarrierStage::AllGraphicsShaders, VkUtilities::ImageMemoryBarrier(loadInfo.img, viewSubres, TransferQueueType, GraphicsQueueType, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); // perform final transition on graphics queue VkUtilities::ImageBarrier(CoreGraphics::SubmissionContextGetCmdBuffer(gfxSub), CoreGraphics::BarrierStage::Transfer, CoreGraphics::BarrierStage::AllGraphicsShaders, VkUtilities::ImageMemoryBarrier(loadInfo.img, viewSubres, TransferQueueType, GraphicsQueueType, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); CoreGraphics::UnlockResourceSubmission(); // update lod info and add image view for recreation streamInfo.lowestLod = adjustedLod; if (immediate) { VkResult res = vkCreateImageView(GetCurrentDevice(), &viewCreate, nullptr, &runtimeInfo.view); n_assert(res == VK_SUCCESS); } else { VkShaderServer::Instance()->AddPendingImageView(TextureId(id), viewCreate, runtimeInfo.bind); } } } // namespace Vulkan
6,683
4,962
package net.bytebuddy.implementation.bind; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.implementation.bytecode.Removal; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.test.utility.MockitoRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.mockito.Mock; import static net.bytebuddy.test.utility.FieldByFieldComparison.hasPrototype; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class MethodDelegationBinderTerminationHandlerTest { @Rule public TestRule mockitoRule = new MockitoRule(this); @Mock private Assigner assigner; @Mock private MethodDescription source, target; @Mock private TypeDescription sourceType, targetType; @Mock private TypeDescription.Generic genericSourceType, genericTargetType; @Mock private StackManipulation stackManipulation; @Test public void testDropping() throws Exception { when(target.getReturnType()).thenReturn(genericSourceType); when(genericSourceType.getStackSize()).thenReturn(StackSize.SINGLE); StackManipulation stackManipulation = MethodDelegationBinder.TerminationHandler.Default.DROPPING.resolve(assigner, Assigner.Typing.STATIC, source, target); assertThat(stackManipulation, is((StackManipulation) Removal.SINGLE)); verify(genericSourceType).getStackSize(); verifyNoMoreInteractions(genericSourceType); } @Test public void testReturning() throws Exception { when(source.getReturnType()).thenReturn(genericSourceType); when(target.getReturnType()).thenReturn(genericTargetType); when(genericSourceType.asErasure()).thenReturn(sourceType); when(genericTargetType.asErasure()).thenReturn(targetType); when(assigner.assign(genericTargetType, genericSourceType, Assigner.Typing.STATIC)).thenReturn(stackManipulation); StackManipulation stackManipulation = MethodDelegationBinder.TerminationHandler.Default.RETURNING.resolve(assigner, Assigner.Typing.STATIC, source, target); assertThat(stackManipulation, hasPrototype((StackManipulation) new StackManipulation.Compound(this.stackManipulation, MethodReturn.REFERENCE))); verify(assigner).assign(genericTargetType, genericSourceType, Assigner.Typing.STATIC); } }
959
418
/* MIT License Copyright (c) 2019 Advanced Micro Devices, Inc. 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. */ //--------------------------------------------------------------------------------------- // Structure-of-arrays SIMD implementation of 3x3 SVD //--------------------------------------------------------------------------------------- #pragma once #include "FEMFXVectorMath.h" namespace AMD { // Reference: McAdams et al., "Computing the Singular Value Decomposition of 3 x 3 matrices with minimal branching and elementary floating point operations" // Approximation of sin,cos values needed for Givens rotation used in Jacobi iteration template<class T> void FmApproxGivens(typename T::SoaFloat* s, typename T::SoaFloat* c, typename T::SoaFloat a00, typename T::SoaFloat a01, typename T::SoaFloat a11) { typename T::SoaFloat a00m11 = a00 - a11; typename T::SoaFloat a00m11_2 = a00m11*a00m11; typename T::SoaFloat a01_2 = a01*a01; typename T::SoaBool useOmega = (a01_2 < a00m11_2); typename T::SoaFloat omega = 1.0f / sqrtf(a01_2 + a00m11_2); const typename T::SoaFloat sqrtOneHalf = 0.70710678118654752440084436210485f; // sqrtf(0.5f); *s = select(sqrtOneHalf, omega*a01, useOmega); *c = select(sqrtOneHalf, omega*a00m11, useOmega); } // Compute eigenvectors and values for symmetric matrix, using Jacobi iteration with fixed cycle of (row, col) pairs template<class T> void FmEigenSymm3x3CyclicJacobi(typename T::SoaVector3* eigenvals, typename T::SoaMatrix3* eigenvectors, const typename T::SoaMatrix3& symmMat) { typename T::SoaFloat s00 = symmMat.col0.x; typename T::SoaFloat s01 = symmMat.col1.x; typename T::SoaFloat s02 = symmMat.col2.x; typename T::SoaFloat s11 = symmMat.col1.y; typename T::SoaFloat s12 = symmMat.col2.y; typename T::SoaFloat s22 = symmMat.col2.z; const int numIterations = 4; typename T::SoaMatrix3 V = typename T::SoaMatrix3::identity(); for (int i = 0; i < numIterations; i++) { // (p, q) = (0, 1) typename T::SoaFloat s, c; FmApproxGivens<T>(&s, &c, s00, s01, s11); typename T::SoaMatrix3 GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(c, s, 0.0f), FmInitVector3<T>(-s, c, 0.0f), FmInitVector3<T>(0.0f, 0.0f, 1.0f)); V = mul(V, GivensMat); typename T::SoaFloat s00_next = s*s*s11 + s*c*s01 + c*s*s01 + c*c*s00; typename T::SoaFloat s01_next = s*c*s11 - s*s*s01 + c*c*s01 - c*s*s00; typename T::SoaFloat s02_next = s*s12 + c*s02; typename T::SoaFloat s11_next = c*c*s11 - c*s*s01 - s*c*s01 + s*s*s00; typename T::SoaFloat s12_next = c*s12 - s*s02; typename T::SoaFloat s22_next; // = s22; s00 = s00_next; s01 = s01_next; s02 = s02_next; s11 = s11_next; s12 = s12_next; //s22 = s22_next; // (p, q) = (0, 2) FmApproxGivens<T>(&s, &c, s00, s02, s22); GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(c, 0.0f, s), FmInitVector3<T>(0.0f, 1.0f, 0.0f), FmInitVector3<T>(-s, 0.0f, c)); V = mul(V, GivensMat); s00_next = s*s*s22 + s*c*s02 + c*s*s02 + c*c*s00; s01_next = s*s12 + c*s01; s02_next = s*c*s22 - s*s*s02 + c*c*s02 - c*s*s00; //s11_next = s11; s12_next = c*s12 - s*s01; s22_next = c*c*s22 - c*s*s02 - s*c*s02 + s*s*s00; s00 = s00_next; s01 = s01_next; s02 = s02_next; //s11 = s11_next; s12 = s12_next; s22 = s22_next; // (p, q) = (1, 2) FmApproxGivens<T>(&s, &c, s11, s12, s22); GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(1.0f, 0.0f, 0.0f), FmInitVector3<T>(0.0f, c, s), FmInitVector3<T>(0.0f, -s, c)); V = mul(V, GivensMat); //s00_next = s00; s01_next = s*s02 + c*s01; s02_next = c*s02 - s*s01; s11_next = s*s*s22 + s*c*s12 + c*s*s12 + c*c*s11; s12_next = s*c*s22 - s*s*s12 + c*c*s12 - c*s*s11; s22_next = c*c*s22 - c*s*s12 - s*c*s12 + s*s*s11; //s00 = s00_next; s01 = s01_next; s02 = s02_next; s11 = s11_next; s12 = s12_next; s22 = s22_next; } // Sort eigenvalues in order of decreasing magnitude, and swap eigenvectors to match. // Signs flipped during swaps to preserve rotation. typename T::SoaVector3 eigenvec0 = V.col0; typename T::SoaVector3 eigenvec1 = V.col1; typename T::SoaVector3 eigenvec2 = V.col2; typename T::SoaVector3 eigenvectemp; typename T::SoaFloat eigenval0 = s00; typename T::SoaFloat eigenval1 = s11; typename T::SoaFloat eigenval2 = s22; typename T::SoaFloat eigenvaltemp; typename T::SoaFloat abseigenval0 = fabsf(eigenval0); typename T::SoaFloat abseigenval1 = fabsf(eigenval1); typename T::SoaFloat abseigenval2 = fabsf(eigenval2); typename T::SoaFloat abseigenvaltemp; typename T::SoaBool swap = (abseigenval0 < abseigenval1); eigenvectemp = -eigenvec0; eigenvec0 = select(eigenvec0, eigenvec1, swap); eigenvec1 = select(eigenvec1, eigenvectemp, swap); eigenvaltemp = -eigenval0; eigenval0 = select(eigenval0, eigenval1, swap); eigenval1 = select(eigenval1, eigenvaltemp, swap); abseigenvaltemp = abseigenval0; abseigenval0 = select(abseigenval0, abseigenval1, swap); abseigenval1 = select(abseigenval1, abseigenvaltemp, swap); swap = (abseigenval0 < abseigenval2); eigenvectemp = -eigenvec0; eigenvec0 = select(eigenvec0, eigenvec2, swap); eigenvec2 = select(eigenvec2, eigenvectemp, swap); eigenvaltemp = -eigenval0; eigenval0 = select(eigenval0, eigenval2, swap); eigenval2 = select(eigenval2, eigenvaltemp, swap); abseigenvaltemp = abseigenval0; //abseigenval0 = select(abseigenval0, abseigenval2, swap); abseigenval2 = select(abseigenval2, abseigenvaltemp, swap); swap = (abseigenval1 < abseigenval2); eigenvectemp = -eigenvec1; eigenvec1 = select(eigenvec1, eigenvec2, swap); eigenvec2 = select(eigenvec2, eigenvectemp, swap); eigenvaltemp = -eigenval1; eigenval1 = select(eigenval1, eigenval2, swap); eigenval2 = select(eigenval2, eigenvaltemp, swap); //abseigenvaltemp = abseigenval1; //abseigenval1 = select(abseigenval1, abseigenval2, swap); //abseigenval2 = select(abseigenval2, abseigenvaltemp, swap); *eigenvectors = FmInitMatrix3<T>(eigenvec0, eigenvec1, eigenvec2); *eigenvals = FmInitVector3<T>(eigenval0, eigenval1, eigenval2); } // Givens rotation used in QR decomposition template<class T> void FmQRGivens(typename T::SoaFloat& s, typename T::SoaFloat& c, typename T::SoaFloat apq, typename T::SoaFloat aqq, typename T::SoaFloat tolerance) { typename T::SoaFloat sum = apq*apq + aqq*aqq; typename T::SoaFloat denomInv = 1.0f / sqrtf(sum); s = select(apq * denomInv, 0.0f, (sum < tolerance)); c = select(aqq * denomInv, 1.0f, (sum < tolerance)); } // SVD(mat) = U * Sigma * V^T // Reference: McAdams et al., "Computing the Singular Value Decomposition of 3 x 3 matrices with minimal branching and elementary floating point operations" template<class T> void FmSvd3x3(typename T::SoaMatrix3* U, typename T::SoaVector3* sigma, typename T::SoaMatrix3* V, const typename T::SoaMatrix3& mat, typename T::SoaFloat givensTolerance = typename T::SoaFloat(FLT_EPSILON)) { // Compute V^T * Sigma^2 * V as Eigendecomposition of Mat^T * Mat typename T::SoaMatrix3 symmMat = mul(transpose(mat), mat); typename T::SoaVector3 eigenvals; typename T::SoaMatrix3 eigenvecs; FmEigenSymm3x3CyclicJacobi<T>(&eigenvals, &eigenvecs, symmMat); // B = U * Sigma = Mat * V typename T::SoaMatrix3 B = mul(mat, eigenvecs); // Decompose into U and Sigma with Givens rotations typename T::SoaMatrix3 Q, GivensMat; typename T::SoaFloat s, c; typename T::SoaFloat B_00, B_10, B_20, B_21, B_11, B_22; B_10 = B.getElem(0, 1); B_00 = B.getElem(0, 0); FmQRGivens<T>(s, c, B_10, B_00, givensTolerance); GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(c, s, 0.0f), FmInitVector3<T>(-s, c, 0.0f), FmInitVector3<T>(0.0f, 0.0f, 1.0f)); Q = GivensMat; B = mul(transpose(GivensMat), B); B_20 = B.getElem(0, 2); B_00 = B.getElem(0, 0); FmQRGivens<T>(s, c, B_20, B_00, givensTolerance); GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(c, 0.0f, s), FmInitVector3<T>(0.0f, 1.0f, 0.0f), FmInitVector3<T>(-s, 0.0f, c)); Q = mul(Q, GivensMat); B = mul(transpose(GivensMat), B); B_21 = B.getElem(1, 2); B_11 = B.getElem(1, 1); FmQRGivens<T>(s, c, B_21, B_11, givensTolerance); GivensMat = FmInitMatrix3<T>(FmInitVector3<T>(1.0f, 0.0f, 0.0f), FmInitVector3<T>(0.0f, c, s), FmInitVector3<T>(0.0f, -s, c)); Q = mul(Q, GivensMat); B = mul(transpose(GivensMat), B); B_00 = B.getElem(0, 0); B_11 = B.getElem(1, 1); B_22 = B.getElem(2, 2); *U = Q; sigma->x = B_00; sigma->y = B_11; sigma->z = B_22; *V = eigenvecs; } template<class T> typename T::SoaMatrix3 FmPseudoInverse(const typename T::SoaMatrix3& mat) { typename T::SoaMatrix3 U, V; typename T::SoaVector3 sigma; FmSvd3x3(&U, &sigma, &V, mat); // Tolerance from https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse typename T::SoaVector3 absSigma = abs(sigma); typename T::SoaFloat tol = FLT_EPSILON * 3.0f * FmMaxFloat(absSigma.x, FmMaxFloat(absSigma.y, absSigma.z)); sigma.x = select(0.0f, 1.0f / sigma.x, absSigma.x > tol); sigma.y = select(0.0f, 1.0f / sigma.y, absSigma.y > tol); sigma.z = select(0.0f, 1.0f / sigma.z, absSigma.z > tol); return mul(V, mul(typename T::SoaMatrix3::scale(sigma), transpose(U))); } }
5,635
5,079
from unittest import TestCase from thriftpy2.thrift import TType, TPayload from thriftpy2.transport.memory import TMemoryBuffer from thriftpy2.protocol.binary import TBinaryProtocol from thriftpy2._compat import CYTHON class Struct(TPayload): thrift_spec = { 1: (TType.I32, 'a', False), 2: (TType.STRING, 'b', False), 3: (TType.DOUBLE, 'c', False) } default_spec = [('a', None), ('b', None), ('c', None)] class TItem(TPayload): thrift_spec = { 1: (TType.I32, "id", False), 2: (TType.LIST, "phones", TType.STRING, False), 3: (TType.MAP, "addr", (TType.I32, TType.STRING), False), 4: (TType.LIST, "data", (TType.STRUCT, Struct), False) } default_spec = [("id", None), ("phones", None), ("addr", None), ("data", None)] class MismatchTestCase(TestCase): BUFFER = TMemoryBuffer PROTO = TBinaryProtocol def test_list_type_mismatch(self): class TMismatchItem(TPayload): thrift_spec = { 1: (TType.I32, "id", False), 2: (TType.LIST, "phones", (TType.I32, False), False), } default_spec = [("id", None), ("phones", None)] t = self.BUFFER() p = self.PROTO(t) item = TItem(id=37, phones=["23424", "235125"]) p.write_struct(item) p.write_message_end() item2 = TMismatchItem() p.read_struct(item2) assert item2.phones == [] def test_map_type_mismatch(self): class TMismatchItem(TPayload): thrift_spec = { 1: (TType.I32, "id", False), 3: (TType.MAP, "addr", (TType.STRING, TType.STRING), False) } default_spec = [("id", None), ("addr", None)] t = self.BUFFER() p = self.PROTO(t) item = TItem(id=37, addr={1: "hello", 2: "world"}) p.write_struct(item) p.write_message_end() item2 = TMismatchItem() p.read_struct(item2) assert item2.addr == {} def test_struct_mismatch(self): class MismatchStruct(TPayload): thrift_spec = { 1: (TType.STRING, 'a', False), 2: (TType.STRING, 'b', False) } default_spec = [('a', None), ('b', None)] class TMismatchItem(TPayload): thrift_spec = { 1: (TType.I32, "id", False), 2: (TType.LIST, "phones", TType.STRING, False), 3: (TType.MAP, "addr", (TType.I32, TType.STRING), False), 4: (TType.LIST, "data", (TType.STRUCT, MismatchStruct), False) } default_spec = [("id", None), ("phones", None), ("addr", None)] t = self.BUFFER() p = self.PROTO(t) item = TItem(id=37, data=[Struct(a=1, b="hello", c=0.123), Struct(a=2, b="world", c=34.342346), Struct(a=3, b="when", c=25235.14)]) p.write_struct(item) p.write_message_end() item2 = TMismatchItem() p.read_struct(item2) assert len(item2.data) == 3 assert all([i.b for i in item2.data]) if CYTHON: from thriftpy2.transport.memory import TCyMemoryBuffer from thriftpy2.protocol.cybin import TCyBinaryProtocol class CyMismatchTestCase(MismatchTestCase): BUFFER = TCyMemoryBuffer PROTO = TCyBinaryProtocol
1,766
6,034
<filename>product-service-project/product-service-api/src/main/java/cn/iocoder/mall/productservice/rpc/attr/dto/ProductAttrKeyValueRespDTO.java<gh_stars>1000+ package cn.iocoder.mall.productservice.rpc.attr.dto; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; /** * 商品规格 KEY + VALUE 对的 Response DTO */ @Data @Accessors(chain = true) public class ProductAttrKeyValueRespDTO implements Serializable { /** * 规格 KEY 编号 */ private Integer attrKeyId; /** * 规格 KEY 名 */ private String attrKeyName; /** * 规格 VALUE 编号 */ private Integer attrValueId; /** * 规格 VALUE 名 */ private String attrValueName; }
326
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/resource_coordinator/public/cpp/memory_instrumentation/global_memory_dump.h" #include <vector> namespace memory_instrumentation { GlobalMemoryDump::GlobalMemoryDump( std::vector<mojom::ProcessMemoryDumpPtr> process_dumps, mojom::AggregatedMetricsPtr aggregated_metrics) : aggregated_metrics_(std::move(aggregated_metrics)) { auto it = process_dumps_.before_begin(); for (mojom::ProcessMemoryDumpPtr& process_dump : process_dumps) { it = process_dumps_.emplace_after(it, std::move(process_dump)); } } GlobalMemoryDump::~GlobalMemoryDump() = default; std::unique_ptr<GlobalMemoryDump> GlobalMemoryDump::MoveFrom( mojom::GlobalMemoryDumpPtr ptr) { return ptr ? std::unique_ptr<GlobalMemoryDump>( new GlobalMemoryDump(std::move(ptr->process_dumps), std::move(ptr->aggregated_metrics))) : nullptr; } GlobalMemoryDump::ProcessDump::ProcessDump( mojom::ProcessMemoryDumpPtr process_dump) : raw_dump_(std::move(process_dump)) {} GlobalMemoryDump::ProcessDump::~ProcessDump() = default; absl::optional<uint64_t> GlobalMemoryDump::ProcessDump::GetMetric( const std::string& dump_name, const std::string& metric_name) const { auto dump_it = raw_dump_->chrome_allocator_dumps.find(dump_name); if (dump_it == raw_dump_->chrome_allocator_dumps.cend()) return absl::nullopt; auto metric_it = dump_it->second->numeric_entries.find(metric_name); if (metric_it == dump_it->second->numeric_entries.cend()) return absl::nullopt; return absl::optional<uint64_t>(metric_it->second); } GlobalMemoryDump::AggregatedMetrics::AggregatedMetrics( mojom::AggregatedMetricsPtr aggregated_metrics) : aggregated_metrics_(aggregated_metrics.is_null() ? mojom::AggregatedMetrics::New() : std::move(aggregated_metrics)) {} GlobalMemoryDump::AggregatedMetrics::~AggregatedMetrics() = default; } // namespace memory_instrumentation
875
6,457
#pragma once #include "RealSenseTypes.h" #include "RealSenseContext.generated.h" UCLASS(ClassGroup="RealSense", BlueprintType) class REALSENSE_API URealSenseContext : public UObject { GENERATED_UCLASS_BODY() friend class FRealSensePlugin; public: virtual ~URealSenseContext(); struct rs2_context* GetHandle(); UFUNCTION(Category="RealSense", BlueprintCallable) static URealSenseContext* GetRealSense(); UFUNCTION(Category="RealSense", BlueprintCallable) void QueryDevices(); UFUNCTION(Category="RealSense", BlueprintCallable) class URealSenseDevice* GetDeviceById(int Id); UFUNCTION(Category="RealSense", BlueprintCallable) class URealSenseDevice* FindDeviceBySerial(FString Serial); UPROPERTY(Category="RealSense", BlueprintReadOnly, VisibleAnywhere) TArray<class URealSenseDevice*> Devices; private: void SetHandle(struct rs2_context* Handle); class URealSenseDevice* NewDevice(struct rs2_device* Handle, const TCHAR* Name); struct rs2_context* RsContext = nullptr; FCriticalSection DevicesMx; };
370
1,088
package com.riversoft.weixin.mp.event.care; import com.fasterxml.jackson.annotation.JsonProperty; import com.riversoft.weixin.common.event.EventRequest; /** * Created by exizhai on 11/22/2015. */ public class SessionForwardEvent extends EventRequest { @JsonProperty("FromKfAccount") private String fromCare; @JsonProperty("ToKfAccount") private String toCare; public String getFromCare() { return fromCare; } public void setFromCare(String fromCare) { this.fromCare = fromCare; } public String getToCare() { return toCare; } public void setToCare(String toCare) { this.toCare = toCare; } }
297
521
<reponame>braymar/afl #include <ipxe/nap.h> PROVIDE_NAP_INLINE ( null, cpu_nap );
42
348
{"nom":"Pont-Péan","circ":"1ère circonscription","dpt":"Ille-et-Vilaine","inscrits":3256,"abs":1901,"votants":1355,"blancs":145,"nuls":37,"exp":1173,"res":[{"nuance":"REM","nom":"<NAME>","voix":717},{"nuance":"UDI","nom":"<NAME>","voix":456}]}
101
379
<filename>src/main/java/com/oim/core/net/connect/codec/DataCodecDecoder.java<gh_stars>100-1000 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.oim.core.net.connect.codec; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author 夏辉 * @date 2014年6月14日 下午10:03:05 * @version 0.0.1 */ public class DataCodecDecoder extends CumulativeProtocolDecoder { protected static final Logger logger = LoggerFactory.getLogger(DataCodecDecoder.class); private Charset charset = Charset.forName("UTF-8");// 字符编码类型 public DataCodecDecoder() { } public DataCodecDecoder(Charset charset) { if (null != charset) { this.charset = charset; } } // server @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { try { if (in.prefixedDataAvailable(4, Integer.MAX_VALUE)) { in.mark();// 标记当前位置,以便reset int size = in.getInt(); if ((size) > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size in.reset(); return false;// 接收新数据,以拼凑成完整数据 } byte[] bodyByte = new byte[size]; in.get(bodyByte, 0, size); String xml = new String(bodyByte, charset); out.write(xml); return true;// 接收新数据,以拼凑成完整数据 } } catch (Exception e) { in.sweep(); logger.error("", e); } return false; } public static int bytesToInt(byte[] bytes) { int value = 0; for (int i = 0; i < bytes.length; i++) { value += (bytes[i] & 0XFF) << (8 * (3 - i)); } return value; } public static byte[] intToBytes(int value) { byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (byte) (value >> (24 - i * 8)); } return bytes; } public static void main(String[] s) { int i = 290; byte[] b = intToBytes(i); int j = bytesToInt(b); System.out.println(j); } }
986
1,144
package de.metas.util.time.generator; import java.time.LocalDateTime; import java.util.Set; import com.google.common.collect.ImmutableSet; import lombok.NonNull; import lombok.Value; @Value public final class SameDateSequenceExploder implements IDateSequenceExploder { public static final SameDateSequenceExploder instance = new SameDateSequenceExploder(); private SameDateSequenceExploder() { } @Override public Set<LocalDateTime> explodeForward(@NonNull final LocalDateTime date) { return ImmutableSet.of(date); } @Override public Set<LocalDateTime> explodeBackward(@NonNull final LocalDateTime date) { return ImmutableSet.of(date); } }
215
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.processing.test; import com.yahoo.component.chain.Chain; import com.yahoo.processing.Processor; import com.yahoo.processing.Request; import com.yahoo.processing.Response; import com.yahoo.processing.execution.Execution; import org.junit.Test; import static com.yahoo.processing.test.ProcessorLibrary.*; import static org.junit.Assert.assertEquals; /** * Tests the basic of the processing framework */ public class ProcessingTestCase { /** Execute three simple processors doing some phony processing */ @Test public void testChainedProcessing1() { // Create a chain Chain<Processor> chain=new Chain<>(new CombineData(),new Get6DataItems(), new DataSource()); // Execute it Request request=new Request(); request.properties().set("appendage",1); Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request); // Verify the result assertEquals(6-1,response.data().asList().size()); assertEquals("first.2, third.2",response.data().get(0).toString()); assertEquals("second.2",response.data().get(1).toString()); assertEquals("first.3",response.data().get(2).toString()); assertEquals("second.3",response.data().get(3).toString()); assertEquals("third.3",response.data().get(4).toString()); } /** Execute the same processors in a different order */ @Test public void testChainedProcessing2() { // Create a chain Chain<Processor> chain=new Chain<>(new Get6DataItems(),new CombineData(), new DataSource()); // Execute it Request request=new Request(); request.properties().set("appendage",1); Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request); // Check the result assertEquals(6,response.data().asList().size()); assertEquals("first.2, third.2",response.data().get(0).toString()); assertEquals("second.2",response.data().get(1).toString()); assertEquals("first.4, third.4",response.data().get(2).toString()); assertEquals("second.4",response.data().get(3).toString()); assertEquals("first.6, third.6",response.data().get(4).toString()); assertEquals("second.6",response.data().get(5).toString()); } }
871
778
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: structural_mechanics_application/license.txt // // Main authors: <NAME>, https://github.com/MFusseder // #include "adjoint_finite_difference_cr_beam_element_3D2N.h" #include "structural_mechanics_application_variables.h" #include "custom_response_functions/response_utilities/stress_response_definitions.h" #include "includes/checks.h" #include "custom_elements/cr_beam_element_linear_3D2N.hpp" namespace Kratos { template <class TPrimalElement> void AdjointFiniteDifferenceCrBeamElement<TPrimalElement>::CalculateOnIntegrationPoints(const Variable<array_1d<double, 3 > >& rVariable, std::vector< array_1d<double, 3 > >& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY if (rVariable == ADJOINT_CURVATURE || rVariable == ADJOINT_STRAIN) { const double E = this->GetProperties()[YOUNG_MODULUS]; const double nu = this->GetProperties()[POISSON_RATIO]; const double G = E / (2.0 * (1.0 + nu)); const double A = this->GetProperties()[CROSS_AREA]; const double J = this->GetProperties()[TORSIONAL_INERTIA]; const double Iy = this->GetProperties()[I22]; const double Iz = this->GetProperties()[I33]; if (rVariable == ADJOINT_CURVATURE) { this->CalculateAdjointFieldOnIntegrationPoints(MOMENT, rOutput, rCurrentProcessInfo); for (IndexType i = 0; i < rOutput.size(); ++i) { rOutput[i][0] *= 1.0 / (G * J); rOutput[i][1] *= -1.0 / (E * Iy); rOutput[i][2] *= -1.0 / (E * Iz); } } else if (rVariable == ADJOINT_STRAIN) { this->CalculateAdjointFieldOnIntegrationPoints(FORCE, rOutput, rCurrentProcessInfo); KRATOS_WARNING_IF("ADJOINT_STRAIN", (this->GetProperties().Has(AREA_EFFECTIVE_Y) || this->GetProperties().Has(AREA_EFFECTIVE_Z))) << "Not available for Timoschenko beam!" << std::endl; for (IndexType i = 0; i < rOutput.size(); ++i) { rOutput[i][0] *= 1.0 / (E * A); rOutput[i][1] *= 0.0; rOutput[i][2] *= 0.0; } } } else { this->CalculateAdjointFieldOnIntegrationPoints(rVariable, rOutput, rCurrentProcessInfo); } KRATOS_CATCH("") } template <class TPrimalElement> int AdjointFiniteDifferenceCrBeamElement<TPrimalElement>::Check(const ProcessInfo& rCurrentProcessInfo) const { KRATOS_TRY int return_value = BaseType::Check(rCurrentProcessInfo); KRATOS_ERROR_IF_NOT(this->mHasRotationDofs) << "Adjoint beam element does not have rotation dofs!" << std::endl; KRATOS_ERROR_IF_NOT(this->mpPrimalElement) << "Primal element pointer is nullptr!" << std::endl; //TODO: Check() of primal element should be called, but is not possible because of DOF check! KRATOS_ERROR_IF(this->GetGeometry().WorkingSpaceDimension() != 3 || this->GetGeometry().size() != 2) << "The beam element works only in 3D and with 2 noded elements" << "" << std::endl; // check dofs const GeometryType& r_geom = this->GetGeometry(); for (IndexType i = 0; i < r_geom.size(); i++) { const auto& r_node = r_geom[i]; KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(DISPLACEMENT, r_node); KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(ROTATION, r_node); KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(ADJOINT_DISPLACEMENT, r_node); KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(ADJOINT_ROTATION, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_DISPLACEMENT_X, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_DISPLACEMENT_Y, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_DISPLACEMENT_Z, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_ROTATION_X, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_ROTATION_Y, r_node); KRATOS_CHECK_DOF_IN_NODE(ADJOINT_ROTATION_Z, r_node); } const double numerical_limit = std::numeric_limits<double>::epsilon(); KRATOS_ERROR_IF(this->GetProperties().Has(CROSS_AREA) == false || this->GetProperties()[CROSS_AREA] <= numerical_limit) << "CROSS_AREA not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF(this->GetProperties().Has(YOUNG_MODULUS) == false || this->GetProperties()[YOUNG_MODULUS] <= numerical_limit) << "YOUNG_MODULUS not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF_NOT( this->GetProperties().Has(DENSITY) ) << "DENSITY not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF_NOT( this->GetProperties().Has(POISSON_RATIO) ) << "POISSON_RATIO not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF_NOT( this->GetProperties().Has(TORSIONAL_INERTIA) ) << "TORSIONAL_INERTIA not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF_NOT( this->GetProperties().Has(I22) ) << "I22 not provided for this element" << this->Id() << std::endl; KRATOS_ERROR_IF_NOT( this->GetProperties().Has(I33) ) << "I33 not provided for this element" << this->Id() << std::endl; return return_value; KRATOS_CATCH("") } template <class TPrimalElement> void AdjointFiniteDifferenceCrBeamElement<TPrimalElement>::save(Serializer& rSerializer) const { KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, BaseType); } template <class TPrimalElement> void AdjointFiniteDifferenceCrBeamElement<TPrimalElement>::load(Serializer& rSerializer) { KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, BaseType); } template class AdjointFiniteDifferenceCrBeamElement<CrBeamElementLinear3D2N>; } // namespace Kratos.
2,611
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.formrecognizer.implementation.util; import com.azure.ai.formrecognizer.models.DocumentFieldType; import com.azure.ai.formrecognizer.administration.models.DocumentFieldSchema; import java.util.Map; /** * The helper class to set the non-public properties of an {@link DocumentFieldSchema} instance. */ public final class DocumentFieldSchemaHelper { private static DocumentFieldSchemaAccessor accessor; private DocumentFieldSchemaHelper() { } /** * Type defining the methods to set the non-public properties of an {@link DocumentFieldSchema} instance. */ public interface DocumentFieldSchemaAccessor { void setType(DocumentFieldSchema documentFieldSchema, DocumentFieldType type); void setDescription(DocumentFieldSchema documentFieldSchema, String description); void setExample(DocumentFieldSchema documentFieldSchema, String example); void setItems(DocumentFieldSchema documentFieldSchema, DocumentFieldSchema items); void setProperties(DocumentFieldSchema documentFieldSchema, Map<String, DocumentFieldSchema> properties); } /** * The method called from {@link DocumentFieldSchema} to set it's accessor. * * @param documentFieldSchemaAccessor The accessor. */ public static void setAccessor(final DocumentFieldSchemaHelper.DocumentFieldSchemaAccessor documentFieldSchemaAccessor) { accessor = documentFieldSchemaAccessor; } static void setType(DocumentFieldSchema documentFieldSchema, DocumentFieldType type) { accessor.setType(documentFieldSchema, type); } static void setDescription(DocumentFieldSchema documentFieldSchema, String description) { accessor.setDescription(documentFieldSchema, description); } static void setExample(DocumentFieldSchema documentFieldSchema, String example) { accessor.setExample(documentFieldSchema, example); } static void setItems(DocumentFieldSchema documentFieldSchema, DocumentFieldSchema items) { accessor.setItems(documentFieldSchema, items); } static void setProperties(DocumentFieldSchema documentFieldSchema, Map<String, DocumentFieldSchema> properties) { accessor.setProperties(documentFieldSchema, properties); } }
735
648
{"resourceType":"DataElement","id":"Contract.subject","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/Contract.subject","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"Contract.subject","path":"Contract.subject","short":"Contract Target Entity","definition":"The target entity impacted by or of interest to parties to the agreement.","comment":"The Contract.subject is an entity that has some role with respect to the Contract.topic and Contract.topic.term, which is of focal interest to the parties to the contract and likely impacted in a significant way by the Contract.action/Contract.action.reason and the Contract.term.action/Contract.action.reason. \rIn many cases, the Contract.subject is a Contract.signer if the subject is an adult; has a legal interest in the contract; and incompetent to participate in the contract agreement.","requirements":"The Contract.subject is an entity that has some role with respect to the Contract.topic and Contract.topic.term, which is of focal interest to the parties to the contract and likely impacted in a significant way by the Contract.action/Contract.action.reason and the Contract.term.action/Contract.action.reason. In many cases, the Contract.subject is a Contract.signer if the subject is an adult; has a legal interest in the contract; and incompetent to participate in the contract agreement.","alias":["Patient"],"min":0,"max":"*","type":[{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/Resource"}],"isSummary":true,"mapping":[{"identity":"workflow","map":"Event.subject"},{"identity":"rim","map":"RoleClass, RoleCode"},{"identity":"w5","map":"who.actor"}]}]}
414
1,122
//Problem: https://www.hackerrank.com/challenges/utopian-tree //Java 8 import java.io.*; import java.util.*; import java.lang.Math; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner input = new Scanner(System.in); int testCases = input.nextInt(); for(int i = 0; i < testCases; i++) { int cycles = input.nextInt(); //Calculates according the an equation defined by the arithmetico-geometric sequence if(cycles % 2 == 0) { System.out.println((int) (Math.pow(2, cycles/2)*2) -1); } else { System.out.println((int) ((Math.pow(2, (cycles-1)/2)*2) -1)*2); } } } }
460
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALJOYSTICKDIALOG_H #define CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALJOYSTICKDIALOG_H #pragma once #include "FacialEdContext.h" #include "Controls/JoystickCtrl.h" #include "ToolbarDialog.h" class CFacialJoystickDialog : public CToolbarDialog, public IFacialEdListener, IJoystickCtrlContainer, IEditorNotifyListener { DECLARE_DYNAMIC(CFacialJoystickDialog) friend class CJoystickDialogDropTarget; public: enum { IDD = IDD_DATABASE }; CFacialJoystickDialog(); ~CFacialJoystickDialog(); void SetContext(CFacialEdContext* pContext); protected: virtual BOOL PreTranslateMessage(MSG* pMsg); virtual void OnOK() {}; virtual void OnCancel() {}; virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual void OnSize(UINT nType, int cx, int cy); virtual void OnFacialEdEvent(EFacialEdEvent event, IFacialEffector* pEffector,int nChannelCount,IFacialAnimChannel **ppChannels); void RecalcLayout(); void UpdateFreezeLayoutStatus(); void UpdateAutoCreateKeyStatus(); void ReadDisplayedSnapMargin(); void Update(); // IJoystickCtrlContainer virtual void OnAction(JoystickAction action); virtual void OnFreezeLayoutChanged(); virtual IJoystickChannel* GetPotentialJoystickChannel(); virtual float GetCurrentEvaluationTime(); virtual float GetMaxEvaluationTime(); virtual void OnSplineChanged(); virtual void OnJoysticksChanged(); virtual void OnBeginDraggingJoystickKnob(IJoystick* pJoystick); virtual void OnJoystickSelected(IJoystick* pJoystick, bool exclusive); virtual bool GetPlaying() const; virtual void SetPlaying(bool playing); // IEditorNotifyListener implementation virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); void RefreshControlJoystickSet(); DECLARE_MESSAGE_MAP() afx_msg void OnFreezeLayout(); afx_msg void OnSnapMarginChanged(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnUpdateSnapMarginSizeUI(CCmdUI* pCmdUI); afx_msg void OnAutoCreateKeyChanged(); afx_msg void OnKeyAll(); afx_msg void OnZeroAll(); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); afx_msg void OnDestroy(); CFacialEdContext* m_pContext; CJoystickCtrl m_ctrl; CXTPToolBar m_toolbar; CXTPControlButton* m_pFreezeLayoutButton; CXTPControlButton* m_pAutoCreateKeyButton; typedef std::vector<int> SnapMarginList; SnapMarginList m_snapMargins; int m_displayedSnapMargin; bool m_bIgnoreSplineChangeEvents; HACCEL m_hAccelerators; COleDropTarget* m_pDropTarget; }; #endif // CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALJOYSTICKDIALOG_H
1,049
2,962
<filename>tests/scripts/thread-cert/pktverify/layer_fields_container.py<gh_stars>1000+ #!/usr/bin/env python3 # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # from pyshark.packet.packet import Packet as RawPacket from pktverify.layer_fields import get_layer_field, check_layer_field_exists class LayerFieldsContainer(object): """ Represents a layer field container. """ def __init__(self, packet: RawPacket, path: str): assert isinstance(packet, RawPacket) assert isinstance(path, str) self._packet = packet self._path = path def __getattr__(self, name): subpath = self._path + '.' + name v = get_layer_field(self._packet, subpath) setattr(self, name, v) return v def has(self, subpath): """ Returns if the layer field container has a sub layer field or container. :param subpath: The sub path to the layer field or container. """ subpath = self._path + '.' + subpath return check_layer_field_exists(self._packet, subpath) is not None def __getitem__(self, item): return getattr(self, item) @property def full_path(self): """ Returns the full path to this layer field container. """ return self._path @property def field_path(self): """ Returns the field that references to this layer field container. """ secs = self._path.split('.') assert len(secs) >= 2 return '.'.join(secs[1:]) def __bool__(self): """ Returns if this layer field container exists in the packet. """ return check_layer_field_exists(self._packet, self._path)
1,144
1,652
#pragma once #include <optional.h> #include <chrono> #include <string> struct Timer { using Clock = std::chrono::high_resolution_clock; static long long GetCurrentTimeInMilliseconds(); // Creates a new timer. A timer is always running. Timer(); // Returns elapsed microseconds. long long ElapsedMicroseconds() const; // Returns elapsed microseconds and restarts/resets the timer. long long ElapsedMicrosecondsAndReset(); // Restart/reset the timer. void Reset(); // Resets timer and prints a message like "<foo> took 5ms" void ResetAndPrint(const std::string& message); // Pause the timer. void Pause(); // Resume the timer after it has been paused. void Resume(); // Raw start time. optional<std::chrono::time_point<Clock>> start_; // Elapsed time. long long elapsed_ = 0; }; struct ScopedPerfTimer { ScopedPerfTimer(const std::string& message); ~ScopedPerfTimer(); Timer timer_; std::string message_; };
304
799
<gh_stars>100-1000 import unittest from Base64EncodeV2 import encode class Base64EncodeV2(unittest.TestCase): def test_encode_japanese(self): """ Given: Japanese characters. When: Encoding the characters using Base64. Then: Validate that the human readable and context outputs are properly formatted and that the input was encoded correctly. """ input = '日本語' expected_result = '5pel5pys6Kqe' actual_result, output = encode(input) assert actual_result == expected_result assert output == { 'Base64': { 'encoded': expected_result } } def test_encode_english(self): """ Given: English characters. When: Encoding the characters using Base64. Then: Validate that the human readable and context outputs are properly formatted and that the input was encoded correctly. """ input = 'test' expected_result = 'dGVzdA==' actual_result, output = encode(input) assert actual_result == expected_result assert output == { 'Base64': { 'encoded': expected_result } } def test_encode_german(self): """ Given: German characters. When: Encoding the characters using Base64. Then: Validate that the human readable and context outputs are properly formatted and that the input was encoded correctly. """ input = 'äpfel' expected_result = 'w6RwZmVs' actual_result, output = encode(input) assert actual_result == expected_result assert output == { 'Base64': { 'encoded': expected_result } } def test_encode_hebrew(self): """ Given: Hebrew characters. When: Encoding the characters using Base64. Then: Validate that the human readable and context outputs are properly formatted and that the input was encoded correctly. """ input = 'בדיקה' expected_result = '15HXk9eZ16fXlA==' actual_result, output = encode(input) assert actual_result == expected_result assert output == { 'Base64': { 'encoded': expected_result } } def test_encode_arabic(self): """ Given: Arabic characters. When: Encoding the characters using Base64. Then: Validate that the human readable and context outputs are properly formatted and that the input was encoded correctly. """ input = 'امتحان' expected_result = '2KfZhdiq2K3Yp9mG' actual_result, output = encode(input) assert actual_result == expected_result assert output == { 'Base64': { 'encoded': expected_result } }
1,416
506
// https://uva.onlinejudge.org/external/117/11749.pdf #include<bits/stdc++.h> using namespace std; using iii=tuple<int,int,int>; using vi=vector<int>; using vvi=vector<vi>; using viii=vector<iii>; int main(){ ios::sync_with_stdio(0); cin.tie(0); for(;;){ int n,m,u,v,w,W=-2147483648,M=0; cin>>n>>m; if(!n)break; viii e(m); for(int i=0;i<m;i++){ cin>>u>>v>>w; u--;v--; W=max(W,w); e[i]=make_tuple(u,v,w); } vvi g(n); for (iii &x:e){ tie(u,v,w)=x; if(w==W){ g[u].push_back(v); g[v].push_back(u); } } vi s(n); function<void(int)>dfs=[&](int u){ s[u]=1; for(int v:g[u]) if(!s[v]){ dfs(v); s[u]+=s[v]; } }; for(int i=0;i<n;i++) if(!s[i]) dfs(i); for(int i=0;i<n;i++)M=max(M,s[i]); cout<<M<<"\n"; } }
562