max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,127 | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <iterator>
#include <limits>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "engines_util/test_case.hpp"
#include "engines_util/test_engines.hpp"
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "onnx_import/onnx.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/ndarray.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
using namespace ngraph;
OPENVINO_SUPPRESS_DEPRECATED_START
static std::string s_manifest = "${MANIFEST}";
static std::string s_device = test::backend_name_to_device("${BACKEND_NAME}");
NGRAPH_TEST(${BACKEND_NAME}, onnx_model_affine) {
auto function = onnx_import::import_onnx_model(file_util::path_join(SERIALIZED_ZOO, "onnx/affine.onnx"));
// input/output shape (1, 3)
auto input = test::NDArray<float, 2>{{{0.f, 1.f, 2.f}}}.get_vector();
auto expected_output = test::NDArray<float, 2>{{{50.f, 50.5f, 51.f}}}.get_vector();
auto test_case = test::TestCase(function, s_device);
test_case.add_input(Shape{1, 3}, input);
test_case.add_expected_output(Shape{1, 3}, expected_output);
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, onnx_model_crop) {
auto function = onnx_import::import_onnx_model(file_util::path_join(SERIALIZED_ZOO, "onnx/crop.onnx"));
// input shape (1, 1, 4, 4)
auto input = test::NDArray<float, 4>({{{{19.f, 20.f, 21.f, 22.f},
{23.f, 24.f, 25.f, 26.f},
{27.f, 28.f, 29.f, 30.f},
{31.f, 32.f, 33.f, 34.f}}}})
.get_vector();
// output shape (1, 1, 2, 2)
auto expected_output = test::NDArray<float, 4>{{{{24.f, 25.f}, {28.f, 29.f}}}}.get_vector();
auto test_case = test::TestCase(function, s_device);
test_case.add_input(Shape{1, 1, 4, 4}, input);
test_case.add_expected_output(Shape{1, 1, 2, 2}, expected_output);
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, onnx_model_crop_with_scale) {
auto function = onnx_import::import_onnx_model(file_util::path_join(SERIALIZED_ZOO, "onnx/crop_with_scale.onnx"));
// input shape (1, 1, 4, 4)
auto input = test::NDArray<float, 4>({{{{19.f, 20.f, 21.f, 22.f},
{23.f, 24.f, 25.f, 26.f},
{27.f, 28.f, 29.f, 30.f},
{31.f, 32.f, 33.f, 34.f}}}})
.get_vector();
// output shape (1, 1, 2, 3)
auto expected_output = test::NDArray<float, 4>{{{{24.f, 25.f, 26.f}, {28.f, 29.f, 30.f}}}}.get_vector();
auto test_case = test::TestCase(function, s_device);
test_case.add_input(Shape{1, 1, 4, 4}, input);
test_case.add_expected_output(Shape{1, 1, 2, 3}, expected_output);
test_case.run();
}
| 1,517 |
335 | {
"word": "Blur",
"definitions": [
"A thing that cannot be seen or heard clearly.",
"Something remembered or perceived indistinctly, typically because it happened very fast."
],
"parts-of-speech": "Noun"
} | 86 |
3,296 | <filename>lib/nnc/cmd/tanh/ccv_nnc_tanh.c
#include "ccv.h"
#include "nnc/ccv_nnc.h"
#include "nnc/ccv_nnc_easy.h"
#include "nnc/ccv_nnc_internal.h"
static int _ccv_nnc_tanh_allow_first_replace(const int input_idx, const int input_size, const int output_idx, const int output_size)
{
return input_idx == 0 && output_idx == 0;
}
static int _ccv_nnc_tanh_forw_bitmask(const int input_size, const int output_size, const uint64_t* const input_bitmasks, const int input_bitmask_size, const uint64_t* const output_bitmasks, const int output_bitmask_size)
{
if ((input_bitmasks[0] & 1u) == 1u && output_bitmasks[0] == 1u)
return 1;
return 0;
}
static int _ccv_nnc_tanh_back_bitmask(const int input_size, const int output_size, const uint64_t* const input_bitmasks, const int input_bitmask_size, const uint64_t* const output_bitmasks, const int output_bitmask_size)
{
// gradient, [x], y
if ((input_bitmasks[0] & 5u) == 5u && (output_bitmasks[0] & 1u) == 1u)
return 1;
return 0;
}
static void _ccv_nnc_tanh_tensor_auto_forw(const ccv_nnc_cmd_param_t cmd, const ccv_nnc_tensor_param_t* const inputs, const int input_size, const ccv_nnc_hint_t hint, ccv_nnc_tensor_param_t* const outputs, const int output_size)
{
assert(input_size == 1);
assert(output_size == 1);
outputs[0] = inputs[0];
}
static void _ccv_nnc_tanh_tensor_auto_back(const ccv_nnc_cmd_param_t cmd, const ccv_nnc_tensor_param_t* const inputs, const int input_size, const ccv_nnc_hint_t hint, ccv_nnc_tensor_param_t* const outputs, const int output_size)
{
assert(input_size >= 3);
assert(output_size >= 1);
outputs[0] = inputs[2];
}
REGISTER_COMMAND(CCV_NNC_TANH_FORWARD)(ccv_nnc_cmd_registry_t* const registry)
FIND_BACKEND(ccv_nnc_tanh_cpu_ref.c, gpu/ccv_nnc_tanh_gpu_cudnn.cu)
{
registry->bitmask = _ccv_nnc_tanh_forw_bitmask;
registry->allow_inplace = _ccv_nnc_tanh_allow_first_replace;
registry->tensor_auto = _ccv_nnc_tanh_tensor_auto_forw;
}
REGISTER_COMMAND(CCV_NNC_TANH_BACKWARD)(ccv_nnc_cmd_registry_t* const registry)
FIND_BACKEND(ccv_nnc_tanh_cpu_ref.c, gpu/ccv_nnc_tanh_gpu_cudnn.cu)
{
registry->flags = CCV_NNC_CMD_ATTR_NULL_IS_ONES;
registry->bitmask = _ccv_nnc_tanh_back_bitmask;
registry->allow_inplace = _ccv_nnc_tanh_allow_first_replace;
registry->tensor_auto = _ccv_nnc_tanh_tensor_auto_back;
}
//@REGISTER_EASY_COMMAND_MACRO(CCV_NNC_TANH_FORWARD)
#define CMD_TANH_FORWARD() ccv_nnc_cmd(CCV_NNC_TANH_FORWARD, 0, ccv_nnc_cmd_auto, 0)
//@REGISTER_EASY_COMMAND_MACRO(CCV_NNC_TANH_BACKWARD)
#define CMD_TANH_BACKWARD() ccv_nnc_cmd(CCV_NNC_TANH_BACKWARD, 0, ccv_nnc_cmd_auto, 0)
| 1,171 |
664 | <filename>src/3rdparty/torrent-rasterbar/test/bittorrent_peer.hpp
/*
Copyright (c) 2016, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifndef BITTORRENT_PEER_HPP
#define BITTORRENT_PEER_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/sha1_hash.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/torrent_info.hpp"
#include "test.hpp" // for EXPORT
#include <boost/function.hpp>
using namespace libtorrent;
struct EXPORT peer_conn
{
enum peer_mode_t
{ uploader, downloader, idle };
peer_conn(io_service& ios
, boost::function<void(int, char const*, int)> on_msg
, libtorrent::torrent_info const& ti
, libtorrent::tcp::endpoint const& ep
, peer_mode_t mode);
void start_conn();
void on_connect(error_code const& ec);
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred);
void on_handshake2(error_code const& ec, size_t bytes_transferred);
void write_have_all();
void on_have_all_sent(error_code const& ec, size_t bytes_transferred);
bool write_request();
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred);
void close(char const* fmt, error_code const& ec);
void work_download();
void on_msg_length(error_code const& ec, size_t bytes_transferred);
void on_message(error_code const& ec, size_t bytes_transferred);
bool verify_piece(int piece, int start, char const* ptr, int size);
void write_piece(int piece, int start, int length);
void write_have(int piece);
void abort();
private:
tcp::socket s;
char write_buf_proto[100];
boost::uint32_t write_buffer[17*1024/4];
boost::uint32_t buffer[17*1024/4];
peer_mode_t m_mode;
torrent_info const& m_ti;
int read_pos;
boost::function<void(int, char const*, int)> m_on_msg;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
std::vector<int> suggested_pieces;
std::vector<int> allowed_fast;
bool choked;
int current_piece; // the piece we're currently requesting blocks from
bool m_current_piece_is_allowed;
int block;
int const m_blocks_per_piece;
int outstanding_requests;
// if this is true, this connection is a seed
bool fast_extension;
int blocks_received;
int blocks_sent;
time_point start_time;
time_point end_time;
tcp::endpoint endpoint;
bool restarting;
};
#endif
| 1,292 |
463 | <reponame>jasnzhuang/Personal-Homework
#include "generator.h"
#include "delaunay.h"
#include "minimum_spanning_tree.h"
#include "validate.h"
#include "visualization.h"
#include <boost/program_options.hpp>
using namespace boost::program_options;
int main(int argc, char *argv[])
{
//set generate option
int GENERATE_CASE = 1;
//set the filename to save these points' & graph's data
std::string PREFIX, SUFFIX;
std::string POINTS_FILENAME;
std::string TRIANGULATION_FILENAME;
std::string VORONOI_FILENAME;
std::string MST_FILENAME;
//save points into this container
std::vector<Simple_Point> raw_data;
//save trangulation information into this container
std::vector<Edge> triangulation_data;
//save voronoi diagram infomation into this container
std::vector<std::pair<Simple_Point, Simple_Point> >voronoi_data;
//save mst infomation into this container
std::vector<Edge> mst_data;
//read from command line
try
{
options_description desc("Options");
desc.add_options()
("help,h", "display this help and exit")
("number,n", value<int>(&Generator::TOTAL_NUMBER_OF_POINTS)->default_value(10000), "number of points")
("circle,c", "reset generation method to random in a circle, default: random in full square")
("test,t", value<std::string>(&PREFIX)->default_value("../../testcase/test/"), "test mode & set file path & read data from data.txt")
("range,r", value<int>(&Generator::MAX_COORDINATE)->default_value(10000), "coordinate range [0, number)")
("distance,d", value<ld>(&Generator::MIN_DISTANCE)->default_value(1e-3), "minimum distance between each pair of points")
("img-size,i", value<int>(&Visualization::IMAGE_SIZE)->default_value(2000), "size of image")
("suffix,s", value<std::string>(&SUFFIX)->default_value("png"), "set the suffix of output image")
("window,w", "display the window")
("voronoi,v", "output voronoi diagram infomation");
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help"))
{
std::cout << "Delaunay triangulation for calculating Euclidean distance minimum spanning tree" << std::endl;
std::cout << "Made by n+e\t2017-04" << std::endl;
std::cout << std::endl;
std::cout << desc << std::endl;
std::cout << "Examples:" << std::endl;
std::cout << "Generate new testcase in default file path, 10 points in [0,10), save in jpg file, and show window:" << std::endl;
std::cout << "\t./main -n 10 -r 10 -s jpg -w" << std::endl;
std::cout << "Use circle-shape testcase in file \"../../testcase/circle_100000/\" and output voronoi message:" << std::endl;
std::cout << "\t./main -t ../../testcase/circle_100000/ -v" << std::endl << std::endl;
return 0;
}
if (Generator::TOTAL_NUMBER_OF_POINTS <= 0 || Generator::TOTAL_NUMBER_OF_POINTS >= 5000000)
{
std::cerr << "Number of points is invalid!" << std::endl;
return 1;
}
if (Visualization::IMAGE_SIZE <= 0 || Visualization::IMAGE_SIZE > 5000)
{
std::cerr << "Size of image is invalid!" << std::endl;
return 1;
}
if (Generator::MAX_COORDINATE <= 1)
{
std::cerr << "max coordinate is invalid!" << std::endl;
return 1;
}
if (Generator::MIN_DISTANCE <= 0)
{
std::cerr << "min distance is invalid!" << std::endl;
return 1;
}
if (vm.count("circle"))
Generator::METHOD_CASE = 1;
if (vm.count("voronoi"))
Delaunay_Triangulation::VORONOI_CASE = 1;
if (PREFIX != "../../testcase/test/")
{
GENERATE_CASE = 0;
if (PREFIX[PREFIX.length() - 1] != '/')
PREFIX += '/';
}
POINTS_FILENAME = PREFIX + "data.txt";
TRIANGULATION_FILENAME = PREFIX + "triangulation.txt";
VORONOI_FILENAME = PREFIX + "voronoi.txt";
MST_FILENAME = PREFIX + "mst.txt";
//generate data
if (GENERATE_CASE != 0)
raw_data = Generator().Save(POINTS_FILENAME);
else
{
TIME_BEGIN("Read data from data.txt")
std::ifstream in;
in.open(POINTS_FILENAME.c_str());
ld x, y;
Generator::MAX_COORDINATE = 0;
while (in >> x >> y)
{
raw_data.push_back(Simple_Point(x, y));
if (Generator::MAX_COORDINATE < x)Generator::MAX_COORDINATE = x;
if (Generator::MAX_COORDINATE < y)Generator::MAX_COORDINATE = y;
}
std::sort(raw_data.begin(), raw_data.end());
Generator::TOTAL_NUMBER_OF_POINTS = raw_data.size();
in.close();
TIME_END
}
//calculate triangulation using CGAL library
Delaunay_Triangulation cgal_dt(raw_data);
cgal_dt.Save(TRIANGULATION_FILENAME, VORONOI_FILENAME, triangulation_data, voronoi_data);
//calculate mst with kruskal
MST mymst(triangulation_data);
mst_data = mymst.Save(MST_FILENAME);
//check delaunay triangulation
My_Delaunay myd(raw_data);
//check mst with prim
Prim prim(raw_data);
//visualize the result
Visualization visual(vm.count("window"), PREFIX, SUFFIX, raw_data, triangulation_data, voronoi_data, mst_data);
}
catch (const error &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
| 2,666 |
1,957 | {"username": "<@U407ABLLW|alice>", "subtype": "file_share", "text": "<@U407ABLLW|alice> shared a file: <https://weeslacktest.slack.com/files/alice/F3YTCL8TA/some_post_here|some post here>", "upload": false, "ts": "1485975978.000012", "display_as_bot": false, "user": "U407ABLLW", "file": {"filetype": "space", "channels": ["C407ABS94"], "display_as_bot": false, "id": "F3YTCL8TA", "size": 73, "title": "some post here", "url_private": "https://files.slack.com/files-pri/T3YS5EAL9-F3YTCL8TA/some_post_here", "ims": [], "state": "locked", "editor": "U407ABLLW", "preview": null, "external_type": "", "username": "", "updated": 1485975959, "timestamp": 1485975967, "public_url_shared": false, "editable": true, "url_private_download": "https://files.slack.com/files-pri/T3YS5EAL9-F3YTCL8TA/download/some_post_here", "user": "U407ABLLW", "groups": [], "is_public": false, "last_editor": "U407ABLLW", "pretty_type": "Post", "is_external": false, "mimetype": "text/plain", "permalink_public": "https://slack-files.com/T3YS5EAL9-F3YTCL8TA-9d9391a713", "permalink": "https://weeslacktest.slack.com/files/alice/F3YTCL8TA/some_post_here", "name": "some_post_here", "created": 1485975959, "comments_count": 0, "mode": "space"}, "team": "T3YS5EAL9", "wee_slack_metadata": {"team": "d80c2b6c3127dbb1991917394ed219e8212a2606"}, "type": "message", "channel": "C407ABS94", "bot_id": null}
| 568 |
1,256 | <gh_stars>1000+
import unittest
from . utils import TranspileTestCase
class TestJs2Py(TranspileTestCase):
def js2py_test(self, decl, check, result):
self.assertJavaScriptExecution(
"""
from harness import testfunc
val = testfunc()
%s
print("Done.")
""" % check,
js={
'harness': """
var harness = function(mod) {
mod.testfunc = function() {
%s
return batavia.types.js2py(obj)
};
return mod;
}({});
""" % decl
},
out=result,
)
def test_bool(self):
self.js2py_test(
decl="""
var obj = 42;
""",
check="""
print('Val is a %s = %s' % (type(val), val))
""",
result="""
Val is a <class 'int'> = 42
Done.
"""
)
def test_int(self):
self.js2py_test(
decl="""
var obj = 42;
""",
check="""
print('Val is a %s = %s' % (type(val), val))
""",
result="""
Val is a <class 'int'> = 42
Done.
"""
)
def test_float(self):
self.js2py_test(
decl="""
var obj = 42;
""",
check="""
print('Val is a %s = %s' % (type(val), val))
""",
result="""
Val is a <class 'int'> = 42
Done.
"""
)
def test_list(self):
self.js2py_test(
decl="""
var obj = [true, 42, 3.14159, 'value1', [false, 37]];
""",
check="""
print('Val is a %s = %s' % (type(val), val))
""",
result="""
Val is a <class 'list'> = [True, 42, 3.14159, 'value1', [False, 37]]
Done.
"""
)
def test_dict(self):
self.js2py_test(
decl="""
var obj = {
'bool_value': true,
'integer_value': 42,
'float_value': 3.14159,
'string_value': 'value1',
'list_value': [false, 37]
};
""",
check="""
print('Val is a %s, with %s items' % (type(val), len(val)))
print('boolean:', val['bool_value'])
print('integer:', val['integer_value'])
print('float:', val['float_value'])
print('string:', val['string_value'])
print('list:', val['list_value'])
""",
result="""
Val is a <class 'dict'>, with 5 items
boolean: True
integer: 42
float: 3.14159
string: value1
list: [False, 37]
Done.
"""
)
| 1,874 |
412 | <filename>gld/gld.h
/*
Copyright 2018 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GLD_H
#define GLD_H
#include <curses.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libcl/cl.h"
#include "libcm/cm.h"
#include "libgraph/graph.h"
#include "libgraphdb/graphdb.h"
extern char const gld_build_version[];
typedef struct gld_request_data {
graphdb_request_id d_most_recent_id;
unsigned int d_can_be_empty : 1;
unsigned int d_sent : 1;
} gld_request_data;
typedef struct gld_primitive {
graph_guid pr_guid;
struct gld_primitive *pr_next;
struct gld_primitive *pr_head;
struct gld_primitive **pr_tail;
} gld_primitive;
/* Overall system state.
*/
typedef struct gld_handle {
cl_handle *gld_cl;
cm_handle *gld_cm;
graphdb_handle *gld_graphdb;
/* of gld_request_data */
cm_hashtable *gld_request;
cm_hashtable *gld_var;
long gld_timeout;
size_t gld_outstanding;
bool gld_print_answers;
bool gld_passthrough;
} gld_handle;
/* gld-primitive.c */
void gld_primitive_free(gld_handle *, gld_primitive *);
void gld_primitive_free_contents(gld_handle *, gld_primitive *);
gld_primitive *gld_primitive_alloc(gld_handle *);
void gld_primitive_append(gld_handle *gld, gld_primitive *parent,
gld_primitive *child);
size_t gld_primitive_n(gld_handle *, gld_primitive *pr);
gld_primitive *gld_primitive_nth(gld_handle *gld, gld_primitive *pr, size_t n);
void gld_primitive_set_guid(gld_handle *gld, gld_primitive *pr,
graph_guid const *guid);
void gld_primitive_set_nil(gld_handle *, gld_primitive *);
int gld_primitive_is_list(gld_handle *, gld_primitive *);
/* gld-request.c */
gld_request_data *gld_request_alloc(gld_handle *_gld, char const *_name_s,
char const *_name_e);
int gld_request_send(gld_handle *_gld, gld_request_data *_id,
char const *_request_s, char const *_request_e);
void gld_request_wait(gld_handle *_gld, char const *_name_s,
char const *_name_e);
void gld_request_wait_any(gld_handle *);
size_t gld_request_outstanding(gld_handle *);
/* gld-var.c */
gld_primitive *gld_var_create(gld_handle *gld, char const *name_s,
char const *name_e);
graph_guid const *gld_var_lookup(gld_handle *gld, char const *name_s,
char const *name_e);
#endif /* GLD_H */
| 1,286 |
369 | // Copyright (c) 2017-2022, Mudit<NAME>. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "bsp.hpp"
#include "board.h"
#include "drivers/gpio/DriverGPIO.hpp"
#include <board/BoardDefinitions.hpp>
namespace
{
void board_power_off()
{
/// No memory allocation here as this specific GPIO was initialized at the startup. We are just grabbing here a
/// reference to the already existing object.
using namespace drivers;
auto gpio_power = DriverGPIO::Create(static_cast<GPIOInstances>(BoardDefinitions::POWER_SWITCH_HOLD_GPIO),
DriverGPIOParams{});
gpio_power->WritePin(static_cast<uint32_t>(BoardDefinitions::POWER_SWITCH_HOLD_BUTTON), 0);
}
void board_reset()
{
NVIC_SystemReset();
}
} // namespace
namespace bsp
{
void board_exit(rebootState state)
{
switch (state) {
case rebootState::none:
break;
case rebootState::poweroff:
board_power_off();
break;
case rebootState::reboot:
board_reset();
break;
}
while (true) {}
}
} // namespace bsp
| 548 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(WEBLAYER_MANUAL_JNI_REGISTRATION)
#include "base/android/library_loader/library_loader_hooks.h" // nogncheck
#include "weblayer/browser/java/jni/WebViewCompatibilityHelperImpl_jni.h" // nogncheck
#include "weblayer/browser/java/weblayer_jni_registration.h" // nogncheck
#endif
namespace weblayer {
namespace {
#if defined(WEBLAYER_MANUAL_JNI_REGISTRATION)
void RegisterNonMainDexNativesHook() {
RegisterNonMainDexNatives(base::android::AttachCurrentThread());
}
#endif
} // namespace
bool MaybeRegisterNatives() {
#if defined(WEBLAYER_MANUAL_JNI_REGISTRATION)
JNIEnv* env = base::android::AttachCurrentThread();
if (Java_WebViewCompatibilityHelperImpl_requiresManualJniRegistration(env)) {
if (!RegisterMainDexNatives(env))
return false;
base::android::SetNonMainDexJniRegistrationHook(
RegisterNonMainDexNativesHook);
}
#endif
return true;
}
} // namespace weblayer
| 375 |
2,691 | <gh_stars>1000+
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from client_interface.djinni
#pragma once
#include "../../handwritten-src/cpp/optional.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace testsuite {
struct ClientReturnedRecord;
/** Client interface */
class ClientInterface {
public:
virtual ~ClientInterface() {}
/** Returns record of given string */
virtual ClientReturnedRecord get_record(int64_t record_id, const std::string & utf8string, const std::experimental::optional<std::string> & misc) = 0;
virtual double identifier_check(const std::vector<uint8_t> & data, int32_t r, int64_t jret) = 0;
virtual std::string return_str() = 0;
virtual std::string meth_taking_interface(const std::shared_ptr<ClientInterface> & i) = 0;
virtual std::string meth_taking_optional_interface(const std::shared_ptr<ClientInterface> & i) = 0;
};
} // namespace testsuite
| 319 |
552 | #include <catch2/catch.hpp>
#include <EtFramework/stdafx.h>
#include <mainTesting.h>
#include <EtCore/FileSystem/FileUtil.h>
#include <EtCore/FileSystem/Entry.h>
#include <EtCore/IO/JsonParser.h>
#include <EtEditor/Import/GLTF.h>
using namespace et;
std::string const fileName = "Box.gltf";
std::string const glbFileName = "Corset.glb";
TEST_CASE("Parse GLTF json", "[gltf]")
{
std::string baseDir = global::g_UnitTestDir + "Helper/";
core::File* input = new core::File(baseDir+fileName, nullptr);
REQUIRE(input->Open(core::FILE_ACCESS_MODE::Read) == true);
std::vector<uint8> binaryContent = input->Read();
std::string extension = input->GetExtension();
delete input;
input = nullptr;
REQUIRE(binaryContent.size() > 0);
core::JSON::Parser parser = core::JSON::Parser(core::FileUtil::AsText(binaryContent));
core::JSON::Object* root = parser.GetRoot();
REQUIRE(root != nullptr);
edit::glTF::Dom dom;
REQUIRE(edit::glTF::ParseGlTFJson(root, dom) == true);
}
TEST_CASE("Parse GLB asset", "[gltf]")
{
std::string baseDir = global::g_UnitTestDir + "Helper/";
core::File* input = new core::File(baseDir + glbFileName, nullptr);
REQUIRE(input->Open(core::FILE_ACCESS_MODE::Read) == true);
std::vector<uint8> binaryContent = input->Read();
REQUIRE(binaryContent.size() > 0);
edit::glTF::glTFAsset asset;
REQUIRE(edit::glTF::ParseGLTFData(binaryContent, input->GetPath(), input->GetExtension(), asset) == true);
delete input;
input = nullptr;
} | 550 |
2,151 | <gh_stars>1000+
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/frame/hosts_using_features.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
TEST(HostsUsingFeaturesTest, countName) {
HostsUsingFeatures hosts_using_features;
hosts_using_features.CountName(HostsUsingFeatures::Feature::kEventPath,
"test 1");
EXPECT_EQ(1u, hosts_using_features.ValueByName().size());
hosts_using_features.CountName(
HostsUsingFeatures::Feature::kElementCreateShadowRoot, "test 1");
EXPECT_EQ(1u, hosts_using_features.ValueByName().size());
hosts_using_features.CountName(HostsUsingFeatures::Feature::kEventPath,
"test 2");
EXPECT_EQ(2u, hosts_using_features.ValueByName().size());
EXPECT_TRUE(hosts_using_features.ValueByName().at("test 1").Get(
HostsUsingFeatures::Feature::kEventPath));
EXPECT_TRUE(hosts_using_features.ValueByName().at("test 1").Get(
HostsUsingFeatures::Feature::kElementCreateShadowRoot));
EXPECT_FALSE(hosts_using_features.ValueByName().at("test 1").Get(
HostsUsingFeatures::Feature::kDocumentRegisterElement));
EXPECT_TRUE(hosts_using_features.ValueByName().at("test 2").Get(
HostsUsingFeatures::Feature::kEventPath));
EXPECT_FALSE(hosts_using_features.ValueByName().at("test 2").Get(
HostsUsingFeatures::Feature::kElementCreateShadowRoot));
EXPECT_FALSE(hosts_using_features.ValueByName().at("test 2").Get(
HostsUsingFeatures::Feature::kDocumentRegisterElement));
hosts_using_features.Clear();
}
} // namespace blink
| 634 |
311 | <reponame>jayvdb/django-oscar-api
from django.conf import settings
from rest_framework.permissions import (
BasePermission,
IsAuthenticated,
DjangoModelPermissions,
)
from oscarapi.basket.operations import request_allows_access_to
class IsOwner(IsAuthenticated):
"""
Permission that checks if this object has a foreign key pointing to the
authenticated user of this request
"""
def has_object_permission(self, request, view, obj):
return obj.user == request.user
class APIAdminPermission(DjangoModelPermissions):
"""
The permission for all the admin api views. You only get admin api access when:
- OSCARAPI_BLOCK_ADMIN_API_ACCESS is false
- you are a staff user (is_staff)
- you have any of the model permissions needed (view / add / change / delete)
Feel free to customize!
"""
perms_map = {
"GET": ["%(app_label)s.view_%(model_name)s"],
"OPTIONS": ["%(app_label)s.view_%(model_name)s"],
"HEAD": ["%(app_label)s.view_%(model_name)s"],
"POST": ["%(app_label)s.add_%(model_name)s"],
"PUT": ["%(app_label)s.change_%(model_name)s"],
"PATCH": ["%(app_label)s.change_%(model_name)s"],
"DELETE": ["%(app_label)s.delete_%(model_name)s"],
}
@staticmethod
def disallowed_by_setting_and_request(request):
return (
getattr(settings, "OSCARAPI_BLOCK_ADMIN_API_ACCESS", True)
or not request.user.is_staff
)
def has_permission(self, request, view):
if self.disallowed_by_setting_and_request(request):
return False
return super(APIAdminPermission, self).has_permission(request, view)
class RequestAllowsAccessTo(BasePermission):
def has_object_permission(self, request, view, obj):
return request_allows_access_to(request, obj)
| 744 |
577 | <reponame>rickynilsson/astroquery
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os.path
import os
import sys
import pytest
import requests
from requests import ReadTimeout
from astropy.table import Table
from astropy.units import arcsec, arcmin
from astropy.io import ascii
from astropy.coordinates import SkyCoord
try:
from regions import CircleSkyRegion
except ImportError:
pass
from ...xmatch import XMatch
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
@pytest.mark.remote_data
@pytest.mark.dependency(name='xmatch_up')
def test_is_xmatch_up():
try:
requests.get("http://cdsxmatch.u-strasbg.fr/xmatch/api/v1/sync")
except Exception as ex:
pytest.xfail("XMATCH appears to be down. Exception was: {0}".format(ex))
@pytest.mark.remote_data
@pytest.mark.dependency(depends=["xmatch_up"])
class TestXMatch:
# fixture only used here to save creating XMatch instances in each
# of the following test functions
@pytest.fixture
def xmatch(self):
return XMatch()
def test_xmatch_avail_tables(self, xmatch):
tables = xmatch.get_available_tables()
assert tables
# those example tables are from
# http://cdsxmatch.u-strasbg.fr/xmatch/doc/API-calls.html
assert 'II/311/wise' in tables
assert 'II/246/out' in tables
def test_xmatch_is_avail_table(self, xmatch):
assert xmatch.is_table_available('II/311/wise')
assert xmatch.is_table_available('II/246/out')
assert xmatch.is_table_available('vizier:II/311/wise')
assert not xmatch.is_table_available('blablabla')
def test_xmatch_query(self, xmatch):
with open(os.path.join(DATA_DIR, 'posList.csv'), 'r') as pos_list:
try:
table = xmatch.query(
cat1=pos_list, cat2='vizier:II/246/out', max_distance=5 * arcsec,
colRA1='ra', colDec1='dec')
except ReadTimeout:
pytest.xfail("xmatch query timed out.")
assert isinstance(table, Table)
assert table.colnames == [
'angDist', 'ra', 'dec', 'my_id', '2MASS', 'RAJ2000', 'DEJ2000',
'errHalfMaj', 'errHalfMin', 'errPosAng', 'Jmag', 'Hmag', 'Kmag',
'e_Jmag', 'e_Hmag', 'e_Kmag', 'Qfl', 'Rfl', 'X', 'MeasureJD']
assert len(table) == 11
http_test_table = self.http_test()
assert all(table == http_test_table)
def test_xmatch_query_astropy_table(self, xmatch):
datapath = os.path.join(DATA_DIR, 'posList.csv')
input_table = Table.read(datapath, format='ascii.csv')
try:
table = xmatch.query(
cat1=input_table, cat2='vizier:II/246/out', max_distance=5 * arcsec,
colRA1='ra', colDec1='dec')
except ReadTimeout:
pytest.xfail("xmatch query timed out.")
assert isinstance(table, Table)
assert table.colnames == [
'angDist', 'ra', 'dec', 'my_id', '2MASS', 'RAJ2000', 'DEJ2000',
'errHalfMaj', 'errHalfMin', 'errPosAng', 'Jmag', 'Hmag', 'Kmag',
'e_Jmag', 'e_Hmag', 'e_Kmag', 'Qfl', 'Rfl', 'X', 'MeasureJD']
assert len(table) == 11
http_test_table = self.http_test()
assert all(table == http_test_table)
@pytest.mark.skipif('regions' not in sys.modules,
reason="requires astropy-regions")
def test_xmatch_query_with_cone_area(self, xmatch):
try:
table = xmatch.query(
cat1='vizier:II/311/wise', cat2='vizier:II/246/out', max_distance=5 * arcsec,
area=CircleSkyRegion(center=SkyCoord(10, 10, unit='deg', frame='icrs'), radius=12 * arcmin))
except ReadTimeout:
pytest.xfail("xmatch query timed out.")
assert len(table) == 185
def http_test(self):
# this can be used to check that the API is still functional & doing as expected
infile = os.path.join(DATA_DIR, 'posList.csv')
outfile = os.path.join(DATA_DIR, 'http_result.csv')
os.system('curl -X POST -F request=xmatch -F distMaxArcsec=5 -F RESPONSEFORMAT=csv '
'-F cat1=@{1} -F colRA1=ra -F colDec1=dec -F cat2=vizier:II/246/out '
'http://cdsxmatch.u-strasbg.fr/xmatch/api/v1/sync > {0}'.
format(outfile, infile))
table = ascii.read(outfile, format='csv', fast_reader=False)
return table
| 2,053 |
373 | <filename>Platform/Intel/Vlv2TbltDevicePkg/PlatformDxe/AzaliaVerbTable.h
/*++
Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
--*/
UINT32 mAzaliaVerbTableData12[] = {
//
// Audio Verb Table - 0x80862805
//
// Pin Widget 5 - PORT B
0x20471C10,
0x20471D00,
0x20471E56,
0x20471F18,
// Pin Widget 6 - PORT C
0x20571C20,
0x20571D00,
0x20571E56,
0x20571F18,
// Pin Widget 7 - PORT D
0x20671C30,
0x20671D00,
0x20671E56,
0x20671F58
};
PCH_AZALIA_VERB_TABLE mAzaliaVerbTable[] = {
{
//
// VerbTable:
// Revision ID = 0xFF, support all steps
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0880
//
{
0x10EC0880, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000A, // Number of Rear Jacks = 10
0x0002 // Number of Front Jacks = 2
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// Revision ID >= 0x03
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x434D4980
//
{
0x434D4980, // Vendor ID/Device ID
0x0000, // SubSystem ID
0x00, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x0009, // Number of Rear Jacks = 9
0x0002 // Number of Front Jacks = 2
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// Lawndale Azalia Audio Codec Verb Table
// Revision ID = 0x00
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x11D41984
//
{
0x11D41984, // Vendor ID/Device ID
0x0000, // SubSystem ID
0x04, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x0009, // Number of Rear Jacks = 9
0x0002 // Number of Front Jacks = 2
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable:
// Revision ID = 0xFF, support all steps
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x11D41986
//
{
0x11D41986, // Vendor ID/Device ID
0x0001, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000A, // Number of Rear Jacks = 8
0x0002 // Number of Front Jacks = 2
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (for Slim River, FFDS3)
// Revision ID = 0x00
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0272
//
{
0x10EC0272, // Vendor ID/Device ID
0x0000, // SubSystem ID
0x00, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000E, // Number of Rear Jacks
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (for Buffalo Trail)
// Revision ID = 0x00
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0269
//
{
0x10EC0269, // Vendor ID/Device ID
0x0000, // SubSystem ID
0x00, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000A, // Number of Rear Jacks
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (RealTek ALC888)
// Revision ID = 0xFF
// Codec Verb Table For Redfort
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0888
//
{
0x10EC0888, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000B, // Number of Rear Jacks
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (RealTek ALC885)
// Revision ID = 0xFF
// Codec Verb Table For Redfort
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0885
//
{
0x10EC0885, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000B, // Number of Rear Jacks
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (IDT 92HD81)
// Revision ID = 0xFF
// Codec Vendor: 0x111D7605
//
{
0x111D76d5, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x0008, // Number of Rear Jacks
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (Intel VLV HDMI)
// Revision ID = 0xFF
// Codec Verb Table For EmeraldLake/LosLunas
// Codec Vendor: 0x80862804
//
{
0x80862882, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x02, // Front panel support (1=yes, 2=no)
0x0003, // Number of Rear Jacks
0x0000 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (RealTek ALC262)
// Revision ID = 0xFF, support all steps
// Codec Verb Table For AZALIA
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0262
//
{
0x10EC0262, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xFF, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000B, // Number of Rear Jacks = 11
0x0002 // Number of Front Jacks = 2
},
0 // Pointer to verb table data, need to be inited in the code.
},
{
//
// VerbTable: (RealTek ALC282)
// Revision ID = 0xff
// Codec Verb Table For Azalia on SharkBay-WhiteBluff refresh and Haswell ULT FFRD Harris Beach, WTM1, WTM2iCRB
// Codec Address: CAd value (0/1/2)
// Codec Vendor: 0x10EC0282
//
{
0x10EC0282, // Vendor ID/Device ID
0x0000, // SubSystem ID
0xff, // Revision ID
0x01, // Front panel support (1=yes, 2=no)
0x000C, // Number of Rear Jacks, 0x0010 for Harris Beach, 0x000B for WTM1 & WTM2iCRB
0x0002 // Number of Front Jacks
},
0 // Pointer to verb table data, need to be inited in the code.
}
};
| 4,121 |
568 | package com.jim.framework.rpc.registry;
import com.jim.framework.rpc.common.RpcURL;
import java.util.List;
/**
* Created by jiang on 2017/5/19.
*/
public interface DiscoveryService {
List<RpcURL> getUrls(String registryHost, int registryPort);
}
| 105 |
649 | package net.serenitybdd.screenplay.webtests;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.serenitybdd.screenplay.actions.Open;
import net.serenitybdd.screenplay.annotations.CastMember;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
@RunWith(SerenityRunner.class)
public class WhenAndyIsAnAnnotatedActorWithAnAutomaticallyAssignedBrowser {
@CastMember(driver = "chrome", options = "--headless")
Actor andy;
@Test
public void annotatedActorsAreInstantiatedAutomatically() {
assertThat(andy, notNullValue());
}
@Test
public void annotatedActorsCanInteractWithABrowser() {
andy.attemptsTo(
Open.url("classpath:/sample-web-site/index.html")
);
}
}
| 404 |
6,541 | <filename>tests/core/test_dynamic_cast.cpp
/*
* Copyright 2016 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdio.h>
struct Support {
virtual void f() { printf("f()\n"); }
};
struct Derived : Support {};
int main() {
Support* p = new Derived;
dynamic_cast<Derived*>(p)->f();
}
| 155 |
2,724 | <reponame>piejanssens/openui5<filename>src/sap.ui.fl/test/sap/ui/fl/qunit/testResources/condenser/renameMoveChanges.json
[
{
"id": "id_1580042266646_40_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Doc Number",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.530Z"
},
{
"id": "id_1580042289311_48_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.CompanyCode",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Code",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.534Z"
},
{
"id": "id_1580042301621_52_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Doc-Number",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.538Z"
},
{
"id": "id_1580042307367_53_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.CompanyCode",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "C-Code",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.539Z"
},
{
"id": "id_1580042325452_69_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Number",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.544Z"
},
{
"id": "id_1580048931092_47_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"sourceIndex": 0,
"targetIndex": 2
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-26T14:29:07.087Z"
},
{
"id": "id_1580048931092_48_moveControls",
"changeType": "moveControls",
"reference": "sap.ui.rta.test.Component",
"content": {
"movedElements": [
{
"selector": {
"id": "idMain1--GeneralLedgerDocument.Name",
"idIsLocal": true
},
"sourceIndex": 2,
"targetIndex": 1
}
],
"source": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
},
"target": {
"selector": {
"aggregation": "formElements",
"type": "sap.ui.comp.smartform.Group",
"id": "idMain1--GeneralLedgerDocument",
"idIsLocal": true
}
}
},
"selector": {
"id": "idMain1--MainForm",
"idIsLocal": true
},
"creation": "2020-01-26T14:29:07.087Z"
},
{
"id": "id_1580042336531_70_renameField",
"changeType": "renameField",
"reference": "sap.ui.rta.test.Component",
"content": {
"originalControlType": "sap.ui.comp.smartform.GroupElement"
},
"selector": {
"id": "idMain1--GeneralLedgerDocument.CompanyCode",
"idIsLocal": true
},
"texts": {
"fieldLabel": {
"value": "Code",
"type": "XFLD"
}
},
"creation": "2020-01-26T12:40:25.545Z"
}
]
| 2,151 |
2,281 | /*
* Copyright 2013-2021 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstring>
#include <iostream>
#include <memory>
#include <gtest/gtest.h>
#include "code_generation_test/car.h"
#include "code_generation_test/messageHeader.h"
#define CGT(name) code_generation_test_##name
#define SERIAL_NUMBER 1234u
#define MODEL_YEAR 2013
#define AVAILABLE (CGT(booleanType_T))
#define CODE (CGT(model_A))
#define CRUISE_CONTROL (true)
#define SPORTS_PACK (true)
#define SUNROOF (false)
static char VEHICLE_CODE[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
static char MANUFACTURER_CODE[] = { '1', '2', '3' };
static const char *MANUFACTURER = "Honda";
static const char *MODEL = "Civic VTi";
static const char *ACTIVATION_CODE = "deadbeef";
static const std::uint64_t encodedHdrSz = 8;
static const std::uint64_t encodedCarSz = 191;
class BoundsCheckTest : public testing::Test
{
protected:
std::uint64_t encodeHdr(char *buffer, std::uint64_t offset, std::uint64_t bufferLength)
{
if (!CGT(messageHeader_wrap)(&m_hdr, buffer, offset, 0, bufferLength))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(messageHeader_set_blockLength)(&m_hdr, CGT(car_sbe_block_length)());
CGT(messageHeader_set_templateId)(&m_hdr, CGT(car_sbe_template_id)());
CGT(messageHeader_set_schemaId)(&m_hdr, CGT(car_sbe_schema_id)());
CGT(messageHeader_set_version)(&m_hdr, CGT(car_sbe_schema_version)());
return CGT(messageHeader_encoded_length)();
}
std::uint64_t decodeHdr(char *buffer, std::uint64_t offset, std::uint64_t bufferLength)
{
if (!CGT(messageHeader_wrap)(&m_hdrDecoder, buffer, offset, 0, bufferLength))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(messageHeader_blockLength)(&m_hdrDecoder), CGT(car_sbe_block_length)());
EXPECT_EQ(CGT(messageHeader_templateId)(&m_hdrDecoder), CGT(car_sbe_template_id)());
EXPECT_EQ(CGT(messageHeader_schemaId)(&m_hdrDecoder), CGT(car_sbe_schema_id)());
EXPECT_EQ(CGT(messageHeader_version)(&m_hdrDecoder), CGT(car_sbe_schema_version)());
return CGT(messageHeader_encoded_length)();
}
std::uint64_t encodeCarRoot(char *buffer, std::uint64_t offset, std::uint64_t bufferLength)
{
if (!CGT(car_wrap_for_encode)(&m_car, buffer, offset, bufferLength))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_set_serialNumber)(&m_car, SERIAL_NUMBER);
CGT(car_set_modelYear)(&m_car, MODEL_YEAR);
CGT(car_set_available)(&m_car, AVAILABLE);
CGT(car_set_code)(&m_car, CODE);
CGT(car_put_vehicleCode)(&m_car, VEHICLE_CODE);
for (uint64_t i = 0; i < CGT(car_someNumbers_length)(); i++)
{
CGT(car_set_someNumbers_unsafe)(&m_car, i, (int32_t)(i));
}
CGT(optionalExtras) extras;
if (!CGT(car_extras)(&m_car, &extras))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(optionalExtras_clear)(&extras);
CGT(optionalExtras_set_cruiseControl)(&extras, CRUISE_CONTROL);
CGT(optionalExtras_set_sportsPack)(&extras, SPORTS_PACK);
CGT(optionalExtras_set_sunRoof)(&extras, SUNROOF);
CGT(engine) engine;
if (!CGT(car_engine)(&m_car, &engine))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(engine_set_capacity)(&engine, 2000);
CGT(engine_set_numCylinders)(&engine, (short)4);
CGT(engine_put_manufacturerCode)(&engine, MANUFACTURER_CODE);
CGT(boosterT) booster;
if (!CGT(engine_booster)(&engine, &booster))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(boosterT_set_boostType)(&booster, CGT(boostType_NITROUS));
CGT(boosterT_set_horsePower)(&booster, 200);
return CGT(car_encoded_length)(&m_car);
}
std::uint64_t encodeCarFuelFigures()
{
CGT(car_fuelFigures) fuelFigures;
if (!CGT(car_fuelFigures_set_count)(&m_car, &fuelFigures, 3))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_fuelFigures_set_speed)(&fuelFigures, 30);
CGT(car_fuelFigures_set_mpg)(&fuelFigures, 35.9f);
if (!CGT(car_fuelFigures_put_usageDescription)(&fuelFigures, "Urban Cycle", 11))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_fuelFigures_set_speed)(&fuelFigures, 55);
CGT(car_fuelFigures_set_mpg)(&fuelFigures, 49.0f);
if (!CGT(car_fuelFigures_put_usageDescription)(&fuelFigures, "Combined Cycle", 14))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_fuelFigures_set_speed)(&fuelFigures, 75);
CGT(car_fuelFigures_set_mpg)(&fuelFigures, 40.0f);
if (!CGT(car_fuelFigures_put_usageDescription)(&fuelFigures, "Highway Cycle", 13))
{
throw std::runtime_error(sbe_strerror(errno));
}
return CGT(car_encoded_length)(&m_car);
}
std::uint64_t encodeCarPerformanceFigures()
{
CGT(car_performanceFigures) perf_figs;
if (!CGT(car_performanceFigures_set_count)(&m_car, &perf_figs, 2))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_performanceFigures_next)(&perf_figs))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_set_octaneRating)(&perf_figs, (short)95);
CGT(car_performanceFigures_acceleration) acc;
if (!CGT(car_performanceFigures_acceleration_set_count)(&perf_figs, &acc, 3))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 30);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 4.0f);
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 60);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 7.5f);
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 100);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 12.2f);
if (!CGT(car_performanceFigures_next)(&perf_figs))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_set_octaneRating)(&perf_figs, (short)99);
if (!CGT(car_performanceFigures_acceleration_set_count)(&perf_figs, &acc, 3))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 30);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 3.8f);
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 60);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 7.1f);
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(car_performanceFigures_acceleration_set_mph)(&acc, 100);
CGT(car_performanceFigures_acceleration_set_seconds)(&acc, 11.8f);
return CGT(car_encoded_length)(&m_car);
}
std::uint64_t encodeCarManufacturerModelAndActivationCode()
{
if (!CGT(car_put_manufacturer)(&m_car, MANUFACTURER, (int)(strlen(MANUFACTURER))))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_put_model)(&m_car, MODEL, (int)(strlen(MODEL))))
{
throw std::runtime_error(sbe_strerror(errno));
}
if (!CGT(car_put_activationCode)(&m_car, ACTIVATION_CODE, (int)(strlen(ACTIVATION_CODE))))
{
throw std::runtime_error(sbe_strerror(errno));
}
return CGT(car_encoded_length)(&m_car);
}
std::uint64_t decodeCarRoot(char *buffer, const std::uint64_t offset, const std::uint64_t bufferLength)
{
if (!CGT(car_wrap_for_decode)(
&m_carDecoder,
buffer,
offset,
CGT(car_sbe_block_length)(),
CGT(car_sbe_schema_version)(),
bufferLength))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_serialNumber)(&m_carDecoder), SERIAL_NUMBER);
EXPECT_EQ(CGT(car_modelYear)(&m_carDecoder), MODEL_YEAR);
{
CGT(booleanType) out;
EXPECT_TRUE(CGT(car_available)(&m_carDecoder, &out));
EXPECT_EQ(out, AVAILABLE);
}
{
CGT(model) out;
EXPECT_TRUE(CGT(car_code)(&m_carDecoder, &out));
EXPECT_EQ(out, CODE);
}
EXPECT_EQ(CGT(car_someNumbers_length)(), 5u);
for (std::uint64_t i = 0; i < 5; i++)
{
EXPECT_EQ(CGT(car_someNumbers_unsafe)(&m_carDecoder, i), (int32_t)(i));
}
EXPECT_EQ(CGT(car_vehicleCode_length)(), 6u);
EXPECT_EQ(std::string(CGT(car_vehicleCode_buffer)(&m_carDecoder), 6), std::string(VEHICLE_CODE, 6));
CGT(optionalExtras) extras;
if (!CGT(car_extras)(&m_carDecoder, &extras))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_TRUE(CGT(optionalExtras_cruiseControl)(&extras));
EXPECT_TRUE(CGT(optionalExtras_sportsPack)(&extras));
EXPECT_FALSE(CGT(optionalExtras_sunRoof)(&extras));
CGT(engine) engine;
if (!CGT(car_engine)(&m_carDecoder, &engine))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(engine_capacity)(&engine), 2000);
EXPECT_EQ(CGT(engine_numCylinders)(&engine), 4);
EXPECT_EQ(CGT(engine_maxRpm)(), 9000);
EXPECT_EQ(CGT(engine_manufacturerCode_length)(), 3u);
EXPECT_EQ(std::string(CGT(engine_manufacturerCode_buffer)(&engine), 3), std::string(MANUFACTURER_CODE, 3));
EXPECT_EQ(CGT(engine_fuel_length)(), 6u);
EXPECT_EQ(std::string(CGT(engine_fuel)(), 6), "Petrol");
CGT(boosterT) booster;
if (!CGT(engine_booster)(&engine, &booster))
{
throw std::runtime_error(sbe_strerror(errno));
}
CGT(boostType) out;
EXPECT_TRUE(CGT(boosterT_boostType)(&booster, &out));
EXPECT_EQ(out, CGT(boostType_NITROUS));
EXPECT_EQ(CGT(boosterT_horsePower)(&booster), 200);
return CGT(car_encoded_length)(&m_carDecoder);
}
std::uint64_t decodeCarFuelFigures()
{
char tmp[256] = { 0 };
CGT(car_fuelFigures) fuelFigures;
if (!CGT(car_get_fuelFigures)(&m_carDecoder, &fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_fuelFigures_count)(&fuelFigures), 3u);
EXPECT_TRUE(CGT(car_fuelFigures_has_next)(&fuelFigures));
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_fuelFigures_speed)(&fuelFigures), 30);
EXPECT_EQ(CGT(car_fuelFigures_mpg)(&fuelFigures), 35.9f);
std::uint64_t bytesToCopy =
CGT(car_fuelFigures_get_usageDescription)(&fuelFigures, tmp, sizeof(tmp));
if (!bytesToCopy)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(bytesToCopy, 11u);
EXPECT_EQ(std::string(tmp, 11), "Urban Cycle");
EXPECT_TRUE(CGT(car_fuelFigures_has_next)(&fuelFigures));
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_fuelFigures_speed)(&fuelFigures), 55);
EXPECT_EQ(CGT(car_fuelFigures_mpg)(&fuelFigures), 49.0f);
bytesToCopy = CGT(car_fuelFigures_get_usageDescription)(&fuelFigures, tmp, sizeof(tmp));
if (!bytesToCopy)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(bytesToCopy, 14u);
EXPECT_EQ(std::string(tmp, 14), "Combined Cycle");
EXPECT_TRUE(CGT(car_fuelFigures_has_next)(&fuelFigures));
if (!CGT(car_fuelFigures_next)(&fuelFigures))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_fuelFigures_speed)(&fuelFigures), 75);
EXPECT_EQ(CGT(car_fuelFigures_mpg)(&fuelFigures), 40.0f);
bytesToCopy = CGT(car_fuelFigures_get_usageDescription)(&fuelFigures, tmp, sizeof(tmp));
if (!bytesToCopy)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(bytesToCopy, 13u);
EXPECT_EQ(std::string(tmp, 13), "Highway Cycle");
return CGT(car_encoded_length)(&m_carDecoder);
}
std::uint64_t decodeCarPerformanceFigures()
{
CGT(car_performanceFigures) perfFigs;
if (!CGT(car_get_performanceFigures)(&m_carDecoder, &perfFigs))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_count)(&perfFigs), 2u);
EXPECT_TRUE(CGT(car_performanceFigures_has_next)(&perfFigs));
if (!CGT(car_performanceFigures_next)(&perfFigs))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_octaneRating)(&perfFigs), 95);
CGT(car_performanceFigures_acceleration) acc;
if (!CGT(car_performanceFigures_get_acceleration)(&perfFigs, &acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_count)(&acc), 3u);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 30);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 4.0f);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 60);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 7.5f);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 100);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 12.2f);
EXPECT_TRUE(CGT(car_performanceFigures_has_next)(&perfFigs));
if (!CGT(car_performanceFigures_next)(&perfFigs))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_octaneRating)(&perfFigs), 99);
if (!CGT(car_performanceFigures_get_acceleration)(&perfFigs, &acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_count)(&acc), 3u);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 30);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 3.8f);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 60);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 7.1f);
EXPECT_TRUE(CGT(car_performanceFigures_acceleration_has_next)(&acc));
if (!CGT(car_performanceFigures_acceleration_next)(&acc))
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(CGT(car_performanceFigures_acceleration_mph)(&acc), 100);
EXPECT_EQ(CGT(car_performanceFigures_acceleration_seconds)(&acc), 11.8f);
return CGT(car_encoded_length)(&m_carDecoder);
}
std::uint64_t decodeCarManufacturerModelAndActivationCode()
{
char tmp[256] = { 0 };
std::uint64_t lengthOfField = CGT(car_get_manufacturer)(&m_carDecoder, tmp, sizeof(tmp));
if (!lengthOfField)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(lengthOfField, 5u);
EXPECT_EQ(std::string(tmp, 5), "Honda");
lengthOfField = CGT(car_get_model)(&m_carDecoder, tmp, sizeof(tmp));
if (!lengthOfField)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(lengthOfField, 9u);
EXPECT_EQ(std::string(tmp, 9), "Civic VTi");
lengthOfField = CGT(car_get_activationCode)(&m_carDecoder, tmp, sizeof(tmp));
if (!lengthOfField)
{
throw std::runtime_error(sbe_strerror(errno));
}
EXPECT_EQ(lengthOfField, 8u);
EXPECT_EQ(std::string(tmp, 8), "deadbeef");
EXPECT_EQ(CGT(car_encoded_length)(&m_carDecoder), encodedCarSz);
return CGT(car_encoded_length)(&m_carDecoder);
}
private:
CGT(messageHeader) m_hdr = {};
CGT(messageHeader) m_hdrDecoder = {};
CGT(car) m_car = {};
CGT(car) m_carDecoder = {};
};
class HeaderBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfHeader)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeHdr(buffer.get(), 0, length);
},
std::runtime_error);
}
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfHeader)
{
const int length = GetParam();
char encodeBuffer[8] = { 0 };
std::unique_ptr<char[]> buffer(new char[length]);
encodeHdr(encodeBuffer, 0, sizeof(encodeBuffer));
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeHdr(buffer.get(), 0, length);
},
std::runtime_error);
}
INSTANTIATE_TEST_SUITE_P(
HeaderLengthTest,
HeaderBoundsCheckTest,
::testing::Range(0, static_cast<int>(encodedHdrSz), 1));
class MessageBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfMessage)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeCarRoot(buffer.get(), 0, length);
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarManufacturerModelAndActivationCode();
},
std::runtime_error);
}
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfMessage)
{
const int length = GetParam();
char encodeBuffer[191] = { 0 };
std::unique_ptr<char[]> buffer(new char[length]);
encodeCarRoot(encodeBuffer, 0, sizeof(encodeBuffer));
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarManufacturerModelAndActivationCode();
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeCarRoot(buffer.get(), 0, length);
decodeCarFuelFigures();
decodeCarPerformanceFigures();
decodeCarManufacturerModelAndActivationCode();
},
std::runtime_error);
}
INSTANTIATE_TEST_SUITE_P(
MessageLengthTest,
MessageBoundsCheckTest,
::testing::Range(0, static_cast<int>(encodedCarSz), 1));
| 10,472 |
458 | <reponame>yxqsnz/cproc
int main(void) {
return ((unsigned char)1 - (unsigned char)2) > 0;
}
| 40 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.groovy.refactoring.findusages.impl;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.netbeans.modules.groovy.editor.api.ElementUtils;
import org.netbeans.modules.groovy.refactoring.findusages.model.RefactoringElement;
/**
*
* @author <NAME>
*/
public class FindConstructorUsagesVisitor extends AbstractFindUsagesVisitor {
private final String name;
public FindConstructorUsagesVisitor(ModuleNode moduleNode, RefactoringElement element) {
super(moduleNode);
this.name = element.getOwnerName();
}
@Override
public void visitConstructor(ConstructorNode constructor) {
final String constructorName = ElementUtils.getDeclaringClassName(constructor);
if (!constructor.hasNoRealSourcePosition() && name.equals(constructorName)) {
usages.add(constructor);
}
super.visitConstructor(constructor);
}
}
| 533 |
411 | '''define the config file for ade20k and ViT-Large'''
import os
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG.update({
'type': 'ade20k',
'rootdir': os.path.join(os.getcwd(), 'ADE20k'),
})
# modify dataloader config
DATALOADER_CFG = DATALOADER_CFG.copy()
# modify optimizer config
OPTIMIZER_CFG = OPTIMIZER_CFG.copy()
OPTIMIZER_CFG.update(
{
'max_epochs': 130
}
)
# modify losses config
LOSSES_CFG = LOSSES_CFG.copy()
# modify model config
MODEL_CFG = MODEL_CFG.copy()
MODEL_CFG.update(
{
'num_classes': 150,
'backbone': {
'type': 'jx_vit_large_p16_384',
'series': 'vit',
'img_size': (512, 512),
'drop_rate': 0.,
'out_indices': (9, 14, 19, 23),
'norm_cfg': {'type': 'layernorm', 'opts': {'eps': 1e-6}},
'pretrained': True,
'selected_indices': (0, 1, 2, 3),
},
'auxiliary': [
{'in_channels': 1024, 'out_channels': 256, 'dropout': 0, 'num_convs': 2, 'scale_factor': 4, 'kernel_size': 3},
{'in_channels': 1024, 'out_channels': 256, 'dropout': 0, 'num_convs': 2, 'scale_factor': 4, 'kernel_size': 3},
{'in_channels': 1024, 'out_channels': 256, 'dropout': 0, 'num_convs': 2, 'scale_factor': 4, 'kernel_size': 3},
],
}
)
# modify inference config
INFERENCE_CFG = INFERENCE_CFG.copy()
# modify common config
COMMON_CFG = COMMON_CFG.copy()
COMMON_CFG['train'].update(
{
'backupdir': 'setrpup_vitlarge_ade20k_train',
'logfilepath': 'setrpup_vitlarge_ade20k_train/train.log',
}
)
COMMON_CFG['test'].update(
{
'backupdir': 'setrpup_vitlarge_ade20k_test',
'logfilepath': 'setrpup_vitlarge_ade20k_test/test.log',
'resultsavepath': 'setrpup_vitlarge_ade20k_test/setrpup_vitlarge_ade20k_results.pkl'
}
) | 954 |
2,661 | <gh_stars>1000+
#!/usr/bin/env python2.7
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Wms-plate-carree-as-Mercator-tile error measurement tool.
#
# Tool for showing the pixel errors associated with serving plate
# carree tiles as Mercator tiles if the tile northern and southern
# boundaries match those of the Mercator tile that they are impersonating.
# Plate carree tiles with Mercator bounds are typically requested
# from wms for linear sampling of the plate carree map being served.
#
# In short, it demonstrates for latitudes near the equator at low
# LODs, and for latitudes further from the equator at higher LODs,
# the errors become very small (less than 1 pixel), which is probably
# better than errors within the imagery itself.
#
# Typically, we measure error at the center of the tile, which is not
# the exact position of maximum error, but close enough.
#
# E.g.
# LOD 4
# Tile at 0.0 degrees
# Error at 0.50: 2.41357 pixels
# Tile at 21.9 degrees
# Error at 0.50: 6.59861 pixels
# Tile at 41.0 degrees
# Error at 0.50: 9.41641 pixels
# LOD 6
# Tile at 0.0 degrees
# Error at 0.50: 0.15400 pixels
# Tile at 21.9 degrees
# Error at 0.50: 1.30346 pixels
# Tile at 41.0 degrees
# Error at 0.50: 2.14443 pixels
# LOD 8
# Tile at 0.0 degrees
# Error at 0.50: 0.00964 pixels
# Tile at 21.9 degrees
# Error at 0.50: 0.30174 pixels
# Tile at 41.0 degrees
# Error at 0.50: 0.52049 pixels
# Tile at 82.7 degrees
# Error at 0.50: 0.77914 pixels
import math
# Range of LODs to calculate errors for.
START_LOD = 4
END_LOD = 9
# Define measurement locations within an LOD.
# Steps begin at center of map and move up.
# Mirror results for southern hemisphere.
# E.g. at LOD 4, the x and y dimensions are 16 tiles,
# so 8 steps would touch each tile from the equator to the poles.
# At LOD 5, we would check every other tile. And so on.
NUM_LOD_STEPS = 8
# Define measurement locations within a tile.
# Position is defined from 0 to 1, meaning from
# y_pixel = 0 (southern border) to
# y_pixel = 255 (northern border).
NUM_TILE_STEPS = 4
TILE_START_POSITION = 0.0
TILE_STEP_SIZE = 1.0 / NUM_TILE_STEPS
def ToMercDegrees(y, num_tiles):
"""Calculate latitude of southern border of yth tile in degrees.
LOD is log2(num_tiles)
Args:
y: (float) Position of tile in qt grid moving from south to north.
Non-integer values give latitude within tile.
num_tiles: (integer) Number of tiles in the qt grid.
Returns:
Latitude of southern border of tile in degrees.
"""
# Calculate on standard Mercator scale that spans from -pi to pi.
# There is no intrinsic reason for using these values, which correspond to
# about -85 to 85 degrees, other than it matches (albeit somewhat
# misleadingly) the longitudinal radian span, and it's the span Google
# uses for its 2d maps.
y_merc = 2.0 * math.pi * y / num_tiles - math.pi
latitude_rad = (math.atan(math.exp(y_merc)) - math.pi / 4.0) * 2.0
return latitude_rad / math.pi * 180.0
def ToMercPosition(lat_deg, num_tiles):
"""Calculate position of a given latitude on qt grid.
LOD is log2(num_tiles)
Args:
lat_deg: (float) Latitude in degrees.
num_tiles: (integer) Number of tiles in the qt grid.
Returns:
Floating point position of latitude in tiles relative to equator.
"""
lat_rad = lat_deg / 180.0 * math.pi
y_merc = math.log(math.tan(lat_rad / 2.0 + math.pi / 4.0))
return num_tiles / 2.0 * (1 + y_merc / math.pi)
def ErrorInPixels(y, num_tiles, pos_flat_tile_0_to_1):
"""Calculate error in pixels at given position within tile.
Position ranges from 0.0 to 1.0 (y_pixel = 0 to y_pixel = 255).
Maximum error should be near the middle since it is 0 at the
two borders.
Args:
y: (integer) Position of tile in qt grid moving from south to north.
num_tiles: (integer) Number of tiles in the qt grid.
pos_flat_tile_0_to_1: (float) Position of pixel in plate carree tile.
Position is from 0.0 (southern border) to 1.0 (northern border).
Returns:
Error in pixel distance of given pixel.
"""
# Top and bottom bounds in degrees (same for flat and Mercator)
# since we are passing these to wms as the bounds.
bottom_merc_tile_deg = ToMercDegrees(y + 0.0, num_tiles)
top_merc_tile_deg = ToMercDegrees(y + 1.0, num_tiles)
# Get fractional y position (in tiles).
y_flat = y + pos_flat_tile_0_to_1
# Use linear interpoation to find flag latitude for given point.
flat_deg = ((top_merc_tile_deg - bottom_merc_tile_deg)
* pos_flat_tile_0_to_1 + bottom_merc_tile_deg)
# Get fractional y position of that latitude on Mercator map.
true_y_merc = ToMercPosition(flat_deg, num_tiles)
# Subtract difference and multiply by pixel height of tile to
# get error in pixels.
return (y_flat - true_y_merc) * 256
def main():
for lod in xrange(START_LOD, END_LOD + 1):
print "LOD", lod
num_tiles = 1 << lod
middle = num_tiles / 2
lod_step = middle / NUM_LOD_STEPS
for i in xrange(NUM_LOD_STEPS):
y = middle + lod_step * i
print " Tile at %3.1f degrees" % ToMercDegrees(y, num_tiles)
tile_position = TILE_START_POSITION
for unused_ in xrange(NUM_TILE_STEPS):
print " Error at %3.2f: %6.5f pixels" % (
tile_position, ErrorInPixels(y, num_tiles, tile_position))
tile_position += TILE_STEP_SIZE
if __name__ == "__main__":
main()
| 2,097 |
6,036 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import collections
import csv
import re
import sys
Comparison = collections.namedtuple("Comparison", ["name", "fn"])
class Comparisons:
@staticmethod
def eq():
return Comparison(
name="equal to",
fn=(lambda actual, expected: actual == expected))
@staticmethod
def float_le(tolerance=None):
actual_tolerance = 0.0 if tolerance is None else tolerance
return Comparison(
name="less than or equal to" +
(" (tolerance: {})".format(str(actual_tolerance))
if tolerance is not None else ""),
fn=(lambda actual, expected: float(actual) <= float(expected) + actual_tolerance))
def _printf_stderr(fmt, *args):
print(fmt.format(*args), file=sys.stderr)
def _read_results_file(results_path):
with open(results_path) as results_file:
csv_reader = csv.DictReader(results_file)
return [row for row in csv_reader]
def _compare_results(expected_results, actual_results, field_comparisons):
if len(field_comparisons) == 0:
return True
if len(expected_results) != len(actual_results):
_printf_stderr("Expected and actual result sets have different sizes.")
return False
mismatch_detected = False
for row_idx, (expected_row, actual_row) in enumerate(zip(expected_results, actual_results)):
for field_name, comparison in field_comparisons.items():
actual, expected = actual_row[field_name], expected_row[field_name]
if not comparison.fn(actual, expected):
_printf_stderr("Comparison '{}' failed for {} in row {}, actual: {}, expected: {}",
comparison.name, field_name, row_idx, actual, expected)
mismatch_detected = True
return not mismatch_detected
def compare_results_files(expected_results_path: str, actual_results_path: str, field_comparisons: dict):
expected_results = _read_results_file(expected_results_path)
actual_results = _read_results_file(actual_results_path)
comparison_result = _compare_results(
expected_results, actual_results, field_comparisons)
if not comparison_result:
with open(expected_results_path) as expected_results_file, \
open(actual_results_path) as actual_results_file:
_printf_stderr("===== Expected results =====\n{}\n===== Actual results =====\n{}",
expected_results_file.read(), actual_results_file.read())
return comparison_result
| 867 |
909 | <reponame>khamutov/intellij-scala
public class R {
private final static long serialVersionUID = 42L;
}
/*
@SerialVersionUID(42L)
class R {
}
*/ | 55 |
3,508 | <gh_stars>1000+
package com.fishercoder.solutions;
import java.util.TreeSet;
public class _849 {
public static class Solution1 {
int maxDist = 0;
public int maxDistToClosest(int[] seats) {
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 0) {
extend(seats, i);
}
}
return maxDist;
}
private void extend(int[] seats, int position) {
int left = position - 1;
int right = position + 1;
int leftMinDistance = 1;
while (left >= 0) {
if (seats[left] == 0) {
leftMinDistance++;
left--;
} else {
break;
}
}
int rightMinDistance = 1;
while (right < seats.length) {
if (seats[right] == 0) {
rightMinDistance++;
right++;
} else {
break;
}
}
int maxReach = 0;
if (position == 0) {
maxReach = rightMinDistance;
} else if (position == seats.length - 1) {
maxReach = leftMinDistance;
} else {
maxReach = Math.min(leftMinDistance, rightMinDistance);
}
maxDist = Math.max(maxDist, maxReach);
}
}
public static class Solution2 {
/**
* my completely original solution on 9/13/2021.
*/
public int maxDistToClosest(int[] seats) {
int maxDistance = 0;
TreeSet<Integer> treeMap = new TreeSet<>();
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
treeMap.add(i);
}
}
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 0) {
Integer leftNeighbor = treeMap.floor(i);
Integer rightNeighbor = treeMap.ceiling(i);
if (leftNeighbor != null && rightNeighbor != null) {
maxDistance = Math.max(maxDistance, Math.min(i - leftNeighbor, rightNeighbor - i));
} else if (leftNeighbor == null) {
maxDistance = Math.max(maxDistance, rightNeighbor - i);
} else {
maxDistance = Math.max(maxDistance, i - leftNeighbor);
}
}
}
return maxDistance;
}
}
}
| 1,508 |
383 | <reponame>avidit/home-assistant-config
"""Parser for Acconeer BLE advertisements"""
import logging
from struct import unpack
from .helpers import (
to_mac,
to_unformatted_mac,
)
_LOGGER = logging.getLogger(__name__)
ACCONEER_SENSOR_IDS = {
0x80: "Acconeer XM122"
}
MEASUREMENTS = {
0x80: ["presence", "temperature"],
}
def parse_acconeer(self, data, source_mac, rssi):
"""Acconeer parser"""
msg_length = len(data)
firmware = "Acconeer"
acconeer_mac = source_mac
device_id = data[4]
xvalue = data[5:]
result = {"firmware": firmware}
if msg_length == 19 and device_id in ACCONEER_SENSOR_IDS:
# Acconeer Sensors
device_type = ACCONEER_SENSOR_IDS[device_id]
measurements = MEASUREMENTS[device_id]
(
battery_level,
temperature,
presence,
reserved2
) = unpack("<HhHQ", xvalue)
if "presence" in measurements:
result.update({
"motion": 0 if presence == 0 else 1,
})
if "temperature" in measurements:
result.update({
"temperature": temperature,
})
result.update({
"battery": battery_level,
})
else:
device_type = None
if device_type is None:
if self.report_unknown == "Acconeer":
_LOGGER.info(
"BLE ADV from UNKNOWN Acconeer DEVICE: RSSI: %s, MAC: %s, ADV: %s",
rssi,
to_mac(source_mac),
data.hex()
)
return None
# Check for duplicate messages
packet_id = xvalue.hex()
try:
prev_packet = self.lpacket_ids[acconeer_mac]
except KeyError:
# start with empty first packet
prev_packet = None
if prev_packet == packet_id:
# only process new messages
if self.filter_duplicates is True:
return None
self.lpacket_ids[acconeer_mac] = packet_id
# check for MAC presence in sensor whitelist, if needed
if self.discovery is False and acconeer_mac not in self.sensor_whitelist:
_LOGGER.debug("Discovery is disabled. MAC: %s is not whitelisted!", to_mac(acconeer_mac))
return None
result.update({
"rssi": rssi,
"mac": to_unformatted_mac(acconeer_mac),
"type": device_type,
"packet": packet_id,
"firmware": firmware,
"data": True
})
return result
| 1,177 |
2,542 | <filename>src/prod/src/ServiceModel/naming/GetPropertyBatchOperationDescription.h
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Naming
{
class GetPropertyBatchOperationDescription : public PropertyBatchOperationDescription
{
DENY_COPY(GetPropertyBatchOperationDescription);
public:
GetPropertyBatchOperationDescription()
: PropertyBatchOperationDescription(FABRIC_PROPERTY_BATCH_OPERATION_KIND_GET)
, includeValue_(false)
{
}
GetPropertyBatchOperationDescription(
std::wstring const & propertyName,
bool includeValue)
: PropertyBatchOperationDescription(FABRIC_PROPERTY_BATCH_OPERATION_KIND_GET, propertyName)
, includeValue_(includeValue)
{
}
virtual ~GetPropertyBatchOperationDescription() {};
Common::ErrorCode Verify()
{
if (Kind == FABRIC_PROPERTY_BATCH_OPERATION_KIND_GET)
{
return Common::ErrorCode::Success();
}
return Common::ErrorCodeValue::InvalidArgument;
}
__declspec(property(get=get_IncludeValue)) bool IncludeValue;
bool get_IncludeValue() const { return includeValue_; }
BEGIN_JSON_SERIALIZABLE_PROPERTIES()
SERIALIZABLE_PROPERTY_CHAIN()
SERIALIZABLE_PROPERTY(ServiceModel::Constants::IncludeValue, includeValue_)
END_JSON_SERIALIZABLE_PROPERTIES()
private:
bool includeValue_;
};
using GetPropertyBatchOperationDescriptionSPtr = std::shared_ptr<GetPropertyBatchOperationDescription>;
template<> class PropertyBatchOperationTypeActivator<FABRIC_PROPERTY_BATCH_OPERATION_KIND_GET>
{
public:
static PropertyBatchOperationDescriptionSPtr CreateSPtr()
{
return std::make_shared<GetPropertyBatchOperationDescription>();
}
};
}
| 847 |
1,261 | /**
Onion HTTP server library
Copyright (C) 2010-2018 <NAME> and others
This library is free software; you can redistribute it and/or
modify it under the terms of, at your choice:
a. the Apache License Version 2.0.
b. the GNU General Public License as published by the
Free Software Foundation; either version 2.0 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of both licenses, if not see
<http://www.gnu.org/licenses/> and
<http://www.apache.org/licenses/LICENSE-2.0>.
*/
#include <onion/onion.h>
#include <onion/http.h>
#include <onion/websocket.h>
#include <onion/types_internal.h>
#include "../ctest.h"
#include "buffer_listen_point.h"
struct ws_status_t {
int connected;
int is_connected;
};
struct ws_status_t ws_status;
char *ws_data_tmp = NULL;
int ws_data_length = 0;
typedef ssize_t(lpreader_sig_t) (onion_request * req, char *data, size_t len);
typedef ssize_t(lpwriter_sig_t) (onion_request * req, const char *data,
size_t len);
void websocket_data_buffer_write(onion_request * req, const char *data,
size_t len) {
if (!ws_data_tmp) {
ws_data_length = len;
ws_data_tmp = malloc(ws_data_length);
strncpy(ws_data_tmp, data, ws_data_length);
} else {
char *tmp = malloc(ws_data_length + len);
strncpy(tmp, ws_data_tmp, ws_data_length);
strncpy(tmp + ws_data_length, data, len);
ws_data_length += len;
free(ws_data_tmp);
ws_data_tmp = tmp;
}
}
int websocket_data_buffer_read(onion_request * req, char *data, size_t len) {
if (!ws_data_tmp || !ws_data_length || !data)
return 0;
int i;
for (i = 0; i < ws_data_length; i++) {
data[i] = ws_data_tmp[i];
if (i == len - 1)
break;
}
strncpy(ws_data_tmp, ws_data_tmp + i + 1, ws_data_length - i);
ws_data_length -= i + 1;
return i + 1;
}
onion_connection_status ws_callback(void *privadata, onion_websocket * ws,
ssize_t nbytes_ready) {
return OCS_NEED_MORE_DATA;
}
onion_connection_status ws_handler(void *priv, onion_request * req,
onion_response * res) {
onion_websocket *ws = onion_websocket_new(req, res);
ws_status.connected++;
ws_status.is_connected = (ws != NULL);
if (ws_status.is_connected) {
onion_websocket_set_callback(ws, ws_callback);
return OCS_WEBSOCKET;
}
return OCS_NOT_IMPLEMENTED;
}
onion *websocket_server_new() {
onion *o = onion_new(0);
onion_url *urls = onion_root_url(o);
onion_url_add(urls, "", ws_handler);
onion_listen_point *lp = onion_buffer_listen_point_new();
onion_add_listen_point(o, NULL, NULL, lp);
return o;
}
int websocket_forge_small_packet(char **buffer) {
// Forge 120 bytes Data Packet
int length = 120;
int header_length = 6;
*buffer = malloc(sizeof(char) * length);
char *buf = *buffer;
memset(*buffer, '\0', length);
buf[0] = 0x81; // FIN flag to 1, opcode: 0x01; one message, of type text;
buf[1] = ((char)(0x01 << 7)); // MASK Flag to 1;
buf[1] += length - header_length; // length: 113 bytes of Data;
// Next 4 bytes: Masking-key
buf[2] = 0xF2;
buf[3] = 0x05;
buf[4] = 0xA0;
buf[5] = 0x01;
// actual data
strncpy(&(buf[6]),
"Some UTF-8-encoded chars which will be cut at the 117th char so I write some gap-filling text with no meaning until it is enough",
length - header_length);
// Masking operation on data
int i;
for (i = 0; i < length - header_length; i++) {
buf[i + 6] = buf[i + 6] ^ buf[2 + i % 4];
}
fflush(stdout);
return length;
}
int websocket_forge_close_packet(char **buffer) {
// Forge 120 bytes Data Packet
int length = 8;
int header_length = 6;
*buffer = malloc(sizeof(char) * length);
char *buf = *buffer;
memset(*buffer, '\0', length);
buf[0] = 0x88; // FIN flag to 1, opcode: 0x08
buf[1] = ((char)(0x01 << 7)); // MASK Flag to 1;
buf[1] += length - header_length; // length: 2 bytes of Data;
// Next 4 bytes: Masking-key
buf[2] = 0xF2;
buf[3] = 0x05;
buf[4] = 0xA0;
buf[5] = 0x01;
// Status code masked with key:
buf[6] = 0x03 ^ buf[2];
buf[7] = 0xE8 ^ buf[3];
return length;
}
int onion_request_write0(onion_request * req, const char *data) {
return onion_request_write(req, data, strlen(data));
}
onion_request *websocket_start_handshake(onion * o) {
onion_request *req = onion_request_new(onion_get_listen_point(o, 0));
onion_request_write0(req,
"GET /\nUpgrade: websocket\nSec-Websocket-Version: 13\nSec-Websocket-Key: My-key\n\n");
onion_request_process(req);
return req;
}
void t01_websocket_server_no_ws() {
INIT_LOCAL();
memset(&ws_status, 0, sizeof(ws_status));
onion *o = websocket_server_new();
onion_request *req = onion_request_new(onion_get_listen_point(o, 0));
onion_request_write0(req, "GET /\n\n");
onion_request_process(req);
FAIL_IF(ws_status.is_connected);
FAIL_IF_NOT_EQUAL_INT(ws_status.connected, 1);
onion_request_free(req);
onion_free(o);
END_LOCAL();
}
void t02_websocket_server_w_ws() {
INIT_LOCAL();
memset(&ws_status, 0, sizeof(ws_status));
onion *o = websocket_server_new();
onion_request *req = onion_request_new(onion_get_listen_point(o, 0));
onion_request_write0(req,
"GET /\nUpgrade: websocket\nSec-Websocket-Version: 13\nSec-Websocket-Key: My-key\n\n");
onion_request_process(req);
FAIL_IF_NOT(ws_status.is_connected);
FAIL_IF_NOT_EQUAL_INT(ws_status.connected, 1);
onion_request_free(req);
onion_free(o);
END_LOCAL();
}
void t03_websocket_server_receive_small_packet() {
INIT_LOCAL();
int length = 0;
char *buffer = NULL, buffer2[115];
memset(&ws_status, 0, sizeof(ws_status));
onion *o = websocket_server_new();
onion_request *req = websocket_start_handshake(o);
req->connection.listen_point->read =
(lpreader_sig_t *) websocket_data_buffer_read;
onion_response *res = onion_response_new(req);
onion_websocket *ws = onion_websocket_new(req, res);
length = websocket_forge_small_packet((char **)&buffer);
websocket_data_buffer_write(req, buffer, length);
onion_websocket_read(ws, (char *)&buffer2, 120);
buffer2[114] = '\0';
FAIL_IF_NOT_EQUAL_STR(buffer2,
"Some UTF-8-encoded chars which will be cut at the 117th char so I write some gap-filling text with no meaning unti");
onion_websocket_free(ws);
onion_request_free(req);
onion_free(o);
END_LOCAL();
}
void t04_websocket_server_close_handshake() {
INIT_LOCAL();
int length = 0;
unsigned char *buffer = NULL, buffer2[8];
onion *o = websocket_server_new();
onion_request *req = websocket_start_handshake(o);
req->connection.listen_point->read =
(lpreader_sig_t *) websocket_data_buffer_read;
req->connection.listen_point->write =
(lpwriter_sig_t *) websocket_data_buffer_write;
onion_response *res = onion_response_new(req);
onion_websocket *ws = onion_websocket_new(req, res);
length = websocket_forge_close_packet((char **)&buffer);
websocket_data_buffer_write(req, (char *)buffer, length);
onion_connection_status ret = onion_websocket_call(ws);
FAIL_IF(ret != -2);
websocket_data_buffer_read(req, (char *)&buffer2, 8);
FAIL_IF_NOT(buffer2[0] == 0x88);
FAIL_IF_NOT(buffer2[1] == 0x02);
FAIL_IF_NOT(buffer2[2] == 0x03);
FAIL_IF_NOT(buffer2[3] == 0xE8);
onion_websocket_free(ws);
onion_request_free(req);
onion_free(o);
END_LOCAL();
}
int main(int argc, char **argv) {
START();
t01_websocket_server_no_ws();
t02_websocket_server_w_ws();
t03_websocket_server_receive_small_packet();
t04_websocket_server_close_handshake();
END();
}
| 3,341 |
14,668 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "storage/browser/file_system/remove_operation_delegate.h"
#include "base/bind.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
namespace storage {
RemoveOperationDelegate::RemoveOperationDelegate(
FileSystemContext* file_system_context,
const FileSystemURL& url,
StatusCallback callback)
: RecursiveOperationDelegate(file_system_context),
url_(url),
callback_(std::move(callback)) {}
RemoveOperationDelegate::~RemoveOperationDelegate() = default;
void RemoveOperationDelegate::Run() {
#if DCHECK_IS_ON()
DCHECK(!did_run_);
did_run_ = true;
#endif
operation_runner()->RemoveFile(
url_, base::BindOnce(&RemoveOperationDelegate::DidTryRemoveFile,
weak_factory_.GetWeakPtr()));
}
void RemoveOperationDelegate::RunRecursively() {
#if DCHECK_IS_ON()
DCHECK(!did_run_);
did_run_ = true;
#endif
StartRecursiveOperation(url_, FileSystemOperation::ERROR_BEHAVIOR_ABORT,
std::move(callback_));
}
void RemoveOperationDelegate::ProcessFile(const FileSystemURL& url,
StatusCallback callback) {
operation_runner()->RemoveFile(
url, base::BindOnce(&RemoveOperationDelegate::DidRemoveFile,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void RemoveOperationDelegate::ProcessDirectory(const FileSystemURL& url,
StatusCallback callback) {
std::move(callback).Run(base::File::FILE_OK);
}
void RemoveOperationDelegate::PostProcessDirectory(const FileSystemURL& url,
StatusCallback callback) {
operation_runner()->RemoveDirectory(url, std::move(callback));
}
void RemoveOperationDelegate::DidTryRemoveFile(base::File::Error error) {
if (error != base::File::FILE_ERROR_NOT_A_FILE &&
error != base::File::FILE_ERROR_SECURITY) {
std::move(callback_).Run(error);
return;
}
operation_runner()->RemoveDirectory(
url_, base::BindOnce(&RemoveOperationDelegate::DidTryRemoveDirectory,
weak_factory_.GetWeakPtr(), error));
}
void RemoveOperationDelegate::DidTryRemoveDirectory(
base::File::Error remove_file_error,
base::File::Error remove_directory_error) {
std::move(callback_).Run(remove_directory_error ==
base::File::FILE_ERROR_NOT_A_DIRECTORY
? remove_file_error
: remove_directory_error);
}
void RemoveOperationDelegate::DidRemoveFile(StatusCallback callback,
base::File::Error error) {
if (error == base::File::FILE_ERROR_NOT_FOUND) {
std::move(callback).Run(base::File::FILE_OK);
return;
}
std::move(callback).Run(error);
}
} // namespace storage
| 1,263 |
468 | """Matching Tensor module."""
import typing
import torch
import torch.nn as nn
import torch.nn.functional as F
class MatchingTensor(nn.Module):
"""
Module that captures the basic interactions between two tensors.
:param matching_dims: Word dimension of two interaction texts.
:param channels: Number of word interaction tensor channels.
:param normalize: Whether to L2-normalize samples along the
dot product axis before taking the dot product.
If set to True, then the output of the dot product
is the cosine proximity between the two samples.
:param init_diag: Whether to initialize the diagonal elements
of the matrix.
Examples:
>>> import matchzoo as mz
>>> matching_dim = 5
>>> matching_tensor = mz.modules.MatchingTensor(
... matching_dim,
... channels=4,
... normalize=True,
... init_diag=True
... )
"""
def __init__(
self,
matching_dim: int,
channels: int = 4,
normalize: bool = True,
init_diag: bool = True
):
""":class:`MatchingTensor` constructor."""
super().__init__()
self._matching_dim = matching_dim
self._channels = channels
self._normalize = normalize
self._init_diag = init_diag
self.interaction_matrix = torch.empty(
self._channels, self._matching_dim, self._matching_dim
)
if self._init_diag:
self.interaction_matrix = self.interaction_matrix.uniform_(-0.05, 0.05)
for channel_index in range(self._channels):
self.interaction_matrix[channel_index].fill_diagonal_(0.1)
self.interaction_matrix = nn.Parameter(self.interaction_matrix)
else:
self.interaction_matrix = nn.Parameter(self.interaction_matrix.uniform_())
def forward(self, x, y):
"""
The computation logic of MatchingTensor.
:param inputs: two input tensors.
"""
if self._normalize:
x = F.normalize(x, p=2, dim=-1)
y = F.normalize(y, p=2, dim=-1)
# output = [b, c, l, r]
output = torch.einsum(
'bld,cde,bre->bclr',
x, self.interaction_matrix, y
)
return output
| 1,024 |
349 | package com.ray3k.skincomposer.dialog.scenecomposer.undoables;
public class TreeDeleteUndoable extends ActorDeleteUndoable {
@Override
public String getRedoString() {
return "Redo \"Delete Tree\"";
}
@Override
public String getUndoString() {
return "Undo \"Delete Tree\"";
}
}
| 129 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.gsf.testrunner.api;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* Panel that changes its hight automatically if the components inside
* it cannot fit in the current size. The panel checks and changes only its
* height, not width. The panel changes not only height of its own but also
* height of the toplevel <code>Window</code> it is embedded into. The size
* change occurs only after this panel's children are <em>painted</em>.
* <p>
* This panel is supposed to be used as a replacement for a normal
* <code>JPanel</code> if this panel contains a wrappable text and the panel
* needs to be high enough so that all lines of the possibly wrapped text
* can fit.
* <p>
* This class overrides method <code>paintChildren(Graphics)</code>.
* If overriding this method in this subclasses of this class,
* call <code>super.paintChildren(...)</code> so that the routine which performs
* the size change is not skipped.
*
* @author <NAME>
*/
public class SelfResizingPanel extends JPanel {
/**
* <code>false</code> until this panel's children are painted
* for the first time
*/
private boolean painted = false;
/** Creates a new instance of SelfResizingPanel */
public SelfResizingPanel() {
super();
}
/**
* Paints this panel's children and then displays the initial message
* (in the message area) if any.
* This method is overridden so that this panel receives a notification
* immediately after the children components are painted - it is necessary
* for computation of space needed by the message area for displaying
* the initial message.
* <p>
* The first time this method is called, method
* {@link #paintedFirstTime is called immediately after
* <code>super.paintChildren(..>)</code> finishes.
*
* @param g the <code>Graphics</code> context in which to paint
*/
protected void paintChildren(java.awt.Graphics g) {
/*
* This is a hack to make sure that window size adjustment
* is not done sooner than the text area is painted.
*
* The reason is that the window size adjustment routine
* needs the text area to compute height necessary for displaying
* the given message. But the text area does not return correct
* data (Dimension getPreferredSize()) until it is painted.
*/
super.paintChildren(g);
if (!painted) {
paintedFirstTime(g);
painted = true;
}
}
/**
* This method is called the first time this panel's children are painted.
* By default, this method just calls {@link #adjustWindowSize()}.
*
* @param g <code>Graphics</code> used to paint this panel's children
*/
protected void paintedFirstTime(java.awt.Graphics g) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
adjustWindowSize();
}
});
}
/**
* Checks whether the dialog is large enough for the message (if any)
* to be displayed and adjusts the dialogs size if it is too small.
* <p>
* Note: Resizing the dialog works only once this panel and its children
* are {@linkplain #paintChildren(java.awt.Graphics) painted}.
*/
protected void adjustWindowSize() {
Dimension currSize = getSize();
int currHeight = currSize.height;
int prefHeight = getPreferredSize().height;
if (currHeight < prefHeight) {
int delta = prefHeight - currHeight;
java.awt.Window win = SwingUtilities.getWindowAncestor(this);
Dimension winSize = win.getSize();
win.setSize(winSize.width, winSize.height + delta);
}
}
/**
* Has this panel's children been already painted?
*
* @return <code>true</code> if
* {@link #paintChildren #paintChildren(Graphics) has already been
* called; <code>false</code> otherwise
* @see #paintedFirstTime
*/
protected boolean isPainted() {
return painted;
}
}
| 1,734 |
1,185 | /*
* 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.dubbo.samples.edas;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.samples.edas.provider.DubboProvider;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.GenericContainer;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DubboProvider.class, DubboConsumer.class})
public class EDASIT {
@Autowired
private DubboConsumer dubboConsumer;
@Test
public void testGreeting() throws Exception {
// FIXME, no provider
try {
System.out.println(dubboConsumer.callDemoService());
} catch (Exception e) {
Assert.assertTrue(e instanceof RpcException);
Assert.assertTrue(((RpcException) e).getMessage().contains("No provider available"));
}
}
}
| 600 |
348 | <gh_stars>100-1000
{"nom":"Théziers","circ":"3ème circonscription","dpt":"Gard","inscrits":861,"abs":529,"votants":332,"blancs":22,"nuls":11,"exp":299,"res":[{"nuance":"FN","nom":"<NAME>","voix":166},{"nuance":"REM","nom":"<NAME>","voix":133}]} | 99 |
440 | <reponame>grey-btw/DeepADoTS
import numpy as np
from .synthetic_multivariate_dataset import SyntheticMultivariateDataset
class MultivariateAnomalyFunction:
# ----- Functions generating the anomalous dimension --------- #
# A MultivariateAnomalyFunction should return a tuple containing the following three values:
# * The values of the second dimension (array of max `interval_length` numbers)
# * Starting point for the anomaly
# * End point for the anomaly section
# The last two values are ignored for generation of not anomalous data
# Get a dataset by passing the method name as string. All following parameters
# are passed through. Throws AttributeError if attribute was not found.
@staticmethod
def get_multivariate_dataset(method, name=None, group_size=None, *args, **kwargs):
name = name or f'Synthetic Multivariate {method} Curve Outliers'
func = getattr(MultivariateAnomalyFunction, method)
return SyntheticMultivariateDataset(anomaly_func=func,
name=name,
group_size=group_size,
*args,
**kwargs)
@staticmethod
def doubled(curve_values, anomalous, _):
factor = 4 if anomalous else 2
return curve_values * factor, 0, len(curve_values)
@staticmethod
def inversed(curve_values, anomalous, _):
factor = -2 if anomalous else 2
return curve_values * factor, 0, len(curve_values)
@staticmethod
def shrinked(curve_values, anomalous, _):
if not anomalous:
return curve_values, -1, -1
else:
new_curve = curve_values[::2]
nonce = np.zeros(len(curve_values) - len(new_curve))
values = np.concatenate([nonce, new_curve])
return values, 0, len(values)
@staticmethod
def xor(curve_values, anomalous, interval_length):
pause_length = interval_length - len(curve_values)
if not anomalous:
# No curve during the other curve in the 1st dimension
nonce = np.zeros(len(curve_values))
# Insert a curve with the same amplitude during the pause of the 1st dimension
new_curve = MultivariateAnomalyFunction.shrink_curve(curve_values, pause_length)
return np.concatenate([nonce, new_curve]), -1, -1
else:
# Anomaly: curves overlap (at the same time or at least half overlapping)
max_pause = min(len(curve_values) // 2, pause_length)
nonce = np.zeros(max_pause)
return np.concatenate([nonce, curve_values]), len(nonce), len(curve_values)
@staticmethod
def delayed(curve_values, anomalous, interval_length):
if not anomalous:
return curve_values, -1, -1
else:
# The curve in the second dimension occurs a few timestamps later
left_space = interval_length - len(curve_values)
delay = min(len(curve_values) // 2, left_space)
nonce = np.zeros(delay)
values = np.concatenate([nonce, curve_values])
return values, 0, len(values)
@staticmethod
def delayed_missing(curve_values, anomalous, interval_length):
starting_point = len(curve_values) // 5
# If the space is too small for the normal curve we're shrinking it (which is not anomalous)
left_space = interval_length - starting_point
new_curve_length = min(left_space, len(curve_values))
if not anomalous:
# The curve in the second dimension occurs a few timestamps later
nonce = np.zeros(starting_point)
new_curve = MultivariateAnomalyFunction.shrink_curve(curve_values, new_curve_length)
values = np.concatenate([nonce, new_curve])
return values, -1, -1
else:
end_point = starting_point + new_curve_length
nonce = np.zeros(end_point)
return nonce, starting_point, end_point
"""
This is a helper function for shrinking an already generated curve.
"""
@staticmethod
def shrink_curve(curve_values, new_length):
if new_length == len(curve_values):
return curve_values
orig_amplitude = max(abs(curve_values))
orig_amplitude *= np.sign(curve_values.mean())
return SyntheticMultivariateDataset.get_curve(new_length, orig_amplitude)
| 1,915 |
713 | <filename>persistence/jpa/src/test/java/org/infinispan/persistence/jpa/entity/Vehicle.java
package org.infinispan.persistence.jpa.entity;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import org.infinispan.protostream.annotations.ProtoField;
/**
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
@Entity
public class Vehicle {
@EmbeddedId
private VehicleId id;
private String color;
@ProtoField(1)
public VehicleId getId() {
return id;
}
public void setId(VehicleId id) {
this.id = id;
}
@ProtoField(2)
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vehicle other = (Vehicle) obj;
if (color == null) {
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Vehicle [id=" + id + ", color=" + color + "]";
}
}
| 695 |
3,897 | /*******************************************************************************
* Copyright (c) 2010-2017 Analog Devices, 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.
* - Modified versions of the software must be conspicuously marked as such.
* - This software is licensed solely and exclusively for use with processors
* manufactured by or for Analog Devices, Inc.
* - This software may not be combined or merged with other code in any manner
* that would cause the software to become subject to terms and conditions
* which differ from those listed here.
* - Neither the name of Analog Devices, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* - The use of this software may or may not infringe the patent rights of one
* or more patent holders. This license does not release you from the
* requirement that you obtain separate licenses from these patent holders
* to use this software.
*
* THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES, INC. AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-
* INFRINGEMENT, TITLE, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ANALOG DEVICES, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES ARISING OUT OF
* CLAIMS OF INTELLECTUAL PROPERTY RIGHTS INFRINGEMENT; 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 "sleep_api.h"
#if DEVICE_SLEEP
#include "adi_pwr.h"
#include "adi_pwr_def.h"
#include "adi_rtos_map.h"
#include "adi_ADuCM4050_device.h"
#include "sleep.h"
/**
* Function to put processor into sleep (FLEXI mode only).
*/
static void go_into_WFI(const ADI_PWR_POWER_MODE PowerMode)
{
uint32_t savedPriority;
uint16_t savedWDT;
uint16_t ActiveWDT;
uint32_t scrSetBits = 0u;
uint32_t scrClrBits = 0u;
uint32_t IntStatus = 0u;
/* pre-calculate the sleep-on-exit set/clear bits */
scrSetBits |= SCB_SCR_SLEEPONEXIT_Msk;
/* wfi without deepsleep or sleep-on-exit */
scrClrBits |= (uint32_t)(BITM_NVIC_INTCON0_SLEEPDEEP | BITM_NVIC_INTCON0_SLEEPONEXIT);
ADI_ENTER_CRITICAL_REGION();
{ /* these lines must be in a success-checking loop if they are not inside critical section */
/* Uninterruptable unlock sequence */
pADI_PMG0->PWRKEY = ADI_PMG_KEY;
/* Clear the previous mode and set new mode */
pADI_PMG0->PWRMOD = (uint32_t) ( ( pADI_PMG0->PWRMOD & (uint32_t) (~BITM_PMG_PWRMOD_MODE) ) | PowerMode );
}
/* Update the SCR (sleepdeep and sleep-on-exit bits) */
SCB->SCR = ((SCB->SCR | scrSetBits) & ~scrClrBits);
/* save/restore current Base Priority Level */
savedPriority = __get_BASEPRI();
/* assert caller's priority threshold (left-justified), currently set to 0, i.e. disable interrupt masking */
__set_BASEPRI(0);
/* save/restore WDT control register (which is not retained during hibernation) */
savedWDT = pADI_WDT0->CTL;
/* optimization: compute local WDT enable flag once (outside the loop) */
ActiveWDT = ((savedWDT & BITM_WDT_CTL_EN) >> BITP_WDT_CTL_EN);
/* SAR-51938: insure WDT is fully synchronized or looping on interrupts
in hibernate mode may lock out the sync bits.
In hibernate mode (during which the WDT registers are not retained),
the WDT registers will have been reset to default values after each
interrupt exit and we require a WDT clock domain sync.
We also need to insure a clock domain sync before (re)entering the WFI
in case an interrupt did a watchdog kick.
Optimization: only incur WDT sync overhead (~100us) if the WDT is enabled.
*/
if (ActiveWDT > 0u) {
while ((pADI_WDT0->STAT & (uint32_t)(BITM_WDT_STAT_COUNTING | BITM_WDT_STAT_LOADING | BITM_WDT_STAT_CLRIRQ)) != 0u) {
;
}
}
__DSB(); /* bus sync to insure register writes from interrupt handlers are always complete before WFI */
/* NOTE: aggressive compiler optimizations can muck up critical timing here, so reduce if hangs are present */
/* The WFI loop MUST reside in a critical section because we need to insure that the interrupt
that is planned to take us out of WFI (via a call to adi_pwr_ExitLowPowerMode()) is not
dispatched until we get into the WFI. If that interrupt sneaks in prior to our getting to the
WFI, then we may end up waiting (potentially forever) for an interrupt that has already occurred.
*/
__WFI();
/* Recycle the critical section so that other (non-wakeup) interrupts are dispatched.
This allows *pnInterruptOccurred to be set from any interrupt context.
*/
ADI_EXIT_CRITICAL_REGION();
/* nop */
ADI_ENTER_CRITICAL_REGION();
/* ...still within critical section... */
/* Restore previous base priority */
__set_BASEPRI(savedPriority);
/* conditionally, restore WDT control register.
avoid unnecessary WDT writes which will invoke a sync problem
described above as SAR-51938: going into hibernation with pending,
unsynchronized WDT writes may lock out the sync bits.
Note: it takes over 1000us to sync WDT writes between the 26MHz and
32kHz clock domains, so this write may actually impact the NEXT
low-power entry.
*/
if (ActiveWDT > 0u) {
pADI_WDT0->CTL = savedWDT;
}
/* clear sleep-on-exit bit to avoid sleeping on exception return to thread level */
SCB->SCR &= ~SCB_SCR_SLEEPONEXIT_Msk;
__DSB(); /* bus sync before re-enabling interrupts */
ADI_EXIT_CRITICAL_REGION();
}
/**
* Function to enable/disable clock gating for the available clocks.
* PCLK overrides all the other clocks.
*/
void set_clock_gating(peripheral_clk_t eClk, int enable)
{
uint32_t flag;
switch (eClk) {
case PCLK:
flag = 1 << BITP_CLKG_CLK_CTL5_PERCLKOFF;
break;
case GPT0_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_GPTCLK0OFF;
break;
case GPT1_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_GPTCLK1OFF;
break;
case GPT2_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_GPTCLK2OFF;
break;
case I2C_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_UCLKI2COFF;
break;
case GPIO_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_GPIOCLKOFF;
break;
case TIMER_RGB_CLOCK:
flag = 1 << BITP_CLKG_CLK_CTL5_TMRRGBCLKOFF;
break;
default:
return;
}
// if enable, set the bit otherwise clear the bit
if (enable) {
pADI_CLKG0_CLK->CTL5 |= flag;
} else {
pADI_CLKG0_CLK->CTL5 &= (~flag);
}
}
/** Send the microcontroller to sleep
*
* The processor is setup ready for sleep, and sent to sleep using __WFI(). In this mode, the
* system clock to the core is stopped until a reset or an interrupt occurs. This eliminates
* dynamic power used by the processor, memory systems and buses. The processor, peripheral and
* memory state are maintained, and the peripherals continue to work and can generate interrupts.
*
* The processor can be woken up by any internal peripheral interrupt or external pin interrupt.
*
* @note
* The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored.
* Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be
* able to access the LocalFileSystem
*
* This mode puts the processor into FLEXI mode however the peripheral clocks are not gated
* hence they are still active.
*/
void hal_sleep(void)
{
// set to go into the FLEXI mode where the processor is asleep and all peripherals are
// still active
go_into_WFI(ADI_PWR_MODE_FLEXI);
}
/** Send the microcontroller to deep sleep
*
* This processor is setup ready for deep sleep, and sent to sleep using __WFI(). This mode
* has the same sleep features as sleep plus it powers down peripherals and clocks. All state
* is still maintained.
*
* The processor can only be woken up by an external interrupt on a pin or a watchdog timer.
*
* @note
* The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored.
* Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be
* able to access the LocalFileSystem
*
* This mode puts the processor into FLEXI mode and all the peripheral clocks are clock gated
* hence they are inactive until interrupts are generated in which case the processor is awaken
* from sleep.
*/
void hal_deepsleep(void)
{
// set clock gating to all the peripheral clocks
set_clock_gating(PCLK, 1);
// set to go into the FLEXI mode with peripheral clocks gated.
go_into_WFI(ADI_PWR_MODE_FLEXI);
// when exiting, clear all peripheral clock gating bits. This is done to enable clocks that aren't
// automatically re-enabled out of sleep such as the GPIO clock.
pADI_CLKG0_CLK->CTL5 = 0;
}
#endif // #if DEVICE_SLEEP
| 3,558 |
2,293 | <gh_stars>1000+
#include <signal.h>
#include <io.h>
/* #include <sys/select.h> */
/* HAS_IOCTL:
* This symbol, if defined, indicates that the ioctl() routine is
* available to set I/O characteristics
*/
#define HAS_IOCTL /**/
/* HAS_UTIME:
* This symbol, if defined, indicates that the routine utime() is
* available to update the access and modification times of files.
*/
#define HAS_UTIME /**/
/* BIG_TIME:
* This symbol is defined if Time_t is an unsigned type on this system.
*/
#define BIG_TIME
#define HAS_KILL
#define HAS_WAIT
#define HAS_DLERROR
#define HAS_WAITPID_RUNTIME (_emx_env & 0x200)
/* HAS_PASSWD
* This symbol, if defined, indicates that the getpwnam() and
* getpwuid() routines are available to get password entries.
* The getpwent() has a separate definition, HAS_GETPWENT.
*/
#define HAS_PASSWD
/* HAS_GROUP
* This symbol, if defined, indicates that the getgrnam() and
* getgrgid() routines are available to get group entries.
* The getgrent() has a separate definition, HAS_GETGRENT.
*/
#define HAS_GROUP
#define HAS_GETGRENT /* fake */
#define HAS_SETGRENT /* fake */
#define HAS_ENDGRENT /* fake */
/* USEMYBINMODE
* This symbol, if defined, indicates that the program should
* use the routine my_binmode(FILE *fp, char iotype, int mode) to insure
* that a file is in "binary" mode -- that is, that no translation
* of bytes occurs on read or write operations.
*/
#undef USEMYBINMODE
#define SOCKET_OPEN_MODE "b"
/* Stat_t:
* This symbol holds the type used to declare buffers for information
* returned by stat(). It's usually just struct stat. It may be necessary
* to include <sys/stat.h> and <sys/types.h> to get any typedef'ed
* information.
*/
#define Stat_t struct stat
/* USE_STAT_RDEV:
* This symbol is defined if this system has a stat structure declaring
* st_rdev
*/
#define USE_STAT_RDEV /**/
/* ACME_MESS:
* This symbol, if defined, indicates that error messages should be
* should be generated in a format that allows the use of the Acme
* GUI/editor's autofind feature.
*/
#undef ACME_MESS /**/
/* ALTERNATE_SHEBANG:
* This symbol, if defined, contains a "magic" string which may be used
* as the first line of a Perl program designed to be executed directly
* by name, instead of the standard Unix #!. If ALTERNATE_SHEBANG
* begins with a character other then #, then Perl will only treat
* it as a command line if if finds the string "perl" in the first
* word; otherwise it's treated as the first line of code in the script.
* (IOW, Perl won't hand off to another interpreter via an alternate
* shebang sequence that might be legal Perl code.)
*/
#define ALTERNATE_SHEBANG "extproc "
#ifndef SIGABRT
# define SIGABRT SIGILL
#endif
#ifndef SIGILL
# define SIGILL 6 /* blech */
#endif
#define ABORT() kill(PerlProc_getpid(),SIGABRT);
#define BIT_BUCKET "/dev/nul" /* Will this work? */
/* Apparently TCPIPV4 defines may be included even with only IAK present */
#if !defined(NO_TCPIPV4) && !defined(TCPIPV4)
# define TCPIPV4
# define TCPIPV4_FORCED /* Just in case */
#endif
#if defined(I_SYS_UN) && !defined(TCPIPV4)
/* It is not working without TCPIPV4 defined. */
# undef I_SYS_UN
#endif
#ifdef USE_ITHREADS
#define do_spawn(a) os2_do_spawn(aTHX_ (a))
#define do_aspawn(a,b,c) os2_do_aspawn(aTHX_ (a),(b),(c))
#define OS2_ERROR_ALREADY_POSTED 299 /* Avoid os2.h */
extern int rc;
#define MUTEX_INIT(m) \
STMT_START { \
int rc; \
if ((rc = _rmutex_create(m,0))) \
Perl_croak_nocontext("panic: MUTEX_INIT: rc=%i", rc); \
} STMT_END
#define MUTEX_LOCK(m) \
STMT_START { \
int rc; \
if ((rc = _rmutex_request(m,_FMR_IGNINT))) \
Perl_croak_nocontext("panic: MUTEX_LOCK: rc=%i", rc); \
} STMT_END
#define MUTEX_UNLOCK(m) \
STMT_START { \
int rc; \
if ((rc = _rmutex_release(m))) \
Perl_croak_nocontext("panic: MUTEX_UNLOCK: rc=%i", rc); \
} STMT_END
#define MUTEX_DESTROY(m) \
STMT_START { \
int rc; \
if ((rc = _rmutex_close(m))) \
Perl_croak_nocontext("panic: MUTEX_DESTROY: rc=%i", rc); \
} STMT_END
#define COND_INIT(c) \
STMT_START { \
int rc; \
if ((rc = DosCreateEventSem(NULL,c,0,0))) \
Perl_croak_nocontext("panic: COND_INIT: rc=%i", rc); \
} STMT_END
#define COND_SIGNAL(c) \
STMT_START { \
int rc; \
if ((rc = DosPostEventSem(*(c))) && rc != OS2_ERROR_ALREADY_POSTED)\
Perl_croak_nocontext("panic: COND_SIGNAL, rc=%ld", rc); \
} STMT_END
#define COND_BROADCAST(c) \
STMT_START { \
int rc; \
if ((rc = DosPostEventSem(*(c))) && rc != OS2_ERROR_ALREADY_POSTED)\
Perl_croak_nocontext("panic: COND_BROADCAST, rc=%i", rc); \
} STMT_END
/* #define COND_WAIT(c, m) \
STMT_START { \
if (WaitForSingleObject(*(c),INFINITE) == WAIT_FAILED) \
Perl_croak_nocontext("panic: COND_WAIT"); \
} STMT_END
*/
#define COND_WAIT(c, m) os2_cond_wait(c,m)
#define COND_WAIT_win32(c, m) \
STMT_START { \
int rc; \
if ((rc = SignalObjectAndWait(*(m),*(c),INFINITE,FALSE))) \
Perl_croak_nocontext("panic: COND_WAIT"); \
else \
MUTEX_LOCK(m); \
} STMT_END
#define COND_DESTROY(c) \
STMT_START { \
int rc; \
if ((rc = DosCloseEventSem(*(c)))) \
Perl_croak_nocontext("panic: COND_DESTROY, rc=%i", rc); \
} STMT_END
/*#define THR ((struct thread *) TlsGetValue(PL_thr_key))
*/
#ifdef USE_SLOW_THREAD_SPECIFIC
# define pthread_getspecific(k) (*_threadstore())
# define pthread_setspecific(k,v) (*_threadstore()=v,0)
# define pthread_key_create(keyp,flag) (*keyp=_gettid(),0)
#else /* USE_SLOW_THREAD_SPECIFIC */
# define pthread_getspecific(k) (*(k))
# define pthread_setspecific(k,v) (*(k)=(v),0)
# define pthread_key_create(keyp,flag) \
( DosAllocThreadLocalMemory(1,(unsigned long**)keyp) \
? Perl_croak_nocontext("LocalMemory"),1 \
: 0 \
)
#endif /* USE_SLOW_THREAD_SPECIFIC */
#define pthread_key_delete(keyp)
#define pthread_self() _gettid()
#define YIELD DosSleep(0)
#ifdef PTHREADS_INCLUDED /* For ./x2p stuff. */
int pthread_join(pthread_t tid, void **status);
int pthread_detach(pthread_t tid);
int pthread_create(pthread_t *tid, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
#endif /* PTHREAD_INCLUDED */
#define THREADS_ELSEWHERE
#else /* USE_ITHREADS */
#define do_spawn(a) os2_do_spawn(a)
#define do_aspawn(a,b,c) os2_do_aspawn((a),(b),(c))
void Perl_OS2_init(char **);
void Perl_OS2_init3(char **envp, void **excH, int flags);
void Perl_OS2_term(void **excH, int exitstatus, int flags);
/* The code without INIT3 hideously puts env inside: */
/* These ones should be in the same block as PERL_SYS_TERM() */
#ifdef PERL_CORE
# define PERL_SYS_INIT3_BODY(argcp, argvp, envp) \
{ void *xreg[2]; \
MALLOC_CHECK_TAINT(*argcp, *argvp, *envp) \
_response(argcp, argvp); \
_wildcard(argcp, argvp); \
Perl_OS2_init3(*envp, xreg, 0); \
PERLIO_INIT
# define PERL_SYS_INIT_BODY(argcp, argvp) { \
{ void *xreg[2]; \
_response(argcp, argvp); \
_wildcard(argcp, argvp); \
Perl_OS2_init3(NULL, xreg, 0); \
PERLIO_INIT
#else /* Compiling embedded Perl or Perl extension */
# define PERL_SYS_INIT3_BODY(argcp, argvp, envp) \
{ void *xreg[2]; \
Perl_OS2_init3(*envp, xreg, 0); \
PERLIO_INIT
# define PERL_SYS_INIT_BODY(argcp, argvp) { \
{ void *xreg[2]; \
Perl_OS2_init3(NULL, xreg, 0); \
PERLIO_INIT
#endif
#define FORCE_EMX_DEINIT_EXIT 1
#define FORCE_EMX_DEINIT_CRT_TERM 2
#define FORCE_EMX_DEINIT_RUN_ATEXIT 4
#define PERL_SYS_TERM2(xreg,flags) \
Perl_OS2_term(xreg, 0, flags); \
PERLIO_TERM; \
MALLOC_TERM
#define PERL_SYS_TERM1(xreg) \
Perl_OS2_term(xreg, 0, FORCE_EMX_DEINIT_RUN_ATEXIT)
/* This one should come in pair with PERL_SYS_INIT_BODY() and in the same block */
#define PERL_SYS_TERM_BODY() \
PERL_SYS_TERM1(xreg); \
}
#ifndef __EMX__
# define PERL_CALLCONV _System
#endif
/* #define PERL_SYS_TERM_BODY() STMT_START { \
if (Perl_HAB_set) WinTerminate(Perl_hab); } STMT_END */
#define dXSUB_SYS OS2_XS_init()
#ifdef PERL_IS_AOUT
/* # define HAS_FORK */
/* # define HIDEMYMALLOC */
/* # define PERL_SBRK_VIA_MALLOC */ /* gets off-page sbrk... */
#else /* !PERL_IS_AOUT */
# ifndef PERL_FOR_X2P
# ifdef EMX_BAD_SBRK
# define USE_PERL_SBRK
# endif
# else
# define PerlIO FILE
# endif
# define SYSTEM_ALLOC(a) sys_alloc(a)
void *sys_alloc(int size);
#endif /* !PERL_IS_AOUT */
#if !defined(PERL_CORE) && !defined(PerlIO) /* a2p */
# define PerlIO FILE
#endif
/* os2ish is used from a2p/a2p.h without pTHX/pTHX_ first being
* defined. Hack around this to get us to compile.
*/
#ifdef PTHX_UNUSED
# ifndef pTHX
# define pTHX
# endif
# ifndef pTHX_
# define pTHX_
# endif
#endif
#define TMPPATH1 "plXXXXXX"
extern const char *tmppath;
PerlIO *my_syspopen(pTHX_ char *cmd, char *mode);
#ifdef PERL_CORE
/* Cannot prototype with I32, SV at this point (used in x2p too). */
PerlIO *my_syspopen4(pTHX_ char *cmd, char *mode, I32 cnt, SV** args);
#endif
int my_syspclose(PerlIO *f);
FILE *my_tmpfile (void);
char *my_tmpnam (char *);
int my_mkdir (__const__ char *, long);
int my_rmdir (__const__ char *);
struct passwd *my_getpwent (void);
void my_setpwent (void);
void my_endpwent (void);
char *gcvt_os2(double value, int digits, char *buffer);
extern int async_mssleep(unsigned long ms, int switch_priority);
extern unsigned long msCounter(void);
extern unsigned long InfoTable(int local);
extern unsigned long find_myself(void);
#define MAX_SLEEP (((1<30) / (1000/4))-1) /* 1<32 msec */
static __inline__ unsigned
my_sleep(unsigned sec)
{
int remain;
while (sec > MAX_SLEEP) {
sec -= MAX_SLEEP;
remain = sleep(MAX_SLEEP);
if (remain)
return remain + sec;
}
return sleep(sec);
}
#define sleep my_sleep
#ifndef INCL_DOS
unsigned long DosSleep(unsigned long);
unsigned long DosAllocThreadLocalMemory (unsigned long cb, unsigned long **p);
#endif
struct group *getgrent (void);
void setgrent (void);
void endgrent (void);
struct passwd *my_getpwuid (uid_t);
struct passwd *my_getpwnam (__const__ char *);
#undef L_tmpnam
#define L_tmpnam MAXPATHLEN
#define tmpfile my_tmpfile
#define tmpnam my_tmpnam
#define isatty _isterm
#define rand random
#define srand srandom
#define strtoll _strtoll
#define strtoull _strtoull
#define usleep(usec) ((void)async_mssleep(((usec)+500)/1000, 500))
/*
* fwrite1() should be a routine with the same calling sequence as fwrite(),
* but which outputs all of the bytes requested as a single stream (unlike
* fwrite() itself, which on some systems outputs several distinct records
* if the number_of_items parameter is >1).
*/
#define fwrite1 fwrite
#define my_getenv(var) getenv(var)
#define flock my_flock
#define rmdir my_rmdir
#define mkdir my_mkdir
#define setpwent my_setpwent
#define getpwent my_getpwent
#define endpwent my_endpwent
#define getpwuid my_getpwuid
#define getpwnam my_getpwnam
void *emx_calloc (size_t, size_t);
void emx_free (void *);
void *emx_malloc (size_t);
void *emx_realloc (void *, size_t);
/*****************************************************************************/
#include <stdlib.h> /* before the following definitions */
#include <unistd.h> /* before the following definitions */
#include <fcntl.h>
#include <sys/stat.h>
#define chdir _chdir2
#define getcwd _getcwd2
/* This guy is needed for quick stdstd */
#if defined(USE_STDIO_PTR) && defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
/* Perl uses ungetc only with successful return */
# define ungetc(c,fp) \
(FILE_ptr(fp) > FILE_base(fp) && c == (int)*(FILE_ptr(fp) - 1) \
? (--FILE_ptr(fp), ++FILE_cnt(fp), (int)c) : ungetc(c,fp))
#endif
#define PERLIO_IS_BINMODE_FD(fd) _PERLIO_IS_BINMODE_FD(fd)
#ifdef __GNUG__
# define HAS_BOOL
#endif
#ifndef HAS_BOOL
# define bool char
# define HAS_BOOL 1
#endif
#include <emx/io.h> /* for _fd_flags() prototype */
static inline bool
_PERLIO_IS_BINMODE_FD(int fd)
{
int *pflags = _fd_flags(fd);
return pflags && (*pflags) & O_BINARY;
}
/* ctermid is missing from emx0.9d */
char *ctermid(char *s);
#define OP_BINARY O_BINARY
#define OS2_STAT_HACK 1
#if OS2_STAT_HACK
#define Stat(fname,bufptr) os2_stat((fname),(bufptr))
#define Fstat(fd,bufptr) os2_fstat((fd),(bufptr))
#define Fflush(fp) fflush(fp)
#define Mkdir(path,mode) mkdir((path),(mode))
#define chmod(path,mode) os2_chmod((path),(mode))
#undef S_IFBLK
#undef S_ISBLK
#define S_IFBLK 0120000 /* Hacks to make things compile... */
#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
int os2_chmod(const char *name, int pmode);
int os2_fstat(int handle, struct stat *st);
#else
#define Stat(fname,bufptr) stat((fname),(bufptr))
#define Fstat(fd,bufptr) fstat((fd),(bufptr))
#define Fflush(fp) fflush(fp)
#define Mkdir(path,mode) mkdir((path),(mode))
#endif
/* With SD386 it is impossible to debug register variables. */
#if !defined(PERL_IS_AOUT) && defined(DEBUGGING) && !defined(register)
# define register
#endif
/* Our private OS/2 specific data. */
typedef struct OS2_Perl_data {
unsigned long flags;
unsigned long phab;
int (*xs_init)();
unsigned long rc;
unsigned long severity;
unsigned long phmq; /* Handle to message queue */
unsigned long phmq_refcnt;
unsigned long phmq_servers;
unsigned long initial_mode; /* VIO etc. mode we were started in */
unsigned long morph_refcnt;
} OS2_Perl_data_t;
extern OS2_Perl_data_t OS2_Perl_data;
#define Perl_hab ((HAB)OS2_Perl_data.phab)
#define Perl_rc (OS2_Perl_data.rc)
#define Perl_severity (OS2_Perl_data.severity)
#define errno_isOS2 12345678
#define errno_isOS2_set 12345679
#define OS2_Perl_flags (OS2_Perl_data.flags)
#define Perl_HAB_set_f 1
#define Perl_HAB_set (OS2_Perl_flags & Perl_HAB_set_f)
#define set_Perl_HAB_f (OS2_Perl_flags |= Perl_HAB_set_f)
#define set_Perl_HAB(h) (set_Perl_HAB_f, Perl_hab = h)
#define _obtain_Perl_HAB (init_PMWIN_entries(), \
Perl_hab = (*PMWIN_entries.Initialize)(0), \
set_Perl_HAB_f, Perl_hab)
#define perl_hab_GET() (Perl_HAB_set ? Perl_hab : _obtain_Perl_HAB)
#define Acquire_hab() perl_hab_GET()
#define Perl_hmq ((HMQ)OS2_Perl_data.phmq)
#define Perl_hmq_refcnt (OS2_Perl_data.phmq_refcnt)
#define Perl_hmq_servers (OS2_Perl_data.phmq_servers)
#define Perl_os2_initial_mode (OS2_Perl_data.initial_mode)
#define Perl_morph_refcnt (OS2_Perl_data.morph_refcnt)
unsigned long Perl_hab_GET();
unsigned long Perl_Register_MQ(int serve);
void Perl_Deregister_MQ(int serve);
int Perl_Serve_Messages(int force);
/* Cannot prototype with I32 at this point. */
int Perl_Process_Messages(int force, long *cntp);
char *os2_execname(pTHX);
struct _QMSG;
struct PMWIN_entries_t {
unsigned long (*Initialize)( unsigned long fsOptions );
unsigned long (*CreateMsgQueue)(unsigned long hab, long cmsg);
int (*DestroyMsgQueue)(unsigned long hmq);
int (*PeekMsg)(unsigned long hab, struct _QMSG *pqmsg,
unsigned long hwndFilter, unsigned long msgFilterFirst,
unsigned long msgFilterLast, unsigned long fl);
int (*GetMsg)(unsigned long hab, struct _QMSG *pqmsg,
unsigned long hwndFilter, unsigned long msgFilterFirst,
unsigned long msgFilterLast);
void * (*DispatchMsg)(unsigned long hab, struct _QMSG *pqmsg);
unsigned long (*GetLastError)(unsigned long hab);
unsigned long (*CancelShutdown)(unsigned long hmq, unsigned long fCancelAlways);
};
extern struct PMWIN_entries_t PMWIN_entries;
void init_PMWIN_entries(void);
#define perl_hmq_GET(serve) Perl_Register_MQ(serve)
#define perl_hmq_UNSET(serve) Perl_Deregister_MQ(serve)
#define OS2_XS_init() (*OS2_Perl_data.xs_init)(aTHX)
#if _EMX_CRT_REV_ >= 60
# define os2_setsyserrno(rc) (Perl_rc = rc, errno = errno_isOS2_set, \
_setsyserrno(rc))
#else
# define os2_setsyserrno(rc) (Perl_rc = rc, errno = errno_isOS2)
#endif
/* The expressions below return true on error. */
/* INCL_DOSERRORS needed. rc should be declared outside. */
#define CheckOSError(expr) ((rc = (expr)) ? (FillOSError(rc), rc) : 0)
/* INCL_WINERRORS needed. */
#define CheckWinError(expr) ((expr) ? 0: (FillWinError, 1))
/* This form propagates the return value, setting $^E if needed */
#define SaveWinError(expr) ((expr) ? : (FillWinError, 0))
/* This form propagates the return value, dieing with $^E if needed */
#define SaveCroakWinError(expr,die,name1,name2) \
((expr) ? : (CroakWinError(die,name1 name2), 0))
#define FillOSError(rc) (os2_setsyserrno(rc), \
Perl_severity = SEVERITY_ERROR)
#define WinError_2_Perl_rc \
( init_PMWIN_entries(), \
Perl_rc=(*PMWIN_entries.GetLastError)(perl_hab_GET()) )
/* Calling WinGetLastError() resets the error code of the current thread.
Since for some Win* API return value 0 is normal, one needs to call
this before calling them to distinguish normal and anomalous returns. */
/*#define ResetWinError() WinError_2_Perl_rc */
/* At this moment init_PMWIN_entries() should be a nop (WinInitialize should
be called already, right?), so we do not risk stepping over our own error */
#define FillWinError ( WinError_2_Perl_rc, \
Perl_severity = ERRORIDSEV(Perl_rc), \
Perl_rc = ERRORIDERROR(Perl_rc), \
os2_setsyserrno(Perl_rc))
#define STATIC_FILE_LENGTH 127
/* This should match loadOrdinals[] array in os2.c */
enum entries_ordinals {
ORD_DosQueryExtLibpath,
ORD_DosSetExtLibpath,
ORD_DosVerifyPidTid,
ORD_SETHOSTENT,
ORD_SETNETENT,
ORD_SETPROTOENT,
ORD_SETSERVENT,
ORD_GETHOSTENT,
ORD_GETNETENT,
ORD_GETPROTOENT,
ORD_GETSERVENT,
ORD_ENDHOSTENT,
ORD_ENDNETENT,
ORD_ENDPROTOENT,
ORD_ENDSERVENT,
ORD_WinInitialize,
ORD_WinCreateMsgQueue,
ORD_WinDestroyMsgQueue,
ORD_WinPeekMsg,
ORD_WinGetMsg,
ORD_WinDispatchMsg,
ORD_WinGetLastError,
ORD_WinCancelShutdown,
ORD_RexxStart,
ORD_RexxVariablePool,
ORD_RexxRegisterFunctionExe,
ORD_RexxDeregisterFunction,
ORD_DOSSMSETTITLE,
ORD_PRF32QUERYPROFILESIZE,
ORD_PRF32OPENPROFILE,
ORD_PRF32CLOSEPROFILE,
ORD_PRF32QUERYPROFILE,
ORD_PRF32RESET,
ORD_PRF32QUERYPROFILEDATA,
ORD_PRF32WRITEPROFILEDATA,
ORD_WinChangeSwitchEntry,
ORD_WinQuerySwitchEntry,
ORD_WinQuerySwitchHandle,
ORD_WinQuerySwitchList,
ORD_WinSwitchToProgram,
ORD_WinBeginEnumWindows,
ORD_WinEndEnumWindows,
ORD_WinEnumDlgItem,
ORD_WinGetNextWindow,
ORD_WinIsChild,
ORD_WinQueryActiveWindow,
ORD_WinQueryClassName,
ORD_WinQueryFocus,
ORD_WinQueryWindow,
ORD_WinQueryWindowPos,
ORD_WinQueryWindowProcess,
ORD_WinQueryWindowText,
ORD_WinQueryWindowTextLength,
ORD_WinSetFocus,
ORD_WinSetWindowPos,
ORD_WinSetWindowText,
ORD_WinShowWindow,
ORD_WinIsWindow,
ORD_WinWindowFromId,
ORD_WinWindowFromPoint,
ORD_WinPostMsg,
ORD_WinEnableWindow,
ORD_WinEnableWindowUpdate,
ORD_WinIsWindowEnabled,
ORD_WinIsWindowShowing,
ORD_WinIsWindowVisible,
ORD_WinQueryWindowPtr,
ORD_WinQueryWindowULong,
ORD_WinQueryWindowUShort,
ORD_WinSetWindowBits,
ORD_WinSetWindowPtr,
ORD_WinSetWindowULong,
ORD_WinSetWindowUShort,
ORD_WinQueryDesktopWindow,
ORD_WinSetActiveWindow,
ORD_DosQueryModFromEIP,
ORD_Dos32QueryHeaderInfo,
ORD_DosTmrQueryFreq,
ORD_DosTmrQueryTime,
ORD_WinQueryActiveDesktopPathname,
ORD_WinInvalidateRect,
ORD_WinCreateFrameControls,
ORD_WinQueryClipbrdFmtInfo,
ORD_WinQueryClipbrdOwner,
ORD_WinQueryClipbrdViewer,
ORD_WinQueryClipbrdData,
ORD_WinOpenClipbrd,
ORD_WinCloseClipbrd,
ORD_WinSetClipbrdData,
ORD_WinSetClipbrdOwner,
ORD_WinSetClipbrdViewer,
ORD_WinEnumClipbrdFmts,
ORD_WinEmptyClipbrd,
ORD_WinAddAtom,
ORD_WinFindAtom,
ORD_WinDeleteAtom,
ORD_WinQueryAtomUsage,
ORD_WinQueryAtomName,
ORD_WinQueryAtomLength,
ORD_WinQuerySystemAtomTable,
ORD_WinCreateAtomTable,
ORD_WinDestroyAtomTable,
ORD_WinOpenWindowDC,
ORD_DevOpenDC,
ORD_DevQueryCaps,
ORD_DevCloseDC,
ORD_WinMessageBox,
ORD_WinMessageBox2,
ORD_WinQuerySysValue,
ORD_WinSetSysValue,
ORD_WinAlarm,
ORD_WinFlashWindow,
ORD_WinLoadPointer,
ORD_WinQuerySysPointer,
ORD_DosReplaceModule,
ORD_DosPerfSysCall,
ORD_RexxRegisterSubcomExe,
ORD_NENTRIES
};
/* RET: return type, AT: argument signature in (), ARGS: should be in () */
#define CallORD(ret,o,at,args) (((ret (*)at) loadByOrdinal(o, 1))args)
#define DeclFuncByORD(ret,name,o,at,args) \
ret name at { return CallORD(ret,o,at,args); }
#define DeclVoidFuncByORD(name,o,at,args) \
void name at { CallORD(void,o,at,args); }
/* This function returns error code on error, and saves the error info in $^E and Perl_rc */
#define DeclOSFuncByORD_native(ret,name,o,at,args) \
ret name at { unsigned long rc; return CheckOSError(CallORD(ret,o,at,args)); }
/* These functions return false on error, and save the error info in $^E and Perl_rc */
#define DeclOSFuncByORD(ret,name,o,at,args) \
ret name at { unsigned long rc; return !CheckOSError(CallORD(ret,o,at,args)); }
#define DeclWinFuncByORD(ret,name,o,at,args) \
ret name at { return SaveWinError(CallORD(ret,o,at,args)); }
#define AssignFuncPByORD(p,o) (*(Perl_PFN*)&(p) = (loadByOrdinal(o, 1)))
/* This flavor caches the procedure pointer (named as p__Win#name) locally */
#define DeclWinFuncByORD_CACHE(ret,name,o,at,args) \
DeclWinFuncByORD_CACHE_r(ret,name,o,at,args,0,1)
/* This flavor may reset the last error before the call (if ret=0 may be OK) */
#define DeclWinFuncByORD_CACHE_resetError(ret,name,o,at,args) \
DeclWinFuncByORD_CACHE_r(ret,name,o,at,args,1,1)
/* Two flavors below do the same as above, but do not auto-croak */
/* This flavor caches the procedure pointer (named as p__Win#name) locally */
#define DeclWinFuncByORD_CACHE_survive(ret,name,o,at,args) \
DeclWinFuncByORD_CACHE_r(ret,name,o,at,args,0,0)
/* This flavor may reset the last error before the call (if ret=0 may be OK) */
#define DeclWinFuncByORD_CACHE_resetError_survive(ret,name,o,at,args) \
DeclWinFuncByORD_CACHE_r(ret,name,o,at,args,1,0)
#define DeclWinFuncByORD_CACHE_r(ret,name,o,at,args,r,die) \
static ret (*CAT2(p__Win,name)) at; \
static ret name at { \
if (!CAT2(p__Win,name)) \
AssignFuncPByORD(CAT2(p__Win,name), o); \
if (r) ResetWinError(); \
return SaveCroakWinError(CAT2(p__Win,name) args, die, "[Win]", STRINGIFY(name)); }
/* These flavors additionally assume ORD is name with prepended ORD_Win */
#define DeclWinFunc_CACHE(ret,name,at,args) \
DeclWinFuncByORD_CACHE(ret,name,CAT2(ORD_Win,name),at,args)
#define DeclWinFunc_CACHE_resetError(ret,name,at,args) \
DeclWinFuncByORD_CACHE_resetError(ret,name,CAT2(ORD_Win,name),at,args)
#define DeclWinFunc_CACHE_survive(ret,name,at,args) \
DeclWinFuncByORD_CACHE_survive(ret,name,CAT2(ORD_Win,name),at,args)
#define DeclWinFunc_CACHE_resetError_survive(ret,name,at,args) \
DeclWinFuncByORD_CACHE_resetError_survive(ret,name,CAT2(ORD_Win,name),at,args)
void ResetWinError(void);
void CroakWinError(int die, char *name);
enum Perlos2_handler {
Perlos2_handler_mangle = 1,
Perlos2_handler_perl_sh,
Perlos2_handler_perllib_from,
Perlos2_handler_perllib_to,
};
enum dir_subst_e {
dir_subst_fatal = 1,
dir_subst_pathlike = 2
};
extern int Perl_OS2_handler_install(void *handler, enum Perlos2_handler how);
extern char *dir_subst(char *s, unsigned int l, char *b, unsigned int bl, enum dir_subst_e flags, char *msg);
extern unsigned long fill_extLibpath(int type, char *pre, char *post, int replace, char *msg);
#define PERLLIB_MANGLE(s, n) perllib_mangle((s), (n))
char *perllib_mangle(char *, unsigned int);
#define fork fork_with_resources
#ifdef EINTR /* x2p do not include perl.h!!! */
static __inline__ int
my_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
if (nfds == 0 && timeout && (_emx_env & 0x200)) {
if (async_mssleep(1000 * timeout->tv_sec + (timeout->tv_usec + 500)/1000, 500))
return 0;
errno = EINTR;
return -1;
}
return select(nfds, readfds, writefds, exceptfds, timeout);
}
#define select my_select
#endif
typedef int (*Perl_PFN)();
Perl_PFN loadByOrdinal(enum entries_ordinals ord, int fail);
extern const Perl_PFN * const pExtFCN;
char *os2error(int rc);
int os2_stat(const char *name, struct stat *st);
int fork_with_resources();
int setpriority(int which, int pid, int val);
int getpriority(int which /* ignored */, int pid);
void croak_with_os2error(char *s) __attribute__((noreturn));
/* void return value */
#define os2cp_croak(rc,msg) (CheckOSError(rc) && (croak_with_os2error(msg),0))
/* propagates rc */
#define os2win_croak(rc,msg) \
SaveCroakWinError((expr), 1 /* die */, /* no prefix */, (msg))
/* propagates rc; use with functions which may return 0 on success */
#define os2win_croak_0OK(rc,msg) \
SaveCroakWinError((ResetWinError, (expr)), \
1 /* die */, /* no prefix */, (msg))
#ifdef PERL_CORE
int os2_do_spawn(pTHX_ char *cmd);
int os2_do_aspawn(pTHX_ SV *really, SV **vmark, SV **vsp);
#endif
#ifndef LOG_DAEMON
/* Replacement for syslog.h */
# define LOG_EMERG 0 /* system is unusable */
# define LOG_ALERT 1 /* action must be taken immediately */
# define LOG_CRIT 2 /* critical conditions */
# define LOG_ERR 3 /* error conditions */
# define LOG_WARNING 4 /* warning conditions */
# define LOG_NOTICE 5 /* normal but significant condition */
# define LOG_INFO 6 /* informational */
# define LOG_DEBUG 7 /* debug-level messages */
# define LOG_PRIMASK 0x007 /* mask to extract priority part (internal) */
/* extract priority */
# define LOG_PRI(p) ((p) & LOG_PRIMASK)
# define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri))
/* facility codes */
# define LOG_KERN (0<<3) /* kernel messages */
# define LOG_USER (1<<3) /* random user-level messages */
# define LOG_MAIL (2<<3) /* mail system */
# define LOG_DAEMON (3<<3) /* system daemons */
# define LOG_AUTH (4<<3) /* security/authorization messages */
# define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
# define LOG_LPR (6<<3) /* line printer subsystem */
# define LOG_NEWS (7<<3) /* network news subsystem */
# define LOG_UUCP (8<<3) /* UUCP subsystem */
# define LOG_CRON (15<<3) /* clock daemon */
/* other codes through 15 reserved for system use */
# define LOG_LOCAL0 (16<<3) /* reserved for local use */
# define LOG_LOCAL1 (17<<3) /* reserved for local use */
# define LOG_LOCAL2 (18<<3) /* reserved for local use */
# define LOG_LOCAL3 (19<<3) /* reserved for local use */
# define LOG_LOCAL4 (20<<3) /* reserved for local use */
# define LOG_LOCAL5 (21<<3) /* reserved for local use */
# define LOG_LOCAL6 (22<<3) /* reserved for local use */
# define LOG_LOCAL7 (23<<3) /* reserved for local use */
# define LOG_NFACILITIES 24 /* current number of facilities */
# define LOG_FACMASK 0x03f8 /* mask to extract facility part */
/* facility of pri */
# define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3)
/*
* arguments to setlogmask.
*/
# define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */
# define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */
/*
* Option flags for openlog.
*
* LOG_ODELAY no longer does anything.
* LOG_NDELAY is the inverse of what it used to be.
*/
# define LOG_PID 0x01 /* log the pid with each message */
# define LOG_CONS 0x02 /* log on the console if errors in sending */
# define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */
# define LOG_NDELAY 0x08 /* don't delay open */
# define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */
# define LOG_PERROR 0x20 /* log to stderr as well */
#endif
/* ************************************************* */
#ifndef MAKEPLINFOSEG
/* From $DDK\base32\rel\os2c\include\base\os2\16bit\infoseg.h + typedefs */
/*
* The structure below defines the content and organization of the system
* information segment (InfoSeg). The actual table is statically defined in
* SDATA.ASM. Ring 0, read/write access is obtained by the clock device
* driver using the DevHlp GetDOSVar function. (GetDOSVar returns a ring 0,
* read-only selector to all other requestors.)
*
* In order to prevent an errant process from destroying the infoseg, two
* identical global infosegs are maintained. One is in the tiled shared
* arena and is accessible in user mode (and therefore can potentially be
* overwritten from ring 2), and the other is in the system arena and is
* accessible only in kernel mode. All kernel code (except the clock driver)
* is responsible for updating BOTH copies of the infoseg. The copy kept
* in the system arena is addressable as DOSGROUP:SISData, and the copy
* in the shared arena is addressable via a system arena alias. 16:16 and
* 0:32 pointers to the alias are stored in _Sis2.
*/
typedef struct InfoSegGDT {
/* Time (offset 0x00) */
unsigned long SIS_BigTime; /* Time from 1-1-1970 in seconds */
unsigned long SIS_MsCount; /* Freerunning milliseconds counter */
unsigned char SIS_HrsTime; /* Hours */
unsigned char SIS_MinTime; /* Minutes */
unsigned char SIS_SecTime; /* Seconds */
unsigned char SIS_HunTime; /* Hundredths of seconds */
unsigned short SIS_TimeZone; /* Timezone in min from GMT (Set to EST) */
unsigned short SIS_ClkIntrvl; /* Timer interval (units=0.0001 secs) */
/* Date (offset 0x10) */
unsigned char SIS_DayDate; /* Day-of-month (1-31) */
unsigned char SIS_MonDate; /* Month (1-12) */
unsigned short SIS_YrsDate; /* Year (>= 1980) */
unsigned char SIS_DOWDate; /* Day-of-week (1-1-80 = Tues = 3) */
/* Version (offset 0x15) */
unsigned char SIS_VerMajor; /* Major version number */
unsigned char SIS_VerMinor; /* Minor version number */
unsigned char SIS_RevLettr; /* Revision letter */
/* System Status (offset 0x18) */
unsigned char SIS_CurScrnGrp; /* Fgnd screen group # */
unsigned char SIS_MaxScrnGrp; /* Maximum number of screen groups */
unsigned char SIS_HugeShfCnt; /* Shift count for huge segments */
unsigned char SIS_ProtMdOnly; /* Protect-mode-only indicator */
unsigned short SIS_FgndPID; /* Foreground process ID */
/* Scheduler Parms (offset 0x1E) */
unsigned char SIS_Dynamic; /* Dynamic variation flag (1=enabled) */
unsigned char SIS_MaxWait; /* Maxwait (seconds) */
unsigned short SIS_MinSlice; /* Minimum timeslice (milliseconds) */
unsigned short SIS_MaxSlice; /* Maximum timeslice (milliseconds) */
/* Boot Drive (offset 0x24) */
unsigned short SIS_BootDrv; /* Drive from which system was booted */
/* RAS Major Event Code Table (offset 0x26) */
unsigned char SIS_mec_table[32]; /* Table of RAS Major Event Codes (MECs) */
/* Additional Session Data (offset 0x46) */
unsigned char SIS_MaxVioWinSG; /* Max. no. of VIO windowable SG's */
unsigned char SIS_MaxPresMgrSG; /* Max. no. of Presentation Manager SG's */
/* Error logging Information (offset 0x48) */
unsigned short SIS_SysLog; /* Error Logging Status */
/* Additional RAS Information (offset 0x4A) */
unsigned short SIS_MMIOBase; /* Memory mapped I/O selector */
unsigned long SIS_MMIOAddr; /* Memory mapped I/O address */
/* Additional 2.0 Data (offset 0x50) */
unsigned char SIS_MaxVDMs; /* Max. no. of Virtual DOS machines */
unsigned char SIS_Reserved;
unsigned char SIS_perf_mec_table[32]; /* varga 6/5/97 Table of Perfomance Major Event Codes (MECS) varga*/
} GINFOSEG, *PGINFOSEG;
#define SIS_LEN sizeof(struct InfoSegGDT)
/*
* InfoSeg LDT Data Segment Structure
*
* The structure below defines the content and organization of the system
* information in a special per-process segment to be accessible by the
* process through the LDT (read-only).
*
* As in the global infoseg, two copies of the current processes local
* infoseg exist, one accessible in both user and kernel mode, the other
* only in kernel mode. Kernel code is responsible for updating BOTH copies.
* Pointers to the local infoseg copy are stored in _Lis2.
*
* Note that only the currently running process has an extra copy of the
* local infoseg. The copy is done at context switch time.
*/
typedef struct InfoSegLDT {
unsigned short LIS_CurProcID; /* Current process ID */
unsigned short LIS_ParProcID; /* Process ID of parent */
unsigned short LIS_CurThrdPri; /* Current thread priority */
unsigned short LIS_CurThrdID; /* Current thread ID */
unsigned short LIS_CurScrnGrp; /* Screengroup */
unsigned char LIS_ProcStatus; /* Process status bits */
unsigned char LIS_fillbyte1; /* filler byte */
unsigned short LIS_Fgnd; /* Current process is in foreground */
unsigned char LIS_ProcType; /* Current process type */
unsigned char LIS_fillbyte2; /* filler byte */
unsigned short LIS_AX; /* @@V1 Environment selector */
unsigned short LIS_BX; /* @@V1 Offset of command line start */
unsigned short LIS_CX; /* @@V1 Length of Data Segment */
unsigned short LIS_DX; /* @@V1 STACKSIZE from the .EXE file */
unsigned short LIS_SI; /* @@V1 HEAPSIZE from the .EXE file */
unsigned short LIS_DI; /* @@V1 Module handle of the application */
unsigned short LIS_DS; /* @@V1 Data Segment Handle of application */
unsigned short LIS_PackSel; /* First tiled selector in this EXE */
unsigned short LIS_PackShrSel; /* First selector above shared arena */
unsigned short LIS_PackPckSel; /* First selector above packed arena */
/* #ifdef SMP */
unsigned long LIS_pTIB; /* Pointer to TIB */
unsigned long LIS_pPIB; /* Pointer to PIB */
/* #endif */
} LINFOSEG, *PLINFOSEG;
#define LIS_LEN sizeof(struct InfoSegLDT)
/*
* Process Type codes
*
* These are the definitons for the codes stored
* in the LIS_ProcType field in the local infoseg.
*/
#define LIS_PT_FULLSCRN 0 /* Full screen app. */
#define LIS_PT_REALMODE 1 /* Real mode process */
#define LIS_PT_VIOWIN 2 /* VIO windowable app. */
#define LIS_PT_PRESMGR 3 /* Presentation Manager app. */
#define LIS_PT_DETACHED 4 /* Detached app. */
/*
*
* Process Status Bit Definitions
*
*/
#define LIS_PS_EXITLIST 0x01 /* In exitlist handler */
/*
* Flags equates for the Global Info Segment
* SIS_SysLog WORD in Global Info Segment
*
* xxxx xxxx xxxx xxx0 Error Logging Disabled
* xxxx xxxx xxxx xxx1 Error Logging Enabled
*
* xxxx xxxx xxxx xx0x Error Logging not available
* xxxx xxxx xxxx xx1x Error Logging available
*/
#define LF_LOGENABLE 0x0001 /* Logging enabled */
#define LF_LOGAVAILABLE 0x0002 /* Logging available */
#define MAKEPGINFOSEG(sel) ((PGINFOSEG)MAKEP(sel, 0))
#define MAKEPLINFOSEG(sel) ((PLINFOSEG)MAKEP(sel, 0))
#endif /* ndef(MAKEPLINFOSEG) */
/* ************************************************************ */
#define Dos32QuerySysState DosQuerySysState
#define QuerySysState(flags, pid, buf, bufsz) \
Dos32QuerySysState(flags, 0, pid, 0, buf, bufsz)
#define QSS_PROCESS 1
#define QSS_MODULE 4
#define QSS_SEMAPHORES 2
#define QSS_FILE 8 /* Buggy until fixpack18 */
#define QSS_SHARED 16
#ifdef _OS2_H
APIRET APIENTRY Dos32QuerySysState(ULONG func,ULONG arg1,ULONG pid,
ULONG _res_,PVOID buf,ULONG bufsz);
typedef struct {
ULONG threadcnt;
ULONG proccnt;
ULONG modulecnt;
} QGLOBAL, *PQGLOBAL;
typedef struct {
ULONG rectype;
USHORT threadid;
USHORT slotid;
ULONG sleepid;
ULONG priority;
ULONG systime;
ULONG usertime;
UCHAR state;
UCHAR _reserved1_; /* padding to ULONG */
USHORT _reserved2_; /* padding to ULONG */
} QTHREAD, *PQTHREAD;
typedef struct {
USHORT sfn;
USHORT refcnt;
USHORT flags1;
USHORT flags2;
USHORT accmode1;
USHORT accmode2;
ULONG filesize;
USHORT volhnd;
USHORT attrib;
USHORT _reserved_;
} QFDS, *PQFDS;
typedef struct qfile {
ULONG rectype;
struct qfile *next;
ULONG opencnt;
PQFDS filedata;
char name[1];
} QFILE, *PQFILE;
typedef struct {
ULONG rectype;
PQTHREAD threads;
USHORT pid;
USHORT ppid;
ULONG type;
ULONG state;
ULONG sessid;
USHORT hndmod;
USHORT threadcnt;
ULONG privsem32cnt;
ULONG _reserved2_;
USHORT sem16cnt;
USHORT dllcnt;
USHORT shrmemcnt;
USHORT fdscnt;
PUSHORT sem16s;
PUSHORT dlls;
PUSHORT shrmems;
PUSHORT fds;
} QPROCESS, *PQPROCESS;
typedef struct sema {
struct sema *next;
USHORT refcnt;
UCHAR sysflags;
UCHAR sysproccnt;
ULONG _reserved1_;
USHORT index;
CHAR name[1];
} QSEMA, *PQSEMA;
typedef struct {
ULONG rectype;
ULONG _reserved1_;
USHORT _reserved2_;
USHORT syssemidx;
ULONG index;
QSEMA sema;
} QSEMSTRUC, *PQSEMSTRUC;
typedef struct {
USHORT pid;
USHORT opencnt;
} QSEMOWNER32, *PQSEMOWNER32;
typedef struct {
PQSEMOWNER32 own;
PCHAR name;
PVOID semrecs; /* array of associated sema's */
USHORT flags;
USHORT semreccnt;
USHORT waitcnt;
USHORT _reserved_; /* padding to ULONG */
} QSEMSMUX32, *PQSEMSMUX32;
typedef struct {
PQSEMOWNER32 own;
PCHAR name;
PQSEMSMUX32 mux;
USHORT flags;
USHORT postcnt;
} QSEMEV32, *PQSEMEV32;
typedef struct {
PQSEMOWNER32 own;
PCHAR name;
PQSEMSMUX32 mux;
USHORT flags;
USHORT refcnt;
USHORT thrdnum;
USHORT _reserved_; /* padding to ULONG */
} QSEMMUX32, *PQSEMMUX32;
typedef struct semstr32 {
struct semstr *next;
QSEMEV32 evsem;
QSEMMUX32 muxsem;
QSEMSMUX32 smuxsem;
} QSEMSTRUC32, *PQSEMSTRUC32;
typedef struct shrmem {
struct shrmem *next;
USHORT hndshr;
USHORT selshr;
USHORT refcnt;
CHAR name[1];
} QSHRMEM, *PQSHRMEM;
typedef struct module {
struct module *next;
USHORT hndmod;
USHORT type;
ULONG refcnt;
ULONG segcnt;
PVOID _reserved_;
PCHAR name;
USHORT modref[1];
} QMODULE, *PQMODULE;
typedef struct {
PQGLOBAL gbldata;
PQPROCESS procdata;
PQSEMSTRUC semadata;
PQSEMSTRUC32 sem32data;
PQSHRMEM shrmemdata;
PQMODULE moddata;
PVOID _reserved2_;
PQFILE filedata;
} QTOPLEVEL, *PQTOPLEVEL;
/* ************************************************************ */
PQTOPLEVEL get_sysinfo(ULONG pid, ULONG flags);
#endif /* _OS2_H */
| 16,139 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "MiniLayout",
"version": "1.2.1",
"summary": "Minimal AutoLayout convenience layer. Program constraints succinctly.",
"description": "Usage:\n\n```swift\nview.addConstrainedSubview(label, constrain: .Leading, .Top)\nview.constrain(textField, at: .Leading, to: label, at: .Trailing, diff: 8)\n```",
"homepage": "https://github.com/yonat/MiniLayout",
"license": {
"type": "MIT",
"file": "LICENSE.txt"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "http://twitter.com/yonatsharon",
"swift_version": "4.0",
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"source": {
"git": "https://github.com/yonat/MiniLayout.git",
"tag": "1.2.1"
},
"source_files": "Sources/MiniLayout.swift"
}
| 333 |
2,643 | #ifndef OD_DEBUGPRINTF_H
#define OD_DEBUGPRINTF_H
/*
* Odyssey.
*
* Scalable PostgreSQL connection pooler.
*/
void od_dbg_printf(char *fmt, ...);
#define OD_RELEASE_MODE -1
#ifndef OD_DEVEL_LVL
/* set "release" mode by default */
#define OD_DEVEL_LVL OD_RELEASE_MODE
#endif
#if OD_DEVEL_LVL == OD_RELEASE_MODE
#define od_dbg_printf_on_dvl_lvl(debug_lvl, fmt, ...)
/* zero cost debug print on release mode */
#else
#define od_dbg_printf_on_dvl_lvl(debug_lvl, fmt, ...) \
\
if (OD_DEVEL_LVL >= debug_lvl) { \
od_dbg_printf(fmt, __VA_ARGS__); \
}
#endif
#endif /* OD_DEBUGPRINTF_H */
| 330 |
316 | <gh_stars>100-1000
#include <lfortran/asr.h>
#include <lfortran/containers.h>
#include <lfortran/exception.h>
#include <lfortran/asr_utils.h>
#include <lfortran/asr_verify.h>
#include <lfortran/pass/array_op.h>
#include <lfortran/pass/pass_utils.h>
#include <vector>
#include <utility>
namespace LFortran {
using ASR::down_cast;
using ASR::is_a;
/*
This ASR pass replaces operations over arrays with do loops.
The function `pass_replace_array_op` transforms the ASR tree in-place.
Converts:
c = a + b
to:
do i = lbound(a), ubound(a)
c(i) = a(i) + b(i)
end do
The code below might seem intriguing because of minor but crucial
details. Generally for any node, first, its children are visited.
If any child contains operations over arrays then, the a do loop
pass is added for performing the operation element wise. For stroing
the result, either a new variable is created or a result variable
available from the parent node is used. Once done, this result variable
is used by the parent node in place of the child node from which it was
made available. Consider the example below for better understanding.
Say, BinOp(BinOp(Arr1 Add Arr2) Add Arr3) is the expression we want
to visit. Then, first BinOp(Arr1 Add Arr2) will be visited and its
result will be stored (not actually, just extra ASR do loop node will be added)
in a new variable, Say Result1. Then this Result1 will be used as follows,
BinOp(Result1 Add Arr3). Imagine, this overall expression is further
assigned to some Fortran variable as, Assign(Var1, BinOp(Result1 Add Arr3)).
In this case a new variable will not be created to store the result of RHS, just Var1
will be used as the final destination and a do loop pass will be added as follows,
do i = lbound(Var1), ubound(Var1)
Var1(i) = Result1(i) + Arr3(i)
end do
Note that once the control will reach the above loop, the loop for
Result1 would have already been executed.
All the nodes should be implemented using the above logic to track
array operations and perform the do loop pass. As of now, some of the
nodes are implemented and more are yet to be implemented with time.
*/
class ArrayOpVisitor : public ASR::BaseWalkVisitor<ArrayOpVisitor>
{
private:
Allocator &al;
ASR::TranslationUnit_t &unit;
Vec<ASR::stmt_t*> array_op_result;
/*
This pointer stores the result of a node.
Specifically if a node or its child contains
operations performed over arrays then it points
to the new variable which will store the result
of that operation once the code is compiled.
*/
ASR::expr_t *tmp_val;
/*
This pointer is intened to be a signal for the current
node to create a new variable for storing the result of
array operation or store it in a variable available from
the parent node. For example, if BinOp is a child of the
Assignment node then, the following will point to the target
attribute of the assignment node. This helps in avoiding
unnecessary do loop passes.
*/
ASR::expr_t *result_var;
Vec<ASR::expr_t*> result_lbound, result_ubound, result_inc;
bool use_custom_loop_params;
/*
This integer just maintains the count of new result
variables created. It helps in uniquely identifying
the variables and avoids clash with already existing
variables defined by the user.
*/
int result_var_num;
/*
It stores the address of symbol table of current scope,
which can be program, function, subroutine or even
global scope.
*/
SymbolTable* current_scope;
public:
ArrayOpVisitor(Allocator &al, ASR::TranslationUnit_t &unit) : al{al}, unit{unit},
tmp_val{nullptr}, result_var{nullptr}, use_custom_loop_params{false},
result_var_num{0}, current_scope{nullptr}
{
array_op_result.reserve(al, 1);
result_lbound.reserve(al, 1);
result_ubound.reserve(al, 1);
result_inc.reserve(al, 1);
}
void transform_stmts(ASR::stmt_t **&m_body, size_t &n_body) {
Vec<ASR::stmt_t*> body;
body.reserve(al, n_body);
for (size_t i=0; i<n_body; i++) {
// Not necessary after we check it after each visit_stmt in every
// visitor method:
array_op_result.n = 0;
visit_stmt(*m_body[i]);
if (array_op_result.size() > 0) {
for (size_t j=0; j<array_op_result.size(); j++) {
body.push_back(al, array_op_result[j]);
}
array_op_result.n = 0;
} else {
body.push_back(al, m_body[i]);
}
}
m_body = body.p;
n_body = body.size();
}
// TODO: Only Program and While is processed, we need to process all calls
// to visit_stmt().
void visit_Program(const ASR::Program_t &x) {
std::vector<std::pair<std::string, ASR::symbol_t*>> replace_vec;
// Transform nested functions and subroutines
for (auto &item : x.m_symtab->scope) {
if (is_a<ASR::Subroutine_t>(*item.second)) {
ASR::Subroutine_t *s = down_cast<ASR::Subroutine_t>(item.second);
visit_Subroutine(*s);
}
if (is_a<ASR::Function_t>(*item.second)) {
ASR::Function_t *s = down_cast<ASR::Function_t>(item.second);
visit_Function(*s);
/*
* A function which returns an array will be converted
* to a subroutine with the destination array as the last
* argument. This helps in avoiding deep copies and the
* destination memory directly gets filled inside the subroutine.
*/
if( PassUtils::is_array(s->m_return_var) ) {
for( auto& s_item: s->m_symtab->scope ) {
ASR::symbol_t* curr_sym = s_item.second;
if( curr_sym->type == ASR::symbolType::Variable ) {
ASR::Variable_t* var = down_cast<ASR::Variable_t>(curr_sym);
if( var->m_intent == ASR::intentType::Unspecified ) {
var->m_intent = ASR::intentType::In;
} else if( var->m_intent == ASR::intentType::ReturnVar ) {
var->m_intent = ASR::intentType::Out;
}
}
}
Vec<ASR::expr_t*> a_args;
a_args.reserve(al, s->n_args + 1);
for( size_t i = 0; i < s->n_args; i++ ) {
a_args.push_back(al, s->m_args[i]);
}
a_args.push_back(al, s->m_return_var);
ASR::asr_t* s_sub_asr = ASR::make_Subroutine_t(al, s->base.base.loc, s->m_symtab,
s->m_name, a_args.p, a_args.size(), s->m_body, s->n_body,
s->m_abi, s->m_access, s->m_deftype, nullptr);
ASR::symbol_t* s_sub = ASR::down_cast<ASR::symbol_t>(s_sub_asr);
replace_vec.push_back(std::make_pair(item.first, s_sub));
}
}
}
// FIXME: this is a hack, we need to pass in a non-const `x`,
// which requires to generate a TransformVisitor.
ASR::Program_t &xx = const_cast<ASR::Program_t&>(x);
current_scope = xx.m_symtab;
// Updating the symbol table so that the now the name
// of the function (which returned array) now points
// to the newly created subroutine.
for( auto& item: replace_vec ) {
current_scope->scope[item.first] = item.second;
}
transform_stmts(xx.m_body, xx.n_body);
}
void visit_Subroutine(const ASR::Subroutine_t &x) {
// FIXME: this is a hack, we need to pass in a non-const `x`,
// which requires to generate a TransformVisitor.
ASR::Subroutine_t &xx = const_cast<ASR::Subroutine_t&>(x);
current_scope = xx.m_symtab;
transform_stmts(xx.m_body, xx.n_body);
}
void visit_Function(const ASR::Function_t &x) {
// FIXME: this is a hack, we need to pass in a non-const `x`,
// which requires to generate a TransformVisitor.
ASR::Function_t &xx = const_cast<ASR::Function_t&>(x);
current_scope = xx.m_symtab;
transform_stmts(xx.m_body, xx.n_body);
}
void visit_Assignment(const ASR::Assignment_t& x) {
if( PassUtils::is_array(x.m_target) ) {
result_var = x.m_target;
this->visit_expr(*(x.m_value));
} else if( PassUtils::is_slice_present(x.m_target) ) {
ASR::ArrayRef_t* array_ref = ASR::down_cast<ASR::ArrayRef_t>(x.m_target);
result_var = LFortran::ASRUtils::EXPR(ASR::make_Var_t(al, x.m_target->base.loc, array_ref->m_v));
result_lbound.reserve(al, array_ref->n_args);
result_ubound.reserve(al, array_ref->n_args);
result_inc.reserve(al, array_ref->n_args);
ASR::expr_t *m_start, *m_end, *m_increment;
m_start = m_end = m_increment = nullptr;
for( int i = 0; i < (int) array_ref->n_args; i++ ) {
if( array_ref->m_args[i].m_step != nullptr ) {
if( array_ref->m_args[i].m_left == nullptr ) {
m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
} else {
m_start = array_ref->m_args[i].m_left;
}
if( array_ref->m_args[i].m_right == nullptr ) {
m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
} else {
m_end = array_ref->m_args[i].m_right;
}
} else {
m_start = array_ref->m_args[i].m_right;
m_end = array_ref->m_args[i].m_right;
}
m_increment = array_ref->m_args[i].m_step;
result_lbound.push_back(al, m_start);
result_ubound.push_back(al, m_end);
result_inc.push_back(al, m_increment);
}
use_custom_loop_params = true;
this->visit_expr(*(x.m_value));
}
result_var = nullptr;
}
ASR::ttype_t* get_matching_type(ASR::expr_t* sibling) {
ASR::ttype_t* sibling_type = LFortran::ASRUtils::expr_type(sibling);
if( sibling->type != ASR::exprType::Var ) {
return sibling_type;
}
ASR::dimension_t* m_dims;
int ndims;
PassUtils::get_dim_rank(sibling_type, m_dims, ndims);
for( int i = 0; i < ndims; i++ ) {
if( m_dims[i].m_start != nullptr ||
m_dims[i].m_end != nullptr ) {
return sibling_type;
}
}
Vec<ASR::dimension_t> new_m_dims;
new_m_dims.reserve(al, ndims);
for( int i = 0; i < ndims; i++ ) {
ASR::dimension_t new_m_dim;
new_m_dim.loc = m_dims[i].loc;
new_m_dim.m_start = PassUtils::get_bound(sibling, i + 1, "lbound",
al, unit, current_scope);
new_m_dim.m_end = PassUtils::get_bound(sibling, i + 1, "ubound",
al, unit, current_scope);
new_m_dims.push_back(al, new_m_dim);
}
return PassUtils::set_dim_rank(sibling_type, new_m_dims.p, ndims, true, &al);
}
ASR::expr_t* create_var(int counter, std::string suffix, const Location& loc,
ASR::expr_t* sibling) {
ASR::expr_t* idx_var = nullptr;
ASR::ttype_t* var_type = get_matching_type(sibling);
Str str_name;
str_name.from_str(al, "~" + std::to_string(counter) + suffix);
const char* const_idx_var_name = str_name.c_str(al);
char* idx_var_name = (char*)const_idx_var_name;
if( current_scope->scope.find(std::string(idx_var_name)) == current_scope->scope.end() ) {
ASR::asr_t* idx_sym = ASR::make_Variable_t(al, loc, current_scope, idx_var_name,
ASR::intentType::Local, nullptr, nullptr, ASR::storage_typeType::Default,
var_type, ASR::abiType::Source, ASR::accessType::Public, ASR::presenceType::Required,
false);
current_scope->scope[std::string(idx_var_name)] = ASR::down_cast<ASR::symbol_t>(idx_sym);
idx_var = LFortran::ASRUtils::EXPR(ASR::make_Var_t(al, loc, ASR::down_cast<ASR::symbol_t>(idx_sym)));
} else {
ASR::symbol_t* idx_sym = current_scope->scope[std::string(idx_var_name)];
idx_var = LFortran::ASRUtils::EXPR(ASR::make_Var_t(al, loc, idx_sym));
}
return idx_var;
}
void visit_ConstantInteger(const ASR::ConstantInteger_t& x) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
}
void visit_ConstantComplex(const ASR::ConstantComplex_t& x) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
}
void visit_ConstantReal(const ASR::ConstantReal_t& x) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
}
void fix_dimension(const ASR::ImplicitCast_t& x, ASR::expr_t* arg_expr) {
ASR::ttype_t* x_type = const_cast<ASR::ttype_t*>(x.m_type);
ASR::ttype_t* arg_type = LFortran::ASRUtils::expr_type(arg_expr);
ASR::dimension_t* m_dims;
int ndims;
PassUtils::get_dim_rank(arg_type, m_dims, ndims);
PassUtils::set_dim_rank(x_type, m_dims, ndims);
}
void visit_ImplicitCast(const ASR::ImplicitCast_t& x) {
ASR::expr_t* result_var_copy = result_var;
result_var = nullptr;
this->visit_expr(*(x.m_arg));
result_var = result_var_copy;
if( PassUtils::is_array(tmp_val) ) {
if( result_var == nullptr ) {
fix_dimension(x, tmp_val);
result_var = create_var(result_var_num, std::string("_implicit_cast_res"), x.base.base.loc, const_cast<ASR::expr_t*>(&(x.base)));
result_var_num += 1;
}
int n_dims = PassUtils::get_rank(result_var);
Vec<ASR::expr_t*> idx_vars;
PassUtils::create_idx_vars(idx_vars, n_dims, x.base.base.loc, al, current_scope);
ASR::stmt_t* doloop = nullptr;
for( int i = n_dims - 1; i >= 0; i-- ) {
ASR::do_loop_head_t head;
head.m_v = idx_vars[i];
head.m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
head.m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
head.m_increment = nullptr;
head.loc = head.m_v->base.loc;
Vec<ASR::stmt_t*> doloop_body;
doloop_body.reserve(al, 1);
if( doloop == nullptr ) {
ASR::expr_t* ref = PassUtils::create_array_ref(tmp_val, idx_vars, al);
ASR::expr_t* res = PassUtils::create_array_ref(result_var, idx_vars, al);
ASR::expr_t* impl_cast_el_wise = LFortran::ASRUtils::EXPR(ASR::make_ImplicitCast_t(al, x.base.base.loc, ref, x.m_kind, x.m_type, nullptr));
ASR::stmt_t* assign = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, res, impl_cast_el_wise, nullptr));
doloop_body.push_back(al, assign);
} else {
doloop_body.push_back(al, doloop);
}
doloop = LFortran::ASRUtils::STMT(ASR::make_DoLoop_t(al, x.base.base.loc, head, doloop_body.p, doloop_body.size()));
}
array_op_result.push_back(al, doloop);
tmp_val = result_var;
} else {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
}
}
void visit_Var(const ASR::Var_t& x) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
if( result_var != nullptr && PassUtils::is_array(result_var) ) {
int rank_var = PassUtils::get_rank(tmp_val);
int n_dims = rank_var;
Vec<ASR::expr_t*> idx_vars;
PassUtils::create_idx_vars(idx_vars, n_dims, x.base.base.loc, al, current_scope);
ASR::stmt_t* doloop = nullptr;
for( int i = n_dims - 1; i >= 0; i-- ) {
// TODO: Add an If debug node to check if the lower and upper bounds of both the arrays are same.
ASR::do_loop_head_t head;
head.m_v = idx_vars[i];
head.m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
head.m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
head.m_increment = nullptr;
head.loc = head.m_v->base.loc;
Vec<ASR::stmt_t*> doloop_body;
doloop_body.reserve(al, 1);
if( doloop == nullptr ) {
ASR::expr_t* ref = nullptr;
if( rank_var > 0 ) {
ref = PassUtils::create_array_ref(tmp_val, idx_vars, al);
} else {
ref = tmp_val;
}
ASR::expr_t* res = PassUtils::create_array_ref(result_var, idx_vars, al);
ASR::stmt_t* assign = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, res, ref, nullptr));
doloop_body.push_back(al, assign);
} else {
doloop_body.push_back(al, doloop);
}
doloop = LFortran::ASRUtils::STMT(ASR::make_DoLoop_t(al, x.base.base.loc, head, doloop_body.p, doloop_body.size()));
}
array_op_result.push_back(al, doloop);
tmp_val = nullptr;
}
}
void visit_UnaryOp(const ASR::UnaryOp_t& x) {
std::string res_prefix = "_unary_op_res";
ASR::expr_t* result_var_copy = result_var;
result_var = nullptr;
this->visit_expr(*(x.m_operand));
ASR::expr_t* operand = tmp_val;
int rank_operand = PassUtils::get_rank(operand);
if( rank_operand == 0 ) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
return ;
}
if( rank_operand > 0 ) {
result_var = result_var_copy;
if( result_var == nullptr ) {
result_var = create_var(result_var_num, res_prefix,
x.base.base.loc, operand);
result_var_num += 1;
}
tmp_val = result_var;
int n_dims = rank_operand;
Vec<ASR::expr_t*> idx_vars;
PassUtils::create_idx_vars(idx_vars, n_dims, x.base.base.loc, al, current_scope);
ASR::stmt_t* doloop = nullptr;
for( int i = n_dims - 1; i >= 0; i-- ) {
// TODO: Add an If debug node to check if the lower and upper bounds of both the arrays are same.
ASR::do_loop_head_t head;
head.m_v = idx_vars[i];
head.m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
head.m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
head.m_increment = nullptr;
head.loc = head.m_v->base.loc;
Vec<ASR::stmt_t*> doloop_body;
doloop_body.reserve(al, 1);
if( doloop == nullptr ) {
ASR::expr_t* ref = PassUtils::create_array_ref(operand, idx_vars, al);
ASR::expr_t* res = PassUtils::create_array_ref(result_var, idx_vars, al);
ASR::expr_t* op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_UnaryOp_t(
al, x.base.base.loc,
x.m_op, ref, x.m_type, nullptr));
ASR::stmt_t* assign = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, res, op_el_wise, nullptr));
doloop_body.push_back(al, assign);
} else {
doloop_body.push_back(al, doloop);
}
doloop = LFortran::ASRUtils::STMT(ASR::make_DoLoop_t(al, x.base.base.loc, head, doloop_body.p, doloop_body.size()));
}
array_op_result.push_back(al, doloop);
}
}
template <typename T>
void visit_ArrayOpCommon(const T& x, std::string res_prefix) {
bool current_status = use_custom_loop_params;
use_custom_loop_params = false;
ASR::expr_t* result_var_copy = result_var;
result_var = nullptr;
this->visit_expr(*(x.m_left));
ASR::expr_t* left = tmp_val;
result_var = nullptr;
this->visit_expr(*(x.m_right));
ASR::expr_t* right = tmp_val;
use_custom_loop_params = current_status;
int rank_left = PassUtils::get_rank(left);
int rank_right = PassUtils::get_rank(right);
if( rank_left == 0 && rank_right == 0 ) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
return ;
}
if( rank_left > 0 && rank_right > 0 ) {
if( rank_left != rank_right ) {
// This should be checked by verify() and thus should not happen
throw LFortranException("Cannot generate loop for operands of different shapes");
}
result_var = result_var_copy;
if( result_var == nullptr ) {
result_var = create_var(result_var_num, res_prefix, x.base.base.loc, left);
result_var_num += 1;
}
tmp_val = result_var;
int n_dims = rank_left;
Vec<ASR::expr_t*> idx_vars, idx_vars_value;
PassUtils::create_idx_vars(idx_vars, n_dims, x.base.base.loc, al, current_scope, "_t");
PassUtils::create_idx_vars(idx_vars_value, n_dims, x.base.base.loc, al, current_scope, "_v");
ASR::ttype_t* int32_type = LFortran::ASRUtils::TYPE(ASR::make_Integer_t(al, x.base.base.loc, 4, nullptr, 0));
ASR::expr_t* const_1 = LFortran::ASRUtils::EXPR(ASR::make_ConstantInteger_t(al, x.base.base.loc, 1, int32_type));
ASR::stmt_t* doloop = nullptr;
for( int i = n_dims - 1; i >= 0; i-- ) {
// TODO: Add an If debug node to check if the lower and upper bounds of both the arrays are same.
ASR::do_loop_head_t head;
head.m_v = idx_vars[i];
if( use_custom_loop_params ) {
head.m_start = result_lbound[i];
head.m_end = result_ubound[i];
head.m_increment = result_inc[i];
} else {
head.m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
head.m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
head.m_increment = nullptr;
}
head.loc = head.m_v->base.loc;
Vec<ASR::stmt_t*> doloop_body;
doloop_body.reserve(al, 1);
if( doloop == nullptr ) {
ASR::expr_t* ref_1 = PassUtils::create_array_ref(left, idx_vars_value, al);
ASR::expr_t* ref_2 = PassUtils::create_array_ref(right, idx_vars_value, al);
ASR::expr_t* res = PassUtils::create_array_ref(result_var, idx_vars, al);
ASR::expr_t* op_el_wise = nullptr;
switch( x.class_type ) {
case ASR::exprType::BinOp:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_BinOp_t(
al, x.base.base.loc,
ref_1, (ASR::binopType)x.m_op, ref_2,
x.m_type, nullptr, nullptr));
break;
case ASR::exprType::Compare:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_Compare_t(
al, x.base.base.loc,
ref_1, (ASR::cmpopType)x.m_op, ref_2, x.m_type, nullptr, nullptr));
break;
case ASR::exprType::BoolOp:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_BoolOp_t(
al, x.base.base.loc,
ref_1, (ASR::boolopType)x.m_op, ref_2, x.m_type, nullptr));
break;
default:
throw LFortranException("The desired operation is not supported yet for arrays.");
}
ASR::stmt_t* assign = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, res, op_el_wise, nullptr));
doloop_body.push_back(al, assign);
} else {
ASR::stmt_t* set_to_one = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[i+1], const_1, nullptr));
doloop_body.push_back(al, set_to_one);
doloop_body.push_back(al, doloop);
}
ASR::expr_t* inc_expr = LFortran::ASRUtils::EXPR(ASR::make_BinOp_t(al, x.base.base.loc, idx_vars_value[i],
ASR::binopType::Add, const_1, int32_type,
nullptr, nullptr));
ASR::stmt_t* assign_stmt = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[i], inc_expr, nullptr));
doloop_body.push_back(al, assign_stmt);
doloop = LFortran::ASRUtils::STMT(ASR::make_DoLoop_t(al, x.base.base.loc, head, doloop_body.p, doloop_body.size()));
}
ASR::stmt_t* set_to_one = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[0], const_1, nullptr));
array_op_result.push_back(al, set_to_one);
array_op_result.push_back(al, doloop);
} else if( (rank_left == 0 && rank_right > 0) ||
(rank_right == 0 && rank_left > 0) ) {
result_var = result_var_copy;
ASR::expr_t *arr_expr = nullptr, *other_expr = nullptr;
int n_dims = 0;
if( rank_left > 0 ) {
arr_expr = left;
other_expr = right;
n_dims = rank_left;
} else {
arr_expr = right;
other_expr = left;
n_dims = rank_right;
}
if( result_var == nullptr ) {
result_var = create_var(result_var_num, res_prefix, x.base.base.loc, arr_expr);
result_var_num += 1;
}
tmp_val = result_var;
Vec<ASR::expr_t*> idx_vars, idx_vars_value;
PassUtils::create_idx_vars(idx_vars, n_dims, x.base.base.loc, al, current_scope, "_t");
PassUtils::create_idx_vars(idx_vars_value, n_dims, x.base.base.loc, al, current_scope, "_v");
ASR::ttype_t* int32_type = LFortran::ASRUtils::TYPE(ASR::make_Integer_t(al, x.base.base.loc, 4, nullptr, 0));
ASR::expr_t* const_1 = LFortran::ASRUtils::EXPR(ASR::make_ConstantInteger_t(al, x.base.base.loc, 1, int32_type));
ASR::stmt_t* doloop = nullptr;
for( int i = n_dims - 1; i >= 0; i-- ) {
// TODO: Add an If debug node to check if the lower and upper bounds of both the arrays are same.
ASR::do_loop_head_t head;
head.m_v = idx_vars[i];
if( use_custom_loop_params ) {
head.m_start = result_lbound[i];
head.m_end = result_ubound[i];
head.m_increment = result_inc[i];
} else {
head.m_start = PassUtils::get_bound(result_var, i + 1, "lbound", al, unit, current_scope);
head.m_end = PassUtils::get_bound(result_var, i + 1, "ubound", al, unit, current_scope);
head.m_increment = nullptr;
}
head.loc = head.m_v->base.loc;
Vec<ASR::stmt_t*> doloop_body;
doloop_body.reserve(al, 1);
if( doloop == nullptr ) {
ASR::expr_t* ref = PassUtils::create_array_ref(arr_expr, idx_vars_value, al);
ASR::expr_t* res = PassUtils::create_array_ref(result_var, idx_vars, al);
ASR::expr_t* op_el_wise = nullptr;
switch( x.class_type ) {
case ASR::exprType::BinOp:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_BinOp_t(
al, x.base.base.loc,
ref, (ASR::binopType)x.m_op, other_expr,
x.m_type, nullptr, nullptr));
break;
case ASR::exprType::Compare:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_Compare_t(
al, x.base.base.loc,
ref, (ASR::cmpopType)x.m_op, other_expr, x.m_type, nullptr, nullptr));
break;
case ASR::exprType::BoolOp:
op_el_wise = LFortran::ASRUtils::EXPR(ASR::make_BoolOp_t(
al, x.base.base.loc,
ref, (ASR::boolopType)x.m_op, other_expr, x.m_type, nullptr));
break;
default:
throw LFortranException("The desired operation is not supported yet for arrays.");
}
ASR::stmt_t* assign = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, res, op_el_wise, nullptr));
doloop_body.push_back(al, assign);
} else {
ASR::stmt_t* set_to_one = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[i+1], const_1, nullptr));
doloop_body.push_back(al, set_to_one);
doloop_body.push_back(al, doloop);
}
ASR::expr_t* inc_expr = LFortran::ASRUtils::EXPR(ASR::make_BinOp_t(al, x.base.base.loc, idx_vars_value[i], ASR::binopType::Add, const_1, int32_type, nullptr, nullptr));
ASR::stmt_t* assign_stmt = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[i], inc_expr, nullptr));
doloop_body.push_back(al, assign_stmt);
doloop = LFortran::ASRUtils::STMT(ASR::make_DoLoop_t(al, x.base.base.loc, head, doloop_body.p, doloop_body.size()));
}
ASR::stmt_t* set_to_one = LFortran::ASRUtils::STMT(ASR::make_Assignment_t(al, x.base.base.loc, idx_vars_value[0], const_1, nullptr));
array_op_result.push_back(al, set_to_one);
array_op_result.push_back(al, doloop);
}
}
void visit_BinOp(const ASR::BinOp_t &x) {
visit_ArrayOpCommon<ASR::BinOp_t>(x, "_bin_op_res");
}
void visit_Compare(const ASR::Compare_t &x) {
visit_ArrayOpCommon<ASR::Compare_t>(x, "_comp_op_res");
}
void visit_BoolOp(const ASR::BoolOp_t &x) {
visit_ArrayOpCommon<ASR::BoolOp_t>(x, "_bool_op_res");
}
void visit_FunctionCall(const ASR::FunctionCall_t& x) {
tmp_val = const_cast<ASR::expr_t*>(&(x.base));
std::string x_name;
if( x.m_name->type == ASR::symbolType::ExternalSymbol ) {
x_name = down_cast<ASR::ExternalSymbol_t>(x.m_name)->m_name;
} else if( x.m_name->type == ASR::symbolType::Function ) {
x_name = down_cast<ASR::Function_t>(x.m_name)->m_name;
}
// The following checks if the name of a function actually
// points to a subroutine. If true this would mean that the
// original function returned an array and is now a subroutine.
// So the current function call will be converted to a subroutine
// call. In short, this check acts as a signal whether to convert
// a function call to a subroutine call.
if( current_scope != nullptr &&
current_scope->scope.find(x_name) != current_scope->scope.end() &&
current_scope->scope[x_name]->type == ASR::symbolType::Subroutine ) {
if( result_var == nullptr ) {
result_var = create_var(result_var_num, "_func_call_res", x.base.base.loc, x.m_args[x.n_args - 1]);
result_var_num += 1;
}
Vec<ASR::expr_t*> s_args;
s_args.reserve(al, x.n_args + 1);
for( size_t i = 0; i < x.n_args; i++ ) {
s_args.push_back(al, x.m_args[i]);
}
s_args.push_back(al, result_var);
tmp_val = result_var;
ASR::stmt_t* subrout_call = LFortran::ASRUtils::STMT(ASR::make_SubroutineCall_t(al, x.base.base.loc,
current_scope->scope[x_name], nullptr,
s_args.p, s_args.size(), nullptr));
array_op_result.push_back(al, subrout_call);
}
result_var = nullptr;
}
};
void pass_replace_array_op(Allocator &al, ASR::TranslationUnit_t &unit) {
ArrayOpVisitor v(al, unit);
v.visit_TranslationUnit(unit);
LFORTRAN_ASSERT(asr_verify(unit));
}
} // namespace LFortran
| 18,806 |
517 | <gh_stars>100-1000
package ro.isdc.wro.model.spi;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* @author <NAME>
*/
public class TestDefaultWroModelFactoryProvider {
private DefaultModelFactoryProvider victim;
@Before
public void setUp() {
victim = new DefaultModelFactoryProvider();
}
@Test
public void shouldProvideOneModelFactory() {
assertEquals(1, victim.provideModelFactories().size());
}
}
| 159 |
14,425 | <filename>hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/ByteBufferPool.java
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.io;
import java.nio.ByteBuffer;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
@InterfaceAudience.Public
@InterfaceStability.Stable
public interface ByteBufferPool {
/**
* Get a new direct ByteBuffer. The pool can provide this from
* removing a buffer from its internal cache, or by allocating a
* new buffer.
*
* @param direct Whether the buffer should be direct.
* @param length The minimum length the buffer will have.
* @return A new ByteBuffer. This ByteBuffer must be direct.
* Its capacity can be less than what was requested, but
* must be at least 1 byte.
*/
ByteBuffer getBuffer(boolean direct, int length);
/**
* Release a buffer back to the pool.
* The pool may choose to put this buffer into its cache.
*
* @param buffer a direct bytebuffer
*/
void putBuffer(ByteBuffer buffer);
}
| 576 |
682 | /**CFile****************************************************************
FileName [fxuPair.c]
PackageName [MVSIS 2.0: Multi-valued logic synthesis system.]
Synopsis [Operations on cube pairs.]
Author [MVSIS Group]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - February 1, 2003.]
Revision [$Id: fxuPair.c,v 1.0 2003/02/01 00:00:00 alanmi Exp $]
***********************************************************************/
#include "fxuInt.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
#define MAX_PRIMES 304
static int s_Primes[MAX_PRIMES] =
{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359,
367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433,
439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593,
599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249,
1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321,
1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439,
1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601,
1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693,
1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783,
1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877,
1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003
};
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Find the canonical permutation of two cubes in the pair.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairCanonicize( Fxu_Cube ** ppCube1, Fxu_Cube ** ppCube2 )
{
Fxu_Lit * pLit1, * pLit2;
Fxu_Cube * pCubeTemp;
// walk through the cubes to determine
// the one that has higher first variable
pLit1 = (*ppCube1)->lLits.pHead;
pLit2 = (*ppCube2)->lLits.pHead;
while ( 1 )
{
if ( pLit1->iVar == pLit2->iVar )
{
pLit1 = pLit1->pHNext;
pLit2 = pLit2->pHNext;
continue;
}
assert( pLit1 && pLit2 ); // this is true if the covers are SCC-free
if ( pLit1->iVar > pLit2->iVar )
{ // swap the cubes
pCubeTemp = *ppCube1;
*ppCube1 = *ppCube2;
*ppCube2 = pCubeTemp;
}
break;
}
}
/**Function*************************************************************
Synopsis [Find the canonical permutation of two cubes in the pair.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairCanonicize2( Fxu_Cube ** ppCube1, Fxu_Cube ** ppCube2 )
{
Fxu_Cube * pCubeTemp;
// canonicize the pair by ordering the cubes
if ( (*ppCube1)->iCube > (*ppCube2)->iCube )
{ // swap the cubes
pCubeTemp = *ppCube1;
*ppCube1 = *ppCube2;
*ppCube2 = pCubeTemp;
}
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
unsigned Fxu_PairHashKeyArray( Fxu_Matrix * p, int piVarsC1[], int piVarsC2[], int nVarsC1, int nVarsC2 )
{
int Offset1 = 100, Offset2 = 200, i;
unsigned Key;
// compute the hash key
Key = 0;
for ( i = 0; i < nVarsC1; i++ )
Key ^= s_Primes[Offset1+i] * piVarsC1[i];
for ( i = 0; i < nVarsC2; i++ )
Key ^= s_Primes[Offset2+i] * piVarsC2[i];
return Key;
}
/**Function*************************************************************
Synopsis [Computes the hash key of the divisor represented by the pair of cubes.]
Description [Goes through the variables in both cubes. Skips the identical
ones (this corresponds to making the cubes cube-free). Computes the hash
value of the cubes. Assigns the number of literals in the base and in the
cubes without base.]
SideEffects []
SeeAlso []
***********************************************************************/
unsigned Fxu_PairHashKey( Fxu_Matrix * p, Fxu_Cube * pCube1, Fxu_Cube * pCube2,
int * pnBase, int * pnLits1, int * pnLits2 )
{
int Offset1 = 100, Offset2 = 200;
int nBase, nLits1, nLits2;
Fxu_Lit * pLit1, * pLit2;
unsigned Key;
// compute the hash key
Key = 0;
nLits1 = 0;
nLits2 = 0;
nBase = 0;
pLit1 = pCube1->lLits.pHead;
pLit2 = pCube2->lLits.pHead;
while ( 1 )
{
if ( pLit1 && pLit2 )
{
if ( pLit1->iVar == pLit2->iVar )
{ // ensure cube-free
pLit1 = pLit1->pHNext;
pLit2 = pLit2->pHNext;
// add this literal to the base
nBase++;
}
else if ( pLit1->iVar < pLit2->iVar )
{
Key ^= s_Primes[Offset1+nLits1] * pLit1->iVar;
pLit1 = pLit1->pHNext;
nLits1++;
}
else
{
Key ^= s_Primes[Offset2+nLits2] * pLit2->iVar;
pLit2 = pLit2->pHNext;
nLits2++;
}
}
else if ( pLit1 && !pLit2 )
{
Key ^= s_Primes[Offset1+nLits1] * pLit1->iVar;
pLit1 = pLit1->pHNext;
nLits1++;
}
else if ( !pLit1 && pLit2 )
{
Key ^= s_Primes[Offset2+nLits2] * pLit2->iVar;
pLit2 = pLit2->pHNext;
nLits2++;
}
else
break;
}
*pnBase = nBase;
*pnLits1 = nLits1;
*pnLits2 = nLits2;
return Key;
}
/**Function*************************************************************
Synopsis [Compares the two pairs.]
Description [Returns 1 if the divisors represented by these pairs
are equal.]
SideEffects []
SeeAlso []
***********************************************************************/
int Fxu_PairCompare( Fxu_Pair * pPair1, Fxu_Pair * pPair2 )
{
Fxu_Lit * pD1C1, * pD1C2;
Fxu_Lit * pD2C1, * pD2C2;
int TopVar1, TopVar2;
int Code;
if ( pPair1->nLits1 != pPair2->nLits1 )
return 0;
if ( pPair1->nLits2 != pPair2->nLits2 )
return 0;
pD1C1 = pPair1->pCube1->lLits.pHead;
pD1C2 = pPair1->pCube2->lLits.pHead;
pD2C1 = pPair2->pCube1->lLits.pHead;
pD2C2 = pPair2->pCube2->lLits.pHead;
Code = pD1C1? 8: 0;
Code |= pD1C2? 4: 0;
Code |= pD2C1? 2: 0;
Code |= pD2C2? 1: 0;
assert( Code == 15 );
while ( 1 )
{
switch ( Code )
{
case 0: // -- -- NULL NULL NULL NULL
return 1;
case 1: // -- -1 NULL NULL NULL pD2C2
return 0;
case 2: // -- 1- NULL NULL pD2C1 NULL
return 0;
case 3: // -- 11 NULL NULL pD2C1 pD2C2
if ( pD2C1->iVar != pD2C2->iVar )
return 0;
pD2C1 = pD2C1->pHNext;
pD2C2 = pD2C2->pHNext;
break;
case 4: // -1 -- NULL pD1C2 NULL NULL
return 0;
case 5: // -1 -1 NULL pD1C2 NULL pD2C2
if ( pD1C2->iVar != pD2C2->iVar )
return 0;
pD1C2 = pD1C2->pHNext;
pD2C2 = pD2C2->pHNext;
break;
case 6: // -1 1- NULL pD1C2 pD2C1 NULL
return 0;
case 7: // -1 11 NULL pD1C2 pD2C1 pD2C2
TopVar2 = Fxu_Min( pD2C1->iVar, pD2C2->iVar );
if ( TopVar2 == pD1C2->iVar )
{
if ( pD2C1->iVar <= pD2C2->iVar )
return 0;
pD1C2 = pD1C2->pHNext;
pD2C2 = pD2C2->pHNext;
}
else if ( TopVar2 < pD1C2->iVar )
{
if ( pD2C1->iVar != pD2C2->iVar )
return 0;
pD2C1 = pD2C1->pHNext;
pD2C2 = pD2C2->pHNext;
}
else
return 0;
break;
case 8: // 1- -- pD1C1 NULL NULL NULL
return 0;
case 9: // 1- -1 pD1C1 NULL NULL pD2C2
return 0;
case 10: // 1- 1- pD1C1 NULL pD2C1 NULL
if ( pD1C1->iVar != pD2C1->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD2C1 = pD2C1->pHNext;
break;
case 11: // 1- 11 pD1C1 NULL pD2C1 pD2C2
TopVar2 = Fxu_Min( pD2C1->iVar, pD2C2->iVar );
if ( TopVar2 == pD1C1->iVar )
{
if ( pD2C1->iVar >= pD2C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD2C1 = pD2C1->pHNext;
}
else if ( TopVar2 < pD1C1->iVar )
{
if ( pD2C1->iVar != pD2C2->iVar )
return 0;
pD2C1 = pD2C1->pHNext;
pD2C2 = pD2C2->pHNext;
}
else
return 0;
break;
case 12: // 11 -- pD1C1 pD1C2 NULL NULL
if ( pD1C1->iVar != pD1C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD1C2 = pD1C2->pHNext;
break;
case 13: // 11 -1 pD1C1 pD1C2 NULL pD2C2
TopVar1 = Fxu_Min( pD1C1->iVar, pD1C2->iVar );
if ( TopVar1 == pD2C2->iVar )
{
if ( pD1C1->iVar <= pD1C2->iVar )
return 0;
pD1C2 = pD1C2->pHNext;
pD2C2 = pD2C2->pHNext;
}
else if ( TopVar1 < pD2C2->iVar )
{
if ( pD1C1->iVar != pD1C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD1C2 = pD1C2->pHNext;
}
else
return 0;
break;
case 14: // 11 1- pD1C1 pD1C2 pD2C1 NULL
TopVar1 = Fxu_Min( pD1C1->iVar, pD1C2->iVar );
if ( TopVar1 == pD2C1->iVar )
{
if ( pD1C1->iVar >= pD1C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD2C1 = pD2C1->pHNext;
}
else if ( TopVar1 < pD2C1->iVar )
{
if ( pD1C1->iVar != pD1C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD1C2 = pD1C2->pHNext;
}
else
return 0;
break;
case 15: // 11 11 pD1C1 pD1C2 pD2C1 pD2C2
TopVar1 = Fxu_Min( pD1C1->iVar, pD1C2->iVar );
TopVar2 = Fxu_Min( pD2C1->iVar, pD2C2->iVar );
if ( TopVar1 == TopVar2 )
{
if ( pD1C1->iVar == pD1C2->iVar )
{
if ( pD2C1->iVar != pD2C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD1C2 = pD1C2->pHNext;
pD2C1 = pD2C1->pHNext;
pD2C2 = pD2C2->pHNext;
}
else
{
if ( pD2C1->iVar == pD2C2->iVar )
return 0;
if ( pD1C1->iVar < pD1C2->iVar )
{
if ( pD2C1->iVar > pD2C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD2C1 = pD2C1->pHNext;
}
else
{
if ( pD2C1->iVar < pD2C2->iVar )
return 0;
pD1C2 = pD1C2->pHNext;
pD2C2 = pD2C2->pHNext;
}
}
}
else if ( TopVar1 < TopVar2 )
{
if ( pD1C1->iVar != pD1C2->iVar )
return 0;
pD1C1 = pD1C1->pHNext;
pD1C2 = pD1C2->pHNext;
}
else
{
if ( pD2C1->iVar != pD2C2->iVar )
return 0;
pD2C1 = pD2C1->pHNext;
pD2C2 = pD2C2->pHNext;
}
break;
default:
assert( 0 );
break;
}
Code = pD1C1? 8: 0;
Code |= pD1C2? 4: 0;
Code |= pD2C1? 2: 0;
Code |= pD2C2? 1: 0;
}
return 1;
}
/**Function*************************************************************
Synopsis [Allocates the storage for cubes pairs.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairAllocStorage( Fxu_Var * pVar, int nCubes )
{
int k;
// assert( pVar->nCubes == 0 );
pVar->nCubes = nCubes;
// allocate memory for all the pairs
pVar->ppPairs = ABC_ALLOC( Fxu_Pair **, nCubes );
pVar->ppPairs[0] = ABC_ALLOC( Fxu_Pair *, nCubes * nCubes );
memset( pVar->ppPairs[0], 0, sizeof(Fxu_Pair *) * nCubes * nCubes );
for ( k = 1; k < nCubes; k++ )
pVar->ppPairs[k] = pVar->ppPairs[k-1] + nCubes;
}
/**Function*************************************************************
Synopsis [Clears all pairs associated with this cube.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairClearStorage( Fxu_Cube * pCube )
{
Fxu_Var * pVar;
int i;
pVar = pCube->pVar;
for ( i = 0; i < pVar->nCubes; i++ )
{
pVar->ppPairs[pCube->iCube][i] = NULL;
pVar->ppPairs[i][pCube->iCube] = NULL;
}
}
/**Function*************************************************************
Synopsis [Clears all pairs associated with this cube.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairFreeStorage( Fxu_Var * pVar )
{
if ( pVar->ppPairs )
{
ABC_FREE( pVar->ppPairs[0] );
ABC_FREE( pVar->ppPairs );
}
}
/**Function*************************************************************
Synopsis [Adds the pair to storage.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Fxu_Pair * Fxu_PairAlloc( Fxu_Matrix * p, Fxu_Cube * pCube1, Fxu_Cube * pCube2 )
{
Fxu_Pair * pPair;
assert( pCube1->pVar == pCube2->pVar );
pPair = MEM_ALLOC_FXU( p, Fxu_Pair, 1 );
memset( pPair, 0, sizeof(Fxu_Pair) );
pPair->pCube1 = pCube1;
pPair->pCube2 = pCube2;
pPair->iCube1 = pCube1->iCube;
pPair->iCube2 = pCube2->iCube;
return pPair;
}
/**Function*************************************************************
Synopsis [Adds the pair to storage.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Fxu_PairAdd( Fxu_Pair * pPair )
{
Fxu_Var * pVar;
pVar = pPair->pCube1->pVar;
assert( pVar == pPair->pCube2->pVar );
pVar->ppPairs[pPair->iCube1][pPair->iCube2] = pPair;
pVar->ppPairs[pPair->iCube2][pPair->iCube1] = pPair;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| 9,611 |
1,144 | <reponame>dram/metasfresh
package org.compiere.apps.search;
import java.awt.Component;
import javax.swing.JTable;
import org.compiere.model.MQuery;
import org.compiere.model.MQuery.Operator;
import org.compiere.swing.CComboBox;
import org.compiere.swing.ListComboBoxModel;
import org.compiere.util.DisplayType;
/**
* Advanced search table - cell editor for Operator cell
*
* @author metas-dev <<EMAIL>>
*
*/
class FindOperatorCellEditor extends FindCellEditor
{
private static final long serialVersionUID = 6655568524454256089L;
private CComboBox<Operator> _editor = null;
private final ListComboBoxModel<Operator> modelForLookupColumns = new ListComboBoxModel<>(MQuery.Operator.operatorsForLookups);
private final ListComboBoxModel<Operator> modelForYesNoColumns = new ListComboBoxModel<>(MQuery.Operator.operatorsForBooleans);
private final ListComboBoxModel<Operator> modelDefault = new ListComboBoxModel<>(MQuery.Operator.values());
private final ListComboBoxModel<Operator> modelEmpty = new ListComboBoxModel<>();
public FindOperatorCellEditor()
{
super();
}
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int col)
{
updateEditor(table, row);
return super.getTableCellEditorComponent(table, value, isSelected, row, col);
}
@Override
protected CComboBox<Operator> getEditor()
{
if (_editor == null)
{
_editor = new CComboBox<>();
_editor.enableAutoCompletion();
}
return _editor;
}
private void updateEditor(final JTable table, final int viewRowIndex)
{
final CComboBox<Operator> editor = getEditor();
final IUserQueryRestriction row = getRow(table, viewRowIndex);
final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField());
if (searchField != null)
{
// check if the column is columnSQL with reference (08757)
// final String columnName = searchField.getColumnName();
final int displayType = searchField.getDisplayType();
final boolean isColumnSQL = searchField.isVirtualColumn();
final boolean isReference = searchField.getAD_Reference_Value_ID() > 0;
if (isColumnSQL && isReference)
{
// make sure also the columnSQLs with reference are only getting the ID operators (08757)
editor.setModel(modelForLookupColumns);
}
else if (DisplayType.isAnyLookup(displayType))
{
editor.setModel(modelForLookupColumns);
}
else if (DisplayType.YesNo == displayType)
{
editor.setModel(modelForYesNoColumns);
}
else
{
editor.setModel(modelDefault);
}
}
else
{
editor.setModel(modelEmpty);
}
}
private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex);
return model.getRow(modelRowIndex);
}
}
| 997 |
416 | package org.simpleflatmapper.tuple;
public class Tuple2<T1, T2> {
private final T1 element0;
private final T2 element1;
public Tuple2(T1 element0, T2 element1) {
this.element0 = element0;
this.element1 = element1;
}
public final T1 getElement0() {
return element0;
}
public final T1 first() {
return getElement0();
}
public final T2 getElement1() {
return element1;
}
public final T2 second() {
return getElement1();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple2 tuple2 = (Tuple2) o;
if (element0 != null ? !element0.equals(tuple2.element0) : tuple2.element0 != null) return false;
if (element1 != null ? !element1.equals(tuple2.element1) : tuple2.element1 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = element0 != null ? element0.hashCode() : 0;
result = 31 * result + (element1 != null ? element1.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple2{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
'}';
}
public <T3> Tuple3<T1, T2, T3> tuple3(T3 element2) {
return new Tuple3<T1, T2, T3>(getElement0(), getElement1(), element2);
}
}
| 669 |
14,425 | <filename>hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/TrileanTests.java
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.azurebfs;
import org.junit.Test;
import org.apache.hadoop.fs.azurebfs.contracts.exceptions.TrileanConversionException;
import org.apache.hadoop.fs.azurebfs.enums.Trilean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* Tests for the enum Trilean.
*/
public class TrileanTests {
private static final String TRUE_STR = "true";
private static final String FALSE_STR = "false";
@Test
public void testGetTrileanForBoolean() {
assertThat(Trilean.getTrilean(true)).describedAs(
"getTrilean should return Trilean.TRUE when true is passed")
.isEqualTo(Trilean.TRUE);
assertThat(Trilean.getTrilean(false)).describedAs(
"getTrilean should return Trilean.FALSE when false is passed")
.isEqualTo(Trilean.FALSE);
}
@Test
public void testGetTrileanForString() {
assertThat(Trilean.getTrilean(TRUE_STR.toLowerCase())).describedAs(
"getTrilean should return Trilean.TRUE when true is passed")
.isEqualTo(Trilean.TRUE);
assertThat(Trilean.getTrilean(TRUE_STR.toUpperCase())).describedAs(
"getTrilean should return Trilean.TRUE when TRUE is passed")
.isEqualTo(Trilean.TRUE);
assertThat(Trilean.getTrilean(FALSE_STR.toLowerCase())).describedAs(
"getTrilean should return Trilean.FALSE when false is passed")
.isEqualTo(Trilean.FALSE);
assertThat(Trilean.getTrilean(FALSE_STR.toUpperCase())).describedAs(
"getTrilean should return Trilean.FALSE when FALSE is passed")
.isEqualTo(Trilean.FALSE);
testInvalidString(null);
testInvalidString(" ");
testInvalidString("invalid");
testInvalidString("truee");
testInvalidString("falsee");
}
private void testInvalidString(String invalidString) {
assertThat(Trilean.getTrilean(invalidString)).describedAs(
"getTrilean should return Trilean.UNKNOWN for anything not true/false")
.isEqualTo(Trilean.UNKNOWN);
}
@Test
public void testToBoolean() throws TrileanConversionException {
assertThat(Trilean.TRUE.toBoolean())
.describedAs("toBoolean should return true for Trilean.TRUE").isTrue();
assertThat(Trilean.FALSE.toBoolean())
.describedAs("toBoolean should return false for Trilean.FALSE")
.isFalse();
assertThat(catchThrowable(() -> Trilean.UNKNOWN.toBoolean())).describedAs(
"toBoolean on Trilean.UNKNOWN results in TrileanConversionException")
.isInstanceOf(TrileanConversionException.class).describedAs(
"Exception message should be: catchThrowable(()->Trilean.UNKNOWN"
+ ".toBoolean())")
.hasMessage("Cannot convert Trilean.UNKNOWN to boolean");
}
}
| 1,267 |
5,169 | {
"name": "TheramaF3",
"version": "2.80.0",
"summary": "TheramaF3 is a framework that has been created for the purpose of trying out cocoapods public spec distribution.",
"description": "A long description: TheramaF3 is a framework that has been created for the purpose of trying out cocoapods public spec distribution.",
"homepage": "https://github.com/therama/TheramaF3",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"therama": "<EMAIL>"
},
"source": {
"git": "https://github.com/therama/TheramaF3.git",
"tag": "2.80.0"
},
"vendored_frameworks": "TheramaF3.xcframework",
"platforms": {
"ios": "13.7"
},
"swift_versions": "5.0",
"swift_version": "5.0"
}
| 282 |
852 | <filename>Alignment/APEEstimation/python/SectorBuilder_Tid_cff.py
import FWCore.ParameterSet.Config as cms
from Alignment.APEEstimation.SectorBuilder_cfi import *
##
## Whole Subdetector (means only one for both endcaps)
##
Tid = EmptySector.clone(
name = 'Tid',
subdetId = [4],
)
TID = cms.VPSet(
Tid,
)
##
## Separation of side(+,-)
##
TidMinus = Tid.clone(
name = 'TidMinus',
side = [1],
)
TidPlus = Tid.clone(
name = 'TidPlus',
side = [2],
)
TIDSideSeparation = cms.VPSet(
TidMinus,
TidPlus,
)
##
## Separation of side + rings
##
TidMinusRing1 = TidMinus.clone(
name = 'TidMinusRing1',
ring = [1],
)
TidMinusRing2 = TidMinus.clone(
name = 'TidMinusRing2',
ring = [2],
)
TidMinusRing3 = TidMinus.clone(
name = 'TidMinusRing3',
ring = [3],
)
TidPlusRing1 = TidPlus.clone(
name = 'TidPlusRing1',
ring = [1],
)
TidPlusRing2 = TidPlus.clone(
name = 'TidPlusRing2',
ring = [2],
)
TidPlusRing3 = TidPlus.clone(
name = 'TidPlusRing3',
ring = [3],
)
TIDSideAndPureRingSeparation = cms.VPSet(
TidMinusRing1,
TidMinusRing2,
TidMinusRing3,
TidPlusRing1,
TidPlusRing2,
TidPlusRing3,
)
##
## Separation of side + rings + rphi/stereo
##
TidMinusRing1Rphi = TidMinusRing1.clone(
name = 'TidMinusRing1Rphi',
isRPhi = [1],
)
TidMinusRing1Stereo = TidMinusRing1.clone(
name = 'TidMinusRing1Stereo',
isStereo = [1],
)
TidMinusRing2Rphi = TidMinusRing2.clone(
name = 'TidMinusRing2Rphi',
isRPhi = [1],
)
TidMinusRing2Stereo = TidMinusRing2.clone(
name = 'TidMinusRing2Stereo',
isStereo = [1],
)
TidPlusRing1Rphi = TidPlusRing1.clone(
name = 'TidPlusRing1Rphi',
isRPhi = [1],
)
TidPlusRing1Stereo = TidPlusRing1.clone(
name = 'TidPlusRing1Stereo',
isStereo = [1],
)
TidPlusRing2Rphi = TidPlusRing2.clone(
name = 'TidPlusRing2Rphi',
isRPhi = [1],
)
TidPlusRing2Stereo = TidPlusRing2.clone(
name = 'TidPlusRing2Stereo',
isStereo = [1],
)
TIDSideAndRingSeparation = cms.VPSet(
TidMinusRing1Rphi,
TidMinusRing1Stereo,
TidMinusRing2Rphi,
TidMinusRing2Stereo,
TidMinusRing3,
TidPlusRing1Rphi,
TidPlusRing1Stereo,
TidPlusRing2Rphi,
TidPlusRing2Stereo,
TidPlusRing3,
)
##
## Separation of side + rings + rphi/stereo + orientations
##
TidMinusRing1RphiOut = TidMinusRing1Rphi.clone(
name = 'TidMinusRing1RphiOut',
wDirection = [-1],
)
TidMinusRing1StereoOut = TidMinusRing1Stereo.clone(
name = 'TidMinusRing1StereoOut',
wDirection = [-1],
)
TidMinusRing1RphiIn = TidMinusRing1Rphi.clone(
name = 'TidMinusRing1RphiIn',
wDirection = [1],
)
TidMinusRing1StereoIn = TidMinusRing1Stereo.clone(
name = 'TidMinusRing1StereoIn',
wDirection = [1],
)
TidMinusRing2RphiOut = TidMinusRing2Rphi.clone(
name = 'TidMinusRing2RphiOut',
wDirection = [-1],
)
TidMinusRing2StereoOut = TidMinusRing2Stereo.clone(
name = 'TidMinusRing2StereoOut',
wDirection = [-1],
)
TidMinusRing2RphiIn = TidMinusRing2Rphi.clone(
name = 'TidMinusRing2RphiIn',
wDirection = [1],
)
TidMinusRing2StereoIn = TidMinusRing2Stereo.clone(
name = 'TidMinusRing2StereoIn',
wDirection = [1],
)
TidMinusRing3Out = TidMinusRing3.clone(
name = 'TidMinusRing3Out',
wDirection = [-1],
)
TidMinusRing3In = TidMinusRing3.clone(
name = 'TidMinusRing3In',
wDirection = [1],
)
TidPlusRing1RphiOut = TidPlusRing1Rphi.clone(
name = 'TidPlusRing1RphiOut',
wDirection = [1],
)
TidPlusRing1StereoOut = TidPlusRing1Stereo.clone(
name = 'TidPlusRing1StereoOut',
wDirection = [1],
)
TidPlusRing1RphiIn = TidPlusRing1Rphi.clone(
name = 'TidPlusRing1RphiIn',
wDirection = [-1],
)
TidPlusRing1StereoIn = TidPlusRing1Stereo.clone(
name = 'TidPlusRing1StereoIn',
wDirection = [-1],
)
TidPlusRing2RphiOut = TidPlusRing2Rphi.clone(
name = 'TidPlusRing2RphiOut',
wDirection = [1],
)
TidPlusRing2StereoOut = TidPlusRing2Stereo.clone(
name = 'TidPlusRing2StereoOut',
wDirection = [1],
)
TidPlusRing2RphiIn = TidPlusRing2Rphi.clone(
name = 'TidPlusRing2RphiIn',
wDirection = [-1],
)
TidPlusRing2StereoIn = TidPlusRing2Stereo.clone(
name = 'TidPlusRing2StereoIn',
wDirection = [-1],
)
TidPlusRing3Out = TidPlusRing3.clone(
name = 'TidPlusRing3Out',
wDirection = [1],
)
TidPlusRing3In = TidPlusRing3.clone(
name = 'TidPlusRing3In',
wDirection = [-1],
)
TIDSideAndRingAndOrientationSeparation = cms.VPSet(
TidMinusRing1RphiOut,
TidMinusRing1StereoOut,
TidMinusRing1RphiIn,
TidMinusRing1StereoIn,
TidMinusRing2RphiOut,
TidMinusRing2StereoOut,
TidMinusRing2RphiIn,
TidMinusRing2StereoIn,
TidMinusRing3Out,
TidMinusRing3In,
TidPlusRing1RphiOut,
TidPlusRing1StereoOut,
TidPlusRing1RphiIn,
TidPlusRing1StereoIn,
TidPlusRing2RphiOut,
TidPlusRing2StereoOut,
TidPlusRing2RphiIn,
TidPlusRing2StereoIn,
TidPlusRing3Out,
TidPlusRing3In,
)
| 2,353 |
930 | package com.foxinmy.weixin4j.example.server.handler;
import org.springframework.stereotype.Component;
import com.foxinmy.weixin4j.handler.MessageHandlerAdapter;
import com.foxinmy.weixin4j.message.TextMessage;
import com.foxinmy.weixin4j.request.WeixinRequest;
import com.foxinmy.weixin4j.response.TextResponse;
import com.foxinmy.weixin4j.response.WeixinResponse;
/**
* 文本消息处理
*
* @className TextMessageHandler
* @author jinyu(<EMAIL>)
* @date 2015年11月18日
* @since JDK 1.6
*/
@Component
public class TextMessageHandler extends MessageHandlerAdapter<TextMessage> {
@Override
public WeixinResponse doHandle0(TextMessage message) {
return new TextResponse("收到了文本消息");
}
}
| 281 |
1,801 | <reponame>xzou999/Multitarget-tracker
#pragma once
#include <opencv2/opencv.hpp>
#include <iostream>
cv::Mat gaussianCorrelation(cv::Mat& x1, cv::Mat& x2, int h, int w, int channel, float sigma);
cv::Mat linearCorrelation(cv::Mat& x1, cv::Mat& x2, int h, int w, int channel);
cv::Mat polynomialCorrelation(cv::Mat& x1, cv::Mat& x2, int h, int w, int channel);
cv::Mat phaseCorrelation(cv::Mat& x1, cv::Mat& x2, int h, int w, int channel);
| 184 |
310 | <filename>native/android/PropertyCross/src/com/propertycross/android/presenter/RecentSearch.java
package com.propertycross.android.presenter;
import com.propertycross.android.presenter.searchitems.SearchItem;
public class RecentSearch {
private SearchItem search;
private int resultsCount;
public RecentSearch() {
}
public RecentSearch(SearchItem searchItem, int resultsCount) {
this.search = searchItem;
this.resultsCount = resultsCount;
}
public SearchItem getSearch() {
return search;
}
public void setSearch(SearchItem search) {
this.search = search;
}
public int getResultsCount() {
return resultsCount;
}
public void setResultsCount(int count) {
resultsCount = count;
}
}
| 215 |
1,199 | <filename>2018/futex-basics/mutex-using-futex.cpp
// Following the "mutex2" implementation in Drepper's "Futexes Are Tricky"
// Note: this version works for threads, not between processes.
//
// <NAME> [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <atomic>
#include <cstdint>
#include <iostream>
#include <linux/futex.h>
#include <pthread.h>
#include <sstream>
#include <sys/resource.h>
#include <sys/shm.h>
#include <sys/syscall.h>
#include <thread>
#include <unistd.h>
// An atomic_compare_exchange wrapper with semantics expected by the paper's
// mutex - return the old value stored in the atom.
int cmpxchg(std::atomic<int>* atom, int expected, int desired) {
int* ep = &expected;
std::atomic_compare_exchange_strong(atom, ep, desired);
return *ep;
}
class Mutex {
public:
Mutex() : atom_(0) {}
void lock() {
int c = cmpxchg(&atom_, 0, 1);
// If the lock was previously unlocked, there's nothing else for us to do.
// Otherwise, we'll probably have to wait.
if (c != 0) {
do {
// If the mutex is locked, we signal that we're waiting by setting the
// atom to 2. A shortcut checks is it's 2 already and avoids the atomic
// operation in this case.
if (c == 2 || cmpxchg(&atom_, 1, 2) != 0) {
// Here we have to actually sleep, because the mutex is actually
// locked. Note that it's not necessary to loop around this syscall;
// a spurious wakeup will do no harm since we only exit the do...while
// loop when atom_ is indeed 0.
syscall(SYS_futex, (int*)&atom_, FUTEX_WAIT, 2, 0, 0, 0);
}
// We're here when either:
// (a) the mutex was in fact unlocked (by an intervening thread).
// (b) we slept waiting for the atom and were awoken.
//
// So we try to lock the atom again. We set teh state to 2 because we
// can't be certain there's no other thread at this exact point. So we
// prefer to err on the safe side.
} while ((c = cmpxchg(&atom_, 0, 2)) != 0);
}
}
void unlock() {
if (atom_.fetch_sub(1) != 1) {
atom_.store(0);
syscall(SYS_futex, (int*)&atom_, FUTEX_WAKE, 1, 0, 0, 0);
}
}
private:
// 0 means unlocked
// 1 means locked, no waiters
// 2 means locked, there are waiters in lock()
std::atomic<int> atom_;
};
// Simple function that increments the value pointed to by n, 10 million times.
// If m is not nullptr, it's a Mutex that will be used to protect the increment
// operation.
void threadfunc(int64_t* n, Mutex* m = nullptr) {
for (int i = 0; i < 10000000; ++i) {
if (m != nullptr) {
m->lock();
}
*n += 1;
if (m != nullptr) {
m->unlock();
}
}
}
int main(int argc, char** argv) {
{
int64_t vnoprotect = 0;
std::thread t1(threadfunc, &vnoprotect, nullptr);
std::thread t2(threadfunc, &vnoprotect, nullptr);
std::thread t3(threadfunc, &vnoprotect, nullptr);
t1.join();
t2.join();
t3.join();
std::cout << "vnoprotect = " << vnoprotect << "\n";
}
{
int64_t v = 0;
Mutex m;
std::thread t1(threadfunc, &v, &m);
std::thread t2(threadfunc, &v, &m);
std::thread t3(threadfunc, &v, &m);
t1.join();
t2.join();
t3.join();
std::cout << "v = " << v << "\n";
}
return 0;
}
| 1,378 |
17,481 | <reponame>marcin-kozinski/dagger
/*
* Copyright (C) 2021 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.spi.model;
import com.google.errorprone.annotations.FormatMethod;
import dagger.spi.model.BindingGraph.ChildFactoryMethodEdge;
import dagger.spi.model.BindingGraph.ComponentNode;
import dagger.spi.model.BindingGraph.DependencyEdge;
import dagger.spi.model.BindingGraph.MaybeBinding;
import javax.tools.Diagnostic;
// TODO(bcorso): Move this into dagger/spi?
/**
* An object that {@link BindingGraphPlugin}s can use to report diagnostics while visiting a {@link
* BindingGraph}.
*
* <p>Note: This API is still experimental and will change.
*/
public interface DiagnosticReporter {
/**
* Reports a diagnostic for a component. For non-root components, includes information about the
* path from the root component.
*/
void reportComponent(Diagnostic.Kind diagnosticKind, ComponentNode componentNode, String message);
/**
* Reports a diagnostic for a component. For non-root components, includes information about the
* path from the root component.
*/
@FormatMethod
void reportComponent(
Diagnostic.Kind diagnosticKind,
ComponentNode componentNode,
String messageFormat,
Object firstArg,
Object... moreArgs);
/**
* Reports a diagnostic for a binding or missing binding. Includes information about how the
* binding is reachable from entry points.
*/
void reportBinding(Diagnostic.Kind diagnosticKind, MaybeBinding binding, String message);
/**
* Reports a diagnostic for a binding or missing binding. Includes information about how the
* binding is reachable from entry points.
*/
@FormatMethod
void reportBinding(
Diagnostic.Kind diagnosticKind,
MaybeBinding binding,
String messageFormat,
Object firstArg,
Object... moreArgs);
/**
* Reports a diagnostic for a dependency. Includes information about how the dependency is
* reachable from entry points.
*/
void reportDependency(
Diagnostic.Kind diagnosticKind, DependencyEdge dependencyEdge, String message);
/**
* Reports a diagnostic for a dependency. Includes information about how the dependency is
* reachable from entry points.
*/
@FormatMethod
void reportDependency(
Diagnostic.Kind diagnosticKind,
DependencyEdge dependencyEdge,
String messageFormat,
Object firstArg,
Object... moreArgs);
/** Reports a diagnostic for a subcomponent factory method. */
void reportSubcomponentFactoryMethod(
Diagnostic.Kind diagnosticKind,
ChildFactoryMethodEdge childFactoryMethodEdge,
String message);
/** Reports a diagnostic for a subcomponent factory method. */
@FormatMethod
void reportSubcomponentFactoryMethod(
Diagnostic.Kind diagnosticKind,
ChildFactoryMethodEdge childFactoryMethodEdge,
String messageFormat,
Object firstArg,
Object... moreArgs);
}
| 1,000 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Rapa","circ":"2ème circonscription","dpt":"Polynésie française","inscrits":414,"abs":45,"votants":369,"blancs":0,"nuls":0,"exp":369,"res":[{"nuance":"DVD","nom":"Mme <NAME>","voix":292},{"nuance":"DVD","nom":"Mme <NAME>","voix":77}]} | 116 |
1,020 | package org.robobinding.util;
import java.util.Collection;
/**
* Migrated from {@link com.google.common.base.Preconditions}
* @since 1.0
* @version $Revision: 1.0 $
* @author <NAME>
*/
public class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
private Preconditions() {
}
public static void checkNotBlank(String str, String errorMessage) {
checkArgument(!Strings.isNullOrEmpty(str), errorMessage);
}
public static void checkNotBlank(String errorMessage, String... strs) {
checkArgument(!ArrayUtils.isEmpty(strs), errorMessage);
for (String str : strs) {
checkNotBlank(str, errorMessage);
}
}
public static void checkValidResourceId(int resourceId, String errorMessage) {
checkArgument(resourceId != 0, errorMessage);
}
public static void checkNotEmpty(Collection<?> c, String errorMessage) {
if((c == null) || c.isEmpty()) {
throw new IllegalArgumentException(errorMessage);
}
}
}
| 859 |
377 | <reponame>gburd/Kundera
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.query;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.Constants;
import com.impetus.kundera.client.Client;
import com.impetus.kundera.metadata.MetadataBuilder;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
import com.impetus.kundera.persistence.EntityReader;
import com.impetus.kundera.persistence.PersistenceDelegator;
import com.impetus.kundera.utils.KunderaCoreUtils;
/**
* The Class LuceneQuery.
*
* @author animesh.kumar
*/
public class LuceneQuery extends QueryImpl {
/** the log used by this class. */
private static Logger log = LoggerFactory.getLogger(MetadataBuilder.class);
/** The max result. */
int maxResult = Constants.INVALID;
/** The lucene query. */
String luceneQuery;
/**
* Instantiates a new lucene query.
*
* @param jpaQuery
* the jpa query
* @param kunderaQuery
* the kundera query
* @param pd
* the pd
* @param persistenceUnits
* the persistence units
*/
public LuceneQuery(KunderaQuery kunderaQuery, PersistenceDelegator pd, final KunderaMetadata kunderaMetadata) {
super(kunderaQuery, pd, kunderaMetadata);
}
// @see com.impetus.kundera.query.QueryImpl#getResultList()
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.query.QueryImpl#getResultList()
*/
@Override
public List<?> getResultList() {
if (log.isDebugEnabled())
log.debug("JPA Query: " + getJPAQuery());
// get luence query
String q = luceneQuery;
if (null == q) {
q = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);
}
if (log.isDebugEnabled())
log.debug("Lucene Query: " + q);
EntityMetadata m = kunderaQuery.getEntityMetadata();
Client client = persistenceDelegeator.getClient(m);
handlePostEvent();
Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), q, -1, maxResult);
if (kunderaQuery.isAliasOnly()) {
String[] primaryKeys = searchFilter.values().toArray(new String[] {});
return persistenceDelegeator.find(m.getEntityClazz(), primaryKeys);
} else {
return persistenceDelegeator.find(m.getEntityClazz(), searchFilter);
}
}
// @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)
*/
@Override
public Query setMaxResults(int maxResult) {
this.maxResult = maxResult;
return this;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera .metadata.model.EntityMetadata,
* com.impetus.kundera.client.Client)
*/
@Override
protected List<Object> populateEntities(EntityMetadata m, Client client) {
throw new UnsupportedOperationException("Method not supported for Lucene indexing");
}
@Override
protected EntityReader getReader() {
throw new UnsupportedOperationException("Method not supported for Lucene indexing");
}
@Override
protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client) {
throw new UnsupportedOperationException("Method not supported for Lucene indexing");
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()
*/
@Override
protected int onExecuteUpdate() {
if (kunderaQuery.isDeleteUpdate()) {
List result = getResultList();
return result != null ? result.size() : 0;
}
return 0;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public Iterator iterate() {
// TODO Auto-generated method stub
return null;
}
protected List findUsingLucene(EntityMetadata m, Client client) {
throw new UnsupportedOperationException("Method supported in native clients");
}
}
| 2,187 |
3,294 | <reponame>BaruaSourav/docs
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "OptionsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsDlg
IMPLEMENT_DYNAMIC(COptionsDlg, CMFCPropertySheet)
COptionsDlg::COptionsDlg(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
:CMFCPropertySheet(pszCaption, pParentWnd, iSelectPage)
{
SetLook(CMFCPropertySheet::PropSheetLook_Tree, 150 /* Tree control width */);
SetIconsList(IDB_OPTIONSIMAGES, 16 /* Image width */);
// <snippet23>
// The second parameter is the zero based index of an icon that is displayed when
// the control property page is not selected.
// The third parameter is the zero based index of an icon that is displayed when
// the control property page is selected.
CMFCPropertySheetCategoryInfo* pCat1 = AddTreeCategory(_T("Environment"), 0, 1);
// </snippet23>
AddPageToTree(pCat1, &m_Page11, -1, 2);
AddPageToTree(pCat1, &m_Page12, -1, 2);
CMFCPropertySheetCategoryInfo* pCat2 = AddTreeCategory(_T("Source Control"), 0, 1);
AddPageToTree(pCat2, &m_Page21, -1, 2);
AddPageToTree(pCat2, &m_Page22, -1, 2);
CMFCPropertySheetCategoryInfo* pCat3 = AddTreeCategory(_T("Text Editor"), 0, 1);
AddPageToTree(pCat3, &m_Page31, -1, 2);
AddPageToTree(pCat3, &m_Page32, -1, 2);
}
COptionsDlg::~COptionsDlg()
{
}
BEGIN_MESSAGE_MAP(COptionsDlg, CMFCPropertySheet)
END_MESSAGE_MAP()
| 636 |
513 | """ Wrapper around expRNN's Orthogonal class for convenience """
from .exprnn.orthogonal import Orthogonal
from .exprnn.trivializations import expm, cayley_map
from .exprnn.initialization import henaff_init_, cayley_init_
param_name_to_param = {'cayley': cayley_map, 'expm': expm}
init_name_to_init = {'henaff': henaff_init_, 'cayley': cayley_init_}
class OrthogonalLinear(Orthogonal):
def __init__(self, d_input, d_output, method='dtriv', init='cayley', K=100):
""" Wrapper around expRNN's Orthogonal class taking care of parameter names """
if method == "exprnn":
mode = "static"
param = 'expm'
elif method == "dtriv":
# We use 100 as the default to project back to the manifold.
# This parameter does not really affect the convergence of the algorithms, even for K=1
mode = ("dynamic", K, 100) # TODO maybe K=30? check exprnn codebase
param = 'expm'
elif method == "cayley":
mode = "static"
param = 'cayley'
else:
assert False, f"OrthogonalLinear: orthogonal method {method} not supported"
param = param_name_to_param[param]
init_A = init_name_to_init[init]
super().__init__(d_input, d_output, init_A, mode, param)
# Scale LR by factor of 10
self.A._lr_scale = 0.1
| 583 |
6,132 | from . import MemoryMixin
class UnwrapperMixin(MemoryMixin):
"""
This mixin processes SimActionObjects by passing on their .ast field.
"""
def store(self, addr, data, size=None, condition=None, **kwargs):
return super().store(_raw_ast(addr), _raw_ast(data),
size=_raw_ast(size),
condition=_raw_ast(condition),
**kwargs)
def load(self, addr, size=None, condition=None, fallback=None, **kwargs):
return super().load(_raw_ast(addr),
size=_raw_ast(size),
condition=_raw_ast(condition),
fallback=_raw_ast(fallback),
**kwargs)
def find(self, addr, what, max_search, default=None, **kwargs):
return super().find(_raw_ast(addr), _raw_ast(what), max_search,
default=_raw_ast(default),
**kwargs)
def copy_contents(self, dst, src, size, condition=None, **kwargs):
return super().copy_contents(_raw_ast(dst), _raw_ast(src), _raw_ast(size), _raw_ast(condition), **kwargs)
from ...state_plugins.sim_action_object import _raw_ast
| 470 |
22,779 | <filename>plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/controls/ScriptSelectorPanel.java
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.controls;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.progress.UIJob;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBConstants;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.AbstractPopupPanel;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorUtils.ResourceInfo;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLEditorHandlerOpenEditor;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLNavigatorContext;
import org.jkiss.utils.CommonUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Script selector panel (shell)
*/
public class ScriptSelectorPanel extends AbstractPopupPanel {
private static final Log log = Log.getLog(ScriptSelectorPanel.class);
private static final String DIALOG_ID = "DBeaver.ScriptSelectorPopup";
private final IWorkbenchWindow workbenchWindow;
@NotNull
private final SQLNavigatorContext navigatorContext;
@NotNull
private final IFolder rootFolder;
@NotNull
private final List<ResourceInfo> scriptFiles;
private Text patternText;
private TreeViewer scriptViewer;
private volatile FilterJob filterJob;
private ScriptSelectorPanel(
@NotNull final IWorkbenchWindow workbenchWindow,
@NotNull final SQLNavigatorContext navigatorContext,
@NotNull final IFolder rootFolder,
@NotNull List<ResourceInfo> scriptFiles) {
super(workbenchWindow.getShell(),
navigatorContext.getDataSourceContainer() == null ?
"Choose SQL script" :
"Choose SQL script for '" + navigatorContext.getDataSourceContainer().getName() + "'");
this.workbenchWindow = workbenchWindow;
this.navigatorContext = navigatorContext;
this.rootFolder = rootFolder;
this.scriptFiles = scriptFiles;
}
@Override
protected boolean isShowTitle() {
return true;
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
return UIUtils.getDialogSettings(DIALOG_ID);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
/*Rectangle bounds = new Rectangle(100, 100, 500, 200);
final String boundsStr = getBoundsSettings().get(CONFIG_BOUNDS_PARAM);
if (boundsStr != null && !boundsStr.isEmpty()) {
final String[] bc = boundsStr.split(",");
try {
bounds = new Rectangle(
Integer.parseInt(bc[0]),
Integer.parseInt(bc[1]),
Integer.parseInt(bc[2]),
Integer.parseInt(bc[3]));
} catch (NumberFormatException e) {
log.warn(e);
}
}*/
patternText = new Text(composite, SWT.BORDER);
patternText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
UIUtils.addEmptyTextHint(patternText, text -> "Enter a part of script name here");
//patternText.setForeground(fg);
//patternText.setBackground(bg);
patternText.addModifyListener(e -> {
if (filterJob != null) {
return;
}
filterJob = new FilterJob();
filterJob.schedule(250);
});
final Color fg = patternText.getForeground();//parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND);
final Color bg = patternText.getBackground();//parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
composite.setForeground(fg);
composite.setBackground(bg);
Button newButton = new Button(composite, SWT.PUSH | SWT.FLAT);
newButton.setText("&New Script");
newButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IFile scriptFile;
try {
scriptFile = SQLEditorUtils.createNewScript(
DBWorkbench.getPlatform().getWorkspace().getProject(rootFolder.getProject()),
rootFolder,
navigatorContext);
SQLEditorHandlerOpenEditor.openResource(scriptFile, navigatorContext);
} catch (CoreException ex) {
log.error(ex);
}
cancelPressed();
}
});
((GridData) UIUtils.createHorizontalLine(composite).getLayoutData()).horizontalSpan = 2;
Tree scriptTree = new Tree(composite, SWT.SINGLE | SWT.FULL_SELECTION);
final GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 2;
gd.widthHint = 500;
gd.heightHint = 200;
scriptTree.setLayoutData(gd);
scriptTree.setForeground(fg);
scriptTree.setBackground(bg);
scriptTree.setLinesVisible(true);
//scriptViewer.setHeaderVisible(true);
this.scriptViewer = new TreeViewer(scriptTree);
ColumnViewerToolTipSupport.enableFor(this.scriptViewer);
//scriptTree.setS
this.scriptViewer.setContentProvider(new TreeContentProvider() {
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof ResourceInfo) {
final List<ResourceInfo> children = ((ResourceInfo) parentElement).getChildren();
return CommonUtils.isEmpty(children) ? null : children.toArray();
}
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof ResourceInfo) {
final List<ResourceInfo> children = ((ResourceInfo) element).getChildren();
return !CommonUtils.isEmpty(children);
}
return false;
}
});
ViewerColumnController columnController = new ViewerColumnController("scriptSelectorViewer", scriptViewer);
columnController.addColumn("Script", "Resource name", SWT.LEFT, true, true, new ColumnLabelProvider() {
@Override
public Image getImage(Object element) {
final ResourceInfo ri = (ResourceInfo) element;
if (!ri.isDirectory()) {
if (ri.getDataSource() == null) {
return DBeaverIcons.getImage(UIIcon.SQL_SCRIPT);
} else {
return DBeaverIcons.getImage(ri.getDataSource().getDriver().getIcon());
}
} else {
return DBeaverIcons.getImage(DBIcon.TREE_FOLDER);
}
}
@Override
public String getText(Object element) {
return ((ResourceInfo) element).getName();
}
@Override
public String getToolTipText(Object element) {
final DBPDataSourceContainer dataSource = ((ResourceInfo) element).getDataSource();
return dataSource == null ? null : dataSource.getName();
}
@Override
public Image getToolTipImage(Object element) {
final DBPDataSourceContainer dataSource = ((ResourceInfo) element).getDataSource();
return dataSource == null ? null : DBeaverIcons.getImage(dataSource.getDriver().getIcon());
}
});
columnController.addColumn("Time", "Modification time", SWT.LEFT, true, true, new ColumnLabelProvider() {
private SimpleDateFormat sdf = new SimpleDateFormat(DBConstants.DEFAULT_TIMESTAMP_FORMAT);
@Override
public String getText(Object element) {
final File localFile = ((ResourceInfo) element).getLocalFile();
if (localFile.isDirectory()) {
return null;
} else {
return sdf.format(new Date(localFile.lastModified()));
}
}
});
columnController.addColumn("Info", "Script preview", SWT.LEFT, true, true, new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return "";//((ResourceInfo)element).getDescription();
}
@Override
public Color getForeground(Object element) {
return getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW);
}
@Override
public String getToolTipText(Object element) {
final ResourceInfo ri = (ResourceInfo) element;
String description = ri.getDescription();
return description == null ? null : description.trim();
}
});
columnController.createColumns();
columnController.sortByColumn(1, SWT.DOWN);
scriptTree.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
List<ResourceInfo> files = new ArrayList<>();
for (Object item : ((IStructuredSelection)scriptViewer.getSelection()).toArray()) {
if (!((ResourceInfo)item).isDirectory()) {
files.add((ResourceInfo) item);
}
}
if (files.isEmpty()) {
return;
}
cancelPressed();
for (ResourceInfo ri : files) {
SQLEditorHandlerOpenEditor.openResourceEditor(ScriptSelectorPanel.this.workbenchWindow, ri, navigatorContext);
}
}
});
scriptTree.addListener(SWT.PaintItem, event -> {
final TreeItem item = (TreeItem) event.item;
final ResourceInfo ri = (ResourceInfo) item.getData();
if (ri != null && !ri.isDirectory() && CommonUtils.isEmpty(item.getText(2))) {
UIUtils.asyncExec(() -> {
if (!item.isDisposed()) {
item.setText(2, CommonUtils.getSingleLineString(CommonUtils.notEmpty(ri.getDescription())));
}
});
}
});
this.patternText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
final Tree tree = scriptViewer.getTree();
if (e.keyCode == SWT.ARROW_DOWN) {
//scriptViewer.get
scriptViewer.setSelection(new StructuredSelection(tree.getItem(0).getData()));
tree.setFocus();
} else if (e.keyCode == SWT.ARROW_UP) {
scriptViewer.setSelection(new StructuredSelection(tree.getItem(tree.getItemCount() - 1).getData()));
tree.setFocus();
}
}
});
closeOnFocusLost(patternText, scriptViewer.getTree(), newButton);
scriptViewer.setInput(scriptFiles);
UIUtils.expandAll(scriptViewer);
final Tree tree = scriptViewer.getTree();
final TreeColumn[] columns = tree.getColumns();
tree.setHeaderVisible(true);
columns[0].pack();
columns[0].setWidth(columns[0].getWidth() + 10);
columns[1].pack();
columns[2].setWidth(200 * 8);
UIUtils.asyncExec(scriptTree::setFocus);
return composite;
}
protected void createButtonsForButtonBar(Composite parent)
{
// No buttons
}
public static void showTree(IWorkbenchWindow workbenchWindow, SQLNavigatorContext editorContext, IFolder rootFolder, List<ResourceInfo> scriptFiles) {
// List<ResourceInfo> sortedFiles = new ArrayList<>(scriptFiles);
// sortedFiles.sort((o1, o2) -> (int) (o2.getLocalFile().lastModified() - o1.getLocalFile().lastModified()));
ScriptSelectorPanel selectorPanel = new ScriptSelectorPanel(workbenchWindow, editorContext, rootFolder, scriptFiles);
selectorPanel.setModeless(true);
selectorPanel.open();
}
private class ScriptFilter extends ViewerFilter {
private final String pattern;
ScriptFilter() {
pattern = patternText.getText().toLowerCase(Locale.ENGLISH);
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
final IResource resource = ((ResourceInfo) element).getResource();
if (resource instanceof IFolder) {
return isAnyChildMatches((ResourceInfo) element);
} else {
return ((ResourceInfo) element).getName().toLowerCase(Locale.ENGLISH).contains(pattern);
}
}
private boolean isAnyChildMatches(ResourceInfo ri) {
for (ResourceInfo child : ri.getChildren()) {
if (child.getResource() instanceof IFolder) {
if (isAnyChildMatches(child)) {
return true;
}
} else {
if (child.getName().toLowerCase(Locale.ENGLISH).contains(pattern)) {
return true;
}
}
}
return false;
}
}
private class FilterJob extends UIJob {
FilterJob() {
super("Filter scripts");
}
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
filterJob = null;
scriptViewer.setFilters(new ViewerFilter[] { new ScriptFilter() });
UIUtils.expandAll(scriptViewer);
final Tree tree = scriptViewer.getTree();
if (tree.getItemCount() > 0) {
scriptViewer.reveal(tree.getItem(0).getData());
}
return Status.OK_STATUS;
}
}
}
| 7,095 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sql.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.sql.fluent.models.JobExecutionInner;
import java.nio.ByteBuffer;
import java.time.OffsetDateTime;
import java.util.UUID;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in JobExecutionsClient. */
public interface JobExecutionsClient {
/**
* Lists all executions in a job agent.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param createTimeMin If specified, only job executions created at or after the specified time are included.
* @param createTimeMax If specified, only job executions created before the specified time are included.
* @param endTimeMin If specified, only job executions completed at or after the specified time are included.
* @param endTimeMax If specified, only job executions completed before the specified time are included.
* @param isActive If specified, only active or only completed job executions are included.
* @param skip The number of elements in the collection to skip.
* @param top The number of elements to return from the collection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<JobExecutionInner> listByAgentAsync(
String resourceGroupName,
String serverName,
String jobAgentName,
OffsetDateTime createTimeMin,
OffsetDateTime createTimeMax,
OffsetDateTime endTimeMin,
OffsetDateTime endTimeMax,
Boolean isActive,
Integer skip,
Integer top);
/**
* Lists all executions in a job agent.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<JobExecutionInner> listByAgentAsync(String resourceGroupName, String serverName, String jobAgentName);
/**
* Lists all executions in a job agent.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param createTimeMin If specified, only job executions created at or after the specified time are included.
* @param createTimeMax If specified, only job executions created before the specified time are included.
* @param endTimeMin If specified, only job executions completed at or after the specified time are included.
* @param endTimeMax If specified, only job executions completed before the specified time are included.
* @param isActive If specified, only active or only completed job executions are included.
* @param skip The number of elements in the collection to skip.
* @param top The number of elements to return from the collection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<JobExecutionInner> listByAgent(
String resourceGroupName,
String serverName,
String jobAgentName,
OffsetDateTime createTimeMin,
OffsetDateTime createTimeMax,
OffsetDateTime endTimeMin,
OffsetDateTime endTimeMax,
Boolean isActive,
Integer skip,
Integer top,
Context context);
/**
* Lists all executions in a job agent.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<JobExecutionInner> listByAgent(String resourceGroupName, String serverName, String jobAgentName);
/**
* Requests cancellation of a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution to cancel.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> cancelWithResponseAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Requests cancellation of a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution to cancel.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> cancelAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Requests cancellation of a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution to cancel.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void cancel(String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Requests cancellation of a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution to cancel.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> cancelWithResponse(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
UUID jobExecutionId,
Context context);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> createWithResponseAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<JobExecutionInner>, JobExecutionInner> beginCreateAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<JobExecutionInner>, JobExecutionInner> beginCreate(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<JobExecutionInner>, JobExecutionInner> beginCreate(
String resourceGroupName, String serverName, String jobAgentName, String jobName, Context context);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<JobExecutionInner> createAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
JobExecutionInner create(String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Starts an elastic job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
JobExecutionInner create(
String resourceGroupName, String serverName, String jobAgentName, String jobName, Context context);
/**
* Lists a job's executions.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param createTimeMin If specified, only job executions created at or after the specified time are included.
* @param createTimeMax If specified, only job executions created before the specified time are included.
* @param endTimeMin If specified, only job executions completed at or after the specified time are included.
* @param endTimeMax If specified, only job executions completed before the specified time are included.
* @param isActive If specified, only active or only completed job executions are included.
* @param skip The number of elements in the collection to skip.
* @param top The number of elements to return from the collection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<JobExecutionInner> listByJobAsync(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
OffsetDateTime createTimeMin,
OffsetDateTime createTimeMax,
OffsetDateTime endTimeMin,
OffsetDateTime endTimeMax,
Boolean isActive,
Integer skip,
Integer top);
/**
* Lists a job's executions.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<JobExecutionInner> listByJobAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Lists a job's executions.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param createTimeMin If specified, only job executions created at or after the specified time are included.
* @param createTimeMax If specified, only job executions created before the specified time are included.
* @param endTimeMin If specified, only job executions completed at or after the specified time are included.
* @param endTimeMax If specified, only job executions completed before the specified time are included.
* @param isActive If specified, only active or only completed job executions are included.
* @param skip The number of elements in the collection to skip.
* @param top The number of elements to return from the collection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<JobExecutionInner> listByJob(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
OffsetDateTime createTimeMin,
OffsetDateTime createTimeMax,
OffsetDateTime endTimeMin,
OffsetDateTime endTimeMax,
Boolean isActive,
Integer skip,
Integer top,
Context context);
/**
* Lists a job's executions.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job executions.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<JobExecutionInner> listByJob(
String resourceGroupName, String serverName, String jobAgentName, String jobName);
/**
* Gets a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job execution.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<JobExecutionInner>> getWithResponseAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Gets a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job execution.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<JobExecutionInner> getAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Gets a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job execution.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
JobExecutionInner get(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Gets a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job execution.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<JobExecutionInner> getWithResponse(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
UUID jobExecutionId,
Context context);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<JobExecutionInner>, JobExecutionInner> beginCreateOrUpdateAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<JobExecutionInner>, JobExecutionInner> beginCreateOrUpdate(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<JobExecutionInner>, JobExecutionInner> beginCreateOrUpdate(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
UUID jobExecutionId,
Context context);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<JobExecutionInner> createOrUpdateAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
JobExecutionInner createOrUpdate(
String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId);
/**
* Creates or updates a job execution.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an execution of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
JobExecutionInner createOrUpdate(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
UUID jobExecutionId,
Context context);
}
| 10,472 |
852 | <gh_stars>100-1000
/*
* JsonSerializable.h
*
* Created on: Aug 2, 2012
* Author: aspataru
*/
#ifndef JSONSERIALIZABLE_H_
#define JSONSERIALIZABLE_H_
#include "json.h"
namespace jsoncollector {
class JsonSerializable {
public:
virtual ~JsonSerializable(){};
virtual void serialize(Json::Value& root) const = 0;
virtual void deserialize(Json::Value& root) = 0;
};
} // namespace jsoncollector
#endif /* JSONSERIALIZABLE_H_ */
| 176 |
434 | /***** BEGIN LICENSE BLOCK *****
BSD License
Copyright (c) 2005-2015, NIF File Format Library and Tools
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. The name of the NIF File Format Library and Tools project may not be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
***** END LICENCE BLOCK *****/
#ifndef VALUEEDIT_H
#define VALUEEDIT_H
#include "data/nifvalue.h"
#include <QTextEdit> // Inherited
#include <QWidget> // Inherited
#include <QSpinBox> // Inherited
#include <QValidator> // Inherited
#include <cstring>
//! \file valueedit.h ValueEdit and other widgets
class QAction;
class QDoubleSpinBox;
class QLabel;
//! An editing widget for a NifValue
class ValueEdit : public QWidget
{
Q_OBJECT
public:
//! Constructor
ValueEdit( QWidget * parent = nullptr );
//! The value being edited?
Q_PROPERTY( NifValue value READ getValue WRITE setValue USER true )
//! Accessor for value
NifValue getValue() const;
//! Whether a value can be edited or not
static bool canEdit( NifValue::Type t );
public slots:
//! Sets the value of the widget
void setValue( const NifValue & v );
//! Resizes the widget if the child widget is resized
void childResized( QResizeEvent * e );
protected:
//! Resizes the underlying widget
void resizeEditor();
//! Resize event handler
void resizeEvent( QResizeEvent * e ) override;
private:
//! The type of the value being edited
NifValue::Type typ;
//! The underlying editing widget
QWidget * edit;
};
//! An editing widget for a vector.
class VectorEdit final : public ValueEdit
{
Q_OBJECT
public:
//! Constructor
VectorEdit( QWidget * parent = nullptr );
//! Vector4 being edited
Q_PROPERTY( Vector4 vector4 READ getVector4 WRITE setVector4 STORED false )
//! Vector3 being edited
Q_PROPERTY( Vector3 vector3 READ getVector3 WRITE setVector3 STORED false )
//! Vector2 being edited
Q_PROPERTY( Vector2 vector2 READ getVector2 WRITE setVector2 STORED false )
//! Accessor for the Vector4
Vector4 getVector4() const;
//! Accessor for the Vector3
Vector3 getVector3() const;
//! Accessor for the Vector2
Vector2 getVector2() const;
signals:
//! Signal emitted when the vector is edited
/**
* Used in NifEditBox implementations for real-time updating.
*/
void sigEdited();
public slots:
//! Sets the Vector4
void setVector4( const Vector4 & );
//! Sets the Vector3
void setVector3( const Vector3 & );
//! Sets the Vector2
void setVector2( const Vector2 & );
protected slots:
//! Signal adapter; emits sigEdited()
void sltChanged();
private:
QDoubleSpinBox * x;
QDoubleSpinBox * y;
QDoubleSpinBox * z;
QDoubleSpinBox * w;
QLabel * wl, * zl;
bool setting;
};
class ColorEdit final : public ValueEdit
{
Q_OBJECT
public:
ColorEdit( QWidget * parent = nullptr );
Q_PROPERTY( Color4 color4 READ getColor4 WRITE setColor4 STORED false )
Q_PROPERTY( Color3 color3 READ getColor3 WRITE setColor3 STORED false )
Color4 getColor4() const;
Color3 getColor3() const;
signals:
void sigEdited();
public slots:
void setColor4( const Color4 & );
void setColor3( const Color3 & );
protected slots:
void sltChanged();
private:
QDoubleSpinBox * r, * g, * b, * a;
QLabel * al;
bool setting;
};
class RotationEdit final : public ValueEdit
{
Q_OBJECT
public:
RotationEdit( QWidget * parent = nullptr );
Q_PROPERTY( Matrix matrix READ getMatrix WRITE setMatrix STORED false )
Q_PROPERTY( Quat quat READ getQuat WRITE setQuat STORED false )
Matrix getMatrix() const;
Quat getQuat() const;
signals:
void sigEdited();
public slots:
void setMatrix( const Matrix & );
void setQuat( const Quat & );
protected slots:
void sltChanged();
void switchMode();
void setupMode();
private:
enum
{
mAuto, mEuler, mAxis
} mode;
QLabel * l[4];
QDoubleSpinBox * v[4];
QAction * actMode;
bool setting;
};
class TriangleEdit final : public ValueEdit
{
Q_OBJECT
public:
TriangleEdit( QWidget * parent = nullptr );
Q_PROPERTY( Triangle triangle READ getTriangle WRITE setTriangle STORED false )
Triangle getTriangle() const;
public slots:
void setTriangle( const Triangle & );
private:
QSpinBox * v1;
QSpinBox * v2;
QSpinBox * v3;
};
//! A text editing widget used by ValueEdit
class TextEdit final : public QTextEdit
{
Q_OBJECT
public:
TextEdit( const QString & str, QWidget * parent = nullptr );
void CalcSize();
signals:
void sigResized( QResizeEvent * e );
public slots:
void sltTextChanged();
protected:
void resizeEvent( QResizeEvent * e ) override final;
void keyPressEvent( QKeyEvent * e ) override final;
};
class UnsignedValidator : public QValidator
{
Q_OBJECT
public:
UnsignedValidator( QObject * parent );
~UnsignedValidator() {}
QValidator::State validate( QString &, int & ) const;
void setRange( uint min, uint max );
uint minimum() const { return min; }
uint maximum() const { return max; }
private:
uint min = 0, max = 0xffffffff;
};
class UIntSpinBox final : public QSpinBox
{
Q_OBJECT
public:
UIntSpinBox( QWidget * parent );
~UIntSpinBox()
{
delete validator;
}
QValidator::State validate( QString & text, int & pos ) const override;
public slots:
void setValue( uint value );
protected:
QString textFromValue( int value ) const override;
int valueFromText( const QString & text ) const override;
uint toUInt( int i ) const
{
uint ui;
std::memcpy( &ui, &i, sizeof( ui ) );
return ui;
}
int toInt( uint ui ) const
{
int i;
std::memcpy( &i, &ui, sizeof( i ) );
return i;
}
private:
UnsignedValidator * validator;
};
#endif
| 2,246 |
7,137 | package io.onedev.server.imports;
import java.io.Serializable;
import java.util.List;
import io.onedev.commons.utils.TaskLogger;
import io.onedev.server.util.ReflectionUtils;
public abstract class Importer<Where extends Serializable, What extends Serializable, How extends Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<Where> whereClass;
private final Class<What> whatClass;
private final Class<How> howClass;
@SuppressWarnings("unchecked")
public Importer() {
List<Class<?>> typeArguments = ReflectionUtils.getTypeArguments(Importer.class, getClass());
whereClass = (Class<Where>) typeArguments.get(0);
whatClass = (Class<What>) typeArguments.get(1);
howClass = (Class<How>) typeArguments.get(2);
}
public Class<Where> getWhereClass() {
return whereClass;
}
public Class<What> getWhatClass() {
return whatClass;
}
public Class<How> getHowClass() {
return howClass;
}
public abstract String getName();
public abstract What getWhat(Where where, TaskLogger logger);
public abstract How getHow(Where where, What what, TaskLogger logger);
}
| 375 |
2,139 | <gh_stars>1000+
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jruby.runtime.builtin;
import java.util.List;
/**
* Interface that represents the instance variable aspect of Ruby
* objects.
*
* @author headius
*/
public interface InstanceVariables {
//
// INSTANCE VARIABLE METHODS
//
/**
* Returns true if object has the named instance variable.
*
* @param name the name of an instance variable
* @return true if object has the named instance variable.
*/
boolean hasInstanceVariable(String name);
@Deprecated
boolean fastHasInstanceVariable(String internedName);
/**
* Returns the named instance variable if present, else null.
*
* @param name the name of an instance variable
* @return the named instance variable if present, else null
*/
IRubyObject getInstanceVariable(String name);
@Deprecated
IRubyObject fastGetInstanceVariable(String internedName);
/**
* Sets the named instance variable to the specified value.
*
* @param name the name of an instance variable
* @param value the value to be set
*/
IRubyObject setInstanceVariable(String name, IRubyObject value);
@Deprecated
IRubyObject fastSetInstanceVariable(String internedName, IRubyObject value);
/**
* Removes the named instance variable, if present, returning its
* value.
*
* @param name the name of the variable to remove
* @return the value of the remove variable, if present; else null
*/
IRubyObject removeInstanceVariable(String name);
/**
* @return instance variables
*/
List<Variable<IRubyObject>> getInstanceVariableList();
/**
* @return instance variable names
*/
List<String> getInstanceVariableNameList();
/**
* Copies all instance variables from the given object into the receiver
*/
void copyInstanceVariablesInto(InstanceVariables other);
}
| 666 |
3,459 | #include <stdio.h>
//#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static int search_gcda(const char *str, int len)
{
int i;
for (i = 0; i < len - 6; i++)
if (str[i] == '.' && str[i+1] == 'g' && str[i+2] == 'c' &&
str[i+3] == 'd' && str[i+4] == 'a' && str[i+5] == 0)
return i;
return -1;
}
static int is_good_char(char c)
{
return c >= ' ' && c < 0x7f;
}
static int is_good_path(char *path)
{
int len = strlen(path);
path[len-2] = 'n';
path[len-1] = 'o';
FILE *f = fopen(path, "rb");
path[len-2] = 'd';
path[len-1] = 'a';
if (f) {
fclose(f);
return 1;
}
printf("not good path: %s\n", path);
return 0;
}
int main(int argc, char *argv[])
{
char buff[1024], *p;
char cwd[4096];
FILE *f;
int l, pos, pos1, old_len, cwd_len;
if (argc != 2) return 1;
getcwd(cwd, sizeof(cwd));
cwd_len = strlen(cwd);
if (cwd[cwd_len-1] != '/') {
cwd[cwd_len++] = '/';
cwd[cwd_len] = 0;
}
f = fopen(argv[1], "rb+");
if (f == NULL) return 2;
while (1)
{
readnext:
l = fread(buff, 1, sizeof(buff), f);
if (l <= 16) break;
pos = 0;
while (pos < l)
{
pos1 = search_gcda(buff + pos, l - pos);
if (pos1 < 0) {
fseek(f, -6, SEEK_CUR);
goto readnext;
}
pos += pos1;
while (pos > 0 && is_good_char(buff[pos-1])) pos--;
if (pos == 0) {
fseek(f, -(sizeof(buff) + 16), SEEK_CUR);
goto readnext;
}
// paths must start with /
while (pos < l && buff[pos] != '/') pos++;
p = buff + pos;
old_len = strlen(p);
if (!is_good_path(p)) {
pos += old_len;
continue;
}
if (strncmp(p, cwd, cwd_len) != 0) {
printf("can't handle: %s\n", p);
pos += old_len;
continue;
}
memmove(p, p + cwd_len, old_len - cwd_len + 1);
fseek(f, -(sizeof(buff) - pos), SEEK_CUR);
fwrite(p, 1, old_len, f);
goto readnext;
}
}
fclose(f);
return 0;
}
| 978 |
5,964 | <filename>third_party/WebKit/Source/core/html/parser/HTMLParserThreadTest.cpp
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/html/parser/HTMLParserThread.h"
#include <gtest/gtest.h>
namespace blink {
TEST(HTMLParserThreadTest, Init)
{
// The harness has already run init() for us, so tear down the parser first.
ASSERT_TRUE(HTMLParserThread::shared());
HTMLParserThread::shutdown();
// Make sure starting the parser thread brings it back to life.
ASSERT_FALSE(HTMLParserThread::shared());
HTMLParserThread::init();
ASSERT_TRUE(HTMLParserThread::shared());
}
} // namespace blink
| 240 |
1,909 | /*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.item.database.support;
import org.springframework.batch.item.database.ItemPreparedStatementSetter;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;
import org.springframework.util.Assert;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
/**
* <p>Implementation of the {@link ItemPreparedStatementSetter} interface that assumes all
* keys are contained within a {@link Map} with the column name as the key. It assumes nothing
* about ordering, and assumes that the order the entry set can be iterated over is the same as
* the PreparedStatement should be set.</p>
*
* @author <NAME>
* @author <NAME>
* @see ItemPreparedStatementSetter
* @see ColumnMapRowMapper
*/
public class ColumnMapItemPreparedStatementSetter implements ItemPreparedStatementSetter<Map<String, Object>> {
@Override
public void setValues(Map<String, Object> item, PreparedStatement ps) throws SQLException {
Assert.isInstanceOf(Map.class, item, "Input to map PreparedStatement parameters must be of type Map.");
int counter = 1;
for(Object value : item.values()){
StatementCreatorUtils.setParameterValue(ps, counter, SqlTypeValue.TYPE_UNKNOWN, value);
counter++;
}
}
}
| 574 |
819 | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef VR_SEURAT_IMAGE_COLOR_PROCESSOR_H_
#define VR_SEURAT_IMAGE_COLOR_PROCESSOR_H_
#include "absl/types/span.h"
#include "seurat/base/color.h"
namespace seurat {
namespace image {
// ColorProcessor specifies an interface for transforming sets of colors.
//
// Implementations may perform operations such as tone-mapping and/or
// transformation to premultiplied alpha.
class ColorProcessor {
public:
virtual ~ColorProcessor() = default;
// Processes the color values in |color_set| in place.
virtual void ProcessColors(absl::Span<base::Color4f> color_set) const = 0;
protected:
ColorProcessor() = default;
};
// GammaToneMapper tonemaps sets of colors via a gamma exponent curve. The
// process expects display-referred (i.e. sRGB linear or gamma space),
// possibly-HDR colors as input, and produces the same kind of data, with a
// power distribution depending on the configured gamma-correction value.
class GammaToneMapper : public ColorProcessor {
public:
// Constructs a tone mapper with the given exponent for |gamma| correction.
explicit GammaToneMapper(float gamma) : gamma_(gamma) {}
~GammaToneMapper() override = default;
void ProcessColors(absl::Span<base::Color4f> color_set) const override;
private:
// Exponent for gamma correction.
const float gamma_;
};
// Transforms independent rgba into premultiplied-alpha.
class PremultipliedAlphaConverter : public ColorProcessor {
public:
PremultipliedAlphaConverter() = default;
~PremultipliedAlphaConverter() override = default;
void ProcessColors(absl::Span<base::Color4f> color_set) const override;
};
// Applies a sequence of ColorProcessors in order.
class ColorProcessorPipeline : public ColorProcessor {
public:
explicit ColorProcessorPipeline(
std::vector<std::unique_ptr<ColorProcessor>> sequence)
: sequence_(std::move(sequence)) {}
~ColorProcessorPipeline() override = default;
void ProcessColors(absl::Span<base::Color4f> color_set) const override;
private:
const std::vector<std::unique_ptr<ColorProcessor>> sequence_;
};
} // namespace image
} // namespace seurat
#endif // VR_SEURAT_IMAGE_COLOR_PROCESSOR_H_
| 820 |
882 | package cookbook;
import org.junit.*;
import water.*;
import water.fvec.*;
import water.util.Log;
import water.util.RemoveAllKeysTask;
public class Cookbook extends TestUtil {
@Before
public void removeAllKeys() {
Log.info("Removing all keys...");
RemoveAllKeysTask collector = new RemoveAllKeysTask();
collector.invokeOnAllNodes();
Log.info("Removed all keys.");
}
// @Test
// public void testWillFail() {
// throw new RuntimeException("first test fails");
// }
// ---
// Test flow-coding a filter & group-by computing e.g. mean
@Test
public void testBasic() {
Key k = Key.make("cars.hex");
Frame fr = parseFrame(k, "../smalldata/cars.csv");
//Frame fr = parseFrame(k, "../datasets/UCI/UCI-large/covtype/covtype.data");
// Call into another class so we do not need to weave anything in this class
// when run as a JUnit
Cookbook2.basicStatic(k, fr);
}
// @Test
// public void testWillFail2() {
// throw new RuntimeException("3 test fails");
// }
}
| 359 |
1,467 | <reponame>awishn02/aws-sdk-java-v2
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package utils.test.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
import software.amazon.awssdk.services.dynamodb.model.TableStatus;
/**
* Utility methods for working with DynamoDB tables.
*
* <pre class="brush: java">
* // ... create DynamoDB table ...
* try {
* waitUntilActive(dynamoDB, myTableName());
* } catch (SdkClientException e) {
* // table didn't become active
* }
* // ... start making calls to table ...
* </pre>
*/
public class TableUtils {
private static final int DEFAULT_WAIT_TIMEOUT = 20 * 60 * 1000;
private static final int DEFAULT_WAIT_INTERVAL = 10 * 1000;
/**
* The logging utility.
*/
private static final Logger log = LoggerFactory.getLogger(TableUtils.class);
/**
* Waits up to 10 minutes for a specified DynamoDB table to resolve,
* indicating that it exists. If the table doesn't return a result after
* this time, a SdkClientException is thrown.
*
* @param dynamo
* The DynamoDB client to use to make requests.
* @param tableName
* The name of the table being resolved.
*
* @throws SdkClientException
* If the specified table does not resolve before this method
* times out and stops polling.
* @throws InterruptedException
* If the thread is interrupted while waiting for the table to
* resolve.
*/
public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName)
throws InterruptedException {
waitUntilExists(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL);
}
/**
* Waits up to a specified amount of time for a specified DynamoDB table to
* resolve, indicating that it exists. If the table doesn't return a result
* after this time, a SdkClientException is thrown.
*
* @param dynamo
* The DynamoDB client to use to make requests.
* @param tableName
* The name of the table being resolved.
* @param timeout
* The maximum number of milliseconds to wait.
* @param interval
* The poll interval in milliseconds.
*
* @throws SdkClientException
* If the specified table does not resolve before this method
* times out and stops polling.
* @throws InterruptedException
* If the thread is interrupted while waiting for the table to
* resolve.
*/
public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName, final int timeout,
final int interval) throws InterruptedException {
TableDescription table = waitForTableDescription(dynamo, tableName, null, timeout, interval);
if (table == null) {
throw SdkClientException.builder().message("Table " + tableName + " never returned a result").build();
}
}
/**
* Waits up to 10 minutes for a specified DynamoDB table to move into the
* <code>ACTIVE</code> state. If the table does not exist or does not
* transition to the <code>ACTIVE</code> state after this time, then
* SdkClientException is thrown.
*
* @param dynamo
* The DynamoDB client to use to make requests.
* @param tableName
* The name of the table whose status is being checked.
*
* @throws TableNeverTransitionedToStateException
* If the specified table does not exist or does not transition
* into the <code>ACTIVE</code> state before this method times
* out and stops polling.
* @throws InterruptedException
* If the thread is interrupted while waiting for the table to
* transition into the <code>ACTIVE</code> state.
*/
public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName)
throws InterruptedException, TableNeverTransitionedToStateException {
waitUntilActive(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL);
}
/**
* Waits up to a specified amount of time for a specified DynamoDB table to
* move into the <code>ACTIVE</code> state. If the table does not exist or
* does not transition to the <code>ACTIVE</code> state after this time,
* then a SdkClientException is thrown.
*
* @param dynamo
* The DynamoDB client to use to make requests.
* @param tableName
* The name of the table whose status is being checked.
* @param timeout
* The maximum number of milliseconds to wait.
* @param interval
* The poll interval in milliseconds.
*
* @throws TableNeverTransitionedToStateException
* If the specified table does not exist or does not transition
* into the <code>ACTIVE</code> state before this method times
* out and stops polling.
* @throws InterruptedException
* If the thread is interrupted while waiting for the table to
* transition into the <code>ACTIVE</code> state.
*/
public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName, final int timeout,
final int interval) throws InterruptedException, TableNeverTransitionedToStateException {
TableDescription table = waitForTableDescription(dynamo, tableName, TableStatus.ACTIVE, timeout, interval);
if (table == null || !table.tableStatus().equals(TableStatus.ACTIVE)) {
throw new TableNeverTransitionedToStateException(tableName, TableStatus.ACTIVE);
}
}
/**
* Wait for the table to reach the desired status and returns the table
* description
*
* @param dynamo
* Dynamo client to use
* @param tableName
* Table name to poll status of
* @param desiredStatus
* Desired {@link TableStatus} to wait for. If null this method
* simply waits until DescribeTable returns something non-null
* (i.e. any status)
* @param timeout
* Timeout in milliseconds to continue to poll for desired status
* @param interval
* Time to wait in milliseconds between poll attempts
* @return Null if DescribeTables never returns a result, otherwise the
* result of the last poll attempt (which may or may not have the
* desired state)
* @throws {@link
* IllegalArgumentException} If timeout or interval is invalid
*/
private static TableDescription waitForTableDescription(final DynamoDbClient dynamo, final String tableName,
TableStatus desiredStatus, final int timeout, final int interval)
throws InterruptedException, IllegalArgumentException {
if (timeout < 0) {
throw new IllegalArgumentException("Timeout must be >= 0");
}
if (interval <= 0 || interval >= timeout) {
throw new IllegalArgumentException("Interval must be > 0 and < timeout");
}
long startTime = System.currentTimeMillis();
long endTime = startTime + timeout;
TableDescription table = null;
while (System.currentTimeMillis() < endTime) {
try {
table = dynamo.describeTable(DescribeTableRequest.builder().tableName(tableName).build()).table();
if (desiredStatus == null || table.tableStatus().equals(desiredStatus)) {
return table;
}
} catch (ResourceNotFoundException rnfe) {
// ResourceNotFound means the table doesn't exist yet,
// so ignore this error and just keep polling.
}
Thread.sleep(interval);
}
return table;
}
/**
* Creates the table and ignores any errors if it already exists.
* @param dynamo The Dynamo client to use.
* @param createTableRequest The create table request.
* @return True if created, false otherwise.
*/
public static boolean createTableIfNotExists(final DynamoDbClient dynamo, final CreateTableRequest createTableRequest) {
try {
dynamo.createTable(createTableRequest);
return true;
} catch (final ResourceInUseException e) {
if (log.isTraceEnabled()) {
log.trace("Table " + createTableRequest.tableName() + " already exists", e);
}
}
return false;
}
/**
* Deletes the table and ignores any errors if it doesn't exist.
* @param dynamo The Dynamo client to use.
* @param deleteTableRequest The delete table request.
* @return True if deleted, false otherwise.
*/
public static boolean deleteTableIfExists(final DynamoDbClient dynamo, final DeleteTableRequest deleteTableRequest) {
try {
dynamo.deleteTable(deleteTableRequest);
return true;
} catch (final ResourceNotFoundException e) {
if (log.isTraceEnabled()) {
log.trace("Table " + deleteTableRequest.tableName() + " does not exist", e);
}
}
return false;
}
/**
* Thrown by {@link TableUtils} when a table never reaches a desired state
*/
public static class TableNeverTransitionedToStateException extends SdkClientException {
private static final long serialVersionUID = 8920567021104846647L;
public TableNeverTransitionedToStateException(String tableName, TableStatus desiredStatus) {
super(SdkClientException.builder()
.message("Table " + tableName + " never transitioned to desired state of " +
desiredStatus.toString()));
}
}
}
| 4,300 |
2,542 | <filename>src/prod/src/data/utilities/Encoding.h<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Data
{
namespace Utilities
{
enum Encoding
{
UTF8 = 0,
UTF16 = 1
};
}
}
| 167 |
301 | {
"virtualMachinesTier": {
"type": "String",
"metadata": {
"displayName": "virtualMachinesTier",
"description": "Specifiy whether you want to enable Standard tier for Virtual Machine resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"appServicesTier": {
"type": "String",
"metadata": {
"displayName": "appServicesTier",
"description": "Specify whether you want to enable Standard tier for Azure App Service resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"sqlServersTier": {
"type": "String",
"metadata": {
"displayName": "sqlServersTier",
"description": "Specify whether you want to enable Standard tier for PaaS SQL Service resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"sqlServerVirtualMachinesTier": {
"type": "String",
"metadata": {
"displayName": "sqlServerVirtualMachinesTier",
"description": "Specify whether you want to enable Standard tier for SQL Server on VM resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"storageAccountsTier": {
"type": "String",
"metadata": {
"displayName": "storageAccountsTier",
"description": "Specify whether you want to enable Standard tier for Storage Account resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"kubernetesServiceTier": {
"type": "String",
"metadata": {
"displayName": "kubernetesServiceTier",
"description": "Specify whether you want to enable Standard tier for Kubernetes service resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"containerRegistryTier": {
"type": "String",
"metadata": {
"displayName": "containerRegistryTier",
"description": "Specify whether you want to enable Standard tier for Container Registry resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
},
"keyVaultsTier": {
"type": "String",
"metadata": {
"displayName": "keyVaultsTier",
"description": "Specify whether you want to enable Standard tier for Key Vault resource type"
},
"allowedValues": [
"Standard",
"Free"
],
"defaultValue": "Standard"
}
} | 1,385 |
695 | <gh_stars>100-1000
import debuggee
debuggee.setup()
| 20 |
417 | <reponame>Pecon/Torque3D-1<gh_stars>100-1000
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) 2014 - <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "Verve/Extension/GUI/VFadeEvent.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( VFadeEvent );
//-----------------------------------------------------------------------------
VFadeEvent::VFadeEvent( void )
{
setLabel( "FadeEvent" );
}
//-----------------------------------------------------------------------------
//
// Callback Methods.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// VFadeEvent::onTrigger( pTime, pDelta );
//
// Start the fade sequence if a valid fade control can be found.
//
//-----------------------------------------------------------------------------
void VFadeEvent::onTrigger( const S32 &pTime, const S32 &pDelta )
{
Parent::onTrigger( pTime, pDelta );
// Fetch GUI Control.
VFadeControl *fadeControl;
if ( !Sim::findObject( "VFadeControlGUI", fadeControl ) )
{
// Invalid.
return;
}
// Start Fade.
fadeControl->start( getFadeType(), mDuration );
// Set Elapsed Time.
fadeControl->mElapsedTime = mAbs( pTime - getStartTime() );
}
//-----------------------------------------------------------------------------
//
// VFadeEvent::onComplete( pTime, pDelta );
//
// Tidy up the fade control once the event has finished.
//
//-----------------------------------------------------------------------------
void VFadeEvent::onComplete( const S32 &pTime, const S32 &pDelta )
{
Parent::onTrigger( pTime, pDelta );
// Fetch GUI Control.
VFadeControl *fadeControl;
if ( !Sim::findObject( "VFadeControlGUI", fadeControl ) )
{
// Invalid.
return;
}
// Set Elapsed Time.
fadeControl->mElapsedTime = mDuration;
}
//-----------------------------------------------------------------------------
//
// Property Methods.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// VFadeEvent::getFadeType();
//
// Returns the type of fade (in or out) that this event will use. Zero and Even
// indices will Fade Out, while Odd numbers will Fade In.
//
//-----------------------------------------------------------------------------
VFadeControl::eFadeType VFadeEvent::getFadeType( void )
{
if ( !isControllerPlayingForward() )
{
return ( getIndex() % 2 == 0 ) ? VFadeControl::k_TypeOut : VFadeControl::k_TypeIn;
}
return ( getIndex() % 2 == 0 ) ? VFadeControl::k_TypeIn : VFadeControl::k_TypeOut;
} | 1,039 |
2,151 | <filename>net/third_party/quiche/src/quic/core/uber_received_packet_manager.cc
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/core/uber_received_packet_manager.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
namespace quic {
UberReceivedPacketManager::UberReceivedPacketManager(QuicConnectionStats* stats)
: supports_multiple_packet_number_spaces_(false) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.set_connection_stats(stats);
}
}
UberReceivedPacketManager::~UberReceivedPacketManager() {}
void UberReceivedPacketManager::SetFromConfig(const QuicConfig& config,
Perspective perspective) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.SetFromConfig(config, perspective);
}
}
bool UberReceivedPacketManager::IsAwaitingPacket(
EncryptionLevel decrypted_packet_level,
QuicPacketNumber packet_number) const {
if (!supports_multiple_packet_number_spaces_) {
return received_packet_managers_[0].IsAwaitingPacket(packet_number);
}
return received_packet_managers_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)]
.IsAwaitingPacket(packet_number);
}
const QuicFrame UberReceivedPacketManager::GetUpdatedAckFrame(
PacketNumberSpace packet_number_space,
QuicTime approximate_now) {
if (!supports_multiple_packet_number_spaces_) {
return received_packet_managers_[0].GetUpdatedAckFrame(approximate_now);
}
return received_packet_managers_[packet_number_space].GetUpdatedAckFrame(
approximate_now);
}
void UberReceivedPacketManager::RecordPacketReceived(
EncryptionLevel decrypted_packet_level,
const QuicPacketHeader& header,
QuicTime receipt_time) {
if (!supports_multiple_packet_number_spaces_) {
received_packet_managers_[0].RecordPacketReceived(header, receipt_time);
return;
}
received_packet_managers_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)]
.RecordPacketReceived(header, receipt_time);
}
void UberReceivedPacketManager::DontWaitForPacketsBefore(
EncryptionLevel decrypted_packet_level,
QuicPacketNumber least_unacked) {
if (!supports_multiple_packet_number_spaces_) {
received_packet_managers_[0].DontWaitForPacketsBefore(least_unacked);
return;
}
received_packet_managers_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)]
.DontWaitForPacketsBefore(least_unacked);
}
void UberReceivedPacketManager::MaybeUpdateAckTimeout(
bool should_last_packet_instigate_acks,
EncryptionLevel decrypted_packet_level,
QuicPacketNumber last_received_packet_number,
QuicTime time_of_last_received_packet,
QuicTime now,
const RttStats* rtt_stats,
QuicTime::Delta delayed_ack_time) {
if (!supports_multiple_packet_number_spaces_) {
received_packet_managers_[0].MaybeUpdateAckTimeout(
should_last_packet_instigate_acks, last_received_packet_number,
time_of_last_received_packet, now, rtt_stats, delayed_ack_time);
return;
}
received_packet_managers_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)]
.MaybeUpdateAckTimeout(
should_last_packet_instigate_acks, last_received_packet_number,
time_of_last_received_packet, now, rtt_stats, delayed_ack_time);
}
void UberReceivedPacketManager::ResetAckStates(
EncryptionLevel encryption_level) {
if (!supports_multiple_packet_number_spaces_) {
received_packet_managers_[0].ResetAckStates();
return;
}
received_packet_managers_[QuicUtils::GetPacketNumberSpace(encryption_level)]
.ResetAckStates();
}
void UberReceivedPacketManager::EnableMultiplePacketNumberSpacesSupport() {
if (supports_multiple_packet_number_spaces_) {
QUIC_BUG << "Multiple packet number spaces has already been enabled";
return;
}
if (received_packet_managers_[0].GetLargestObserved().IsInitialized()) {
QUIC_BUG << "Try to enable multiple packet number spaces support after any "
"packet has been received.";
return;
}
supports_multiple_packet_number_spaces_ = true;
}
bool UberReceivedPacketManager::IsAckFrameUpdated() const {
if (!supports_multiple_packet_number_spaces_) {
return received_packet_managers_[0].ack_frame_updated();
}
for (const auto& received_packet_manager : received_packet_managers_) {
if (received_packet_manager.ack_frame_updated()) {
return true;
}
}
return false;
}
QuicPacketNumber UberReceivedPacketManager::GetLargestObserved(
EncryptionLevel decrypted_packet_level) const {
if (!supports_multiple_packet_number_spaces_) {
return received_packet_managers_[0].GetLargestObserved();
}
return received_packet_managers_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)]
.GetLargestObserved();
}
QuicTime UberReceivedPacketManager::GetAckTimeout(
PacketNumberSpace packet_number_space) const {
if (!supports_multiple_packet_number_spaces_) {
return received_packet_managers_[0].ack_timeout();
}
return received_packet_managers_[packet_number_space].ack_timeout();
}
QuicTime UberReceivedPacketManager::GetEarliestAckTimeout() const {
QuicTime ack_timeout = QuicTime::Zero();
// Returns the earliest non-zero ack timeout.
for (const auto& received_packet_manager : received_packet_managers_) {
const QuicTime timeout = received_packet_manager.ack_timeout();
if (!ack_timeout.IsInitialized()) {
ack_timeout = timeout;
continue;
}
if (timeout.IsInitialized()) {
ack_timeout = std::min(ack_timeout, timeout);
}
}
return ack_timeout;
}
QuicPacketNumber UberReceivedPacketManager::peer_least_packet_awaiting_ack()
const {
DCHECK(!supports_multiple_packet_number_spaces_);
return received_packet_managers_[0].peer_least_packet_awaiting_ack();
}
size_t UberReceivedPacketManager::min_received_before_ack_decimation() const {
return received_packet_managers_[0].min_received_before_ack_decimation();
}
void UberReceivedPacketManager::set_min_received_before_ack_decimation(
size_t new_value) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.set_min_received_before_ack_decimation(new_value);
}
}
size_t UberReceivedPacketManager::ack_frequency_before_ack_decimation() const {
return received_packet_managers_[0].ack_frequency_before_ack_decimation();
}
void UberReceivedPacketManager::set_ack_frequency_before_ack_decimation(
size_t new_value) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.set_ack_frequency_before_ack_decimation(new_value);
}
}
const QuicAckFrame& UberReceivedPacketManager::ack_frame() const {
DCHECK(!supports_multiple_packet_number_spaces_);
return received_packet_managers_[0].ack_frame();
}
const QuicAckFrame& UberReceivedPacketManager::GetAckFrame(
PacketNumberSpace packet_number_space) const {
DCHECK(supports_multiple_packet_number_spaces_);
return received_packet_managers_[packet_number_space].ack_frame();
}
void UberReceivedPacketManager::set_max_ack_ranges(size_t max_ack_ranges) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.set_max_ack_ranges(max_ack_ranges);
}
}
void UberReceivedPacketManager::set_save_timestamps(bool save_timestamps) {
for (auto& received_packet_manager : received_packet_managers_) {
received_packet_manager.set_save_timestamps(save_timestamps);
}
}
} // namespace quic
| 3,028 |
860 | <reponame>xiefan46/samza<filename>samza-hdfs/src/test/java/org/apache/samza/system/hdfs/partitioner/TestDirectoryPartitioner.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.system.hdfs.partitioner;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.samza.Partition;
import org.apache.samza.SamzaException;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata;
import static org.apache.samza.system.hdfs.partitioner.FileSystemAdapter.FileMetadata;
public class TestDirectoryPartitioner {
class TestFileSystemAdapter implements FileSystemAdapter {
private List<FileMetadata> expectedList;
public TestFileSystemAdapter(List<FileMetadata> expectedList) {
this.expectedList = expectedList;
}
public List<FileMetadata> getAllFiles(String streamName) {
return expectedList;
}
}
private void verifyPartitionDescriptor(String[] inputFiles, int[][] expectedPartitioning, int expectedNumPartition,
Map<Partition, List<String>> actualPartitioning) {
Assert.assertEquals(expectedNumPartition, actualPartitioning.size());
Set<String> actualPartitioningPath = new HashSet<>();
actualPartitioning.values().forEach(list -> actualPartitioningPath.add(String.join(",", list)));
for (int i = 0; i < expectedNumPartition; i++) {
int[] indexes = expectedPartitioning[i];
List<String> files = new ArrayList<>();
for (int j : indexes) {
files.add(inputFiles[j]);
}
files.sort(Comparator.<String>naturalOrder());
String expectedCombinedPath = String.join(",", files);
Assert.assertTrue(actualPartitioningPath.contains(expectedCombinedPath));
}
}
@Test
public void testBasicWhiteListFiltering() {
List<FileMetadata> testList = new ArrayList<>();
int numInput = 9;
String[] inputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"delta-01.avro",
"part-005.avro",
"delta-03.avro",
"part-004.avro",
"delta-02.avro",
"part-006.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345, 313245, 234212, 413232};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = "part-.*\\.avro";
String blackList = "";
String groupPattern = "";
int expectedNumPartition = 6;
int[][] expectedPartitioning = {{0}, {1}, {2}, {4}, {6}, {8}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriptorMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriptorMap);
}
@Test
public void testBasicBlackListFiltering() {
List<FileMetadata> testList = new ArrayList<>();
int numInput = 9;
String[] inputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"delta-01.avro",
"part-005.avro",
"delta-03.avro",
"part-004.avro",
"delta-02.avro",
"part-006.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345, 313245, 234212, 413232};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = ".*";
String blackList = "delta-.*\\.avro";
String groupPattern = "";
int expectedNumPartition = 6;
int[][] expectedPartitioning = {{0}, {1}, {2}, {4}, {6}, {8}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriporMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriporMap);
}
@Test
public void testWhiteListBlackListFiltering() {
List<FileMetadata> testList = new ArrayList<>();
int numInput = 9;
String[] inputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"delta-01.avro",
"part-005.avro",
"delta-03.avro",
"part-004.avro",
"delta-02.avro",
"part-006.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345, 313245, 234212, 413232};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = "part-.*\\.avro";
String blackList = "part-002.avro";
String groupPattern = "";
int expectedNumPartition = 5;
int[][] expectedPartitioning = {{0}, {2}, {4}, {6}, {8}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriporMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriporMap);
}
@Test
public void testBasicGrouping() {
List<FileMetadata> testList = new ArrayList<>();
int numInput = 9;
String[] inputFiles = {
"00_10-run_2016-08-15-13-04-part.0.150582.avro",
"00_10-run_2016-08-15-13-04-part.1.138132.avro",
"00_10-run_2016-08-15-13-04-part.2.214005.avro",
"00_10-run_2016-08-15-13-05-part.0.205738.avro",
"00_10-run_2016-08-15-13-05-part.1.158273.avro",
"00_10-run_2016-08-15-13-05-part.2.982345.avro",
"00_10-run_2016-08-15-13-06-part.0.313245.avro",
"00_10-run_2016-08-15-13-06-part.1.234212.avro",
"00_10-run_2016-08-15-13-06-part.2.413232.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345, 313245, 234212, 413232};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = ".*\\.avro";
String blackList = "";
String groupPattern = ".*part\\.[id]\\..*\\.avro"; // 00_10-run_2016-08-15-13-04-part.[id].138132.avro
int expectedNumPartition = 3;
int[][] expectedPartitioning = {
{0, 3, 6}, // files from index 0, 3, 6 should be grouped into one partition
{1, 4, 7}, // similar as above
{2, 5, 8}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriporMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriporMap);
}
@Test
public void testValidDirectoryUpdating() {
// the update is valid when there are only new files being added to the directory
// no changes on the old files
List<FileMetadata> testList = new ArrayList<>();
int numInput = 6;
String[] inputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"part-005.avro",
"part-004.avro",
"part-006.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = ".*";
String blackList = "";
String groupPattern = "";
int expectedNumPartition = 6;
int[][] expectedPartitioning = {{0}, {1}, {2}, {3}, {4}, {5}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriporMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriporMap);
numInput = 7;
String[] updatedInputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"part-005.avro",
"part-004.avro",
"part-007.avro", // add a new file to the directory
"part-006.avro"};
long[] updatedFileLength = {150582, 138132, 214005, 205738, 158273, 2513454, 982345};
testList.clear();
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(updatedInputFiles[i], updatedFileLength[i]));
}
directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", descriporMap);
Assert.assertEquals(expectedNumPartition, metadataMap.size()); // still expect only 6 partitions instead of 7
Map<Partition, List<String>> updatedDescriptorMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, updatedDescriptorMap);
}
@Test
public void testInvalidDirectoryUpdating() {
// the update is invalid when at least one old file is removed
List<FileMetadata> testList = new ArrayList<>();
int numInput = 6;
String[] inputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"part-005.avro",
"part-004.avro",
"part-006.avro"};
long[] fileLength = {150582, 138132, 214005, 205738, 158273, 982345};
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(inputFiles[i], fileLength[i]));
}
String whiteList = ".*";
String blackList = "";
String groupPattern = "";
int expectedNumPartition = 6;
int[][] expectedPartitioning = {{0}, {1}, {2}, {3}, {4}, {5}};
DirectoryPartitioner directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
Map<Partition, SystemStreamPartitionMetadata> metadataMap = directoryPartitioner.getPartitionMetadataMap("hdfs", null);
Assert.assertEquals(expectedNumPartition, metadataMap.size());
Map<Partition, List<String>> descriporMap = directoryPartitioner.getPartitionDescriptor("hdfs");
verifyPartitionDescriptor(inputFiles, expectedPartitioning, expectedNumPartition, descriporMap);
String[] updatedInputFiles = {
"part-001.avro",
"part-002.avro",
"part-003.avro",
"part-005.avro",
"part-007.avro", // remove part-004 and replace it with 007
"part-006.avro"};
long[] updatedFileLength = {150582, 138132, 214005, 205738, 158273, 982345};
testList.clear();
for (int i = 0; i < numInput; i++) {
testList.add(new FileMetadata(updatedInputFiles[i], updatedFileLength[i]));
}
directoryPartitioner =
new DirectoryPartitioner(whiteList, blackList, groupPattern, new TestFileSystemAdapter(testList));
try {
directoryPartitioner.getPartitionMetadataMap("hdfs", descriporMap);
Assert.fail("Expect exception thrown from getting metadata. Should not reach this point.");
} catch (SamzaException e) {
// expect exception to be thrown
}
}
}
| 4,857 |
356 | <reponame>airen3339/Android-Application-ZJB
package com.idrv.coach.ui;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import com.idrv.coach.R;
import com.idrv.coach.ZjbApplication;
import com.idrv.coach.bean.User;
import com.idrv.coach.data.constants.SPConstant;
import com.idrv.coach.data.db.DBService;
import com.idrv.coach.data.manager.AppInitManager;
import com.idrv.coach.data.manager.LoginManager;
import com.idrv.coach.data.model.SplashModel;
import com.idrv.coach.utils.PreferenceUtil;
import com.idrv.coach.utils.handler.WeakHandler;
import com.idrv.coach.utils.helper.ResHelper;
import com.zjb.loader.ZjbImageLoader;
import com.zjb.volley.utils.GsonUtil;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by sunjianfei on 2016/3/7.
* 闪屏页面
*/
public class SplashActivity extends BaseActivity<SplashModel> {
@InjectView(R.id.splash_image)
FrameLayout mSplashImage;
WeakHandler mHandler;
boolean mIsLoginValidate;
long mExecuteTime;
private static final long MS_DURATION = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_splash);
ButterKnife.inject(this);
//1.解决安装后直接打开,home键切换到后台再启动重复出现闪屏页面的问题
// http://stackoverflow.com/questions/2280361/app-always-starts-fresh-from-root-activity-instead-of-resuming-background-state
if (!isTaskRoot()) {
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
finish();
return;
}
}
//2.初始化
initialize(this);
//3.显示广告图片
initView();
//4.执行闪屏alpha动画
animateSplash();
//5.跳转
jump();
}
@Override
protected void onLazyLoad() {
mViewModel = new SplashModel();
mViewModel.getSplashData();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//闪屏页面屏蔽掉返回按钮事件
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected boolean isToolbarEnable() {
return false;
}
@Override
public boolean isSwipeBackEnabled() {
return false;
}
private void initView() {
String splashPic = PreferenceUtil.getString(SPConstant.KEY_SPLASH_PIC);
if (TextUtils.isEmpty(splashPic)) {
mSplashImage.setBackgroundResource(R.drawable.splash_default_bg);
} else {
String filePath = ZjbImageLoader.getQiniuDiskCachePath(splashPic);
if (!TextUtils.isEmpty(filePath)) {
ZjbImageLoader.create(splashPic)
.into(mSplashImage);
} else {
mSplashImage.setBackgroundResource(R.drawable.splash_default_bg);
}
}
}
private void initialize(Context context) {
//1.防止application没有初始化完毕,再次初始化
AppInitManager.getInstance().initializeApp(context);
//2.处理初始化
mHandler = new WeakHandler();
//3.创建快捷方式
if (!LoginManager.getInstance().isNotFirstUse()) {
shortcut(this);
}
//4. 初始化数据库
mExecuteTime = System.currentTimeMillis();
mIsLoginValidate = isLoginValidate();
if (mIsLoginValidate) {
//初始化数据库
DBService.init(ZjbApplication.gContext);
}
}
/**
* 在桌面创建快捷方式
*
* @param context 应用上下文
*/
private void shortcut(Context context) {
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcut.putExtra("duplicate", false);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, ResHelper.getString(R.string.app_name));
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_app));
Intent intent = new Intent();
intent.setClass(context.getApplicationContext(), SplashActivity.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
context.sendBroadcast(shortcut);
}
/**
* 判断是否登录有效
*
* @return
*/
private boolean isLoginValidate() {
long tokenValidateTime = PreferenceUtil.getLong(SPConstant.KEY_USER_TOKEN_TIME);
boolean isValid = System.currentTimeMillis() - tokenValidateTime < 2505600000L
&& LoginManager.getInstance().isLoginValidate();
PreferenceUtil.putLong(SPConstant.KEY_USER_TOKEN_TIME, System.currentTimeMillis());
return isValid;
}
/**
* 闪屏页的alpha动画
*/
private void animateSplash() {
Animation alphaAnimation = AnimationUtils.loadAnimation(this, R.anim.splash_alpha_anim);
mSplashImage.startAnimation(alphaAnimation);
}
/**
* 跳转
*/
private void jump() {
long delay = MS_DURATION - (System.currentTimeMillis() - mExecuteTime);
delay = delay > 0 ? delay : 0;
if (mIsLoginValidate) {
if (LoginManager.getInstance().isBindPhone()) {
mHandler.postDelayed(this::toMainPage, delay);
} else {
mHandler.postDelayed(this::toBind, delay);
}
} else {
if (LoginManager.getInstance().isNotFirstUse()) {
mHandler.postDelayed(this::toLogin, delay);
} else {
mHandler.postDelayed(this::toGuide, delay);
}
}
}
/**
* 跳转到主界面
*/
private void toMainPage() {
Intent intent = getIntent();
if (null != intent) {
Uri uri = getIntent().getData();
if (null == uri) {
MainActivity.launch(this);
} else {
MainActivity.launch(this, uri);
}
}
finish();
}
/**
* 跳转到登录界面
*/
private void toLogin() {
LoginActivity.launch(this);
finish();
}
/**
* 跳转到引导界面
*/
private void toGuide() {
GuideActivity.launch(this);
finish();
}
/**
* 跳转到邀请码界面
*/
private void toBind() {
BindPhoneActivity.launch(this);
finish();
}
private void cheat() {
/*********模拟假数据开始**********/
User user = User.getFakeUser();
PreferenceUtil.putString(SPConstant.KEY_USER, GsonUtil.toJson(user));
PreferenceUtil.putLong(SPConstant.KEY_USER_TOKEN_TIME, System.currentTimeMillis());
AppInitManager.getInstance().updateAfterLogin(user.getUid(), user.getToken());
PreferenceUtil.putBoolean(SPConstant.KEY_FIRST_USE, true);
PreferenceUtil.putBoolean(DynamicActivity.KEY_FIRST_USE_DYNAMIC, true);
PreferenceUtil.putBoolean(NewsHallActivity.KEY_FIRST_USE_NEWS, true);
PreferenceUtil.putBoolean(BusinessHallActivity.KEY_FIRST_USE_BUSINESS, true);
/***********模拟假数据结束*****/
}
}
| 3,649 |
5,169 | {
"name": "BRLocaleMap",
"version": "1.0.0",
"summary": "iOS/Mac library for mapping between Cocoa langauge codes (ISO639-1) to Google/Bing translate service",
"homepage": "https://github.com/b123400/BRLocaleMap",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/b123400/BRLocaleMap.git",
"submodules": true,
"tag": "1.0.0"
},
"source_files": "BRLocaleMap",
"resources": "locale-mapping/*.json",
"requires_arc": true,
"platforms": {
"osx": null,
"ios": null,
"tvos": null,
"watchos": null
}
}
| 284 |
575 | // 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 THIRD_PARTY_BLINK_RENDERER_CORE_FULLSCREEN_SCOPED_ALLOW_FULLSCREEN_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FULLSCREEN_SCOPED_ALLOW_FULLSCREEN_H_
#include "base/macros.h"
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class CORE_EXPORT ScopedAllowFullscreen {
STACK_ALLOCATED();
public:
enum Reason { kOrientationChange, kXrOverlay };
static base::Optional<Reason> FullscreenAllowedReason();
explicit ScopedAllowFullscreen(Reason);
~ScopedAllowFullscreen();
private:
static base::Optional<Reason> reason_;
base::Optional<Reason> previous_reason_;
DISALLOW_COPY_AND_ASSIGN(ScopedAllowFullscreen);
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FULLSCREEN_SCOPED_ALLOW_FULLSCREEN_H_
| 383 |
1,511 |
/* SPDX-License-Identifier: EUDatagrid */
/*
EU DataGrid Software License Copyright (c) 2001 EU DataGrid. All
rights reserved.
This software includes voluntary contributions made
to the EU DataGrid. For more information on the EU DataGrid, please
see http://www.eu-datagrid.org/.
Installation, use, reproduction,
display, modification and redistribution of this software, with or
without modification, in source and binary forms, are permitted. Any
exercise of rights under this license by you or your sub-licensees is
subject to the following conditions:
1. Redistributions of this
software, with or without modification, must reproduce the above
copyright notice and the above license statement as well as this list
of conditions, in the software, the user documentation and any other
materials provided with the software.
2. The user documentation,
if any, included with a redistribution, must include the following
notice:
"This product includes software developed by the EU
DataGrid (http://www.eu-datagrid.org/)."
Alternatively, if that is
where third-party acknowledgments normally appear, this acknowledgment
must be reproduced in the software itself.
3. The names "EDG",
"EDG Toolkit", "EU DataGrid" and "EU DataGrid Project" may not be used
to endorse or promote software, or products derived therefrom, except
with prior written permission by
<EMAIL>.
4. You are under no
obligation to provide anyone with any bug fixes, patches, upgrades or
other modifications, enhancements or derivatives of the features,
functionality or performance of this software that you may develop.
However, if you publish or distribute your modifications, enhancements
or derivative works without contemporaneously requiring users to enter
into a separate written license agreement, then you are deemed to have
granted participants in the EU DataGrid a worldwide, non-exclusive,
royalty-free, perpetual license to install, use, reproduce, display,
modify, redistribute and sub-license your modifications, enhancements
or derivative works, whether in binary or source code form, under the
license conditions stated in this list of conditions.
5.
DISCLAIMER
THIS SOFTWARE IS PROVIDED BY THE EU DATAGRID AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, OF
SATISFACTORY QUALITY, AND FITNESS FOR A PARTICULAR PURPOSE OR USE ARE
DISCLAIMED. THE EU DATAGRID AND CONTRIBUTORS MAKE NO REPRESENTATION
THAT THE SOFTWARE, MODIFICATIONS, ENHANCEMENTS OR DERIVATIVE WORKS
THEREOF, WILL NOT INFRINGE ANY PATENT, COPYRIGHT, TRADE SECRET OR
OTHER PROPRIETARY RIGHT.
6. LIMITATION OF LIABILITY
THE EU
DATAGRID AND CONTRIBUTORS SHALL HAVE NO LIABILITY TO LICENSEE OR OTHER
PERSONS FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL,
EXEMPLARY, OR PUNITIVE DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
LIMITATION, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE,
DATA OR PROFITS, OR BUSINESS INTERRUPTION, HOWEVER CAUSED AND ON ANY
THEORY OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT
LIABILITY OR OTHERWISE, ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
/*
** Fake code so we have something.
*/
#include <nothing.h>
int
noop_fun(int arg1)
{
short retval;
recalculatearg(&arg1);
switch (arg1)
{
case 0:
if (arg1) {
retval = 1;
} else {
retval = 2;
}
case 1:
retval = 2;
case 2:
retval = morpharg(arg1);
case 3:
if (arg1) {
retval = 6;
} else {
retval = 7;
}
case 4:
retval = upscalearg(arg1);
default:
retval = 0;
}
return retval;
}
| 1,103 |
4,901 | <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 libcore.java.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
import tests.support.Support_ASimpleOutputStream;
import tests.support.Support_OutputStream;
public class OldObjectOutputStreamTest extends TestCase implements Serializable {
static final long serialVersionUID = 1L;
java.io.File f;
public class SerializableTestHelper implements Serializable {
public String aField1;
public String aField2;
SerializableTestHelper(String s, String t) {
aField1 = s;
aField2 = t;
}
private void readObject(ObjectInputStream ois) throws IOException {
// note aField2 is not read
try {
ObjectInputStream.GetField fields = ois.readFields();
aField1 = (String) fields.get("aField1", "Zap");
} catch (Exception e) {
}
}
private void writeObject(ObjectOutputStream oos) throws IOException {
// note aField2 is not written
ObjectOutputStream.PutField fields = oos.putFields();
fields.put("aField1", aField1);
oos.writeFields();
}
public String getText1() {
return aField1;
}
public String getText2() {
return aField2;
}
}
private static class BasicObjectOutputStream extends ObjectOutputStream {
public boolean writeStreamHeaderCalled;
public BasicObjectOutputStream() throws IOException, SecurityException {
super();
writeStreamHeaderCalled = false;
}
public BasicObjectOutputStream(OutputStream output) throws IOException {
super(output);
}
public void drain() throws IOException {
super.drain();
}
public boolean enableReplaceObject(boolean enable)
throws SecurityException {
return super.enableReplaceObject(enable);
}
public void writeObjectOverride(Object object) throws IOException {
super.writeObjectOverride(object);
}
public void writeStreamHeader() throws IOException {
super.writeStreamHeader();
writeStreamHeaderCalled = true;
}
}
private static class NoFlushTestOutputStream extends ByteArrayOutputStream {
public boolean flushCalled;
public NoFlushTestOutputStream() {
super();
flushCalled = false;
}
public void flush() throws IOException {
super.flush();
flushCalled = true;
}
}
protected static final String MODE_XLOAD = "xload";
protected static final String MODE_XDUMP = "xdump";
static final String FOO = "foo";
static final String MSG_WITE_FAILED = "Failed to write: ";
private static final boolean DEBUG = false;
protected static boolean xload = false;
protected static boolean xdump = false;
protected static String xFileName = null;
protected ObjectInputStream ois;
protected ObjectOutputStream oos;
protected ObjectOutputStream oos_ioe;
protected Support_OutputStream sos;
protected ByteArrayOutputStream bao;
static final int INIT_INT_VALUE = 7;
static final String INIT_STR_VALUE = "a string that is blortz";
/**
* java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
*/
public void test_ConstructorLjava_io_OutputStream() throws IOException {
oos.close();
oos = new ObjectOutputStream(new ByteArrayOutputStream());
oos.close();
try {
oos = new ObjectOutputStream(null);
fail("Test 1: NullPointerException expected.");
} catch (NullPointerException e) {
// Expected.
}
Support_ASimpleOutputStream sos = new Support_ASimpleOutputStream(true);
try {
oos = new ObjectOutputStream(sos);
fail("Test 2: IOException expected.");
} catch (IOException e) {
// Expected.
}
}
public void test_close() throws IOException {
int outputSize = bao.size();
// Writing of a primitive type should be buffered.
oos.writeInt(42);
assertTrue("Test 1: Primitive data unexpectedly written to the target stream.",
bao.size() == outputSize);
// Closing should write the buffered data to the target stream.
oos.close();
assertTrue("Test 2: Primitive data has not been written to the the target stream.",
bao.size() > outputSize);
try {
oos_ioe.close();
fail("Test 3: IOException expected.");
} catch (IOException e) {
// Expected.
}
}
public void test_drain() throws IOException {
NoFlushTestOutputStream target = new NoFlushTestOutputStream();
BasicObjectOutputStream boos = new BasicObjectOutputStream(target);
int initialSize = target.size();
boolean written = false;
boos.writeBytes("Lorem ipsum");
// If there is no buffer then the bytes have already been written.
written = (target.size() > initialSize);
boos.drain();
assertTrue("Content has not been written to the target.",
written || (target.size() > initialSize));
assertFalse("flush() has been called on the target.",
target.flushCalled);
}
public void test_enableReplaceObjectB() throws IOException {
// Start testing without a SecurityManager.
BasicObjectOutputStream boos = new BasicObjectOutputStream();
assertFalse("Test 1: Object resolving must be disabled by default.",
boos.enableReplaceObject(true));
assertTrue("Test 2: enableReplaceObject did not return the previous value.",
boos.enableReplaceObject(false));
}
public void test_flush() throws Exception {
// Test for method void java.io.ObjectOutputStream.flush()
int size = bao.size();
oos.writeByte(127);
assertTrue("Test 1: Data already flushed.", bao.size() == size);
oos.flush();
assertTrue("Test 2: Failed to flush data.", bao.size() > size);
try {
oos_ioe.flush();
fail("Test 3: IOException expected.");
} catch (IOException e) {
// Expected.
}
}
public void test_putFields() throws Exception {
/*
* "SerializableTestHelper" is an object created for these tests with
* two fields (Strings) and simple implementations of readObject and
* writeObject which simply read and write the first field but not the
* second one.
*/
SerializableTestHelper sth;
try {
oos.putFields();
fail("Test 1: NotActiveException expected.");
} catch (NotActiveException e) {
// Expected.
}
oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
oos.flush();
ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
sth = (SerializableTestHelper) (ois.readObject());
assertEquals("Test 2: readFields or writeFields failed; first field not set.",
"Gabba", sth.getText1());
assertNull("Test 3: readFields or writeFields failed; second field should not have been set.",
sth.getText2());
}
public void test_reset() throws Exception {
String o = "HelloWorld";
sos = new Support_OutputStream(200);
oos.close();
oos = new ObjectOutputStream(sos);
oos.writeObject(o);
oos.writeObject(o);
oos.reset();
oos.writeObject(o);
sos.setThrowsException(true);
try {
oos.reset();
fail("Test 1: IOException expected.");
} catch (IOException e) {
// Expected.
}
sos.setThrowsException(false);
ois = new ObjectInputStream(new ByteArrayInputStream(sos.toByteArray()));
assertEquals("Test 2: Incorrect object read.", o, ois.readObject());
assertEquals("Test 3: Incorrect object read.", o, ois.readObject());
assertEquals("Test 4: Incorrect object read.", o, ois.readObject());
ois.close();
}
public void test_write$BII() throws Exception {
byte[] buf = new byte[10];
ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
try {
ois.read(buf, 0, -1);
fail("IndexOutOfBoundsException not thrown");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
ois.read(buf, -1, 1);
fail("IndexOutOfBoundsException not thrown");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
ois.read(buf, 10, 1);
fail("IndexOutOfBoundsException not thrown");
} catch (IndexOutOfBoundsException e) {
// Expected
}
ois.close();
}
public void test_writeObjectOverrideLjava_lang_Object() throws IOException {
BasicObjectOutputStream boos =
new BasicObjectOutputStream(new ByteArrayOutputStream());
try {
boos.writeObjectOverride(new Object());
fail("IOException expected.");
}
catch (IOException e) {
}
finally {
boos.close();
}
}
public void test_writeStreamHeader() throws IOException {
BasicObjectOutputStream boos;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
short s;
byte[] buffer;
// Test 1: Make sure that writeStreamHeader() has been called.
boos = new BasicObjectOutputStream(baos);
try {
assertTrue("Test 1: writeStreamHeader() has not been called.",
boos.writeStreamHeaderCalled);
// Test 2: Check that at least four bytes have been written.
buffer = baos.toByteArray();
assertTrue("Test 2: At least four bytes should have been written",
buffer.length >= 4);
// Test 3: Check the magic number.
s = buffer[0];
s <<= 8;
s += ((short) buffer[1] & 0x00ff);
assertEquals("Test 3: Invalid magic number written.",
java.io.ObjectStreamConstants.STREAM_MAGIC, s);
// Test 4: Check the stream version number.
s = buffer[2];
s <<= 8;
s += ((short) buffer[3] & 0x00ff);
assertEquals("Invalid stream version number written.",
java.io.ObjectStreamConstants.STREAM_VERSION, s);
}
finally {
boos.close();
}
}
/**
* Sets up the fixture, for example, open a network connection. This method
* is called before a test is executed.
*/
protected void setUp() throws Exception {
super.setUp();
oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
oos_ioe = new ObjectOutputStream(sos = new Support_OutputStream());
sos.setThrowsException(true);
}
/**
* Tears down the fixture, for example, close a network connection. This
* method is called after a test is executed.
*/
protected void tearDown() throws Exception {
super.tearDown();
if (oos != null) {
try {
oos.close();
} catch (Exception e) {}
}
if (oos_ioe != null) {
try {
oos_ioe.close();
} catch (Exception e) {}
}
if (f != null && f.exists()) {
if (!f.delete()) {
fail("Error cleaning up files during teardown");
}
}
}
protected Object reload() throws IOException, ClassNotFoundException {
// Choose the load stream
if (xload || xdump) {
// Load from pre-existing file
ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
+ getName() + ".ser"));
} else {
// Just load from memory, we dumped to memory
ois = new ObjectInputStream(new ByteArrayInputStream(bao
.toByteArray()));
}
try {
return ois.readObject();
} finally {
ois.close();
}
}
protected void dump(Object o) throws IOException, ClassNotFoundException {
// Choose the dump stream
if (xdump) {
oos = new ObjectOutputStream(new FileOutputStream(
f = new java.io.File(xFileName + "-" + getName() + ".ser")));
} else {
oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
}
// Dump the object
try {
oos.writeObject(o);
} finally {
oos.close();
}
}
}
| 5,973 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Nuisance",
"definitions": [
"A person or thing causing inconvenience or annoyance.",
"An act which is harmful or offensive to the public or a member of it and for which there is a legal remedy."
],
"parts-of-speech": "Noun"
} | 112 |
521 | <reponame>wk8/elle<filename>src/elle/bench.hh
#pragma once
#include <elle/Duration.hh>
#include <elle/attribute.hh>
#include <elle/compiler.hh>
namespace elle
{
/// Bench a block of code or display statistics about some data.
///
/// N.B. The Bench is active if the LOG_LEVEL related is activated.
///
/// @code{.cc}
///
/// static auto bench = elle::Bench("bench.loop");
/// for (int i = 0; i < 1000; ++i)
/// {
/// elle::Bench::BenchScope s(bench);
/// ::usleep(10);
/// }
/// // Result (with ELLE_LOG_LEVEL="bench*:TRACE"):
/// [bench.loop] AVG: 1162.05 MIN: 1050 MAX: 2578 CNT: 1000 TOT: 1162 ms
///
/// @endcode
template <typename Type = elle::Duration>
class ELLE_API Bench
{
public:
using Clock = elle::Clock;
using Time = Clock::time_point;
using Duration = Clock::duration;
/// Construct a Bench.
///
/// @param log_interval If set, bench will automatically log and reset at
/// given interval
/// @param round The round values to that many digits below 1.
Bench(std::string name,
Duration log_interval = {},
int roundto = 2);
/// Destroy the Bench.
///
/// This call show() if the component is enabled.
~Bench();
/// Add a value for a given Bench.
///
/// BenchScope automatically adds its lifetime duration to its owner Bench.
///
/// @param val A duration (in milliseconds) to add to the Bench.
void
add(Type val);
/// Reset all underlying values of the Bench.
void
reset();
/// Output the Bench result.
void
log();
/// Output the well-formatted Bench results.
void
show();
/// Pretty print.
void
print(std::ostream& os) const;
template <typename Type_ = Type,
typename = std::enable_if_t<is_duration<Type_>{}>>
struct BenchScope
{
BenchScope(Bench& owner);
~BenchScope();
private:
Time _start;
Bench& _owner;
};
template <typename Type_ = Type,
typename = std::enable_if_t<is_duration<Type_>{}>>
BenchScope<Type_>
scoped()
{
return *this;
}
/// Name of the bench.
ELLE_ATTRIBUTE_R(std::string, name);
/// Accumulated values.
ELLE_ATTRIBUTE_R(Type, sum);
/// Number of durations recorded.
ELLE_ATTRIBUTE_R(long, count);
/// Smallest value.
ELLE_ATTRIBUTE_R(Type, min);
/// Greatest value.
ELLE_ATTRIBUTE_R(Type, max);
ELLE_ATTRIBUTE_R(Duration, log_interval);
ELLE_ATTRIBUTE(double, roundfactor);
ELLE_ATTRIBUTE_R(bool, enabled);
// Make it last, so that it is set only when the remainder was
// initialized.
ELLE_ATTRIBUTE_R(Time, start);
};
}
#include <elle/bench.hxx>
| 1,103 |
1,180 | <reponame>cntrump/libtomcrypt<gh_stars>1000+
/* LibTomCrypt, modular cryptographic library -- <NAME> */
/* SPDX-License-Identifier: Unlicense */
/**
@file gcm_reset.c
GCM implementation, reset a used state so it can accept IV data, by <NAME>
*/
#include "tomcrypt_private.h"
#ifdef LTC_GCM_MODE
/**
Reset a GCM state to as if you just called gcm_init(). This saves the initialization time.
@param gcm The GCM state to reset
@return CRYPT_OK on success
*/
int gcm_reset(gcm_state *gcm)
{
LTC_ARGCHK(gcm != NULL);
zeromem(gcm->buf, sizeof(gcm->buf));
zeromem(gcm->X, sizeof(gcm->X));
gcm->mode = LTC_GCM_MODE_IV;
gcm->ivmode = 0;
gcm->buflen = 0;
gcm->totlen = 0;
gcm->pttotlen = 0;
return CRYPT_OK;
}
#endif
| 331 |
719 | /*
* Copyright 2020 momosecurity.
*
* 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.immomo.momosec.lang.java.rule.momosecurity;
import com.immomo.momosec.lang.InspectionBundle;
import com.immomo.momosec.lang.MomoBaseLocalInspectionTool;
import com.immomo.momosec.lang.java.utils.MoExpressionUtils;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.siyeh.ig.psiutils.MethodCallUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.regex.Pattern;
/**
* 1005: RegexDos风险
*
* 正则表达式拒绝服务攻击(RegexDos)
*
* 当编写校验的正则表达式存在缺陷或者不严谨时, 攻击者可以构造特殊的字符串来大量消耗服务器的系统资源,造成服务器的服务中断或停止。
* ref: https://cloud.tencent.com/developer/article/1041326
*
* check:
* java.util.regex.Pattern#compile args:0
* java.util.regex.Pattern#matchers args:0
*
* fix:
* (1) optimize Regular Expressions
* (2) use com.google.re2j
*
* notes:
* `isExponentialRegex` method copy from CodeQL
*/
public class RegexDos extends MomoBaseLocalInspectionTool {
public static final String MESSAGE = InspectionBundle.message("regex.dos.msg");
private static final String QUICK_FIX_NAME = InspectionBundle.message("regex.dos.fix");
private final RegexDosWithRe2jQuickFix regexDosWithRe2jQuickFix = new RegexDosWithRe2jQuickFix();
public static boolean isExponentialRegex(String s) {
return
// Example: ([a-z]+)+
Pattern.matches(".*\\([^()*+\\]]+\\]?(\\*|\\+)\\)(\\*|\\+).*", s) ||
// Example: (([a-z])?([a-z]+))+
Pattern.matches(".*\\((\\([^()]+\\)\\?)?\\([^()*+\\]]+\\]?(\\*|\\+)\\)\\)(\\*|\\+).*", s) ||
// Example: (([a-z])+)+
Pattern.matches(".*\\(\\([^()*+\\]]+\\]?\\)(\\*|\\+)\\)(\\*|\\+).*", s) ||
// Example: (a|aa)+
Pattern.matches(".*\\(([^()*+\\]]+\\]?)\\|\\1+\\??\\)(\\*|\\+).*", s) ||
// Example: (.*[a-z]){n} n >= 10
Pattern.matches(".*\\(\\.\\*[^()*+\\]]+\\]?\\)\\{[1-9][0-9]+,?[0-9]*\\}.*", s);
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
if (MethodCallUtils.isCallToRegexMethod(expression)) { // `isCallToRegexMethod` judges include java.util.regex.Pattern
String methodName = MethodCallUtils.getMethodName(expression);
if (methodName != null && ( methodName.equals("compile") || methodName.equals("matches") )) {
PsiExpression[] expressions = expression.getArgumentList().getExpressions();
if (expressions.length > 0) {
PsiLiteralExpression literal = getLiteralExpression(expressions[0]);
if (literal != null && isExponentialRegex(MoExpressionUtils.getLiteralInnerText(literal))) {
holder.registerProblem(expressions[0], MESSAGE, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, regexDosWithRe2jQuickFix);
}
}
}
}
}
};
}
@Nullable
private PsiLiteralExpression getLiteralExpression(PsiExpression expression) {
if (expression instanceof PsiReferenceExpression) {
PsiElement elem = ((PsiReferenceExpression) expression).resolve();
if (elem instanceof PsiVariable) {
PsiExpression initializer = ((PsiVariable) elem).getInitializer();
if (initializer instanceof PsiLiteralExpression) {
return (PsiLiteralExpression)initializer;
}
}
} else if (expression instanceof PsiLiteralExpression) {
return (PsiLiteralExpression)expression;
}
return null;
}
public static class RegexDosWithRe2jQuickFix implements LocalQuickFix {
@Override
public @Nls(capitalization = Nls.Capitalization.Sentence) @NotNull String getFamilyName() {
return QUICK_FIX_NAME;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiElement problemLiteral = descriptor.getPsiElement();
PsiElement methodCall = problemLiteral.getParent().getParent();
if (methodCall instanceof PsiMethodCallExpression) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
PsiExpression newQualifier = factory.createExpressionFromText("com.google.re2j.Pattern", null);
((PsiMethodCallExpression) methodCall).getMethodExpression().setQualifierExpression(newQualifier);
}
}
}
}
| 2,497 |
595 | <gh_stars>100-1000
/******************************************************************************
* Copyright (c) 2015 - 2021 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
*******************************************************************************/
/*****************************************************************************/
/**
*
* @file xfsbl_csu_dma.c
*
* Contains code for the CSU DMA initialization
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- ---- -------- -------------------------------------------------------
* 1.00 kc 07/22/14 Initial release
* 2.0 bv 12/05/16 Made compliance to MISRAC 2012 guidelines
* 3.0 bsv 04/01/21 Added TPM support
*
* </pre>
*
* @note
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "xcsudma.h"
#include "xfsbl_csu_dma.h"
/************************** Constant Definitions *****************************/
/**************************** Type Definitions *******************************/
/***************** Macros (Inline Functions) Definitions *********************/
/************************** Function Prototypes ******************************/
/************************** Variable Definitions *****************************/
XCsuDma CsuDma = {0U};
/*****************************************************************************/
/**
* This function is used to initialize the DMA driver
*
* @param CsuDmaPtr is pointer to XCsuDma instance
*
* @return returns the error codes described in xfsbl_error.h on any error
* returns XFSBL_SUCCESS on success
*
*****************************************************************************/
u32 XFsbl_CsuDmaInit(XCsuDma* CsuDmaPtr)
{
u32 Status;
s32 SStatus;
XCsuDma_Config * CsuDmaConfig;
if (CsuDmaPtr == NULL) {
CsuDmaPtr = &CsuDma;
}
(void)memset(CsuDmaPtr, 0, sizeof(XCsuDma));
CsuDmaConfig = XCsuDma_LookupConfig(0);
if (NULL == CsuDmaConfig) {
XFsbl_Printf(DEBUG_GENERAL, "XFSBL_ERROR_CSUDMA_INIT_FAIL \n\r");
Status = XFSBL_ERROR_CSUDMA_INIT_FAIL;
goto END;
}
SStatus = XCsuDma_CfgInitialize(CsuDmaPtr, CsuDmaConfig,
CsuDmaConfig->BaseAddress);
if (SStatus != XFSBL_SUCCESS) {
XFsbl_Printf(DEBUG_GENERAL, "XFSBL_ERROR_CSUDMA_INIT_FAIL \n\r");
Status = XFSBL_ERROR_CSUDMA_INIT_FAIL;
goto END;
}
Status = XFSBL_SUCCESS;
END:
return Status;
}
| 777 |
742 | package org.support.project.common.util;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ListUtilsTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConvertList() throws InstantiationException, IllegalAccessException {
List<TestClass1> list = new ArrayList<TestClass1>();
for (int num = 0; num < 5; num++) {
TestClass1 class1 = new TestClass1();
class1.setNum(num);
class1.setStr("hoge-" + num);
list.add(class1);
}
List<TestClass2> list2 = ListUtils.convertList(list, TestClass2.class);
assertEquals(list.size(), list2.size());
// assertArrayEquals(list.toArray(new TestClass1[0]), list2.toArray(new TestClass2[0]));
for (int i = 0; i < list.size(); i++) {
TestClass1 class1 = list.get(i);
TestClass2 class2 = list2.get(i);
assertTrue(PropertyUtil.equalsProperty(class1, class2));
}
}
@Test
public void testToStringObjectArray() {
List<TestClass1> list = new ArrayList<TestClass1>();
for (int num = 0; num < 3; num++) {
TestClass1 class1 = new TestClass1();
class1.setNum(num);
class1.setStr("hoge-" + num);
list.add(class1);
}
String str = ListUtils.toString(list);
assertEquals(
"[0]{\"bool\":false,\"num\":0,\"str\":\"hoge-0\"}\n[1]{\"bool\":false,\"num\":1,\"str\":\"hoge-1\"}\n[2]{\"bool\":false,\"num\":2,\"str\":\"hoge-2\"}",
str);
}
@Test
public void testToStringListOfObject() {
List<TestClass1> list = new ArrayList<TestClass1>();
for (int num = 0; num < 3; num++) {
TestClass1 class1 = new TestClass1();
class1.setNum(num);
class1.setStr("hoge-" + num);
list.add(class1);
}
String str = ListUtils.toString(list.toArray(new TestClass1[0]));
assertEquals(
"[0]{\"bool\":false,\"num\":0,\"str\":\"hoge-0\"}\n[1]{\"bool\":false,\"num\":1,\"str\":\"hoge-1\"}\n[2]{\"bool\":false,\"num\":2,\"str\":\"hoge-2\"}",
str);
}
}
| 1,207 |
803 | #include <ir/ir.h>
#include <target/util.h>
//=============================================================
// Configurations
//=============================================================
#define QFTASM_RAM_AS_STDIN_BUFFER
#define QFTASM_RAM_AS_STDOUT_BUFFER
#define QFTASM_JMPTABLE_IN_ROM
#ifdef QFTASM_RAM_AS_STDIN_BUFFER
static const int QFTASM_RAMSTDIN_BUF_STARTPOSITION = 7167;
#endif
#ifdef QFTASM_RAM_AS_STDOUT_BUFFER
static const int QFTASM_RAMSTDOUT_BUF_STARTPOSITION = 8191;
#endif
// RAM pointer offset to prevent negative-value RAM addresses
// from underflowing into the register regions
static const int QFTASM_MEM_OFFSET = 2048;
// This is required to run tests on ELVM,
// since the Makefile compiles all files at first
#define QFTASM_SUPPRESS_MEMORY_INIT_OVERFLOW_ERROR
//=============================================================
static const int QFTASM_PC = 0;
static const int QFTASM_STDIN = 1;
static const int QFTASM_STDOUT = 2;
static const int QFTASM_A = 3;
static const int QFTASM_B = 4;
static const int QFTASM_C = 5;
static const int QFTASM_D = 6;
static const int QFTASM_BP = 7;
static const int QFTASM_SP = 8;
static const int QFTASM_TEMP = 9;
static const int QFTASM_TEMP_2 = 10;
#ifdef QFTASM_JMPTABLE_IN_ROM
static const int QFTASM_JMPTABLE_OFFSET = 4;
#else
static const int QFTASM_JMPTABLE_OFFSET = 11;
#endif
#define QFTASM_STDIO_OPEN (1 << 8)
#define QFTASM_STDIO_CLOSED (1 << 9)
static void qftasm_emit_line(const char* fmt, ...) {
static int qftasm_lineno_counter_ = 0;
printf("%d. ", qftasm_lineno_counter_);
qftasm_lineno_counter_++;
if (fmt[0]) {
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
putchar('\n');
}
static int qftasm_int24_to_int16(int x) {
// Interpret x as a 24-bit signed integer.
// If it is negative, then reinterpret x as a 16-bit signed integer.
if (x < 0) {
x += (1 << 16);
} else if (x > (1 << 23)) {
x = x - (1 << 24) + (1 << 16);
}
x = x & ((1 << 16) - 1);
return x;
}
static int get_max_pc(Inst* inst) {
int max_pc = 0;
for (; inst; inst = inst->next) {
max_pc = inst->pc > max_pc ? inst->pc : max_pc;
}
return max_pc;
}
static void qftasm_emit_jump_table(Inst* init_inst) {
int max_pc = get_max_pc(init_inst);
#ifdef QFTASM_JMPTABLE_IN_ROM
qftasm_emit_line("MNZ 1 %d %d; Initially skip the jump table", QFTASM_JMPTABLE_OFFSET + (max_pc+1)*2 - 1, QFTASM_PC);
qftasm_emit_line("MNZ 0 0 0;");
for (int pc = 0; pc <= max_pc; pc++){
qftasm_emit_line("MNZ 1 {pc%d} %d;%s", pc, QFTASM_PC,
pc == 0 ? " Jump table" : "");
qftasm_emit_line("MNZ 0 0 0");
}
#else
for (int pc = 0; pc <= max_pc; pc++){
qftasm_emit_line("MNZ 1 {pc%d} %d;%s", pc, pc + QFTASM_JMPTABLE_OFFSET,
pc == 0 ? " Jump table" : "");
}
#endif
}
static void qftasm_emit_memory_initialization(Data* data) {
// RAM initialization
for (int mp = 0; data; data = data->next, mp++) {
if (data->v) {
#ifndef QFTASM_SUPPRESS_MEMORY_INIT_OVERFLOW_ERROR
if (mp + QFTASM_MEM_OFFSET>= (1 << 16)) {
error("Memory pointer overflow occured at memory initialization: Address %d", mp + QFTASM_MEM_OFFSET);
}
#endif
qftasm_emit_line("MNZ 1 %d %d;%s",
qftasm_int24_to_int16(data->v), mp + QFTASM_MEM_OFFSET,
mp == 0 ? " Memory table" : "");
}
}
}
static void init_state_qftasm(Data* data, Inst* init_inst) {
// stdin, stdout
#ifdef QFTASM_RAM_AS_STDIN_BUFFER
qftasm_emit_line("MNZ 1 %d %d; Register initialization (stdin buffer pointer)", QFTASM_RAMSTDIN_BUF_STARTPOSITION, QFTASM_STDIN);
#else
qftasm_emit_line("MNZ 1 %d %d; Register initialization (stdin)", QFTASM_STDIO_CLOSED, QFTASM_STDIN);
#endif
#ifdef QFTASM_RAM_AS_STDOUT_BUFFER
qftasm_emit_line("MNZ 1 %d %d; Register initialization (stdout buffer pointer)", QFTASM_RAMSTDOUT_BUF_STARTPOSITION, QFTASM_STDOUT);
#else
qftasm_emit_line("MNZ 1 %d %d; Register initialization (stdout)", QFTASM_STDIO_CLOSED, QFTASM_STDOUT);
#endif
qftasm_emit_jump_table(init_inst);
qftasm_emit_memory_initialization(data);
}
static int qftasm_reg2addr(Reg reg) {
switch (reg) {
case A: return QFTASM_A;
case B: return QFTASM_B;
case C: return QFTASM_C;
case D: return QFTASM_D;
case BP: return QFTASM_BP;
case SP: return QFTASM_SP;
default:
error("Undefined register name in qftasm_reg2addr: %d", reg);
}
}
static const char* qftasm_value_str(Value* v) {
if (v->type == REG) {
return format("A%d", qftasm_reg2addr(v->reg));
} else if (v->type == IMM) {
return format("%d", qftasm_int24_to_int16(v->imm));
} else {
error("invalid value");
}
}
#ifdef QFTASM_JMPTABLE_IN_ROM
static void qftasm_emit_conditional_jmp_inst(Inst* inst) {
Value* v = &inst->jmp;
if (v->type == REG) {
qftasm_emit_line("ADD A%d A%d %d;", qftasm_reg2addr(v->reg), qftasm_reg2addr(v->reg), QFTASM_TEMP_2);
qftasm_emit_line("ADD A%d %d %d;", QFTASM_TEMP_2, QFTASM_JMPTABLE_OFFSET-1, QFTASM_TEMP_2);
qftasm_emit_line("MNZ A%d A%d %d; (reg)", QFTASM_TEMP, QFTASM_TEMP_2, QFTASM_PC);
} else if (v->type == IMM) {
qftasm_emit_line("MNZ A%d {pc%d} %d; (imm)", QFTASM_TEMP, v->imm, QFTASM_PC);
} else {
error("Invalid value at conditional jump");
}
}
static void qftasm_emit_unconditional_jmp_inst(Inst* inst) {
Value* v = &inst->jmp;
if (v->type == REG) {
qftasm_emit_line("ADD A%d A%d %d;", qftasm_reg2addr(v->reg), qftasm_reg2addr(v->reg), QFTASM_TEMP_2);
qftasm_emit_line("ADD A%d %d %d;", QFTASM_TEMP_2, QFTASM_JMPTABLE_OFFSET-1, QFTASM_PC);
} else if (v->type == IMM) {
qftasm_emit_line("MNZ 1 {pc%d} %d; JMP (imm)", v->imm, QFTASM_PC);
} else {
error("Invalid value at JMP");
}
}
#else
static void qftasm_emit_conditional_jmp_inst(Inst* inst) {
Value* v = &inst->jmp;
if (v->type == REG) {
qftasm_emit_line("ADD A%d %d %d;", qftasm_reg2addr(v->reg), QFTASM_JMPTABLE_OFFSET, QFTASM_TEMP_2);
qftasm_emit_line("MNZ A%d B%d %d; (reg)", QFTASM_TEMP, QFTASM_TEMP_2, QFTASM_PC);
} else if (v->type == IMM) {
qftasm_emit_line("MNZ A%d A%d %d; (imm)", QFTASM_TEMP, v->imm + QFTASM_JMPTABLE_OFFSET, QFTASM_PC);
} else {
error("Invalid value at conditional jump");
}
}
static void qftasm_emit_unconditional_jmp_inst(Inst* inst) {
Value* v = &inst->jmp;
if (v->type == REG) {
qftasm_emit_line("ADD A%d %d %d; JMP (reg)", qftasm_reg2addr(v->reg), QFTASM_JMPTABLE_OFFSET, QFTASM_TEMP_2);
qftasm_emit_line("MNZ 1 B%d %d;", QFTASM_TEMP_2, QFTASM_PC);
} else if (v->type == IMM) {
qftasm_emit_line("MNZ 1 A%d %d; JMP (imm)", v->imm + QFTASM_JMPTABLE_OFFSET, QFTASM_PC);
} else {
error("Invalid value at JMP");
}
}
#endif
static const char* qftasm_src_str(Inst* inst) {
return qftasm_value_str(&inst->src);
}
static const char* qftasm_dst_str(Inst* inst) {
return qftasm_value_str(&inst->dst);
}
static void qftasm_emit_func_prologue(int func_id) {
// Placeholder code that does nothing, to suppress compilation errors
if (func_id) {
return;
}
}
static void qftasm_emit_func_epilogue(void) {
}
static void qftasm_emit_pc_change(int pc) {
// The comments in this line are required for post-processing step in ./tools/qftasm_pp.py
qftasm_emit_line("MNZ 0 0 0; pc == %d:", pc);
}
static void qftasm_emit_inst(Inst* inst) {
switch (inst->op) {
case MOV:
qftasm_emit_line("MNZ 1 %s %d; MOV",
qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg));
break;
case ADD:
qftasm_emit_line("ADD A%d %s %d; ADD",
qftasm_reg2addr(inst->dst.reg),
qftasm_src_str(inst),
qftasm_reg2addr(inst->dst.reg));
break;
case SUB:
qftasm_emit_line("SUB A%d %s %d; SUB",
qftasm_reg2addr(inst->dst.reg),
qftasm_src_str(inst),
qftasm_reg2addr(inst->dst.reg));
break;
case LOAD:
if (inst->src.type == REG) {
qftasm_emit_line("ADD A%d %d %d; LOAD (reg)",
qftasm_reg2addr(inst->src.reg), QFTASM_MEM_OFFSET, QFTASM_TEMP);
qftasm_emit_line("MNZ 1 B%d %d;",
QFTASM_TEMP, qftasm_reg2addr(inst->dst.reg));
} else if (inst->src.type == IMM) {
qftasm_emit_line("MNZ 1 A%d %d; LOAD (imm)",
qftasm_int24_to_int16(inst->src.imm) + QFTASM_MEM_OFFSET, qftasm_reg2addr(inst->dst.reg));
} else {
error("Invalid value at LOAD");
}
break;
case STORE:
// Here, "src" and "dst" have opposite meanings from their names
if (inst->src.type == REG) {
qftasm_emit_line("ADD A%d %d %d; STORE (reg)",
qftasm_reg2addr(inst->src.reg), QFTASM_MEM_OFFSET, QFTASM_TEMP);
qftasm_emit_line("MNZ 1 A%d A%d;",
qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
} else if (inst->src.type == IMM) {
qftasm_emit_line("MNZ 1 A%d %d; STORE (imm)",
qftasm_reg2addr(inst->dst.reg),
qftasm_int24_to_int16(inst->src.imm) + QFTASM_MEM_OFFSET);
} else {
error("Invalid value at STORE");
}
break;
case PUTC:
#ifdef QFTASM_RAM_AS_STDOUT_BUFFER
qftasm_emit_line("MNZ 1 %s A%d; PUTC", qftasm_src_str(inst), QFTASM_STDOUT);
qftasm_emit_line("SUB A%d 1 %d;", QFTASM_STDOUT, QFTASM_STDOUT);
#else
qftasm_emit_line("MNZ 1 %s %d; PUTC", qftasm_src_str(inst), QFTASM_STDOUT);
qftasm_emit_line("MNZ 1 %d %d;", QFTASM_STDIO_CLOSED, QFTASM_STDOUT);
#endif
break;
case GETC:
#ifdef QFTASM_RAM_AS_STDIN_BUFFER
qftasm_emit_line("MNZ 1 B%d %d; GETC", QFTASM_STDIN, qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("SUB A%d 1 %d;", QFTASM_STDIN, QFTASM_STDIN);
#else
qftasm_emit_line("MNZ 1 %d %d; GETC", QFTASM_STDIO_OPEN, QFTASM_STDIN);
qftasm_emit_line("MNZ 0 0 0;"); // Required due to the delay between memory writing and instruction execution
qftasm_emit_line("MNZ 1 A%d %d;", QFTASM_STDIN, qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MNZ 1 %d %d;", QFTASM_STDIO_CLOSED, QFTASM_STDIN);
#endif
break;
case EXIT:
qftasm_emit_line("MNZ 1 65534 0; EXIT");
qftasm_emit_line("MNZ 0 0 0;");
break;
case DUMP:
break;
case EQ:
qftasm_emit_line("XOR %s A%d %d; EQ",
qftasm_src_str(inst),
qftasm_reg2addr(inst->dst.reg),
qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MNZ A%d 1 %d;", qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("XOR 1 A%d %d;", qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
break;
case NE:
qftasm_emit_line("XOR %s A%d %d; NE",
qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MNZ A%d 1 %d;", qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
break;
case LT:
qftasm_emit_line("MNZ 1 0 %d; LT", QFTASM_TEMP);
qftasm_emit_line("SUB A%d %s %d",
qftasm_reg2addr(inst->dst.reg), qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MLZ A%d 1 %d", qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP, qftasm_reg2addr(inst->dst.reg));
break;
case GT:
qftasm_emit_line("MNZ 1 0 %d; GT", QFTASM_TEMP);
qftasm_emit_line("SUB %s %s %d",
qftasm_src_str(inst), qftasm_dst_str(inst), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MLZ A%d 1 %d", qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP, qftasm_reg2addr(inst->dst.reg));
break;
case LE:
qftasm_emit_line("MNZ 1 0 %d; LE", QFTASM_TEMP);
qftasm_emit_line("SUB %s %s %d",
qftasm_src_str(inst), qftasm_dst_str(inst), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MLZ A%d 1 %d", qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP, qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("XOR 1 A%d %d", qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
break;
case GE:
qftasm_emit_line("MNZ 1 0 %d; GE", QFTASM_TEMP);
qftasm_emit_line("SUB %s %s %d",
qftasm_dst_str(inst), qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("MLZ A%d 1 %d", qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP, qftasm_reg2addr(inst->dst.reg));
qftasm_emit_line("XOR 1 A%d %d", qftasm_reg2addr(inst->dst.reg), qftasm_reg2addr(inst->dst.reg));
break;
case JEQ:
qftasm_emit_line("XOR %s A%d %d; JEQ",
qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_line("MNZ A%d 1 %d;", QFTASM_TEMP, QFTASM_TEMP);
qftasm_emit_line("XOR 1 A%d %d;", QFTASM_TEMP, QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JNE:
qftasm_emit_line("XOR %s A%d %d; JNE",
qftasm_src_str(inst), qftasm_reg2addr(inst->dst.reg), QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JLT:
qftasm_emit_line("MNZ 1 0 %d; JLT", QFTASM_TEMP_2);
qftasm_emit_line("SUB %s %s %d",
qftasm_dst_str(inst), qftasm_src_str(inst), QFTASM_TEMP);
qftasm_emit_line("MLZ A%d 1 %d", QFTASM_TEMP, QFTASM_TEMP_2);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP_2, QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JGT:
qftasm_emit_line("MNZ 1 0 %d; JGT", QFTASM_TEMP_2);
qftasm_emit_line("SUB %s %s %d",
qftasm_src_str(inst), qftasm_dst_str(inst), QFTASM_TEMP);
qftasm_emit_line("MLZ A%d 1 %d", QFTASM_TEMP, QFTASM_TEMP_2);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP_2, QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JLE:
qftasm_emit_line("MNZ 1 0 %d; JLE", QFTASM_TEMP_2);
qftasm_emit_line("SUB %s %s %d",
qftasm_src_str(inst), qftasm_dst_str(inst), QFTASM_TEMP);
qftasm_emit_line("MLZ A%d 1 %d", QFTASM_TEMP, QFTASM_TEMP_2);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP_2, QFTASM_TEMP);
qftasm_emit_line("XOR 1 A%d %d", QFTASM_TEMP, QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JGE:
qftasm_emit_line("MNZ 1 0 %d; GE", QFTASM_TEMP_2);
qftasm_emit_line("SUB %s %s %d",
qftasm_dst_str(inst), qftasm_src_str(inst), QFTASM_TEMP);
qftasm_emit_line("MLZ A%d 1 %d", QFTASM_TEMP, QFTASM_TEMP_2);
qftasm_emit_line("MNZ 1 A%d %d", QFTASM_TEMP_2, QFTASM_TEMP);
qftasm_emit_line("XOR 1 A%d %d", QFTASM_TEMP, QFTASM_TEMP);
qftasm_emit_conditional_jmp_inst(inst);
break;
case JMP:
qftasm_emit_unconditional_jmp_inst(inst);
break;
default:
error("oops");
}
}
void target_qftasm(Module* module) {
init_state_qftasm(module->data, module->text);
emit_chunked_main_loop(module->text,
qftasm_emit_func_prologue,
qftasm_emit_func_epilogue,
qftasm_emit_pc_change,
qftasm_emit_inst);
}
| 7,770 |
3,008 | /// @ref gtx_associated_min_max
/// @file glm/gtx/associated_min_max.hpp
///
/// @see core (dependence)
/// @see gtx_extented_min_max (dependence)
///
/// @defgroup gtx_associated_min_max GLM_GTX_associated_min_max
/// @ingroup gtx
///
/// @brief Min and max functions that return associated values not the compared onces.
/// <glm/gtx/associated_min_max.hpp> need to be included to use these functionalities.
#pragma once
// Dependency:
#include "../glm.hpp"
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_associated_min_max extension included")
#endif
namespace glm
{
/// @addtogroup gtx_associated_min_max
/// @{
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P>
GLM_FUNC_DECL U associatedMin(T x, U a, T y, U b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL tvec2<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
T x, const vecType<U, P>& a,
T y, const vecType<U, P>& b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b);
/// Minimum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMin(
T x, U a,
T y, U b,
T z, U c);
/// Minimum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMin(
T x, U a,
T y, U b,
T z, U c,
T w, U d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c,
vecType<T, P> const & w, vecType<U, P> const & d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c,
T w, vecType<U, P> const & d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c,
vecType<T, P> const & w, U d);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(T x, U a, T y, U b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL tvec2<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<T, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(
T x, U a,
T y, U b,
T z, U c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<T, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(
T x, U a,
T y, U b,
T z, U c,
T w, U d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c,
vecType<T, P> const & w, vecType<U, P> const & d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c,
T w, vecType<U, P> const & d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c,
vecType<T, P> const & w, U d);
/// @}
} //namespace glm
#include "associated_min_max.inl"
| 2,923 |
373 | <gh_stars>100-1000
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2018 Adobe
* %%
* 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.
* #L%
*/
package com.adobe.acs.commons.httpcache.engine;
import com.adobe.acs.commons.httpcache.store.TempSink;
import com.adobe.acs.commons.httpcache.store.mem.impl.MemTempSinkImpl;
import com.day.cq.commons.feed.StringResponseWrapper;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.commons.testing.sling.MockSlingHttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class HttpCacheServletResponseWrapperTest {
@Spy
SlingHttpServletResponse response = new MockSlingHttpServletResponse();
@Before
public void init(){
response.setCharacterEncoding("utf-8");
}
@Test
public void getHeaderNames_NullHeaderNames() throws IOException {
TempSink tempSink = new MemTempSinkImpl();
when(response.getHeaderNames()).thenThrow(AbstractMethodError.class);
HttpCacheServletResponseWrapper systemUnderTest = new HttpCacheServletResponseWrapper(response, tempSink);
assertEquals(0, systemUnderTest.getHeaderNames().size());
}
@Test
public void test_printwriter() throws IOException {
TempSink tempSink = new MemTempSinkImpl();
HttpCacheServletResponseWrapper systemUnderTest = new HttpCacheServletResponseWrapper(response, tempSink);
PrintWriter writer = systemUnderTest.getWriter();
assertNotNull(writer);
assertEquals(HttpCacheServletResponseWrapper.ResponseWriteMethod.PRINTWRITER, systemUnderTest.getWriteMethod());
}
@Test(expected = IllegalStateException.class)
public void test_printwriter_exception() throws IOException {
TempSink tempSink = new MemTempSinkImpl();
HttpCacheServletResponseWrapper systemUnderTest = new HttpCacheServletResponseWrapper(response, tempSink);
systemUnderTest.getWriter();
systemUnderTest.getOutputStream();
}
@Test
public void test_outputstream() throws IOException {
TempSink tempSink = new MemTempSinkImpl();
HttpCacheServletResponseWrapper systemUnderTest = new HttpCacheServletResponseWrapper(new StringResponseWrapper(response), tempSink);
OutputStream outputStream = systemUnderTest.getOutputStream();
assertNotNull(outputStream);
assertEquals(HttpCacheServletResponseWrapper.ResponseWriteMethod.OUTPUTSTREAM, systemUnderTest.getWriteMethod());
}
@Test(expected = IllegalStateException.class)
public void test_outputstream_exception() throws IOException {
TempSink tempSink = new MemTempSinkImpl();
HttpCacheServletResponseWrapper systemUnderTest = new HttpCacheServletResponseWrapper(new StringResponseWrapper(response), tempSink);
systemUnderTest.getOutputStream();
systemUnderTest.getWriter();
}
}
| 1,238 |
1,747 | <gh_stars>1000+
/*
* Copyright (c) 2017 <NAME>
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
/* This is a private GC header which provides an implementation of */
/* libatomic_ops subset primitives sufficient for GC assuming that C11 */
/* atomic intrinsics are available (and have correct implementation). */
/* This is enabled by defining GC_BUILTIN_ATOMIC macro. Otherwise, */
/* libatomic_ops library is used to define the primitives. */
#ifndef GC_ATOMIC_OPS_H
#define GC_ATOMIC_OPS_H
#ifdef GC_BUILTIN_ATOMIC
# include "gc.h" /* for GC_word */
# ifdef __cplusplus
extern "C" {
# endif
typedef GC_word AO_t;
# ifdef GC_PRIVATE_H /* have GC_INLINE */
# define AO_INLINE GC_INLINE
# else
# define AO_INLINE static __inline
# endif
typedef unsigned char AO_TS_t;
# define AO_TS_CLEAR 0
# define AO_TS_INITIALIZER (AO_TS_t)AO_TS_CLEAR
# if defined(__GCC_ATOMIC_TEST_AND_SET_TRUEVAL) && !defined(CPPCHECK)
# define AO_TS_SET __GCC_ATOMIC_TEST_AND_SET_TRUEVAL
# else
# define AO_TS_SET (AO_TS_t)1 /* true */
# endif
# define AO_CLEAR(p) __atomic_clear(p, __ATOMIC_RELEASE)
# define AO_test_and_set_acquire(p) __atomic_test_and_set(p, __ATOMIC_ACQUIRE)
# define AO_HAVE_test_and_set_acquire
# define AO_compiler_barrier() __atomic_signal_fence(__ATOMIC_SEQ_CST)
# define AO_nop_full() __atomic_thread_fence(__ATOMIC_SEQ_CST)
# define AO_HAVE_nop_full
# define AO_fetch_and_add(p, v) __atomic_fetch_add(p, v, __ATOMIC_RELAXED)
# define AO_HAVE_fetch_and_add
# define AO_fetch_and_add1(p) AO_fetch_and_add(p, 1)
# define AO_HAVE_fetch_and_add1
# define AO_or(p, v) (void)__atomic_or_fetch(p, v, __ATOMIC_RELAXED)
# define AO_HAVE_or
# define AO_load(p) __atomic_load_n(p, __ATOMIC_RELAXED)
# define AO_HAVE_load
# define AO_load_acquire(p) __atomic_load_n(p, __ATOMIC_ACQUIRE)
# define AO_HAVE_load_acquire
# define AO_load_acquire_read(p) AO_load_acquire(p)
# define AO_HAVE_load_acquire_read
# define AO_store(p, v) __atomic_store_n(p, v, __ATOMIC_RELAXED)
# define AO_HAVE_store
# define AO_store_release(p, v) __atomic_store_n(p, v, __ATOMIC_RELEASE)
# define AO_HAVE_store_release
# define AO_store_release_write(p, v) AO_store_release(p, v)
# define AO_HAVE_store_release_write
# define AO_char_load(p) __atomic_load_n(p, __ATOMIC_RELAXED)
# define AO_HAVE_char_load
# define AO_char_store(p, v) __atomic_store_n(p, v, __ATOMIC_RELAXED)
# define AO_HAVE_char_store
# ifdef AO_REQUIRE_CAS
AO_INLINE int
AO_compare_and_swap(volatile AO_t *p, AO_t ov, AO_t nv)
{
return (int)__atomic_compare_exchange_n(p, &ov, nv, 0,
__ATOMIC_RELAXED, __ATOMIC_RELAXED);
}
AO_INLINE int
AO_compare_and_swap_release(volatile AO_t *p, AO_t ov, AO_t nv)
{
return (int)__atomic_compare_exchange_n(p, &ov, nv, 0,
__ATOMIC_RELEASE, __ATOMIC_RELAXED);
}
# define AO_HAVE_compare_and_swap_release
# endif
# ifdef __cplusplus
} /* extern "C" */
# endif
# ifndef NO_LOCKFREE_AO_OR
/* __atomic_or_fetch is assumed to be lock-free. */
# define HAVE_LOCKFREE_AO_OR 1
# endif
#else
/* Fallback to libatomic_ops. */
# include "atomic_ops.h"
/* AO_compiler_barrier, AO_load and AO_store should be defined for */
/* all targets; the rest of the primitives are guaranteed to exist */
/* only if AO_REQUIRE_CAS is defined (or if the corresponding */
/* AO_HAVE_x macro is defined). x86/x64 targets have AO_nop_full, */
/* AO_load_acquire, AO_store_release, at least. */
# if (!defined(AO_HAVE_load) || !defined(AO_HAVE_store)) && !defined(CPPCHECK)
# error AO_load or AO_store is missing; probably old version of atomic_ops
# endif
#endif /* !GC_BUILTIN_ATOMIC */
#endif /* GC_ATOMIC_OPS_H */
| 1,870 |
348 | <filename>docs/data/leg-t2/054/05404269.json
{"nom":"Hudiviller","circ":"4ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":299,"abs":156,"votants":143,"blancs":5,"nuls":3,"exp":135,"res":[{"nuance":"LR","nom":"<NAME>","voix":72},{"nuance":"REM","nom":"<NAME>","voix":63}]} | 118 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_CONTROLLER_IMPL_H_
#define CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_CONTROLLER_IMPL_H_
#include <set>
#include <vector>
#include "base/memory/scoped_refptr.h"
#include "base/task/sequenced_task_runner.h"
#include "chrome/chrome_cleaner/engines/broker/engine_client.h"
#include "chrome/chrome_cleaner/engines/controllers/scanner_impl.h"
#include "chrome/chrome_cleaner/pup_data/pup_data.h"
#include "chrome/chrome_cleaner/scanner/scanner_controller.h"
namespace chrome_cleaner {
// The sandboxed implementation of the ScannerController.
class ScannerControllerImpl : public ScannerController {
public:
explicit ScannerControllerImpl(
EngineClient* engine_client,
RegistryLogger* registry_logger,
scoped_refptr<base::SequencedTaskRunner> task_runner,
ShortcutParserAPI* shortcut_parser);
ScannerControllerImpl(const ScannerControllerImpl&) = delete;
ScannerControllerImpl& operator=(const ScannerControllerImpl&) = delete;
// If |StartScan| has been called, pumps the message loop until
// |HandleScanDone| is called.
~ScannerControllerImpl() override;
protected:
// ScannerController:
void StartScan() override;
int WatchdogTimeoutCallback() override;
private:
void OnFoundUwS(UwSId pup_id);
void OnScanDone(ResultCode result_code, const std::vector<UwSId>& found_uws);
void UpdateResultsOnFoundUwS(UwSId pup_id);
void HandleScanDone(ResultCode result, const std::vector<UwSId>& found_uws);
bool IsScanningInProgress() const;
ScannerImpl scanner_;
EngineClient* engine_client_ = nullptr;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
enum class State {
kIdle,
kScanningStarting,
kScanningInProgress,
kScanningFinishing,
};
State state_ = State::kIdle;
// TODO(veranika): This is getting out of hand. Now there are two of them.
// We should have only one source of truth for the list of UwS found, and
// this list is also kept by the scanner.
std::set<UwSId> pup_ids_;
};
} // namespace chrome_cleaner
#endif // CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_CONTROLLER_IMPL_H_
| 802 |
2,690 | """
Tests for the Flocker volume manager.
"""
| 14 |
1,444 | <reponame>J-VOL/mage
package org.mage.test.cards.single.ogw;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
public class ThoughtKnotSeerTest extends CardTestPlayerBase {
/**
* Reported bug I bounced a Thought-Knot Seer my opponent controlled with
* enter the battlefield ability of a Reflector Mage. I should have drawn a
* card since the Thought-Knot Seer left the battlefield but I didn't.
*/
@Test
public void testThoughtKnotSeerBouncedReflectorMage() {
// {1}{W}{U} When Reflector Mage enters the battlefield, return target creature an opponent controls to its owner's hand.
// That creature's owner can't cast spells with the same name as that creature until your next turn.
addCard(Zone.HAND, playerA, "Reflector Mage"); // 2/3
addCard(Zone.BATTLEFIELD, playerA, "Plains", 2);
addCard(Zone.BATTLEFIELD, playerA, "Island", 2);
// {3}{<>} 4/4
// When Thought-Knot Seer enters the battlefield, target opponent reveals their hand. You choose a nonland card from it and exile that card.
// When Thought-Knot Seer leaves the battlefield, target opponent draws a card.
addCard(Zone.BATTLEFIELD, playerB, "Thought-Knot Seer");
addCard(Zone.BATTLEFIELD, playerB, "Wastes", 4);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Reflector Mage");
addTarget(playerA, "Thought-Knot Seer");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerA, "Reflector Mage", 1);
assertHandCount(playerB, "Thought-Knot Seer", 1);
assertHandCount(playerA, 1); // should have drawn a card from Thought-Knot Seer leaving
}
/**
* Simple bounce test on Thought-Knot Seer to differentiate between this and
* Reflector Mage issue
*/
@Test
public void testThoughtKnotSeerBouncedUnsummon() {
// {U} Return target creature to its owner's hand.
addCard(Zone.HAND, playerA, "Unsummon");
addCard(Zone.BATTLEFIELD, playerA, "Island", 2);
// {3}{<>} 4/4
// When Thought-Knot Seer enters the battlefield, target opponent reveals their hand. You choose a nonland card from it and exile that card.
// When Thought-Knot Seer leaves the battlefield, target opponent draws a card.
addCard(Zone.BATTLEFIELD, playerB, "Thought-Knot Seer");
addCard(Zone.BATTLEFIELD, playerB, "Wastes", 4);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Unsummon");
addTarget(playerA, "Thought-Knot Seer");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertGraveyardCount(playerA, "Unsummon", 1);
assertHandCount(playerB, "Thought-Knot Seer", 1);
assertHandCount(playerA, 1); // should have drawn a card from Thought-Knot Seer leaving
}
/**
*
*/
@Test
public void testThoughtKnotSeerDestroyed() {
// {1}{B} Destroy target nonblack creature.
addCard(Zone.HAND, playerA, "Doom Blade");
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 2);
// {3}{<>} 4/4
// When Thought-Knot Seer enters the battlefield, target opponent reveals their hand. You choose a nonland card from it and exile that card.
// When Thought-Knot Seer leaves the battlefield, target opponent draws a card.
addCard(Zone.BATTLEFIELD, playerB, "Thought-Knot Seer");
addCard(Zone.BATTLEFIELD, playerB, "Wastes", 4);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Doom Blade");
addTarget(playerA, "Thought-Knot Seer");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertGraveyardCount(playerB, "Thought-Knot Seer", 1);
assertHandCount(playerA, 1); // should have drawn a card from Thought-Knot Seer leaving
}
/**
*
*/
@Test
public void testThoughtKnotSeerExiled() {
// {W} Exile target creature. Its controller may search their library for a basic land card, put that card onto the battlefield tapped, then shuffle their library.
addCard(Zone.HAND, playerA, "Path to Exile");
addCard(Zone.BATTLEFIELD, playerA, "Plains", 1);
// {3}{<>} 4/4
// When Thought-Knot Seer enters the battlefield, target opponent reveals their hand. You choose a nonland card from it and exile that card.
// When Thought-Knot Seer leaves the battlefield, target opponent draws a card.
addCard(Zone.BATTLEFIELD, playerB, "Thought-Knot Seer");
addCard(Zone.BATTLEFIELD, playerB, "Wastes", 4);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Path to Exile");
addTarget(playerA, "Thought-Knot Seer");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertExileCount(playerB, 1);
assertExileCount("Thought-Knot Seer", 1);
assertHandCount(playerA, 1); // should have drawn a card from Thought-Knot Seer leaving
}
}
| 1,938 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.