max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,745
<filename>models/shared_base.py import numpy as np import torch def size(p): return np.prod(p.size()) class SharedModel(torch.nn.Module): def __init__(self): torch.nn.Module.__init__(self) @property def num_parameters(self): return sum([size(param) for param in self.parameters()]) def get_f(self, name): raise NotImplementedError() def get_num_cell_parameters(self, dag): raise NotImplementedError() def reset_parameters(self): raise NotImplementedError()
215
311
<filename>src/snowflake/connector/cpp/ArrowIterator/TimeStampConverter.cpp // // Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved. // #include "TimeStampConverter.hpp" #include "Python/Helpers.hpp" #include "Util/time.hpp" #include <memory> namespace sf { TimeStampBaseConverter::TimeStampBaseConverter(PyObject* context, int32_t scale) : m_context(context), m_scale(scale) { } OneFieldTimeStampNTZConverter::OneFieldTimeStampNTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::Int64Array>(array)) { } PyObject* OneFieldTimeStampNTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { double microseconds = internal::getFormattedDoubleFromEpoch( m_array->Value(rowIndex), m_scale); #ifdef _WIN32 return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_to_python_windows", "d", microseconds); #else return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_to_python", "d", microseconds); #endif } else { Py_RETURN_NONE; } } NumpyOneFieldTimeStampNTZConverter::NumpyOneFieldTimeStampNTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::Int64Array>(array)) { } PyObject* NumpyOneFieldTimeStampNTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t val = m_array->Value(rowIndex); return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_ONE_FIELD_to_numpy_datetime64", "Li", val, m_scale); } else { Py_RETURN_NONE; } } TwoFieldTimeStampNTZConverter::TwoFieldTimeStampNTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::StructArray>(array)), m_epoch(std::dynamic_pointer_cast<arrow::Int64Array>( m_array->GetFieldByName(internal::FIELD_NAME_EPOCH))), m_fraction(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_FRACTION))) { } PyObject* TwoFieldTimeStampNTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t epoch = m_epoch->Value(rowIndex); int32_t frac = m_fraction->Value(rowIndex); double microseconds = internal::getFormattedDoubleFromEpochFraction(epoch, frac, m_scale); #ifdef _WIN32 return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_to_python_windows", "d", microseconds); #else return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_to_python", "d", microseconds); #endif } else { Py_RETURN_NONE; } } NumpyTwoFieldTimeStampNTZConverter::NumpyTwoFieldTimeStampNTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::StructArray>(array)), m_epoch(std::dynamic_pointer_cast<arrow::Int64Array>( m_array->GetFieldByName(internal::FIELD_NAME_EPOCH))), m_fraction(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_FRACTION))) { } PyObject* NumpyTwoFieldTimeStampNTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t epoch = m_epoch->Value(rowIndex); int32_t frac = m_fraction->Value(rowIndex); return PyObject_CallMethod(m_context, "TIMESTAMP_NTZ_TWO_FIELD_to_numpy_datetime64", "Li", epoch, frac); } else { Py_RETURN_NONE; } } OneFieldTimeStampLTZConverter::OneFieldTimeStampLTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::Int64Array>(array)) { } PyObject* OneFieldTimeStampLTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { double microseconds = internal::getFormattedDoubleFromEpoch( m_array->Value(rowIndex), m_scale); #ifdef _WIN32 // this macro is enough for both win32 and win64 return PyObject_CallMethod(m_context, "TIMESTAMP_LTZ_to_python_windows", "d", microseconds); #else return PyObject_CallMethod(m_context, "TIMESTAMP_LTZ_to_python", "d", microseconds); #endif } Py_RETURN_NONE; } TwoFieldTimeStampLTZConverter::TwoFieldTimeStampLTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::StructArray>(array)), m_epoch(std::dynamic_pointer_cast<arrow::Int64Array>( m_array->GetFieldByName(internal::FIELD_NAME_EPOCH))), m_fraction(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_FRACTION))) { } PyObject* TwoFieldTimeStampLTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t epoch = m_epoch->Value(rowIndex); int32_t frac = m_fraction->Value(rowIndex); double microseconds = internal::getFormattedDoubleFromEpochFraction(epoch, frac, m_scale); #ifdef _WIN32 return PyObject_CallMethod(m_context, "TIMESTAMP_LTZ_to_python_windows", "d", microseconds); #else return PyObject_CallMethod(m_context, "TIMESTAMP_LTZ_to_python", "d", microseconds); #endif } Py_RETURN_NONE; } TwoFieldTimeStampTZConverter::TwoFieldTimeStampTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::StructArray>(array)), m_epoch(std::dynamic_pointer_cast<arrow::Int64Array>( m_array->GetFieldByName(internal::FIELD_NAME_EPOCH))), m_timezone(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_TIME_ZONE))) { } PyObject* TwoFieldTimeStampTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t epoch = m_epoch->Value(rowIndex); double microseconds = internal::getFormattedDoubleFromEpoch(epoch, m_scale); int32_t timezone = m_timezone->Value(rowIndex); #ifdef _WIN32 return PyObject_CallMethod(m_context, "TIMESTAMP_TZ_to_python_windows", "di", microseconds, timezone); #else return PyObject_CallMethod(m_context, "TIMESTAMP_TZ_to_python", "di", microseconds, timezone); #endif } Py_RETURN_NONE; } ThreeFieldTimeStampTZConverter::ThreeFieldTimeStampTZConverter( std::shared_ptr<arrow::Array> array, int32_t scale, PyObject* context) : TimeStampBaseConverter(context, scale), m_array(std::dynamic_pointer_cast<arrow::StructArray>(array)), m_epoch(std::dynamic_pointer_cast<arrow::Int64Array>( m_array->GetFieldByName(internal::FIELD_NAME_EPOCH))), m_timezone(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_TIME_ZONE))), m_fraction(std::dynamic_pointer_cast<arrow::Int32Array>( m_array->GetFieldByName(internal::FIELD_NAME_FRACTION))) { } PyObject* ThreeFieldTimeStampTZConverter::toPyObject(int64_t rowIndex) const { if (m_array->IsValid(rowIndex)) { int64_t epoch = m_epoch->Value(rowIndex); int32_t frac = m_fraction->Value(rowIndex); double microseconds = internal::getFormattedDoubleFromEpochFraction(epoch, frac, m_scale); int32_t timezone = m_timezone->Value(rowIndex); #ifdef _WIN32 return PyObject_CallMethod(m_context, "TIMESTAMP_TZ_to_python_windows", "di", microseconds, timezone); #else return PyObject_CallMethod(m_context, "TIMESTAMP_TZ_to_python", "di", microseconds, timezone); #endif } Py_RETURN_NONE; } } // namespace sf
3,413
3,428
<reponame>ghalimi/stdlib {"id":"02246","group":"easy-ham-1","checksum":{"type":"MD5","value":"b353269018884d01ee252bca5bd419ef"},"text":"From <EMAIL> Fri Oct 4 11:01:52 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>ass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 806D216F1B\n\tfor <jm@localhost>; Fri, 4 Oct 2002 11:01:26 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Fri, 04 Oct 2002 11:01:26 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g94806K08775 for\n <<EMAIL>>; Fri, 4 Oct 2002 09:00:06 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy<EMAIL>int.org\nFrom: diveintomark <<EMAIL>>\nSubject: Microsoft redesign\nDate: Fri, 04 Oct 2002 08:00:05 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://diveintomark.org/archives/2002/10/03.html#microsoft_redesign\nDate: 2002-10-03T14:42:29-05:00\n\n_<NAME>_: Party like it's 1997[1]. &#8220;Microsoft has redesigned. \nIts new layout uses font tags and other deprecated junk straight out of the \nmid-1990s. ... When a W3C member company that helped create XHTML and CSS \nignores or misuses those web standards on its corporate site, you have to \nwonder who didn't get the memo.&#8221; \n\nThe new design also fails even the most basic accessibility tests[2]; the home \npage contains 80 instances of images without ALT text. This is the same basic \nfailing for which the Sydney Organizing Committee for the Olympic Games was \nsuccessfully sued in 2000[3]. \n\nHere is what microsoft.com looks like in a text-only browser[4]. (To better \nunderstand the experience, take a piece of paper and cover your entire monitor \nexcept for the top line, then scroll the window slowly so you can only read one \nline at a time.) While nothing is technically locked out (all the links are \nregular links, nothing requires Javascript to function properly), all the \nun-ALT-enhanced images (which are mostly spacer images and images-as-bullets) \nadd so much clutter to the page that it's very difficult to navigate. \n\nMeanwhile, I don't want to imagine what it would sound like through a screen \nreader. Want to find the search box? That's &#8220;1pttrans dot gif 1pttrans \ndot gif search for 1pttrans dot gif 1pttrans dot gif form edit box 1pttrans dot \ngif submit button go 1pttrans dot gif link advanced search 1pttrans dot gif \n...&#8221; And I hope you weren't looking for Microsoft's accessibility home \npage[5]; it's the 76th link on the page (out of 76).\n\n\n\n[1] http://www.zeldman.com/daily/0902b.html#prince\n[2] http://bobby.watchfire.com/bobby/bobbyServlet?advanced=true&URL=http%3A%2F%2Fwww.microsoft.com%2F&gl=wcag1-a&Text=text&line=line&an_errs=an_errs&stealth=Bobby%2F3.3&output=Submit\n[3] http://www.contenu.nu/socog.html\n[4] http://diveintomark.org/public/microsoft_lynx_output.txt\n[5] http://www.microsoft.com/enable/\n\n\n"}
1,058
669
<gh_stars>100-1000 """ Copyright (c) Facebook, Inc. and its affiliates. """ import sys from os import curdir, sep import qrcode from PIL import Image from http.server import BaseHTTPRequestHandler, HTTPServer PORT = 8000 class HTTPHandler(BaseHTTPRequestHandler): def do_GET(self): if (self.path.endswith(".png")): self.send_response(200) self.send_header('Content-type','image/png') self.end_headers() with open(curdir+sep+self.path, 'rb') as file: self.wfile.write(file.read()) else: self.send_response(200) self.send_header('Content-type',"text/html") self.end_headers() content = ''' <html><head><title>Minecraft QR Code Connect</title></head> <body> <h1>Minecraft Bot - QR Code Connect!</h1> <img src = "qrcode.png" alt="qr code"> </body> </html> ''' self.wfile.write(bytes(content,'utf8')) return def makeQRCode(info): img = qrcode.make(info) img.save(curdir+sep+"qrcode.png","PNG") def run(): server_address = ('',8000) httpd = HTTPServer(server_address, HTTPHandler) httpd.serve_forever() if __name__ == "__main__": info = sys.argv[1] makeQRCode(info) run()
481
3,041
class PytestEthereumError(Exception): """ Base class for all Pytest-Ethereum errors. """ pass class DeployerError(PytestEthereumError): """ Raised when the Deployer is unable to deploy a contract type. """ pass class LinkerError(PytestEthereumError): """ Raised when the Linker is unable to link two contract types. """ pass
132
441
<gh_stars>100-1000 package org.beetl.ext.jfinal3; import org.beetl.core.GroupTemplate; import org.beetl.ext.web.WebRender; import com.jfinal.render.Render; public class JFinal3BeetlRender extends Render { GroupTemplate groupTemplate; public JFinal3BeetlRender( GroupTemplate groupTemplate,String view){ super(); super.setView(view); this.groupTemplate = groupTemplate; } @Override public void render() { response.setContentType("text/html; charset=" + this.getEncoding()); WebRender web = new WebRender(groupTemplate); web.render(this.view, this.request, this.response, null); } }
210
384
<filename>src/programs/mdrun/tests/mdruncomparison.h /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2018,2019,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \libinternal * * \brief Functionality for testing whether calls to mdrun produce the * same energy and force quantities when they should do so. */ #ifndef GMX_MDRUN_TESTS_MDRUNCOMPARISON_H #define GMX_MDRUN_TESTS_MDRUNCOMPARISON_H #include <functional> #include <memory> #include <gtest/gtest.h> namespace gmx { namespace test { /*! \internal * \brief Manages returning a pair of frames from two * equivalent simulations that are meaningful to compare. * * \todo This is largely duplicated by ContinuationFrameManager. These * could be refactored into components that compare iterators to * frames. * * \tparam FrameReader Has readNextFrame() and frame() methods * useful for returning successive Frame objects */ template<class FrameReader> class FramePairManager { public: //! Convenience typedef typedef std::unique_ptr<FrameReader> FrameReaderPtr; //! Constructor FramePairManager(FrameReaderPtr first, FrameReaderPtr second) : first_(std::move(first)), second_(std::move(second)) { } private: /*! \brief Probe for a pair of valid frames, and return true if both are found. * * Give a test failure if exactly one frame is found, because * that file is longer than the other one, and this is not * expected behaviour. */ bool shouldContinueComparing() { if (first_->readNextFrame()) { if (second_->readNextFrame()) { // Two valid next frames exist, so we should continue comparing. return true; } else { ADD_FAILURE() << "first file had at least one more frame than second file"; } } else { if (second_->readNextFrame()) { ADD_FAILURE() << "second file had at least one more frame than first file"; } else { // Both files ran out of frames at the same time, which is the expected behaviour. } } // At least one file is out of frames, so should not continue comparing. return false; } public: /*! \brief Compare all possible pairs of frames using \c compareTwoFrames. * * \tparam Frame The type of frame used in the comparison (returned * by FrameReader and used by compareTwoFrames). */ template<class Frame> void compareAllFramePairs(std::function<void(const Frame&, const Frame&)> compareTwoFrames) { while (shouldContinueComparing()) { Frame firstFrame = first_->frame(); Frame secondFrame = second_->frame(); SCOPED_TRACE("Comparing frames from two runs '" + firstFrame.frameName() + "' and '" + secondFrame.frameName() + "'"); compareTwoFrames(firstFrame, secondFrame); } } private: FrameReaderPtr first_; FrameReaderPtr second_; }; } // namespace test } // namespace gmx #endif
1,703
412
char a[100]; int main() { char *p, *q; q = p; __CPROVER_assume(!__CPROVER_same_object(p, 0)); p++; assert(!__CPROVER_same_object(p, 0)); }
76
1,805
#include <sys/time.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> //#include <proc/readproc.h> // need to install procps-devel-3.2.8-25.el6.i686 #include <sys/time.h> #include <sys/resource.h> /* void getcpumem(float *scpu, float *smem) { struct rusage rusage; struct proc_t usage; getrusage(RUSAGE_SELF, &rusage); *scpu = ((float) (rusage.ru_utime.tv_usec + rusage.ru_stime.tv_usec) / 1000000) + ((float) (rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec)); look_up_our_self(&usage); *smem = (float) usage.vsize / 1000000; } */ void getmaxcpumem(float *scpu, float *smem) { struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); *scpu = ((float) (rusage.ru_utime.tv_usec + rusage.ru_stime.tv_usec) / 1000000) + ((float) (rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec)); *smem = (float) (rusage.ru_maxrss) / 1000; }
438
406
<gh_stars>100-1000 import pytest import gevent import logging import time from struct import pack, unpack from volttron.platform import get_services_core, jsonapi from platform_driver.interfaces.modbus_tk.server import Server from platform_driver.interfaces.modbus_tk.client import Client, Field from platform_driver.interfaces.modbus_tk import helpers from volttrontesting.utils.utils import get_rand_ip_and_port from volttron.platform.agent.known_identities import PLATFORM_DRIVER logger = logging.getLogger(__name__) IP, _port = get_rand_ip_and_port().split(":") PORT = int(_port) DRIVER_CONFIG = { "driver_config": { "device_address": IP, "port": PORT, "slave_id": 1 }, "driver_type": "modbus", "registry_config": "config://modbus.csv", "interval": 120, "timezone": "UTC" } # This registry configuration contains only required fields REGISTRY_CONFIG_STRING = """Volttron Point Name,Units,Modbus Register,Writable,Point Address BigUShort,PPM,>H,TRUE,0 BigUInt,PPM,>I,TRUE,1 BigULong,PPM,>Q,TRUE,3 BigShort,PPM,>h,TRUE,7 BigInt,PPM,>i,TRUE,8 BigFloat,PPM,>f,TRUE,10 BigLong,PPM,>q,TRUE,12 LittleUShort,PPM,<H,TRUE,100 LittleUInt,PPM,<I,TRUE,101 LittleULong,PPM,<Q,TRUE,103 LittleShort,PPM,<h,TRUE,107 LittleInt,PPM,<i,TRUE,108 LittleFloat,PPM,<f,TRUE,110 LittleLong,PPM,<q,TRUE,112""" # Register values dictionary for testing set_point and get_point registers_dict = {"BigUShort": 2**16-1, "BigUInt": 2**32-1, "BigULong": 2**64-1, "BigShort": -(2**16)//2, "BigInt": -(2**32)//2, "BigFloat": -1234.0, "BigLong": -(2**64)//2, "LittleUShort": 0, "LittleUInt": 0, "LittleULong": 0, "LittleShort": (2**16)//2-1, "LittleInt": (2**32)//2-1, "LittleFloat": 1.0, "LittleLong": (2**64)//2-1 } @pytest.fixture(scope="module") def agent(request, volttron_instance): """ Build PlatformDriverAgent, add Modbus driver & csv configurations """ # Build platform driver agent md_agent = volttron_instance.build_agent(identity="test_md_agent") capabilities = {'edit_config_store': {'identity': PLATFORM_DRIVER}} volttron_instance.add_capabilities(md_agent.core.publickey, capabilities) gevent.sleep(1) # Clean out platform driver configurations # wait for it to return before adding new config md_agent.vip.rpc.call('config.store', 'manage_delete_store', PLATFORM_DRIVER).get() # Add driver configurations md_agent.vip.rpc.call('config.store', 'manage_store', PLATFORM_DRIVER, 'devices/modbus', jsonapi.dumps(DRIVER_CONFIG), config_type='json') # Add csv configurations md_agent.vip.rpc.call('config.store', 'manage_store', PLATFORM_DRIVER, 'modbus.csv', REGISTRY_CONFIG_STRING, config_type='csv') platform_uuid = volttron_instance.install_agent( agent_dir=get_services_core("PlatformDriverAgent"), config_file={}, start=True) gevent.sleep(10) # wait for the agent to start and start the devices def stop(): """Stop platform driver agent """ volttron_instance.stop_agent(platform_uuid) md_agent.core.stop() request.addfinalizer(stop) return md_agent class PPSPi32Client(Client): """ Define some registers to PPSPi32Client """ def __init__(self, *args, **kwargs): super(PPSPi32Client, self).__init__(*args, **kwargs) byte_order = helpers.BIG_ENDIAN addressing = helpers.ADDRESS_OFFSET BigUShort = Field("BigUShort", 0, helpers.USHORT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigUInt = Field("BigUInt", 1, helpers.UINT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigULong = Field("BigULong", 3, helpers.UINT64, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigShort = Field("BigShort", 7, helpers.SHORT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigInt = Field("BigInt", 8, helpers.INT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigFloat = Field("BigFloat", 10, helpers.FLOAT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) BigLong = Field("BigLong", 12, helpers.INT64, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleUShort = Field( "LittleUShort", 100, helpers.USHORT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleUInt = Field( "LittleUInt", 101, helpers.UINT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleULong = Field( "LittleULong", 103, helpers.UINT64, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleShort = Field( "LittleShort", 107, helpers.SHORT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleInt = Field( "LittleInt", 108, helpers.INT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleFloat = Field( "LittleFloat", 110, helpers.FLOAT, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) LittleLong = Field( "LittleLong", 112, helpers.INT64, 'PPM', 2, helpers.no_op, helpers.REGISTER_READ_WRITE, helpers.OP_MODE_READ_WRITE) @pytest.fixture def modbus_server(request): modbus_server = Server(address=IP, port=PORT) modbus_server.define_slave(1, PPSPi32Client, unsigned=True) # Set values for registers from server as the default values modbus_server.set_values(1, PPSPi32Client().field_by_name("BigUShort"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigUInt"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigULong"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigShort"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigInt"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigFloat"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("BigLong"), 0) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleUShort"), unpack('<H', pack('>H', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleUInt"), unpack('<HH', pack('>I', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleULong"), unpack('<HHHH', pack('>Q', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleShort"), unpack('<H', pack('>h', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleInt"), unpack('<HH', pack('>i', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleFloat"), unpack('<HH', pack('>f', 0))) modbus_server.set_values(1, PPSPi32Client().field_by_name("LittleLong"), unpack('<HHHH', pack('>q', 0))) modbus_server.start() time.sleep(1) yield modbus_server modbus_server.stop() @pytest.mark.usefixtures("modbus_server") class TestModbusDriver: """ Regression tests for the modbus driver interface. """ def get_point(self, agent, point_name): """ Issue a get_point RPC call for the named point and return the result. @param agent: The test Agent. @param point_name: The name of the point to query. @return: The returned value from the RPC call. """ return agent.vip.rpc.call(PLATFORM_DRIVER, 'get_point', 'modbus', point_name).get(timeout=10) def set_point(self, agent, point_name, point_value): """ Issue a set_point RPC call for the named point and value, and return the result. @param agent: The test Agent. @param point_name: The name of the point to query. @param point_value: The value to set on the point. @return: The returned value from the RPC call. """ return agent.vip.rpc.call(PLATFORM_DRIVER, 'set_point', 'modbus', point_name, point_value).get(timeout=10) def scrape_all(self, agent): """ Issue a get_point RPC call for the named point and return the result. @param agent: The test Agent. @return: The returned value from the RPC call. """ return agent.vip.rpc.call(PLATFORM_DRIVER, 'scrape_all', 'modbus').get(timeout=10) def test_default_values(self, agent): """ By default server setting, all registers values are 0 """ default_values = self.scrape_all(agent) assert type(default_values) is dict for key in default_values.keys(): assert default_values[key] == 0 or 0.0 def test_set_point(self, agent): for key in registers_dict.keys(): self.set_point(agent, key, registers_dict[key]) assert self.get_point(agent, key) == registers_dict[key] assert self.scrape_all(agent) == registers_dict
4,352
432
package io.activej.rpc.client.sender; import io.activej.rpc.client.sender.helper.RpcClientConnectionPoolStub; import io.activej.rpc.client.sender.helper.RpcSenderStub; import io.activej.rpc.hash.ShardingFunction; import org.junit.Before; import org.junit.Test; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static io.activej.rpc.client.sender.Callbacks.assertNoCalls; import static io.activej.rpc.client.sender.Callbacks.forFuture; import static io.activej.rpc.client.sender.RpcStrategies.servers; import static io.activej.rpc.client.sender.RpcStrategies.sharding; import static io.activej.test.TestUtils.getFreePort; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @SuppressWarnings("ConstantConditions") public class RpcStrategyShardingTest { private static final String HOST = "localhost"; private InetSocketAddress address1; private InetSocketAddress address2; private InetSocketAddress address3; @Before public void setUp() { address1 = new InetSocketAddress(HOST, getFreePort()); address2 = new InetSocketAddress(HOST, getFreePort()); address3 = new InetSocketAddress(HOST, getFreePort()); } @Test public void itShouldSelectSubSenderConsideringHashCodeOfRequestData() { RpcClientConnectionPoolStub pool = new RpcClientConnectionPoolStub(); RpcSenderStub connection1 = new RpcSenderStub(); RpcSenderStub connection2 = new RpcSenderStub(); RpcSenderStub connection3 = new RpcSenderStub(); int shardsAmount = 3; ShardingFunction<Integer> shardingFunction = item -> item % shardsAmount; RpcStrategy shardingStrategy = sharding(shardingFunction, servers(address1, address2, address3)); RpcSender senderSharding; int timeout = 50; pool.put(address1, connection1); pool.put(address2, connection2); pool.put(address3, connection3); senderSharding = shardingStrategy.createSender(pool); senderSharding.sendRequest(0, timeout, assertNoCalls()); senderSharding.sendRequest(0, timeout, assertNoCalls()); senderSharding.sendRequest(1, timeout, assertNoCalls()); senderSharding.sendRequest(0, timeout, assertNoCalls()); senderSharding.sendRequest(2, timeout, assertNoCalls()); senderSharding.sendRequest(0, timeout, assertNoCalls()); senderSharding.sendRequest(0, timeout, assertNoCalls()); senderSharding.sendRequest(2, timeout, assertNoCalls()); assertEquals(5, connection1.getRequests()); assertEquals(1, connection2.getRequests()); assertEquals(2, connection3.getRequests()); } @Test public void itShouldCallOnExceptionOfCallbackWhenChosenServerIsNotActive() throws ExecutionException, InterruptedException { RpcClientConnectionPoolStub pool = new RpcClientConnectionPoolStub(); RpcSenderStub connection2 = new RpcSenderStub(); RpcSenderStub connection3 = new RpcSenderStub(); int shardsAmount = 3; ShardingFunction<Integer> shardingFunction = item -> item % shardsAmount; RpcStrategy shardingStrategy = sharding(shardingFunction, servers(address1, address2, address3)); // we don't add connection for ADDRESS_1 pool.put(address2, connection2); pool.put(address3, connection3); RpcSender sender = shardingStrategy.createSender(pool); CompletableFuture<Object> future1 = new CompletableFuture<>(); CompletableFuture<Object> future2 = new CompletableFuture<>(); CompletableFuture<Object> future3 = new CompletableFuture<>(); sender.sendRequest(0, 50, forFuture(future1)); sender.sendRequest(1, 50, forFuture(future2)); sender.sendRequest(2, 50, forFuture(future3)); assertEquals(1, connection2.getRequests()); assertEquals(1, connection3.getRequests()); try { future1.get(); fail(); } catch (ExecutionException e) { assertEquals("No senders available", e.getCause().getMessage()); } } }
1,311
1,178
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "avionics/firmware/drivers/metpak.h" #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include "avionics/common/gill_ascii.h" #include "avionics/common/gill_serial.h" #include "avionics/common/gill_types.h" #include "avionics/common/serial_parse.h" #include "avionics/firmware/cpu/clock.h" #include "avionics/firmware/cpu/sci.h" #include "common/macros.h" #define METPAK_BAUD 19200 // Manual specifies 9.5 seconds. #define METPAK_POWER_UP_TIMEOUT_CYCLES CLOCK32_MSEC_TO_CYCLES(9500) #define METPAK_REPLY_TIMEOUT_CYCLES CLOCK32_MSEC_TO_CYCLES(100) #define METPAK_WATCHDOG_TIMEOUT_CYCLES CLOCK32_MSEC_TO_CYCLES(5000) #define METPAK_VERIFY_TRIES 3 static const char *kInitStrings[] = { "ASCTERM CRLF\n", "ECHO OFF\n", "REPORT FULL\n", "UNITS WIND MS\n", "UNITS PRESS HPA\n", "UNITS TEMP C\n", "UNITS DEWPOINT C\n", "UNITS RH %\n", "OUTFREQ 1HZ\n", "MSGMODE CONT\n", }; typedef enum { kDevStatePowerUpDelay, kDevStateResetMode, kDevStateEnterSetupMode, kDevStateSendInitStrings, kDevStateVerifyReport, kDevStateVerifyUnits, kDevStateLeaveSetupMode, kDevStateWatchdog } DevState; static struct { DevState state; bool first_entry; uint32_t timeout; int32_t index; bool setup_mode; bool received_prompt; bool received_reply; bool verified_report; bool verified_units; bool watchdog_reset; } g_init; static SerialReceiveBuffer g_recv; static GillReceive g_parse; static void DevStatePowerUpDelay(const MetPakConfig *config, DevState next) { if (g_init.first_entry) { g_init.timeout = Clock32GetCycles() + METPAK_POWER_UP_TIMEOUT_CYCLES; g_init.watchdog_reset = false; SerialParseInit(&g_recv); SciInit(config->device, METPAK_BAUD); } else if (CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { g_init.state = next; } } // Make sure we're not already in SETUP MODE. static void DevStateResetMode(const MetPakConfig *config, DevState next) { if (g_init.first_entry) { g_init.timeout = Clock32GetCycles() + METPAK_REPLY_TIMEOUT_CYCLES; SciWriteString(config->device, "EXIT\n"); } else if (CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { g_init.state = next; } } static void DevStateEnterSetupMode(const MetPakConfig *config, DevState next) { if (g_init.first_entry) { g_init.timeout = Clock32GetCycles() + METPAK_REPLY_TIMEOUT_CYCLES; g_init.setup_mode = false; g_init.received_prompt = false; SciWriteString(config->device, "*Q\n"); } else if (g_init.setup_mode && g_init.received_prompt) { g_init.state = next; } else if (CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { g_init.state = kDevStatePowerUpDelay; } } static void DevStateSendInitStrings(const MetPakConfig *config, DevState next) { if (g_init.first_entry) { g_init.index = 0; } if (g_init.first_entry || g_init.received_reply || g_init.received_prompt || CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { if (g_init.index < ARRAYSIZE(kInitStrings)) { g_init.received_reply = false; g_init.received_prompt = false; g_init.timeout = Clock32GetCycles() + METPAK_REPLY_TIMEOUT_CYCLES; SciWriteString(config->device, kInitStrings[g_init.index]); ++g_init.index; } else { g_init.state = next; } } } // Argument 'command' corresponds to one of MetPak's commands (i.e., REPORT or // UNITS). static void DevStateVerify(const MetPakConfig *config, const char *command, DevState next, bool *response_verified) { assert(command != NULL); assert(response_verified != NULL); if (g_init.first_entry) { g_init.index = 0; g_init.received_reply = false; *response_verified = false; } if (*response_verified) { g_init.state = next; } else if (g_init.index > METPAK_VERIFY_TRIES) { // Device fails to respond. g_init.state = kDevStatePowerUpDelay; } else if (g_init.first_entry || CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { // Send command. g_init.timeout = Clock32GetCycles() + METPAK_REPLY_TIMEOUT_CYCLES; g_init.received_reply = false; SciWriteString(config->device, command); SciWriteString(config->device, "\n"); ++g_init.index; // Retry counter. } else if (g_init.received_reply) { // Device reports unexpected string. g_init.state = kDevStatePowerUpDelay; } } static void DevStateLeaveSetupMode(const MetPakConfig *config, DevState next) { SciWriteString(config->device, "EXIT\n"); g_init.setup_mode = false; g_init.state = next; } static void DevStateWatchdog(uint32_t timeout, DevState next) { if (g_init.first_entry || g_init.watchdog_reset) { g_init.timeout = Clock32GetCycles() + timeout; g_init.watchdog_reset = false; } else if (CLOCK32_GE(Clock32GetCycles(), g_init.timeout)) { g_init.state = next; } } static void DevPollState(const MetPakConfig *config) { do { DevState current = g_init.state; switch (current) { case kDevStatePowerUpDelay: DevStatePowerUpDelay(config, kDevStateResetMode); break; case kDevStateResetMode: DevStateResetMode(config, kDevStateEnterSetupMode); break; case kDevStateEnterSetupMode: DevStateEnterSetupMode(config, kDevStateSendInitStrings); break; case kDevStateSendInitStrings: DevStateSendInitStrings(config, kDevStateVerifyReport); break; case kDevStateVerifyReport: DevStateVerify(config, "REPORT", kDevStateVerifyUnits, &g_init.verified_report); break; case kDevStateVerifyUnits: DevStateVerify(config, "UNITS", kDevStateLeaveSetupMode, &g_init.verified_units); break; case kDevStateLeaveSetupMode: DevStateLeaveSetupMode(config, kDevStateWatchdog); break; case kDevStateWatchdog: DevStateWatchdog(METPAK_WATCHDOG_TIMEOUT_CYCLES, kDevStatePowerUpDelay); break; default: g_init.state = kDevStatePowerUpDelay; assert(false); break; } g_init.first_entry = (current != g_init.state); } while (g_init.first_entry); } static bool DecodeSetupMode(int32_t length, const uint8_t *data) { assert(data != NULL); assert(length >= 0); const char *token = "<PASSWORD>"; int32_t token_length = (int32_t)strlen(token); if (length == token_length && memcmp(data, token, token_length) == 0) { g_init.setup_mode = true; g_init.received_reply = true; return true; } return false; } static bool DecodeReport(int32_t length, const uint8_t *data) { assert(data != NULL); assert(length >= 0); const char *token = "REPORT = "; int32_t token_length = (int32_t)strlen(token); if (length >= token_length && memcmp(data, token, token_length) == 0) { const char *expect = "REPORT = NODE,DIR,SPEED,W-AXIS,PRESS,RH,TEMP," "DEWPOINT,VOLT,STATUS,CHECK"; int32_t expect_length = (int32_t)strlen(expect); g_init.verified_report = (length == expect_length && memcmp(data, expect, expect_length) == 0); g_init.received_reply = true; return true; } return false; } static bool DecodeUnits(int32_t length, const uint8_t *data) { assert(data != NULL); assert(length >= 0); const char *token = "<PASSWORD> = "; int32_t token_length = (int32_t)strlen(token); if (length >= token_length && memcmp(data, token, token_length) == 0) { const char *expect = "UNITS = -,DEG,MS,MS,HPA,%,C,C,V,-,-"; int32_t expect_length = (int32_t)strlen(expect); g_init.verified_units = (length == expect_length && memcmp(data, expect, expect_length) == 0); g_init.received_reply = true; return true; } return false; } static void MetPakLineDecode(int32_t length, const uint8_t *data) { if (DecodeSetupMode(length, data) || DecodeReport(length, data) || DecodeUnits(length, data)) { } } static bool PollNewMessage(const MetPakConfig *config, GillData *out) { bool new_message = false; if (SerialPollSci(config->device, &g_recv) && GillParse(&g_recv, &g_parse)) { g_init.watchdog_reset = true; switch (g_parse.proto) { case kGillProtoAscii: new_message = GillAsciiDecodeMetPak(&g_parse.ascii, g_parse.data, out); break; case kGillProtoLine: MetPakLineDecode(g_parse.data_length, g_parse.data); break; case kGillProtoPrompt: g_init.received_prompt = true; break; case kGillProtoNmea: // Output not supported, use kGillProtoAscii. break; default: break; } } return new_message; } void MetPakInit(void) { memset(&g_init, 0, sizeof(g_init)); g_init.state = kDevStatePowerUpDelay; g_init.first_entry = true; } bool MetPakPoll(const MetPakConfig *config, GillData *out) { DevPollState(config); return PollNewMessage(config, out); }
3,908
3,673
<gh_stars>1000+ #pragma once #ifndef INCLUDE_SOCKFD_HPP #define INCLUDE_SOCKFD_HPP #include <sys/socket.h> #include <net/inet> #include "fd.hpp" class SockFD : public FD { public: explicit SockFD(const int id) : FD(id) {} bool is_socket() override { return true; } }; struct sockaddr; typedef uint32_t socklen_t; extern bool validate_sockaddr_in(const struct sockaddr*, socklen_t); #endif
171
407
// MIT License // // Copyright (c) 2019 <NAME>, Chair for Embedded Security. All Rights reserved. // Copyright (c) 2021 Max Planck Institute for Security and Privacy. All Rights reserved. // // 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. #pragma once #include "gui/content_widget/content_widget.h" #include "gui/graph_widget/contexts/graph_context.h" #include "gui/graph_widget/graph_widget.h" #include "gui/graph_widget/graphics_scene.h" #include <QMap> class QTabWidget; class QVBoxLayout; namespace hal { class SettingsItemDropdown; class SettingsItemKeybind; /** * @ingroup graph * @brief A ContentWidget that holds all GraphWidget objects (GraphView) as tabs of a QTabWidget. */ class GraphTabWidget : public ContentWidget { Q_OBJECT public: enum GraphCursor { Select, PickModule, PickGate }; /** * Constructor. * * @param parent - The parent widget. */ GraphTabWidget(QWidget* parent = nullptr); /** * Create and register all shortcuts associated with the graph tab widget. * * @returns the list of shortcuts. */ virtual QList<QShortcut*> createShortcuts() override; /** * Add a QWidget as a tab to the QTabWidget. * * @param tab - The wiget to add * @param tab_name - The title of the tab * @returns the index of the new tab within the QTabWidget */ int addTab(QWidget* tab, QString tab_name = "default"); /** * Shows a certain GraphContext. If there is already a tab showing the context it is selected. Otherwise, a new * tab with a graph widget tab for this context is created and selected. * * @param context - The GraphContext to show */ void showContext(GraphContext* context); /** * Moves (and scales) the camera in the current GraphWidget to the current selection so that every selected * GraphicsItem can be seen. */ void ensureSelectionVisible(); /** * returns whether shape of cursor has been changed to indicate pick-select-module mode */ GraphCursor selectCursor() const { return mSelectCursor; } enum KeyboardModifier{Alt, Ctrl, Shift}; Q_ENUM(KeyboardModifier) public Q_SLOTS: /** * Q_SLOT that should be called whenever a new GraphContext was created. It is used to show the new context in * a new tab. * * @param context - The new context */ void handleContextCreated(GraphContext* context); /** * Q_SLOT that should be called whenever a GraphContext was renamed. It is used to rename the associated tab. * * @param context - The renamed context */ void handleContextRenamed(GraphContext* context); /** * Q_SLOT that should be called whenever a GraphContext is about to be removed. * It is used to close the associated tab. * * @param context - The context that will be removed. */ void handleContextRemoved(GraphContext* context); /** * * @param index - The index of the tab within the QTabWidget */ void handleTabChanged(int index); /** * Q_SLOT that should be called whenever the focus is set to a gate. Used to show the focused gate in the * GraphWidget. * * @param gateId - The id of the gate in focus. */ void handleGateFocus(u32 gateId); /** * Q_SLOT that should be called whenever the focus is set to a net. Used to show the focused net in the * GraphWidget. * * @param netId - The id of the net in focus. */ void handleNetFocus(u32 netId); /** * Q_SLOT that should be called whenever the focus is set to a module. Used to show the focused module in the * GraphWidget. * * @param moduleId - The id of the module in focus. */ void handleModuleFocus(u32 moduleId); /** * Q_SLOT that should be called whenever a tab is rightclicked. * * @param pos - Mouse position as QPoint. */ void handleCustomContextMenuRequested(const QPoint &pos); /** * Change shape of cursor to indicate that a module or gate should be picked by user. * Possible values are provided by GraphCursor enumeration. * * @param icurs - 0 = standard select, 1 = module pick, 2 = gate pick */ void setSelectCursor(int icurs); /** * Q_SLOT to close a single tab. * * @param index - The index of the tab within the QTabWidget */ void handleTabCloseRequested(int index); /** * Q_SLOT to close all tabs which are right to the right-clicked. * * @param index - The index of the right-clicked tab within the QTabWidget */ void handleCloseTabsToRight(int index); /** * Q_SLOT to close all tabs which are left to the right-clicked. * * @param index - The index of the right-clicked tab within the QTabWidget */ void handleCloseTabsToLeft(int index); /** * Q_SLOT to close all tabs. */ void handleCloseAllTabs(); private: QTabWidget* mTabWidget; QVBoxLayout* mLayout; float mZoomFactor; QMap<GraphContext*, QWidget*> mContextWidgetMap; int getContextTabIndex(GraphContext* context) const; void addGraphWidgetTab(GraphContext* context); void zoomInShortcut(); void zoomOutShortcut(); static SettingsItemDropdown* sSettingGridType; static SettingsItemDropdown* sSettingDragModifier; static SettingsItemDropdown* sSettingPanModifier; static SettingsItemKeybind* sSettingZoomIn; static SettingsItemKeybind* sSettingZoomOut; static bool sSettingsInitialized; static bool initSettings(); QMap<KeyboardModifier, Qt::KeyboardModifier> mKeyModifierMap; GraphCursor mSelectCursor; }; }
2,845
1,895
<reponame>a759389099/mybatis-plus-samples<filename>mybatis-plus-sample-resultmap/src/main/java/com/baomidou/mybatisplus/samples/resultmap/mapper/ManMapper.java package com.baomidou.mybatisplus.samples.resultmap.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.samples.resultmap.entity.Man; /** * @author miemie * @since 2019-11-27 */ public interface ManMapper extends BaseMapper<Man> { Man selectLinkById(Long id); }
186
3,976
<filename>NKUCodingCat/0006/0006.py<gh_stars>1000+ #coding=utf-8 #拿以前代码改的 import re,sys,os path = os.path.split(os.path.realpath(__file__))[0]+"/" Fliter = re.compile("[^A-Za-z-\']|((?<![A-Za-z])[-\'])|([-\'](?![A-Za-z]))") Divider = re.compile("\s") File = open(path+"list.txt").read() ex = re.split("[\r\n]",File) ex.append(" ") ex.append("") ex = list(set(ex)) def Stat(input): Dict = {} File = open(input).read() Data = Divider.split(Fliter.sub(" ",File)) for i in Data: j = i.lower() try: Dict[j]+=1 except KeyError: Dict[j] =1 except: raise for i in ex: j = i.lower() try: del(Dict[j]) except KeyError: pass except: raise return sorted(Dict.items(),key = lambda i:i[1],reverse=True)[0][0] ls = os.listdir(path+"src/") for i in ls: print i,Stat(path+"src/"+i)
416
3,442
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.slick.protocol.generic; import net.java.sip.communicator.service.protocol.*; /** * A very simple straight forward implementation of a security authority * that would always return the same password (the one specified upon * construction) when asked for credentials. */ public class SecurityAuthorityImpl implements SecurityAuthority { /** * The password to return when asked for credentials */ private char[] passwd = null; private boolean isUserNameEditable = false; /** * Creates an instance of this class that would always return "passwd" * when asked for credentials. * * @param passwd the password that this class should return when * asked for credentials. */ public SecurityAuthorityImpl(char[] passwd) { this.passwd = passwd; } /** * Returns a Credentials object associated with the specified realm. * <p> * @param realm The realm that the credentials are needed for. * @param defaultValues the values to propose the user by default * @return The credentials associated with the specified realm or null * if none could be obtained. */ public UserCredentials obtainCredentials(String realm, UserCredentials defaultValues) { defaultValues.setPassword(passwd); return defaultValues; } /** * Returns a Credentials object associated with the specified realm. * <p> * @param realm The realm that the credentials are needed for. * @param defaultValues the values to propose the user by default * @param reasonCode the reason for which we're obtaining the * credentials. * @return The credentials associated with the specified realm or null * if none could be obtained. */ public UserCredentials obtainCredentials(String realm, UserCredentials defaultValues, int reasonCode) { return obtainCredentials(realm, defaultValues); } /** * Sets the userNameEditable property, which should indicate if the * user name could be changed by user or not. * * @param isUserNameEditable indicates if the user name could be changed */ public void setUserNameEditable(boolean isUserNameEditable) { this.isUserNameEditable = isUserNameEditable; } /** * Indicates if the user name is currently editable, i.e. could be changed * by user or not. * * @return <code>true</code> if the user name could be changed, * <code>false</code> - otherwise. */ public boolean isUserNameEditable() { return isUserNameEditable; } }
1,202
2,023
""" Small scanf-implementation. Python has powerful regular expressions but sometimes they are totally overkill when you just want to parse a simple-formatted string. C programmers use the scanf-function for these tasks (see link below). This implementation of scanf translates the simple scanf-format into regular expressions. Unlike C you can be sure that there are no buffer overflows possible. For more information see * http://www.python.org/doc/current/lib/node49.html * http://en.wikipedia.org/wiki/Scanf """ import re import sys __all__ = ["scanf"] DEBUG = False # As you can probably see it is relatively easy to add more format types scanf_translate = [ (re.compile(_token), _pattern, _cast) for _token, _pattern, _cast in [ ("%c", "(.)", lambda x:x), ("%(\d)c", "(.{%s})", lambda x:x), ("%(\d)[di]", "([+-]?\d{%s})", int), ("%[di]", "([+-]?\d+)", int), ("%u", "(\d+)", int), ("%[fgeE]", "(\d+\.\d+)", float), ("%s", "(\S+)", lambda x:x), ("%([xX])", "(0%s[\dA-Za-f]+)", lambda x:int(x, 16)), ("%o", "(0[0-7]*)", lambda x:int(x, 7)), ]] # Cache formats SCANF_CACHE_SIZE = 1000 scanf_cache = {} def _scanf_compile(format): """ This is an internal function which translates the format into regular expressions For example: >>> format_re, casts = _scanf_compile('%s - %d errors, %d warnings') >>> print format_re.pattern (\S+) \- ([+-]?\d+) errors, ([+-]?\d+) warnings Translated formats are cached for faster use """ compiled = scanf_cache.get(format) if compiled: return compiled format_pat = "" cast_list = [] i = 0 length = len(format) while i < length: found = None for token, pattern, cast in scanf_translate: found = token.match(format, i) if found: cast_list.append(cast) groups = found.groupdict() or found.groups() if groups: pattern = pattern % groups format_pat += pattern i = found.end() break if not found: char = format[i] # escape special characters if char in "()[]-.+*?{}<>\\": format_pat += "\\" format_pat += char i += 1 if DEBUG: print "DEBUG: %r -> %s" % (format, format_pat) format_re = re.compile(format_pat) if len(scanf_cache) > SCANF_CACHE_SIZE: scanf_cache.clear() scanf_cache[format] = (format_re, cast_list) return format_re, cast_list def scanf(format, s=None): """ scanf supports the following formats: %c One character %5c 5 characters %d int value %7d int value with length 7 %f float value %o octal value %X, %x hex value %s string terminated by whitespace Examples: >>> scanf("%s - %d errors, %d warnings", "/usr/sbin/sendmail - 0 errors, 4 warnings") ('/usr/sbin/sendmail', 0, 4) >>> scanf("%o %x %d", "0123 0x123 123") (66, 291, 123) If the parameter s is a file-like object, s.readline is called. If s is not specified, stdin is assumed. The function returns a tuple of found values or None if the format does not match. """ if s == None: s = sys.stdin if hasattr(s, "readline"): s = s.readline() format_re, casts = _scanf_compile(format) found = format_re.match(s) if found: groups = found.groups() return tuple([casts[i](groups[i]) for i in range(len(groups))]) if __name__ == "__main__": import doctest doctest.testmod(verbose=True, report=True)
1,617
423
<filename>pysen/process_utils.py import contextlib import logging import subprocess import sys from concurrent.futures import ThreadPoolExecutor from typing import IO, List, Optional, Sequence, Tuple from .reporter import Reporter def _read_stream(stream: IO[str], reporter: Reporter, loglevel: int) -> str: ret: List[str] = [] for line in stream: ret.append(line) reporter.process_output.log(loglevel, line.rstrip("\n")) return "".join(ret) def add_python_executable(*cmd: str) -> Sequence[str]: return [sys.executable, "-m"] + list(cmd) def run( cmd: Sequence[str], reporter: Reporter, stdout_loglevel: int = logging.INFO, stderr_loglevel: int = logging.WARNING, encoding: Optional[str] = None, ) -> Tuple[int, str, str]: # NOTE: As pysen doesn't configure `sys.stdout` with `errors=ignore` option, # it may cause an error when unsupported characters in an environment are # going to be printed. # As such, `run` method returns strings of printable characters in the environment # so that pysen doesn't need to reconfigure `sys.stdout`. encoding = encoding or sys.stdout.encoding returncode: int = -1 stdout: str = "" stderr: str = "" with contextlib.ExitStack() as stack: reporter.report_command(" ".join(cmd)) proc = stack.enter_context( subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding=encoding, universal_newlines=True, errors="ignore", ) ) try: pool = stack.enter_context(ThreadPoolExecutor(max_workers=2)) stdout_task = pool.submit( _read_stream, proc.stdout, reporter, stdout_loglevel ) stderr_task = pool.submit( _read_stream, proc.stderr, reporter, stderr_loglevel ) proc.wait() stdout = stdout_task.result() stderr = stderr_task.result() returncode = proc.returncode except Exception: proc.kill() raise return returncode, stdout, stderr
967
2,035
package org.splitbrain.giraffe; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.net.MalformedURLException; import java.net.URL; public class OptionsActivity extends Activity { Context context; SharedPreferences prefs; EventLoader eventloader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.options); this.context = this; prefs = PreferenceManager.getDefaultSharedPreferences(this); resetLayout(); // attach Event listeners Button btn_refresh = (Button) findViewById(R.id.opt_btn_refresh); btn_refresh.setOnClickListener(click_refresh); Button btn_cancel = (Button) findViewById(R.id.opt_btn_cancel); btn_cancel.setOnClickListener(click_cancel); Button btn_barcode = (Button) findViewById(R.id.opt_btn_barcode); btn_barcode.setOnClickListener(click_barcode); } public void resetLayout() { // set URL field from intent or preferences EditText txturl = (EditText) findViewById(R.id.opt_txt_url); Uri intenturl = getIntent().getData(); if (intenturl != null) { txturl.setText(intenturl.toString().replaceAll("^webcal://", "http://")); } else { txturl.setText(prefs.getString("url", "")); } // hide progress panel LinearLayout ll = (LinearLayout) findViewById(R.id.opt_panel_running); ll.setVisibility(View.GONE); // empty output TextView txtprg = (TextView) findViewById(R.id.opt_txt_progress); txtprg.setText(""); // show refresh button Button btn_refresh = (Button) findViewById(R.id.opt_btn_refresh); btn_refresh.setVisibility(View.VISIBLE); Button btn_barcode = (Button) findViewById(R.id.opt_btn_barcode); btn_barcode.setVisibility(View.VISIBLE); } public void writeProgress(String text) { TextView txtprg = (TextView) findViewById(R.id.opt_txt_progress); txtprg.setText(text); } private final OnClickListener click_cancel = new OnClickListener() { public void onClick(View v) { eventloader.cancel(false); } }; private final OnClickListener click_barcode = new OnClickListener() { public void onClick(View v) { Intent barcodeScanner = new Intent("com.google.zxing.client.android.SCAN"); barcodeScanner.putExtra("FORMATS", "QR_CODE,DATA_MATRIX"); // See if we have the zxing app installed. If we do, we handle the results of this later. try { startActivityForResult(barcodeScanner, 0); } // if the app isn't installed, we ask if we can download it catch (ActivityNotFoundException e) { AlertDialog.Builder notFoundBuilder = new AlertDialog.Builder(context); notFoundBuilder.setMessage(R.string.opt_zxing_text) .setTitle(R.string.opt_zxing_title) .setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { // if so, get it from the market... Intent getApp = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_market_zxing))); startActivity(getApp); } // ...or from the website if we don't have the Market catch (ActivityNotFoundException e) { Intent getAppAlt = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_web_zxing))); startActivity(getAppAlt); } } }) .setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); notFoundBuilder.show(); } } }; private final OnClickListener click_refresh = new OnClickListener() { public void onClick(View v) { // check if URL was set EditText txturl = (EditText) findViewById(R.id.opt_txt_url); String url = txturl.getText().toString().trim(); if (url.length() == 0) { Toast toast = Toast.makeText(context, R.string.opt_error_no_url, Toast.LENGTH_SHORT); toast.show(); return; } URL link; try { link = new URL(url); } catch (MalformedURLException e) { Toast toast = Toast.makeText(context, R.string.opt_error_bad_url, Toast.LENGTH_SHORT); toast.show(); return; } // save the URL Editor edit = prefs.edit(); edit.putString("url", url); edit.commit(); // hide the buttons v.setVisibility(View.GONE); Button btn_barcode = (Button) findViewById(R.id.opt_btn_barcode); btn_barcode.setVisibility(View.GONE); // show the progress LinearLayout ll = (LinearLayout) findViewById(R.id.opt_panel_running); ll.setVisibility(View.VISIBLE); eventloader = new EventLoader(OptionsActivity.this); eventloader.setIgnoreSSLCerts(((CheckBox) findViewById(R.id.opt_ignoressl)).isChecked()); eventloader.execute(link); } }; // This is the callback that handles barcode scans. @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // First, check to see if the scanner returned successfully if (resultCode == RESULT_OK) { // now, we see if there's any barcode data... String barcodeText = data.getStringExtra("SCAN_RESULT"); if (!barcodeText.equals("")) { // Success! Now to fill in the new URL. The user still needs to press the load button to commit it. EditText txturl = (EditText) findViewById(R.id.opt_txt_url); txturl.setText(barcodeText); Toast toast = Toast.makeText(context, R.string.opt_barcode_ok, Toast.LENGTH_SHORT); toast.show(); } else { // No barcode data was found. Bizarre, but the user should know. Toast toast = Toast.makeText(context, R.string.opt_barcode_fail, Toast.LENGTH_SHORT); toast.show(); } } else if (resultCode != RESULT_CANCELED) { // If the user didn't back out of the app and we've arrived here, something's gone wrong. Toast toast = Toast.makeText(context, R.string.opt_barcode_fail, Toast.LENGTH_SHORT); toast.show(); } } }
3,664
892
<filename>advisories/unreviewed/2022/05/GHSA-r338-g5vj-mxfp/GHSA-r338-g5vj-mxfp.json { "schema_version": "1.2.0", "id": "GHSA-r338-g5vj-mxfp", "modified": "2022-05-13T01:14:47Z", "published": "2022-05-13T01:14:47Z", "aliases": [ "CVE-2019-1754" ], "details": "A vulnerability in the authorization subsystem of Cisco IOS XE Software could allow an authenticated but unprivileged (level 1), remote attacker to run privileged Cisco IOS commands by using the web UI. The vulnerability is due to improper validation of user privileges of web UI users. An attacker could exploit this vulnerability by submitting a malicious payload to a specific endpoint in the web UI. A successful exploit could allow the lower-privileged attacker to execute arbitrary commands with higher privileges on the affected device.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1754" }, { "type": "WEB", "url": "https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190327-iosxe-privesc" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/107590" } ], "database_specific": { "cwe_ids": [ "CWE-269" ], "severity": "HIGH", "github_reviewed": false } }
592
852
/// /// \class l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1 /// /// \author: <NAME> /// /// Description: first iteration of stage 2 jet algo #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "L1Trigger/L1TCalorimeter/interface/Stage2Layer2EGammaAlgorithmFirmware.h" #include "L1Trigger/L1TCalorimeter/interface/CaloStage2Nav.h" #include "L1Trigger/L1TCalorimeter/interface/CaloTools.h" #include "L1Trigger/L1TCalorimeter/interface/BitonicSort.h" #include "L1Trigger/L1TCalorimeter/interface/AccumulatingSort.h" namespace l1t { bool operator>(const l1t::EGamma& a, const l1t::EGamma& b) { return a.pt() > b.pt(); } } // namespace l1t /*****************************************************************/ l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::Stage2Layer2EGammaAlgorithmFirmwareImp1(CaloParamsHelper const* params) : params_(params) /*****************************************************************/ {} /*****************************************************************/ void l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::processEvent(const std::vector<l1t::CaloCluster>& clusters, const std::vector<l1t::CaloTower>& towers, std::vector<l1t::EGamma>& egammas) /*****************************************************************/ { l1t::CaloStage2Nav caloNav; egammas.clear(); //EGammas without check of FG and shape ID std::vector<l1t::EGamma> egammas_raw; for (const auto& cluster : clusters) { // Keep only valid clusters if (cluster.isValid()) { // need tower energies to recompute egamma trimmed energy int iEta = cluster.hwEta(); int iPhi = cluster.hwPhi(); int iEtaP = caloNav.offsetIEta(iEta, 1); int iEtaM = caloNav.offsetIEta(iEta, -1); int iPhiP = caloNav.offsetIPhi(iPhi, 1); int iPhiP2 = caloNav.offsetIPhi(iPhi, 2); int iPhiM = caloNav.offsetIPhi(iPhi, -1); int iPhiM2 = caloNav.offsetIPhi(iPhi, -2); const l1t::CaloTower& seed = l1t::CaloTools::getTower(towers, iEta, iPhi); const l1t::CaloTower& towerNW = l1t::CaloTools::getTower(towers, iEtaM, iPhiM); const l1t::CaloTower& towerN = l1t::CaloTools::getTower(towers, iEta, iPhiM); const l1t::CaloTower& towerNE = l1t::CaloTools::getTower(towers, iEtaP, iPhiM); const l1t::CaloTower& towerE = l1t::CaloTools::getTower(towers, iEtaP, iPhi); const l1t::CaloTower& towerSE = l1t::CaloTools::getTower(towers, iEtaP, iPhiP); const l1t::CaloTower& towerS = l1t::CaloTools::getTower(towers, iEta, iPhiP); const l1t::CaloTower& towerSW = l1t::CaloTools::getTower(towers, iEtaM, iPhiP); const l1t::CaloTower& towerW = l1t::CaloTools::getTower(towers, iEtaM, iPhi); const l1t::CaloTower& towerNN = l1t::CaloTools::getTower(towers, iEta, iPhiM2); const l1t::CaloTower& towerSS = l1t::CaloTools::getTower(towers, iEta, iPhiP2); // int seedEt = seed.hwPt(); int towerEtNW = towerNW.hwPt(); int towerEtN = towerN.hwPt(); int towerEtNE = towerNE.hwPt(); int towerEtE = towerE.hwPt(); int towerEtSE = towerSE.hwPt(); int towerEtS = towerS.hwPt(); int towerEtSW = towerSW.hwPt(); int towerEtW = towerW.hwPt(); int towerEtNN = towerNN.hwPt(); int towerEtSS = towerSS.hwPt(); if (abs(iEta) > params_->egEtaCut()) continue; // initialize egamma from cluster egammas_raw.push_back(cluster); l1t::EGamma& egamma = egammas_raw.back(); // Trim cluster (only for egamma energy computation, the original cluster is unchanged) l1t::CaloCluster clusterTrim = trimCluster(cluster); // Recompute hw energy (of the trimmed cluster) from towers egamma.setHwPt(seedEt); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NW)) egamma.setHwPt(egamma.hwPt() + towerEtNW); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_N)) egamma.setHwPt(egamma.hwPt() + towerEtN); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NE)) egamma.setHwPt(egamma.hwPt() + towerEtNE); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_E)) egamma.setHwPt(egamma.hwPt() + towerEtE); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SE)) egamma.setHwPt(egamma.hwPt() + towerEtSE); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_S)) egamma.setHwPt(egamma.hwPt() + towerEtS); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SW)) egamma.setHwPt(egamma.hwPt() + towerEtSW); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_W)) egamma.setHwPt(egamma.hwPt() + towerEtW); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NN)) egamma.setHwPt(egamma.hwPt() + towerEtNN); if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SS)) egamma.setHwPt(egamma.hwPt() + towerEtSS); //Extended H/E flag computed using all neighbouring towers bool HoE_ext = idHoverE_ext(seed); HoE_ext &= idHoverE_ext(towerNW); HoE_ext &= idHoverE_ext(towerN); HoE_ext &= idHoverE_ext(towerNE); HoE_ext &= idHoverE_ext(towerE); HoE_ext &= idHoverE_ext(towerSE); HoE_ext &= idHoverE_ext(towerS); HoE_ext &= idHoverE_ext(towerSW); HoE_ext &= idHoverE_ext(towerW); //NN and SS only checked if included if (cluster.checkClusterFlag(CaloCluster::INCLUDE_NN)) HoE_ext &= idHoverE_ext(towerNN); if (cluster.checkClusterFlag(CaloCluster::INCLUDE_SS)) HoE_ext &= idHoverE_ext(towerSS); // Identification of the egamma // Based on the seed tower FG bit, the H/E ratio of the seed tower, and the shape of the cluster bool hOverEBit = cluster.hOverE() > 0 || params_->egBypassHoE(); bool hOverEExtBit = HoE_ext || params_->egBypassExtHOverE(); if (!params_->egBypassExtHOverE()) hOverEExtBit = HoE_ext; bool shapeBit = idShape(cluster, egamma.hwPt()) || params_->egBypassShape(); bool fgBit = !(cluster.fgECAL()) || params_->egBypassECALFG(); int qual = 0; if (fgBit) qual |= (0x1); // first bit = FG if (hOverEBit) qual |= (0x1 << 1); // second bit = H/E if (shapeBit) qual |= (0x1 << 2); // third bit = shape if (hOverEExtBit) qual |= (0x1 << 3); // fourth bit = shape egamma.setHwQual(qual); // Isolation int isoLeftExtension = params_->egIsoAreaNrTowersEta(); int isoRightExtension = params_->egIsoAreaNrTowersEta(); if (cluster.checkClusterFlag(CaloCluster::TRIM_LEFT)) isoRightExtension++; else isoLeftExtension++; int hwEtSum = CaloTools::calHwEtSum(cluster.hwEta(), cluster.hwPhi(), towers, -isoLeftExtension, isoRightExtension, -1 * params_->egIsoAreaNrTowersPhi(), params_->egIsoAreaNrTowersPhi(), params_->egPUSParam(2)); int hwFootPrint = isoCalEgHwFootPrint(cluster, towers); int nrTowers = CaloTools::calNrTowers(-1 * params_->egPUSParam(1), params_->egPUSParam(1), 1, 72, towers, 1 + params_->pileUpTowerThreshold(), 999, CaloTools::CALO); unsigned int lutAddress = isoLutIndex(egamma.hwEta(), nrTowers, egamma.hwPt()); int isolBit = (((hwEtSum - hwFootPrint) < params_->egIsolationLUT()->data(lutAddress)) || (params_->egIsolationLUT()->data(lutAddress) > 255)); int isolBit2 = (((hwEtSum - hwFootPrint) < params_->egIsolationLUT2()->data(lutAddress)) || (params_->egIsolationLUT2()->data(lutAddress) > 255)); isolBit += (isolBit2 << 1); egamma.setHwIso(isolBit); int hwIsoEnergy = hwEtSum - hwFootPrint; // development vars egamma.setTowerIPhi((short int)cluster.hwPhi()); egamma.setTowerIEta((short int)cluster.hwEta()); egamma.setRawEt((short int)egamma.hwPt()); egamma.setIsoEt((short int)hwIsoEnergy); egamma.setFootprintEt((short int)hwFootPrint); egamma.setNTT((short int)nrTowers); egamma.setShape((short int)returnShape(cluster)); egamma.setTowerHoE((short int)returnHoE(seed)); // Energy calibration // Corrections function of ieta, ET, and cluster shape int calibPt = calibratedPt(cluster, egamma.hwPt()); egamma.setHwPt(calibPt); // Physical eta/phi. Computed from ieta/iphi of the seed tower and the fine-grain position within the seed double eta = 0.; double phi = 0.; double seedEta = CaloTools::towerEta(cluster.hwEta()); double seedEtaSize = CaloTools::towerEtaSize(cluster.hwEta()); double seedPhi = CaloTools::towerPhi(cluster.hwEta(), cluster.hwPhi()); double seedPhiSize = CaloTools::towerPhiSize(cluster.hwEta()); if (cluster.fgEta() == 0) eta = seedEta; // center //Test else if (cluster.fgEta() == 2) eta = seedEta + seedEtaSize * 0.251; // center + 1/4 else if (cluster.fgEta() == 1) eta = seedEta - seedEtaSize * 0.251; // center - 1/4 //fgPhi is recomputed after trimming int fgPhi = 0; int EtUp = 0; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NE)) EtUp += towerEtNE; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_N)) EtUp += towerEtN; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NW)) EtUp += towerEtNW; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NN)) EtUp += towerEtNN; int EtDown = 0; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SE)) EtDown += towerEtSE; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_S)) EtDown += towerEtS; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SW)) EtDown += towerEtSW; if (clusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SS)) EtDown += towerEtSS; // if (EtDown > EtUp) fgPhi = 2; else if (EtUp > EtDown) fgPhi = 1; if (fgPhi == 0) phi = seedPhi; // center else if (fgPhi == 2) phi = seedPhi + seedPhiSize * 0.251; // center + 1/4 else if (fgPhi == 1) phi = seedPhi - seedPhiSize * 0.251; // center - 1/4 // Set 4-vector math::PtEtaPhiMLorentzVector calibP4((double)calibPt * params_->egLsb(), eta, phi, 0.); egamma.setP4(calibP4); } //end of cuts on cluster to make EGamma } //end of cluster loop // prepare content to be sorted -- each phi ring contains 18 elements, with Et = 0 if no candidate exists math::PtEtaPhiMLorentzVector emptyP4; l1t::EGamma tempEG(emptyP4, 0, 0, 0, 0); std::vector<std::vector<l1t::EGamma> > egEtaPos(params_->egEtaCut(), std::vector<l1t::EGamma>(18, tempEG)); std::vector<std::vector<l1t::EGamma> > egEtaNeg(params_->egEtaCut(), std::vector<l1t::EGamma>(18, tempEG)); for (unsigned int iEG = 0; iEG < egammas_raw.size(); iEG++) { int fgBit = egammas_raw.at(iEG).hwQual() & (0x1); int hOverEBit = egammas_raw.at(iEG).hwQual() >> 1 & (0x1); int shapeBit = egammas_raw.at(iEG).hwQual() >> 2 & (0x1); int hOverEExtBit = egammas_raw.at(iEG).hwQual() >> 3 & (0x1); bool IDcuts = (fgBit && hOverEBit && shapeBit && hOverEExtBit) || (egammas_raw.at(iEG).pt() >= params_->egMaxPtHOverE()) || (params_->egBypassEGVetos()); if (!IDcuts) continue; egammas_raw.at(iEG).setHwQual(7); //Default value in firmware, not used if (egammas_raw.at(iEG).hwEta() > 0) egEtaPos.at(egammas_raw.at(iEG).hwEta() - 1).at((72 - egammas_raw.at(iEG).hwPhi()) / 4) = egammas_raw.at(iEG); else egEtaNeg.at(-(egammas_raw.at(iEG).hwEta() + 1)).at((72 - egammas_raw.at(iEG).hwPhi()) / 4) = egammas_raw.at(iEG); } AccumulatingSort<l1t::EGamma> etaPosSorter(6); AccumulatingSort<l1t::EGamma> etaNegSorter(6); std::vector<l1t::EGamma> accumEtaPos; std::vector<l1t::EGamma> accumEtaNeg; for (int ieta = 0; ieta < params_->egEtaCut(); ++ieta) { // eta + std::vector<l1t::EGamma>::iterator start_, end_; start_ = egEtaPos.at(ieta).begin(); end_ = egEtaPos.at(ieta).end(); BitonicSort<l1t::EGamma>(down, start_, end_); etaPosSorter.Merge(egEtaPos.at(ieta), accumEtaPos); // eta - start_ = egEtaNeg.at(ieta).begin(); end_ = egEtaNeg.at(ieta).end(); BitonicSort<l1t::EGamma>(down, start_, end_); etaNegSorter.Merge(egEtaNeg.at(ieta), accumEtaNeg); } // put all 12 candidates in the original tau vector, removing zero energy ones egammas.clear(); for (const l1t::EGamma& acceg : accumEtaPos) { if (acceg.hwPt() > 0) egammas.push_back(acceg); } for (const l1t::EGamma& acceg : accumEtaNeg) { if (acceg.hwPt() > 0) egammas.push_back(acceg); } } /*****************************************************************/ bool l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::idShape(const l1t::CaloCluster& clus, int hwPt) /*****************************************************************/ { unsigned int shape = 0; if ((clus.checkClusterFlag(CaloCluster::INCLUDE_N))) shape |= (0x1); if ((clus.checkClusterFlag(CaloCluster::INCLUDE_S))) shape |= (0x1 << 1); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_E))) shape |= (0x1 << 2); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_W))) shape |= (0x1 << 2); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NE))) shape |= (0x1 << 3); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NW))) shape |= (0x1 << 3); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SE))) shape |= (0x1 << 4); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SW))) shape |= (0x1 << 4); if (clus.checkClusterFlag(CaloCluster::INCLUDE_NN)) shape |= (0x1 << 5); if (clus.checkClusterFlag(CaloCluster::INCLUDE_SS)) shape |= (0x1 << 6); unsigned int lutAddress = idShapeLutIndex(clus.hwEta(), hwPt, shape); bool shapeBit = ((params_->egCalibrationLUT()->data(lutAddress)) >> 9) & 0x1; return shapeBit; } /*****************************************************************/ unsigned int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::idShapeLutIndex(int iEta, int E, int shape) /*****************************************************************/ { if (params_->egShapeIdType() == "compressed") { unsigned int iEtaNormed = abs(iEta); if (iEtaNormed > 28) iEtaNormed = 28; if (E > 255) E = 255; unsigned int compressedShape = params_->egCompressShapesLUT()->data(shape); unsigned int compressedE = params_->egCompressShapesLUT()->data((0x1 << 7) + E); unsigned int compressedEta = params_->egCompressShapesLUT()->data((0x1 << 7) + (0x1 << 8) + iEtaNormed); return (compressedShape | compressedE | compressedEta); } else // Uncompressed (kept for backward compatibility) { unsigned int iEtaNormed = abs(iEta); if (iEtaNormed > 28) iEtaNormed = 28; if (E > 255) E = 255; unsigned int compressedShape = params_->egCompressShapesLUT()->data(shape); return E + compressedShape * 256 + (iEtaNormed - 1) * 256 * 64; } } //calculates the footprint of the electron in hardware values /*****************************************************************/ int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::isoCalEgHwFootPrint(const l1t::CaloCluster& clus, const std::vector<l1t::CaloTower>& towers) /*****************************************************************/ { int iEta = clus.hwEta(); int iPhi = clus.hwPhi(); // hwEmEtSumLeft = CaloTools::calHwEtSum(iEta,iPhi,towers,-1,-1,-1,1,CaloTools::ECAL); // int hwEmEtSumRight = CaloTools::calHwEtSum(iEta,iPhi,towers,1,1,-1,1,CaloTools::ECAL); int etaSide = clus.checkClusterFlag(CaloCluster::TRIM_LEFT) ? 1 : -1; //if we trimed left, its the right (ie +ve) side we want int phiSide = iEta > 0 ? 1 : -1; int ecalHwFootPrint = CaloTools::calHwEtSum(iEta, iPhi, towers, 0, 0, -1 * params_->egIsoVetoNrTowersPhi(), params_->egIsoVetoNrTowersPhi(), params_->egPUSParam(2), CaloTools::ECAL) + CaloTools::calHwEtSum(iEta, iPhi, towers, etaSide, etaSide, -1 * params_->egIsoVetoNrTowersPhi(), params_->egIsoVetoNrTowersPhi(), params_->egPUSParam(2), CaloTools::ECAL); //Because of compression E+H can be different from E + H int ecalHwFootPrint_2x1 = CaloTools::calHwEtSum(iEta, iPhi, towers, 0, 0, 0, 0, params_->egPUSParam(2), CaloTools::ECAL) + CaloTools::calHwEtSum(iEta, iPhi, towers, 0, 0, phiSide, phiSide, params_->egPUSParam(2), CaloTools::ECAL); int ecalhcal_HwFootPrint_2x1 = CaloTools::calHwEtSum(iEta, iPhi, towers, 0, 0, 0, 0, params_->egPUSParam(2)) + CaloTools::calHwEtSum(iEta, iPhi, towers, 0, 0, phiSide, phiSide, params_->egPUSParam(2)); return ecalHwFootPrint - ecalHwFootPrint_2x1 + ecalhcal_HwFootPrint_2x1; } //ieta =-28, nrTowers 0 is 0, increases to ieta28, nrTowers=kNrTowersInSum /*****************************************************************/ unsigned l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::isoLutIndex(int iEta, unsigned int nrTowers, int E) /*****************************************************************/ { if (params_->egIsolationType() == "compressed") { if (nrTowers > 255) nrTowers = 255; unsigned int iEtaNormed = abs(iEta); if (iEtaNormed > 28) iEtaNormed = 28; if (E > 255) E = 255; unsigned int compressednTT = params_->egCompressShapesLUT()->data((0x1 << 7) + (0x1 << 8) + (0x1 << 5) + nrTowers); unsigned int compressedE = params_->egCompressShapesLUT()->data((0x1 << 7) + E) << 1; unsigned int compressedEta = params_->egCompressShapesLUT()->data((0x1 << 7) + (0x1 << 8) + iEtaNormed) << 1; return (compressednTT | compressedE | compressedEta); } else // Uncompressed (kept for backward compatibility) { const unsigned int kNrTowersInSum = 72 * params_->egPUSParam(1) * 2; const unsigned int kTowerGranularity = params_->egPUSParam(0); const unsigned int kMaxAddress = kNrTowersInSum % kTowerGranularity == 0 ? (kNrTowersInSum / kTowerGranularity + 1) * 28 * 2 : (kNrTowersInSum / kTowerGranularity) * 28 * 2; unsigned int nrTowersNormed = nrTowers / kTowerGranularity; unsigned int iEtaNormed = iEta + 28; if (iEta > 0) iEtaNormed--; //we skip zero if (std::abs(iEta) > 28 || iEta == 0 || nrTowers > kNrTowersInSum) return kMaxAddress; else return iEtaNormed * (kNrTowersInSum / kTowerGranularity + 1) + nrTowersNormed; } } /*****************************************************************/ int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::calibratedPt(const l1t::CaloCluster& clus, int hwPt) /*****************************************************************/ { unsigned int shape = 0; if ((clus.checkClusterFlag(CaloCluster::INCLUDE_N))) shape |= (0x1); if ((clus.checkClusterFlag(CaloCluster::INCLUDE_S))) shape |= (0x1 << 1); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_E))) shape |= (0x1 << 2); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_W))) shape |= (0x1 << 2); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NE))) shape |= (0x1 << 3); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NW))) shape |= (0x1 << 3); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SE))) shape |= (0x1 << 4); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SW))) shape |= (0x1 << 4); if (clus.checkClusterFlag(CaloCluster::INCLUDE_NN)) shape |= (0x1 << 5); if (clus.checkClusterFlag(CaloCluster::INCLUDE_SS)) shape |= (0x1 << 6); unsigned int lutAddress = calibrationLutIndex(clus.hwEta(), hwPt, shape); int corr = params_->egCalibrationLUT()->data(lutAddress) & (0x1ff); // 9 bits. [0,2]. corrPt = (corr)*rawPt // the correction can increase or decrease the energy int rawPt = hwPt; int corrXrawPt = corr * rawPt; // 17 bits // round corr*rawPt int corrPt = corrXrawPt >> 8; // 8 MS bits (truncation) //12 bits saturation if (corrPt > 4095) corrPt = 4095; return corrPt; } /*****************************************************************/ unsigned int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::calibrationLutIndex(int iEta, int E, int shape) /*****************************************************************/ { if (params_->egCalibrationType() == "compressed") { unsigned int iEtaNormed = abs(iEta); if (iEtaNormed > 28) iEtaNormed = 28; if (E > 255) E = 255; unsigned int compressedShape = params_->egCompressShapesLUT()->data(shape); unsigned int compressedE = params_->egCompressShapesLUT()->data((0x1 << 7) + E); unsigned int compressedEta = params_->egCompressShapesLUT()->data((0x1 << 7) + (0x1 << 8) + iEtaNormed); return (compressedShape | compressedE | compressedEta); } else // Uncompressed (kept for backward compatibility) { unsigned int iEtaNormed = abs(iEta); if (iEtaNormed > 28) iEtaNormed = 28; if (E > 255) E = 255; if (E < 22) E = 22; unsigned int compressedShape = params_->egCompressShapesLUT()->data(shape); if (compressedShape > 31) compressedShape = 31; return (E - 20) + compressedShape * 236 + (iEtaNormed - 1) * 236 * 32; } } /*****************************************************************/ l1t::CaloCluster l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::trimCluster(const l1t::CaloCluster& clus) /*****************************************************************/ { l1t::CaloCluster clusCopy = clus; unsigned int shape = 0; if ((clus.checkClusterFlag(CaloCluster::INCLUDE_N))) shape |= (0x1); if ((clus.checkClusterFlag(CaloCluster::INCLUDE_S))) shape |= (0x1 << 1); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_E))) shape |= (0x1 << 2); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_W))) shape |= (0x1 << 2); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NE))) shape |= (0x1 << 3); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NW))) shape |= (0x1 << 3); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SE))) shape |= (0x1 << 4); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SW))) shape |= (0x1 << 4); if (clus.checkClusterFlag(CaloCluster::INCLUDE_NN)) shape |= (0x1 << 5); if (clus.checkClusterFlag(CaloCluster::INCLUDE_SS)) shape |= (0x1 << 6); unsigned int lutAddress = trimmingLutIndex(shape, clus.hwEta()); unsigned int shapeTrim = params_->egTrimmingLUT()->data(lutAddress); // apply trimming flags clusCopy.setClusterFlag(CaloCluster::INCLUDE_N, (shapeTrim & (0x1)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_S, (shapeTrim & (0x1 << 1)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_NN, (shapeTrim & (0x1 << 5)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_SS, (shapeTrim & (0x1 << 6)) ? true : false); if (clusCopy.checkClusterFlag(CaloCluster::TRIM_LEFT)) { clusCopy.setClusterFlag(CaloCluster::INCLUDE_E, (shapeTrim & (0x1 << 2)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_NE, (shapeTrim & (0x1 << 3)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_SE, (shapeTrim & (0x1 << 4)) ? true : false); } else { clusCopy.setClusterFlag(CaloCluster::INCLUDE_W, (shapeTrim & (0x1 << 2)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_NW, (shapeTrim & (0x1 << 3)) ? true : false); clusCopy.setClusterFlag(CaloCluster::INCLUDE_SW, (shapeTrim & (0x1 << 4)) ? true : false); } return clusCopy; } /*****************************************************************/ unsigned int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::trimmingLutIndex(unsigned int shape, int iEta) /*****************************************************************/ { unsigned int iEtaNormed = abs(iEta) - 1; if (iEtaNormed > 31) iEtaNormed = 31; if (shape > 127) shape = 127; unsigned int index = iEtaNormed * 128 + shape; return index; } /*****************************************************************/ unsigned int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::returnShape(const l1t::CaloCluster& clus) /*****************************************************************/ { unsigned int shape = 0; if ((clus.checkClusterFlag(CaloCluster::INCLUDE_N))) shape |= (0x1); if ((clus.checkClusterFlag(CaloCluster::INCLUDE_S))) shape |= (0x1 << 1); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_E))) shape |= (0x1 << 2); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_W))) shape |= (0x1 << 2); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NE))) shape |= (0x1 << 3); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_NW))) shape |= (0x1 << 3); if (clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SE))) shape |= (0x1 << 4); if (!clus.checkClusterFlag(CaloCluster::TRIM_LEFT) && (clus.checkClusterFlag(CaloCluster::INCLUDE_SW))) shape |= (0x1 << 4); if (clus.checkClusterFlag(CaloCluster::INCLUDE_NN)) shape |= (0x1 << 5); if (clus.checkClusterFlag(CaloCluster::INCLUDE_SS)) shape |= (0x1 << 6); return shape; } /*****************************************************************/ int l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::returnHoE(const l1t::CaloTower& tow) /*****************************************************************/ { int ratio = tow.hwEtRatio(); int qual = tow.hwQual(); bool denomZeroFlag = ((qual & 0x1) > 0); bool eOverHFlag = ((qual & 0x2) > 0); if (denomZeroFlag && !eOverHFlag) //E=0 ratio = -1; if (denomZeroFlag && eOverHFlag) //H=0 ratio = 8; // ratio is on 3 bits, so 8 should be ok for overflow if (!denomZeroFlag && !eOverHFlag) // H > E ratio = -1; //else E >= H , so ratio=log(E/H) return ratio; } bool l1t::Stage2Layer2EGammaAlgorithmFirmwareImp1::idHoverE_ext(const l1t::CaloTower tow) { int qual = tow.hwQual(); bool eOverHFlag = ((qual & 0x2) > 0); if (tow.hwPt() <= 10) return true; //Only applied for towers with ET>5 GeV else return eOverHFlag; }
13,299
347
<reponame>sp4cerat/Game-GUI<filename>src/Bmp.h<gh_stars>100-1000 /////////////////////////////////////////// #pragma once /////////////////////////////////////////// #include "core.h" #include "mathlib/Vector.h" #include <stdio.h> #include <stdlib.h> #include <string.h> //#include "error.h" /////////////////////////////////////////// #pragma comment(lib,"DevIL.lib") #pragma comment(lib,"ILU.lib") #pragma comment(lib,"ILUT.lib") /////////////////////////////////////////// class Bmp { public: Bmp(); Bmp(int x,int y,int bpp,unsigned char*data=0); Bmp(const char*filename, bool convert32=0); ~Bmp(); void load(const char*filename, bool convert32=0); void save(const char*filename); void set(int x,int y,int bpp,unsigned char*data); void crop(int x,int y,int x0=0,int y0=0); void scale(int x,int y); void blur(int count); void hblur(int count); void vblur(int count); void convert_24_32(); void save_float(const char*filename, float* fdata=0); bool load_float(const char*filename, float* fdata=0); void MakeBump() { int stride=bpp/8; std::vector<vec3f> normals;normals.resize(width*height); loopi(0,width)loopj(0,height) { float h =data[( i+j*width)*stride+0]; float hx=data[((i+2)%width+j*width)*stride+0]; float hy=data[( i+((j+2)%height)*width)*stride+0]; vec3f d1(64,0,hx-h); vec3f d2(0,64,hy-h); vec3f n;n.cross(d1,d2);n.norm(); normals[i+j*width]=n; } loopi(0,width)loopj(0,height) { vec3f n=normals[i+j*width]; data[(i+j*width)*stride+0] = n.x*127.5+127.5; data[(i+j*width)*stride+1] = n.y*127.5+127.5; data[(i+j*width)*stride+2] = n.z*127.5+127.5; } } void set_pixel(int x,int y,int r,int g,int b) { data[(x+y*width)*(bpp/8)+2]=r; data[(x+y*width)*(bpp/8)+1]=g; data[(x+y*width)*(bpp/8)+0]=b; } int get_pixel(int x,int y) { if(data.size()==0) error_stop("get_pixel data=0"); if(x>=width)return 0; if(y>=height)return 0; return data[(x+y*width)*(bpp/8)+0]+ data[(x+y*width)*(bpp/8)+1]*256+ data[(x+y*width)*(bpp/8)+2]*256*256; } vec3f get_pixel3f(int x,int y) { int color=get_pixel(x,y); float r=float(color&255)/255.0f; float g=float((color>>8)&255)/255.0f; float b=float((color>>16)&255)/255.0f; return vec3f(r,g,b); } void flip() { loopijk(0,0,0,width,height/2,bpp/8) { vswap( data[(i+j*width)*(bpp/8)+k], data[(i+(height-1-j)*width)*(bpp/8)+k] ); } } public: std::vector<uchar> data; int width; int height; int bpp; int tex_handle; };
1,203
777
<reponame>Sun-Joong/aifh /* * Artificial Intelligence for Humans * Volume 2: Nature Inspired Algorithms * Java Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * * Copyright 2014 by <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.evolutionary.score; import com.heatonresearch.aifh.learning.MLMethod; import com.heatonresearch.aifh.learning.score.ScoreFunction; import java.io.Serializable; /** * An empty score function. Simply returns zero as the score, always. */ public class EmptyScoreFunction implements ScoreFunction, Serializable { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override public double calculateScore(final MLMethod phenotype) { return 0; } /** * {@inheritDoc} */ @Override public boolean shouldMinimize() { return true; } }
528
1,144
<gh_stars>1000+ /* SPDX-License-Identifier: GPL-2.0+ */ /* * Copyright (C) 2009 Samsung Electrnoics * <NAME> <<EMAIL>> */ #ifndef _SYS_PROTO_H_ #define _SYS_PROTO_H_ u32 get_device_type(void); #endif
93
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/vr/model/toolbar_state.h" #include "chrome/browser/vr/test/constants.h" #include "chrome/browser/vr/test/ui_pixel_test.h" #include "components/toolbar/vector_icons.h" #include "testing/gtest/include/gtest/gtest.h" namespace vr { namespace { static const gfx::Transform kIdentity; } // namespace // TODO(crbug/771794): Test temporarily disabled on Windows because it crashes // on trybots. Fix before enabling Windows support. #if defined(OS_WIN) #define MAYBE(x) DISABLED_##x #else #define MAYBE(x) x #endif TEST_F(UiPixelTest, MAYBE(DrawVrBrowsingMode)) { // Set up scene. UiInitialState ui_initial_state; ui_initial_state.in_cct = false; ui_initial_state.in_web_vr = false; ui_initial_state.web_vr_autopresentation_expected = false; MakeUi(ui_initial_state, ToolbarState(GURL("https://example.com"), security_state::SECURE, &toolbar::kHttpsValidIcon, true, false)); // Draw UI. DrawUi(gfx::Vector3dF(0.0f, 0.0f, -1.0f), gfx::Point3F(0.5f, -0.5f, 0.0f), UiInputManager::ButtonState::UP, 1.0f, kIdentity, kIdentity, kPixelDaydreamProjMatrix); // Read pixels into SkBitmap. auto bitmap = SaveCurrentFrameBufferToSkBitmap(); EXPECT_TRUE(bitmap); } } // namespace vr
594
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.performance.cnd; import java.io.*; import java.util.*; import java.util.logging.*; import java.util.zip.*; import junit.framework.Assert; import org.openide.filesystems.*; import org.openide.util.*; import org.openide.util.lookup.*; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.api.project.ui.OpenProjects; /** * Utilities methods. * * @author <NAME> */ public class Utilities { /** * Prevent creation. */ private Utilities() { } /** * Unzip the file <code>f</code> to folder <code>destDir</code>. * * @param f file to unzip * @param destDir destination directory */ public static void unzip(File f, String destDir) { final int BUFFER = 2048; try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(f); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File dir = new File(destDir + '/' + entry.getName()); dir.mkdir(); } else { int count; byte contents[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(destDir + "/" + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(contents, 0, BUFFER)) != -1) { dest.write(contents, 0, count); } dest.flush(); dest.close(); } } zis.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Open project <code>projectName</code> located in <code>dir</code> * directory. * * @param projectName project name to open * @param dir project's enclosing directory * @return file-object representing project * @throws java.io.IOException when project cannot be opened */ public static FileObject openProject(String projectName, File dir) throws IOException { File projectsDir = FileUtil.normalizeFile(dir); FileObject projectsDirFO = FileUtil.toFileObject(projectsDir); FileObject projdir = projectsDirFO.getFileObject(projectName); Project p = ProjectManager.getDefault().findProject(projdir); OpenProjects.getDefault().open(new Project[]{p}, false); if (p == null) { throw new IOException("Project is not opened " + projectName); } return projdir; } public static class TestLkp extends ProxyLookup { private static TestLkp DEFAULT; public TestLkp() { Assert.assertNull(DEFAULT); DEFAULT = this; ClassLoader l = TestLkp.class.getClassLoader(); this.setLookups( new Lookup[] { Lookups.metaInfServices(l), Lookups.singleton(l) } ); } public static void setLookupsWrapper(Lookup... l) { DEFAULT.setLookups(l); } } public static interface ParameterSetter { void setParameters(); } public static class MyHandler extends Handler { private Map<String, Long> map = new HashMap<String, Long>(); @Override public void publish(LogRecord record) { Long data; if (record == null) { return; } for (Object o : record.getParameters()) { if (o instanceof Long) { data = (Long) o; map.put(record.getMessage(), data); } } } public Long get(String key) { return map.get(key); } @Override public void flush() { } @Override public void close() throws SecurityException { } } }
2,246
737
/* default_pipeline.h <NAME>, 26 February 2014 Copyright (c) 2014 Datacratic Inc. All rights reserved. */ namespace Datacratic { struct DefaultPipeline : public Pipeline { DefaultPipeline(); void run(); Connector * createConnector(IncomingPin * incoming, OutgoingPin * outgoing); private: struct State { DefaultPipeline * pipeline; int count; Block * block; }; struct DefaultConnector : public Connector { DefaultConnector(IncomingPin * incoming, OutgoingPin * outgoing); void push(); State * state; }; std::set<std::shared_ptr<DefaultConnector>> connectors; std::vector<Block *> ready; std::map<Block *, State> states; friend struct DefaultConnector; }; }
384
4,262
/* * 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.camel.component.vertx; import java.io.InputStream; import java.util.Map; import io.netty.buffer.Unpooled; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class VertxJsonObjectConverterTest extends CamelTestSupport { private static final String BODY = "{\"Hello\":\"World\"}"; @Test public void testBufferToJsonObject() { JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, Buffer.buffer(BODY)); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testStringToJsonObject() { JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, BODY); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testByteArrayToJsonObject() { JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, BODY.getBytes()); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testByteBufToJsonObject() { JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, Unpooled.wrappedBuffer(BODY.getBytes())); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testMapArrayToJsonObject() { JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, new JsonObject(BODY).getMap()); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testInputStreamToJsonObject() { InputStream inputStream = context.getTypeConverter().convertTo(InputStream.class, BODY); JsonObject jsonObject = context.getTypeConverter().convertTo(JsonObject.class, inputStream); Assertions.assertEquals(BODY, jsonObject.toString()); } @Test public void testJsonObjectToBuffer() { Buffer result = context.getTypeConverter().convertTo(Buffer.class, Buffer.buffer(BODY).toJsonObject()); Assertions.assertEquals(BODY, result.toString()); } @Test public void testJsonObjectToString() { String result = context.getTypeConverter().convertTo(String.class, Buffer.buffer(BODY).toJsonObject()); Assertions.assertEquals(BODY, result); } @Test public void testJsonObjectToByteArray() { byte[] result = context.getTypeConverter().convertTo(byte[].class, Buffer.buffer(BODY.getBytes()).toJsonObject()); Assertions.assertEquals(BODY, new String(result)); } @Test public void testJsonObjectToMap() { Map<String, Object> result = context.getTypeConverter().convertTo(Map.class, Buffer.buffer(BODY).toJsonObject()); Assertions.assertEquals(BODY, new JsonObject(result).toString()); } }
1,298
2,389
<gh_stars>1000+ package io.kubernetes.client.openapi.models; import io.kubernetes.client.fluent.VisitableBuilder; import io.kubernetes.client.fluent.Nested; import java.util.ArrayList; import java.util.function.Predicate; import java.lang.Integer; import java.lang.Deprecated; import io.kubernetes.client.fluent.BaseFluent; import java.util.Iterator; import java.util.Collection; import java.lang.Object; import java.util.List; import java.lang.Boolean; /** * Generated */ public class V1NodeSelectorFluentImpl<A extends io.kubernetes.client.openapi.models.V1NodeSelectorFluent<A>> extends io.kubernetes.client.fluent.BaseFluent<A> implements io.kubernetes.client.openapi.models.V1NodeSelectorFluent<A>{ public V1NodeSelectorFluentImpl() { } public V1NodeSelectorFluentImpl(io.kubernetes.client.openapi.models.V1NodeSelector instance) { this.withNodeSelectorTerms(instance.getNodeSelectorTerms()); } private java.util.ArrayList<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> nodeSelectorTerms; public A addToNodeSelectorTerms(java.lang.Integer index,io.kubernetes.client.openapi.models.V1NodeSelectorTerm item) { if (this.nodeSelectorTerms == null) {this.nodeSelectorTerms = new java.util.ArrayList<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder>();} io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item);_visitables.get("nodeSelectorTerms").add(index >= 0 ? index : _visitables.get("nodeSelectorTerms").size(), builder);this.nodeSelectorTerms.add(index >= 0 ? index : nodeSelectorTerms.size(), builder); return (A)this; } public A setToNodeSelectorTerms(java.lang.Integer index,io.kubernetes.client.openapi.models.V1NodeSelectorTerm item) { if (this.nodeSelectorTerms == null) {this.nodeSelectorTerms = new java.util.ArrayList<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder>();} io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item); if (index < 0 || index >= _visitables.get("nodeSelectorTerms").size()) { _visitables.get("nodeSelectorTerms").add(builder); } else { _visitables.get("nodeSelectorTerms").set(index, builder);} if (index < 0 || index >= nodeSelectorTerms.size()) { nodeSelectorTerms.add(builder); } else { nodeSelectorTerms.set(index, builder);} return (A)this; } public A addToNodeSelectorTerms(io.kubernetes.client.openapi.models.V1NodeSelectorTerm... items) { if (this.nodeSelectorTerms == null) {this.nodeSelectorTerms = new java.util.ArrayList<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder>();} for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item : items) {io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item);_visitables.get("nodeSelectorTerms").add(builder);this.nodeSelectorTerms.add(builder);} return (A)this; } public A addAllToNodeSelectorTerms(java.util.Collection<io.kubernetes.client.openapi.models.V1NodeSelectorTerm> items) { if (this.nodeSelectorTerms == null) {this.nodeSelectorTerms = new java.util.ArrayList<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder>();} for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item : items) {io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item);_visitables.get("nodeSelectorTerms").add(builder);this.nodeSelectorTerms.add(builder);} return (A)this; } public A removeFromNodeSelectorTerms(io.kubernetes.client.openapi.models.V1NodeSelectorTerm... items) { for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item : items) {io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item);_visitables.get("nodeSelectorTerms").remove(builder);if (this.nodeSelectorTerms != null) {this.nodeSelectorTerms.remove(builder);}} return (A)this; } public A removeAllFromNodeSelectorTerms(java.util.Collection<io.kubernetes.client.openapi.models.V1NodeSelectorTerm> items) { for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item : items) {io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(item);_visitables.get("nodeSelectorTerms").remove(builder);if (this.nodeSelectorTerms != null) {this.nodeSelectorTerms.remove(builder);}} return (A)this; } public A removeMatchingFromNodeSelectorTerms(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> predicate) { if (nodeSelectorTerms == null) return (A) this; final Iterator<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> each = nodeSelectorTerms.iterator(); final List visitables = _visitables.get("nodeSelectorTerms"); while (each.hasNext()) { io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder = each.next(); if (predicate.test(builder)) { visitables.remove(builder); each.remove(); } } return (A)this; } /** * This method has been deprecated, please use method buildNodeSelectorTerms instead. * @return The buildable object. */ @java.lang.Deprecated public java.util.List<io.kubernetes.client.openapi.models.V1NodeSelectorTerm> getNodeSelectorTerms() { return nodeSelectorTerms != null ? build(nodeSelectorTerms) : null; } public java.util.List<io.kubernetes.client.openapi.models.V1NodeSelectorTerm> buildNodeSelectorTerms() { return nodeSelectorTerms != null ? build(nodeSelectorTerms) : null; } public io.kubernetes.client.openapi.models.V1NodeSelectorTerm buildNodeSelectorTerm(java.lang.Integer index) { return this.nodeSelectorTerms.get(index).build(); } public io.kubernetes.client.openapi.models.V1NodeSelectorTerm buildFirstNodeSelectorTerm() { return this.nodeSelectorTerms.get(0).build(); } public io.kubernetes.client.openapi.models.V1NodeSelectorTerm buildLastNodeSelectorTerm() { return this.nodeSelectorTerms.get(nodeSelectorTerms.size() - 1).build(); } public io.kubernetes.client.openapi.models.V1NodeSelectorTerm buildMatchingNodeSelectorTerm(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> predicate) { for (io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder item: nodeSelectorTerms) { if(predicate.test(item)){ return item.build();} } return null; } public java.lang.Boolean hasMatchingNodeSelectorTerm(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> predicate) { for (io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder item: nodeSelectorTerms) { if(predicate.test(item)){ return true;} } return false; } public A withNodeSelectorTerms(java.util.List<io.kubernetes.client.openapi.models.V1NodeSelectorTerm> nodeSelectorTerms) { if (this.nodeSelectorTerms != null) { _visitables.get("nodeSelectorTerms").removeAll(this.nodeSelectorTerms);} if (nodeSelectorTerms != null) {this.nodeSelectorTerms = new java.util.ArrayList(); for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item : nodeSelectorTerms){this.addToNodeSelectorTerms(item);}} else { this.nodeSelectorTerms = null;} return (A) this; } public A withNodeSelectorTerms(io.kubernetes.client.openapi.models.V1NodeSelectorTerm... nodeSelectorTerms) { if (this.nodeSelectorTerms != null) {this.nodeSelectorTerms.clear();} if (nodeSelectorTerms != null) {for (io.kubernetes.client.openapi.models.V1NodeSelectorTerm item :nodeSelectorTerms){ this.addToNodeSelectorTerms(item);}} return (A) this; } public java.lang.Boolean hasNodeSelectorTerms() { return nodeSelectorTerms != null && !nodeSelectorTerms.isEmpty(); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> addNewNodeSelectorTerm() { return new io.kubernetes.client.openapi.models.V1NodeSelectorFluentImpl.NodeSelectorTermsNestedImpl(); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> addNewNodeSelectorTermLike(io.kubernetes.client.openapi.models.V1NodeSelectorTerm item) { return new io.kubernetes.client.openapi.models.V1NodeSelectorFluentImpl.NodeSelectorTermsNestedImpl(-1, item); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> setNewNodeSelectorTermLike(java.lang.Integer index,io.kubernetes.client.openapi.models.V1NodeSelectorTerm item) { return new io.kubernetes.client.openapi.models.V1NodeSelectorFluentImpl.NodeSelectorTermsNestedImpl(index, item); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> editNodeSelectorTerm(java.lang.Integer index) { if (nodeSelectorTerms.size() <= index) throw new RuntimeException("Can't edit nodeSelectorTerms. Index exceeds size."); return setNewNodeSelectorTermLike(index, buildNodeSelectorTerm(index)); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> editFirstNodeSelectorTerm() { if (nodeSelectorTerms.size() == 0) throw new RuntimeException("Can't edit first nodeSelectorTerms. The list is empty."); return setNewNodeSelectorTermLike(0, buildNodeSelectorTerm(0)); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> editLastNodeSelectorTerm() { int index = nodeSelectorTerms.size() - 1; if (index < 0) throw new RuntimeException("Can't edit last nodeSelectorTerms. The list is empty."); return setNewNodeSelectorTermLike(index, buildNodeSelectorTerm(index)); } public io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<A> editMatchingNodeSelectorTerm(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder> predicate) { int index = -1; for (int i=0;i<nodeSelectorTerms.size();i++) { if (predicate.test(nodeSelectorTerms.get(i))) {index = i; break;} } if (index < 0) throw new RuntimeException("Can't edit matching nodeSelectorTerms. No match found."); return setNewNodeSelectorTermLike(index, buildNodeSelectorTerm(index)); } public boolean equals(java.lang.Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; V1NodeSelectorFluentImpl that = (V1NodeSelectorFluentImpl) o; if (nodeSelectorTerms != null ? !nodeSelectorTerms.equals(that.nodeSelectorTerms) :that.nodeSelectorTerms != null) return false; return true; } public int hashCode() { return java.util.Objects.hash(nodeSelectorTerms, super.hashCode()); } public class NodeSelectorTermsNestedImpl<N> extends io.kubernetes.client.openapi.models.V1NodeSelectorTermFluentImpl<io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<N>> implements io.kubernetes.client.openapi.models.V1NodeSelectorFluent.NodeSelectorTermsNested<N>,io.kubernetes.client.fluent.Nested<N>{ NodeSelectorTermsNestedImpl(java.lang.Integer index,io.kubernetes.client.openapi.models.V1NodeSelectorTerm item) { this.index = index; this.builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(this, item); } NodeSelectorTermsNestedImpl() { this.index = -1; this.builder = new io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder(this); } io.kubernetes.client.openapi.models.V1NodeSelectorTermBuilder builder; java.lang.Integer index; public N and() { return (N) V1NodeSelectorFluentImpl.this.setToNodeSelectorTerms(index,builder.build()); } public N endNodeSelectorTerm() { return and(); } } }
4,256
839
<reponame>spring-cloud/spring-cloud-function /* * Copyright 2020-2020 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.cloud.function.context.catalog; import java.util.function.BiFunction; import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry.FunctionInvocationWrapper; import org.springframework.messaging.Message; /** * Wrapper that acts as around advise over function invocation. * If registered as bean it will be autowired into {@link FunctionInvocationWrapper}. * Keep in mind that it only affects imperative invocations where input is {@link Message} * * NOTE: This API is experimental and and could change without notice. It is * intended for internal use only (e.g., spring-cloud-sleuth) * * @author <NAME> * @since 3.1 */ public abstract class FunctionAroundWrapper implements BiFunction<Object, FunctionInvocationWrapper, Object> { @Override public final Object apply(Object input, FunctionInvocationWrapper targetFunction) { boolean isSkipOutputConversion = targetFunction.isSkipOutputConversion(); targetFunction.setSkipOutputConversion(true); Object result = null; if (input instanceof Message || targetFunction.isOutputTypePublisher() || targetFunction.isInputTypePublisher()) { return this.doApply(input, targetFunction); } else if (targetFunction.isSupplier() && !targetFunction.isOutputTypePublisher()) { result = this.doApply(null, targetFunction); } else { result = targetFunction.apply(input); } targetFunction.setSkipOutputConversion(isSkipOutputConversion); return result; } protected abstract Object doApply(Object input, FunctionInvocationWrapper targetFunction); }
606
14,668
<gh_stars>1000+ // 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_UPDATER_UTIL_H_ #define CHROME_UPDATER_UTIL_H_ #include "base/files/file_path.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "chrome/updater/updater_scope.h" #include "third_party/abseil-cpp/absl/types/optional.h" class GURL; // Externally-defined printers for base types. namespace base { class CommandLine; class Version; template <class T> std::ostream& operator<<(std::ostream& os, const absl::optional<T>& opt) { if (opt.has_value()) { return os << opt.value(); } else { return os << "absl::nullopt"; } } } // namespace base namespace updater { namespace tagging { struct TagArgs; } enum class UpdaterScope; // Returns the base directory common to all versions of the updater. For // instance, this function may return %localappdata%\Chromium\ChromiumUpdater // for a user install. absl::optional<base::FilePath> GetBaseDirectory(UpdaterScope scope); // Returns a versioned directory under which the running version of the updater // stores its files and data. For instance, this function may return // %localappdata%\Chromium\ChromiumUpdater\1.2.3.4 for a user install. absl::optional<base::FilePath> GetVersionedDirectory(UpdaterScope scope); // For user installations: // ~/Library/Google/GoogleUpdater/88.0.4293.0 // For system installations: // /Library/Google/GoogleUpdater/88.0.4293.0 absl::optional<base::FilePath> GetVersionedUpdaterFolderPathForVersion( UpdaterScope scope, const base::Version& version); // The same as GetVersionedUpdaterFolderPathForVersion, where the version is // kUpdaterVersion. absl::optional<base::FilePath> GetVersionedUpdaterFolderPath( UpdaterScope scope); // For user installations: // ~/Library/Google/GoogleUpdater // For system installations: // /Library/Google/GoogleUpdater absl::optional<base::FilePath> GetUpdaterFolderPath(UpdaterScope scope); #if defined(OS_MAC) // For example: ~/Library/Google/GoogleUpdater/88.0.4293.0/GoogleUpdater.app absl::optional<base::FilePath> GetUpdaterAppBundlePath(UpdaterScope scope); #endif // defined(OS_MAC) // For user installations: // ~/Library/Google/GoogleUpdater/88.0.4293.0/GoogleUpdater.app/Contents/ // MacOS/GoogleUpdater // For system installations: // /Library/Google/GoogleUpdater/88.0.4293.0/GoogleUpdater.app/Contents/ // MacOS/GoogleUpdater absl::optional<base::FilePath> GetUpdaterExecutablePath(UpdaterScope scope); // For user installations: // ~/Library/Google/GoogleUpdater/88.0.4293.0/GoogleUpdater.app/Contents/MacOS // For system installations: // /Library/Google/GoogleUpdater/88.0.4293.0/GoogleUpdater.app/Contents/MacOS absl::optional<base::FilePath> GetExecutableFolderPathForVersion( UpdaterScope scope, const base::Version& version); // Returns a relative path to the executable, such as // "GoogleUpdater.app/Contents/MacOS/GoogleUpdater" on macOS. // "updater.exe" on Win. base::FilePath GetExecutableRelativePath(); // Returns the parsed values from --tag command line argument. The function // implementation uses lazy initialization and caching to avoid reparsing // the tag. absl::optional<tagging::TagArgs> GetTagArgs(); // Returns true if the user running the updater also owns the `path`. bool PathOwnedByUser(const base::FilePath& path); // Initializes logging for an executable. void InitLogging(UpdaterScope updater_scope, const base::FilePath::StringType& filename); // Wraps the 'command_line' to be executed in an elevated context. // On macOS this is done with 'sudo'. base::CommandLine MakeElevated(base::CommandLine command_line); // Functor used by associative containers of strings as a case-insensitive ASCII // compare. `StringT` could be either UTF-8 or UTF-16. struct CaseInsensitiveASCIICompare { public: template <typename StringT> bool operator()(const StringT& x, const StringT& y) const { return base::CompareCaseInsensitiveASCII(x, y) > 0; } }; // Returns a new GURL by appending the given query parameter name and the // value. Unsafe characters in the name and the value are escaped like // %XX%XX. The original query component is preserved if it's present. // // Examples: // // AppendQueryParameter(GURL("http://example.com"), "name", "value").spec() // => "http://example.com?name=value" // AppendQueryParameter(GURL("http://example.com?x=y"), "name", "value").spec() // => "http://example.com?x=y&name=value" GURL AppendQueryParameter(const GURL& url, const std::string& name, const std::string& value); #if defined(OS_MAC) // Uses the builtin unzip utility within macOS /usr/bin/unzip to unzip instead // of using the configurator's UnzipperFactory. The UnzipperFactory utilizes the // //third_party/zlib/google, which has a bug that does not preserve the // permissions when it extracts the contents. For updates via zip or // differentials, use UnzipWithExe. bool UnzipWithExe(const base::FilePath& src_path, const base::FilePath& dest_path); absl::optional<base::FilePath> GetKeystoneFolderPath(UpdaterScope scope); // Read the file at path to confirm that the file at the path has the same // permissions as the given permissions mask. bool ConfirmFilePermissions(const base::FilePath& root_path, int kPermissionsMask); #endif // defined(OS_MAC) } // namespace updater #endif // CHROME_UPDATER_UTIL_H_
1,876
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "value_converter.h" #include <vespa/config/common/exceptions.h> #include <vespa/vespalib/locale/c.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::slime; namespace config::internal { template<> int32_t convertValue(const ::vespalib::slime::Inspector & __inspector) { switch (__inspector.type().getId()) { case LONG::ID: return static_cast<int32_t>(__inspector.asLong()); case DOUBLE::ID: return static_cast<int32_t>(__inspector.asDouble()); case STRING::ID: return static_cast<int32_t>(strtoll(__inspector.asString().make_string().c_str(), 0, 0)); } throw InvalidConfigException(make_string("Expected int32_t, but got incompatible config type %u", __inspector.type().getId())); } template<> int64_t convertValue(const ::vespalib::slime::Inspector & __inspector) { switch (__inspector.type().getId()) { case LONG::ID: return static_cast<int64_t>(__inspector.asLong()); case DOUBLE::ID: return static_cast<int64_t>(__inspector.asDouble()); case STRING::ID: return static_cast<int64_t>(strtoll(__inspector.asString().make_string().c_str(), 0, 0)); } throw InvalidConfigException(make_string("Expected int64_t, but got incompatible config type %u", __inspector.type().getId())); } template<> double convertValue(const ::vespalib::slime::Inspector & __inspector) { switch (__inspector.type().getId()) { case LONG::ID: return static_cast<double>(__inspector.asLong()); case DOUBLE::ID: return static_cast<double>(__inspector.asDouble()); case STRING::ID: return static_cast<double>(vespalib::locale::c::strtod(__inspector.asString().make_string().c_str(), 0)); } throw InvalidConfigException(make_string("Expected double, but got incompatible config type %u", __inspector.type().getId())); } template<> bool convertValue(const ::vespalib::slime::Inspector & __inspector) { switch (__inspector.type().getId()) { case BOOL::ID: return __inspector.asBool(); case STRING::ID: vespalib::string s(__inspector.asString().make_string()); return s.compare("true") == 0 ? true : false; } throw InvalidConfigException(make_string("Expected bool, but got incompatible config type %u", __inspector.type().getId())); } template<> vespalib::string convertValue(const ::vespalib::slime::Inspector & __inspector) { return __inspector.asString().make_string(); } void requireValid(const vespalib::string & __fieldName, const ::vespalib::slime::Inspector & __inspector) { if (!__inspector.valid()) { throw ::config::InvalidConfigException("Value for '" + __fieldName + "' required but not found"); } } }
1,065
577
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """Test for sequence summary network.""" import importlib import numpy as np import pytest import torch from neural_sp.models.torch_utils import np2tensor from neural_sp.models.torch_utils import pad_list def make_args(**kwargs): args = dict( input_dim=80, n_units=64, n_layers=2, bottleneck_dim=0, dropout=0.1, param_init=0.1, ) args.update(kwargs) return args @pytest.mark.parametrize( "args", [ ({'n_layers': 2, 'bottleneck_dim': 0}), ({'n_layers': 2, 'bottleneck_dim': 100}), ({'n_layers': 3, 'bottleneck_dim': 0}), ({'n_layers': 3, 'bottleneck_dim': 100}), ] ) def test_forward(args): args = make_args(**args) batch_size = 4 xmax = 40 device = "cpu" xs = np.random.randn(batch_size, xmax, args['input_dim']).astype(np.float32) xlens = torch.IntTensor([len(x) for x in xs]) xs = pad_list([np2tensor(x, device).float() for x in xs], 0.) module = importlib.import_module('neural_sp.models.seq2seq.frontends.sequence_summary') ssn = module.SequenceSummaryNetwork(**args) ssn = ssn.to(device) out = ssn(xs, xlens) assert out.size() == xs.size()
581
514
<filename>duke-core/src/test/java/no/priv/garshol/duke/utils/ObjectUtilsTest.java package no.priv.garshol.duke.utils; import java.util.Collection; import java.util.HashMap; import java.util.Map; import no.priv.garshol.duke.DukeConfigException; import no.priv.garshol.duke.comparators.QGramComparator; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; public class ObjectUtilsTest { private TestBean bean; private Map<String, Object> objects; @Before public void setup() { bean = new TestBean(); objects = new HashMap(); } @Test public void testOneWord() { ObjectUtils.setBeanProperty(bean, "property", "value", objects); assertEquals("property not set correctly", "value", bean.getProperty()); } @Test public void testTwoWords() { ObjectUtils.setBeanProperty(bean, "property-name", "value", objects); assertEquals("property not set correctly", "value", bean.getPropertyName()); } @Test public void testThreeWords() { ObjectUtils.setBeanProperty(bean, "long-property-name", "value", objects); assertEquals("property not set correctly", "value", bean.getLongPropertyName()); } @Test public void testIntProperty() { ObjectUtils.setBeanProperty(bean, "int-property", "25", objects); assertEquals("property not set correctly", 25, bean.getIntProperty()); } @Test public void testBoolProperty() { ObjectUtils.setBeanProperty(bean, "bool-property", "true", objects); assertEquals("property not set correctly", true, bean.getBoolProperty()); } @Test public void testDoubleProperty() { ObjectUtils.setBeanProperty(bean, "double-property", "0.25", objects); assertEquals("property not set correctly", 0.25, bean.getDoubleProperty()); } @Test public void testFloatProperty() { ObjectUtils.setBeanProperty(bean, "float-property", "0.25", objects); assertEquals("property not set correctly", 0.25f, bean.getFloatProperty()); } @Test public void testNamedObject() { objects.put("thetest", this); ObjectUtils.setBeanProperty(bean, "test", "thetest", objects); assertEquals("property not set correctly", this, bean.getTest()); } @Test public void testEnumConstant() { ObjectUtils.setBeanProperty(bean, "enum", "JACCARD", objects); assertEquals("property not set correctly", QGramComparator.Formula.JACCARD, bean.getEnum()); } @Test public void testCharProperty() { ObjectUtils.setBeanProperty(bean, "char-property", "g", objects); assertEquals("property not set correctly", 'g', bean.getCharProperty()); } @Test public void testCharPropertyError() { try { ObjectUtils.setBeanProperty(bean, "char-property", "goo", objects); fail("shouldn't accept three-character string as value of character prop"); } catch (DukeConfigException e) { // this is right. we're trying to set a three-character string // into a character property } } @Test public void testCollection() { objects.put("foo", "gurgle"); objects.put("bar", "gargle"); ObjectUtils.setBeanProperty(bean, "collection", "foo bar", objects); Collection<String> coll = bean.getCollection(); assertEquals(2, coll.size()); assertTrue(coll.contains("gurgle")); assertTrue(coll.contains("gargle")); } // ----- TESTBEAN public static class TestBean { private String value; private int theint; private boolean thebool; private double thedouble; private float thefloat; private char thechar; private ObjectUtilsTest thetest; private QGramComparator.Formula theenum; private Collection<String> collection; public void setProperty(String value) { this.value = value; } public String getProperty() { return value; } public void setPropertyName(String value) { this.value = value; } public String getPropertyName() { return value; } public void setLongPropertyName(String value) { this.value = value; } public String getLongPropertyName() { return value; } public void setIntProperty(int value) { this.theint = value; } public int getIntProperty() { return theint; } public void setBoolProperty(boolean value) { this.thebool = value; } public boolean getBoolProperty() { return thebool; } public void setDoubleProperty(double value) { this.thedouble = value; } public double getDoubleProperty() { return thedouble; } public void setFloatProperty(float value) { this.thefloat = value; } public float getFloatProperty() { return thefloat; } public void setTest(ObjectUtilsTest test) { this.thetest = test; } public ObjectUtilsTest getTest() { return thetest; } public void setCharProperty(char ch) { this.thechar = ch; } public char getCharProperty() { return thechar; } public void setEnum(QGramComparator.Formula theenum) { this.theenum = theenum; } public QGramComparator.Formula getEnum() { return theenum; } public Collection<String> getCollection() { return collection; } public void setCollection(Collection<String> collection) { this.collection = collection; } } }
2,058
1,886
<reponame>isabella232/cinder-1 // Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #pragma once #include "Python.h" /* * This file defines the C interface to the strict module loader. */ #ifdef __cplusplus extern "C" { #endif typedef struct _ErrorInfo { PyObject* msg; PyObject* filename; int lineno; int col; } ErrorInfo; void ErrorInfo_Clean(ErrorInfo* info); typedef struct StrictModuleChecker StrictModuleChecker; typedef struct StrictAnalyzedModule StrictAnalyzedModule; /* * Create a new strict module checker * * Returns a pointer to a new StrictModuleChecker on success or NULL on error. */ StrictModuleChecker* StrictModuleChecker_New(void); /** Set import paths * return 0 for success and -1 for failure */ int StrictModuleChecker_SetImportPaths( StrictModuleChecker* checker, const char* import_paths[], int length); /** Set stub import path * return 0 for success and -1 for failure */ int StrictModuleChecker_SetStubImportPath( StrictModuleChecker* checker, const char* stub_import_path); int StrictModuleChecker_SetAllowListPrefix( StrictModuleChecker* checker, const char* allowList[], int length); int StrictModuleChecker_SetAllowListExact( StrictModuleChecker* checker, const char* allowList[], int length); int StrictModuleChecker_LoadStrictModuleBuiltins(StrictModuleChecker* checker); void StrictModuleChecker_Free(StrictModuleChecker* checker); /** Return the analyzed module * return NULL for internal error cases * out parameter: `error_count` how many errors in error sink * is reported */ StrictAnalyzedModule* StrictModuleChecker_Check( StrictModuleChecker* checker, PyObject* module_name, int* out_error_count, int* is_strict_out); /** Return the analyzed module * return NULL for internal error cases * in parameter: `source` need to be parsed by python ast parser * out parameter: `error_count` how many errors in error sink * is reported */ StrictAnalyzedModule* StrictModuleChecker_CheckSource( StrictModuleChecker* checker, const char* source, PyObject* module_name, PyObject* file_name, const char* submodule_search_locations[], int search_locations_size, int* out_error_count, int* is_strict_out); /** Fill in errors_out (of size `length`) with ErrorInfo * Of the given module. The size is obtained in `StrictModuleChecker_Check` * Return 0 for success and -1 for failure */ int StrictModuleChecker_GetErrors( StrictAnalyzedModule* mod, ErrorInfo errors_out[], size_t length); /** Return how many modules have been analyzed*/ int StrictModuleChecker_GetAnalyzedModuleCount(StrictModuleChecker* checker); /** Set whether the loader should force a module to be strict * reutrn 0 if no error and -1 for internal error */ int StrictModuleChecker_SetForceStrict( StrictModuleChecker* checker, PyObject* force_strict); int StrictModuleChecker_SetForceStrictByName( StrictModuleChecker* checker, const char* forced_module_name); // Delete the module named `mod` from the analyzed modules int StrictModuleChecker_DeleteModule( StrictModuleChecker* checker, const char* module_name); PyArena* StrictModuleChecker_GetArena(StrictModuleChecker* checker); /** Retrieve the AST for a given module name * If the module with given name is not yet checked, * This will *not* trigger a check and NULL will be returned. * * preprocess: if preprocess is true, indicator decorators will be * added to the AST for further compiler usage. See preprocessor.h * Note that preprocessing modifieds the mod_ty ast, and we should not * call preprocess on already preprocessed ast */ PyObject* StrictAnalyzedModule_GetAST( StrictAnalyzedModule* mod, PyArena* arena, int preprocess); /** Retrieve the symtable for a given module name * If the module with given name is not yet checked, * This will *not* trigger a check and NULL will be returned. */ PyObject* StrictAnalyzedModule_GetSymtable(StrictAnalyzedModule* mod); // retrieve filename PyObject* StrictAnalyzedModule_GetFilename(StrictAnalyzedModule* mod); // retrieve modulekind as int int StrictAnalyzedModule_GetModuleKind(StrictAnalyzedModule* mod); // retrieve stubkind as int int StrictAnalyzedModule_GetStubKind(StrictAnalyzedModule* mod); #ifdef __cplusplus } #endif
1,404
2,868
/* * Copyright (c) 2015-2020, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \file * \brief Small-write engine build code. */ #include "smallwrite/smallwrite_build.h" #include "grey.h" #include "ue2common.h" #include "compiler/compiler.h" #include "nfa/dfa_min.h" #include "nfa/mcclellancompile.h" #include "nfa/mcclellancompile_util.h" #include "nfa/nfa_internal.h" #include "nfa/rdfa_merge.h" #include "nfa/shengcompile.h" #include "nfagraph/ng.h" #include "nfagraph/ng_depth.h" #include "nfagraph/ng_holder.h" #include "nfagraph/ng_mcclellan.h" #include "nfagraph/ng_reports.h" #include "nfagraph/ng_prune.h" #include "nfagraph/ng_util.h" #include "smallwrite/smallwrite_internal.h" #include "util/alloc.h" #include "util/bytecode_ptr.h" #include "util/charreach.h" #include "util/compare.h" #include "util/compile_context.h" #include "util/container.h" #include "util/make_unique.h" #include "util/ue2_graph.h" #include "util/ue2string.h" #include "util/verify_types.h" #include <map> #include <set> #include <vector> #include <utility> #include <boost/graph/breadth_first_search.hpp> using namespace std; namespace ue2 { #define DFA_MERGE_MAX_STATES 8000 #define MAX_TRIE_VERTICES 8000 struct LitTrieVertexProps { LitTrieVertexProps() = default; explicit LitTrieVertexProps(u8 c_in) : c(c_in) {} size_t index; // managed by ue2_graph u8 c = 0; //!< character reached on this vertex flat_set<ReportID> reports; //!< managed reports fired on this vertex }; struct LitTrieEdgeProps { size_t index; // managed by ue2_graph }; /** * \brief BGL graph used to store a trie of literals (for later AC construction * into a DFA). */ struct LitTrie : public ue2_graph<LitTrie, LitTrieVertexProps, LitTrieEdgeProps> { LitTrie() : root(add_vertex(*this)) {} const vertex_descriptor root; //!< Root vertex for the trie. }; static bool is_empty(const LitTrie &trie) { return num_vertices(trie) <= 1; } static std::set<ReportID> all_reports(const LitTrie &trie) { std::set<ReportID> reports; for (auto v : vertices_range(trie)) { insert(&reports, trie[v].reports); } return reports; } using LitTrieVertex = LitTrie::vertex_descriptor; using LitTrieEdge = LitTrie::edge_descriptor; namespace { // unnamed // Concrete impl class class SmallWriteBuildImpl : public SmallWriteBuild { public: SmallWriteBuildImpl(size_t num_patterns, const ReportManager &rm, const CompileContext &cc); // Construct a runtime implementation. bytecode_ptr<SmallWriteEngine> build(u32 roseQuality) override; void add(const NGHolder &g, const ExpressionInfo &expr) override; void add(const ue2_literal &literal, ReportID r) override; set<ReportID> all_reports() const override; const ReportManager &rm; const CompileContext &cc; vector<unique_ptr<raw_dfa>> dfas; LitTrie lit_trie; LitTrie lit_trie_nocase; size_t num_literals = 0; bool poisoned; }; } // namespace SmallWriteBuild::~SmallWriteBuild() = default; SmallWriteBuildImpl::SmallWriteBuildImpl(size_t num_patterns, const ReportManager &rm_in, const CompileContext &cc_in) : rm(rm_in), cc(cc_in), /* small write is block mode only */ poisoned(!cc.grey.allowSmallWrite || cc.streaming || num_patterns > cc.grey.smallWriteMaxPatterns) { } /** * \brief Remove any reports from the given vertex that cannot match within * max_depth due to their constraints. */ static bool pruneOverlongReports(NFAVertex v, NGHolder &g, const depth &max_depth, const ReportManager &rm) { assert(!g[v].reports.empty()); vector<ReportID> bad_reports; for (ReportID id : g[v].reports) { const auto &report = rm.getReport(id); if (report.minOffset > max_depth) { bad_reports.push_back(id); } } for (ReportID id : bad_reports) { g[v].reports.erase(id); } if (g[v].reports.empty()) { DEBUG_PRINTF("none of vertex %zu's reports can match, cut accepts\n", g[v].index); remove_edge(v, g.accept, g); remove_edge(v, g.acceptEod, g); } return !bad_reports.empty(); } /** * \brief Prune vertices and reports from the graph that cannot match within * max_depth. */ static bool pruneOverlong(NGHolder &g, const depth &max_depth, const ReportManager &rm) { bool modified = false; auto depths = calcBidiDepths(g); for (auto v : vertices_range(g)) { if (is_special(v, g)) { continue; } const auto &d = depths.at(g[v].index); depth min_match_offset = min(d.fromStart.min, d.fromStartDotStar.min) + min(d.toAccept.min, d.toAcceptEod.min); if (min_match_offset > max_depth) { clear_vertex(v, g); modified = true; continue; } if (is_match_vertex(v, g)) { modified |= pruneOverlongReports(v, g, max_depth, rm); } } if (modified) { pruneUseless(g); DEBUG_PRINTF("pruned graph down to %zu vertices\n", num_vertices(g)); } return modified; } /** * \brief Attempt to merge the set of DFAs given down into a single raw_dfa. * Returns false on failure. */ static bool mergeDfas(vector<unique_ptr<raw_dfa>> &dfas, const ReportManager &rm, const CompileContext &cc) { assert(!dfas.empty()); if (dfas.size() == 1) { return true; } DEBUG_PRINTF("attempting to merge %zu DFAs\n", dfas.size()); vector<const raw_dfa *> dfa_ptrs; dfa_ptrs.reserve(dfas.size()); for (auto &d : dfas) { dfa_ptrs.push_back(d.get()); } auto merged = mergeAllDfas(dfa_ptrs, DFA_MERGE_MAX_STATES, &rm, cc.grey); if (!merged) { DEBUG_PRINTF("merge failed\n"); return false; } DEBUG_PRINTF("merge succeeded, result has %zu states\n", merged->states.size()); dfas.clear(); dfas.push_back(std::move(merged)); return true; } void SmallWriteBuildImpl::add(const NGHolder &g, const ExpressionInfo &expr) { // If the graph is poisoned (i.e. we can't build a SmallWrite version), // we don't even try. if (poisoned) { return; } if (expr.som) { DEBUG_PRINTF("no SOM support in small-write engine\n"); poisoned = true; return; } if (isVacuous(g)) { DEBUG_PRINTF("no vacuous graph support in small-write engine\n"); poisoned = true; return; } if (any_of_in(::ue2::all_reports(g), [&](ReportID id) { return rm.getReport(id).minLength > 0; })) { DEBUG_PRINTF("no min_length extparam support in small-write engine\n"); poisoned = true; return; } DEBUG_PRINTF("g=%p\n", &g); // make a copy of the graph so that we can modify it for our purposes unique_ptr<NGHolder> h = cloneHolder(g); pruneOverlong(*h, depth(cc.grey.smallWriteLargestBuffer), rm); reduceGraph(*h, SOM_NONE, expr.utf8, cc); if (can_never_match(*h)) { DEBUG_PRINTF("graph can never match in small block\n"); return; } // Now we can actually build the McClellan DFA assert(h->kind == NFA_OUTFIX); auto r = buildMcClellan(*h, &rm, cc.grey); // If we couldn't build a McClellan DFA for this portion, we won't be able // build a smwr which represents the pattern set if (!r) { DEBUG_PRINTF("failed to determinise\n"); poisoned = true; return; } if (clear_deeper_reports(*r, cc.grey.smallWriteLargestBuffer)) { minimize_hopcroft(*r, cc.grey); } dfas.push_back(std::move(r)); if (dfas.size() >= cc.grey.smallWriteMergeBatchSize) { if (!mergeDfas(dfas, rm, cc)) { dfas.clear(); poisoned = true; return; } } } static bool add_to_trie(const ue2_literal &literal, ReportID report, LitTrie &trie) { auto u = trie.root; for (const auto &c : literal) { auto next = LitTrie::null_vertex(); for (auto v : adjacent_vertices_range(u, trie)) { if (trie[v].c == (u8)c.c) { next = v; break; } } if (!next) { next = add_vertex(LitTrieVertexProps((u8)c.c), trie); add_edge(u, next, trie); } u = next; } trie[u].reports.insert(report); DEBUG_PRINTF("added '%s' (report %u) to trie, now %zu vertices\n", escapeString(literal).c_str(), report, num_vertices(trie)); return num_vertices(trie) <= MAX_TRIE_VERTICES; } void SmallWriteBuildImpl::add(const ue2_literal &literal, ReportID r) { // If the graph is poisoned (i.e. we can't build a SmallWrite version), // we don't even try. if (poisoned) { DEBUG_PRINTF("poisoned\n"); return; } if (literal.length() > cc.grey.smallWriteLargestBuffer) { DEBUG_PRINTF("exceeded length limit\n"); return; /* too long */ } if (++num_literals > cc.grey.smallWriteMaxLiterals) { DEBUG_PRINTF("exceeded literal limit\n"); poisoned = true; return; } auto &trie = literal.any_nocase() ? lit_trie_nocase : lit_trie; if (!add_to_trie(literal, r, trie)) { DEBUG_PRINTF("trie add failed\n"); poisoned = true; } } namespace { /** * \brief BFS visitor for Aho-Corasick automaton construction. * * This is doing two things: * * - Computing the failure edges (also called fall or supply edges) for each * vertex, giving the longest suffix of the path to that point that is also * a prefix in the trie reached on the same character. The BFS traversal * makes it possible to build these from earlier failure paths. * * - Computing the output function for each vertex, which is done by * propagating the reports from failure paths as well. This ensures that * substrings of the current path also report correctly. */ struct ACVisitor : public boost::default_bfs_visitor { ACVisitor(LitTrie &trie_in, unordered_map<LitTrieVertex, LitTrieVertex> &failure_map_in, vector<LitTrieVertex> &ordering_in) : mutable_trie(trie_in), failure_map(failure_map_in), ordering(ordering_in) {} LitTrieVertex find_failure_target(LitTrieVertex u, LitTrieVertex v, const LitTrie &trie) { assert(u == trie.root || contains(failure_map, u)); assert(!contains(failure_map, v)); const auto &c = trie[v].c; while (u != trie.root) { auto f = failure_map.at(u); for (auto w : adjacent_vertices_range(f, trie)) { if (trie[w].c == c) { return w; } } u = f; } DEBUG_PRINTF("no failure edge\n"); return LitTrie::null_vertex(); } void tree_edge(LitTrieEdge e, const LitTrie &trie) { auto u = source(e, trie); auto v = target(e, trie); DEBUG_PRINTF("bfs (%zu, %zu) on '%c'\n", trie[u].index, trie[v].index, trie[v].c); ordering.push_back(v); auto f = find_failure_target(u, v, trie); if (f) { DEBUG_PRINTF("final failure vertex %zu\n", trie[f].index); failure_map.emplace(v, f); // Propagate reports from failure path to ensure we correctly // report substrings. insert(&mutable_trie[v].reports, mutable_trie[f].reports); } else { DEBUG_PRINTF("final failure vertex root\n"); failure_map.emplace(v, trie.root); } } private: LitTrie &mutable_trie; //!< For setting reports property. unordered_map<LitTrieVertex, LitTrieVertex> &failure_map; vector<LitTrieVertex> &ordering; //!< BFS ordering for vertices. }; } static UNUSED bool isSaneTrie(const LitTrie &trie) { CharReach seen; for (auto u : vertices_range(trie)) { seen.clear(); for (auto v : adjacent_vertices_range(u, trie)) { if (seen.test(trie[v].c)) { return false; } seen.set(trie[v].c); } } return true; } /** * \brief Turn the given literal trie into an AC automaton by adding additional * edges and reports. */ static void buildAutomaton(LitTrie &trie, unordered_map<LitTrieVertex, LitTrieVertex> &failure_map, vector<LitTrieVertex> &ordering) { assert(isSaneTrie(trie)); // Find our failure transitions and reports. failure_map.reserve(num_vertices(trie)); ordering.reserve(num_vertices(trie)); ACVisitor ac_vis(trie, failure_map, ordering); boost::breadth_first_search(trie, trie.root, visitor(ac_vis)); // Compute missing edges from failure map. for (auto v : ordering) { DEBUG_PRINTF("vertex %zu\n", trie[v].index); CharReach seen; for (auto w : adjacent_vertices_range(v, trie)) { DEBUG_PRINTF("edge to %zu with reach 0x%02x\n", trie[w].index, trie[w].c); assert(!seen.test(trie[w].c)); seen.set(trie[w].c); } auto parent = failure_map.at(v); for (auto w : adjacent_vertices_range(parent, trie)) { if (!seen.test(trie[w].c)) { add_edge(v, w, trie); } } } } static vector<u32> findDistFromRoot(const LitTrie &trie) { vector<u32> dist(num_vertices(trie), UINT32_MAX); dist[trie[trie.root].index] = 0; // BFS to find dist from root. breadth_first_search( trie, trie.root, visitor(make_bfs_visitor(record_distances( make_iterator_property_map(dist.begin(), get(&LitTrieVertexProps::index, trie)), boost::on_tree_edge())))); return dist; } static vector<u32> findDistToAccept(const LitTrie &trie) { vector<u32> dist(num_vertices(trie), UINT32_MAX); // Start with all reporting vertices. deque<LitTrieVertex> q; for (auto v : vertices_range(trie)) { if (!trie[v].reports.empty()) { q.push_back(v); dist[trie[v].index] = 0; } } // Custom BFS, since we have a pile of sources. while (!q.empty()) { auto v = q.front(); q.pop_front(); u32 d = dist[trie[v].index]; for (auto u : inv_adjacent_vertices_range(v, trie)) { auto &u_dist = dist[trie[u].index]; if (u_dist == UINT32_MAX) { q.push_back(u); u_dist = d + 1; } } } return dist; } /** * \brief Prune all vertices from the trie that do not lie on a path from root * to accept of length <= max_depth. */ static void pruneTrie(LitTrie &trie, u32 max_depth) { DEBUG_PRINTF("pruning trie to %u\n", max_depth); auto dist_from_root = findDistFromRoot(trie); auto dist_to_accept = findDistToAccept(trie); vector<LitTrieVertex> dead; for (auto v : vertices_range(trie)) { if (v == trie.root) { continue; } auto v_index = trie[v].index; DEBUG_PRINTF("vertex %zu: from_start=%u, to_accept=%u\n", trie[v].index, dist_from_root[v_index], dist_to_accept[v_index]); assert(dist_from_root[v_index] != UINT32_MAX); assert(dist_to_accept[v_index] != UINT32_MAX); u32 min_path_len = dist_from_root[v_index] + dist_to_accept[v_index]; if (min_path_len > max_depth) { DEBUG_PRINTF("pruning vertex %zu (min path len %u)\n", trie[v].index, min_path_len); clear_vertex(v, trie); dead.push_back(v); } } if (dead.empty()) { return; } for (auto v : dead) { remove_vertex(v, trie); } DEBUG_PRINTF("%zu vertices remain\n", num_vertices(trie)); renumber_edges(trie); renumber_vertices(trie); } static vector<CharReach> getAlphabet(const LitTrie &trie, bool nocase) { vector<CharReach> esets = {CharReach::dot()}; for (auto v : vertices_range(trie)) { if (v == trie.root) { continue; } CharReach cr; if (nocase) { cr.set(mytoupper(trie[v].c)); cr.set(mytolower(trie[v].c)); } else { cr.set(trie[v].c); } for (size_t i = 0; i < esets.size(); i++) { if (esets[i].count() == 1) { continue; } CharReach t = cr & esets[i]; if (t.any() && t != esets[i]) { esets[i] &= ~t; esets.push_back(t); } } } // For deterministic compiles. sort(esets.begin(), esets.end()); return esets; } static u16 buildAlphabet(const LitTrie &trie, bool nocase, array<u16, ALPHABET_SIZE> &alpha, array<u16, ALPHABET_SIZE> &unalpha) { const auto &esets = getAlphabet(trie, nocase); u16 i = 0; for (const auto &cr : esets) { u16 leader = cr.find_first(); for (size_t s = cr.find_first(); s != cr.npos; s = cr.find_next(s)) { alpha[s] = i; } unalpha[i] = leader; i++; } for (u16 j = N_CHARS; j < ALPHABET_SIZE; j++, i++) { alpha[j] = i; unalpha[i] = j; } DEBUG_PRINTF("alphabet size %u\n", i); return i; } /** * \brief Calculate state mapping, from vertex in trie to state index in BFS * ordering. */ static unordered_map<LitTrieVertex, u32> makeStateMap(const LitTrie &trie, const vector<LitTrieVertex> &ordering) { unordered_map<LitTrieVertex, u32> state_ids; state_ids.reserve(num_vertices(trie)); u32 idx = DEAD_STATE + 1; state_ids.emplace(trie.root, idx++); for (auto v : ordering) { state_ids.emplace(v, idx++); } assert(state_ids.size() == num_vertices(trie)); return state_ids; } /** \brief Construct a raw_dfa from a literal trie. */ static unique_ptr<raw_dfa> buildDfa(LitTrie &trie, bool nocase) { DEBUG_PRINTF("trie has %zu states\n", num_vertices(trie)); vector<LitTrieVertex> ordering; unordered_map<LitTrieVertex, LitTrieVertex> failure_map; buildAutomaton(trie, failure_map, ordering); // Construct DFA states in BFS order. const auto state_ids = makeStateMap(trie, ordering); auto rdfa = make_unique<raw_dfa>(NFA_OUTFIX); // Calculate alphabet. array<u16, ALPHABET_SIZE> unalpha; auto &alpha = rdfa->alpha_remap; rdfa->alpha_size = buildAlphabet(trie, nocase, alpha, unalpha); // Construct states and transitions. const u16 root_state = state_ids.at(trie.root); assert(root_state == DEAD_STATE + 1); rdfa->start_anchored = root_state; rdfa->start_floating = root_state; rdfa->states.resize(num_vertices(trie) + 1, dstate(rdfa->alpha_size)); // Dead state. fill(rdfa->states[DEAD_STATE].next.begin(), rdfa->states[DEAD_STATE].next.end(), DEAD_STATE); for (auto u : vertices_range(trie)) { auto u_state = state_ids.at(u); DEBUG_PRINTF("state %u\n", u_state); assert(u_state < rdfa->states.size()); auto &ds = rdfa->states[u_state]; ds.reports = trie[u].reports; if (!ds.reports.empty()) { DEBUG_PRINTF("reports: %s\n", as_string_list(ds.reports).c_str()); } // Set daddy state from failure map. if (u == trie.root) { ds.daddy = DEAD_STATE; } else { assert(contains(failure_map, u)); ds.daddy = state_ids.at(failure_map.at(u)); } // By default, transition back to the root. fill(ds.next.begin(), ds.next.end(), root_state); // TOP should be a self-loop. ds.next[alpha[TOP]] = u_state; // Add in the real transitions. for (auto v : adjacent_vertices_range(u, trie)) { if (v == trie.root) { continue; } auto v_state = state_ids.at(v); u16 sym = alpha[trie[v].c]; DEBUG_PRINTF("edge to %u on 0x%02x (sym %u)\n", v_state, trie[v].c, sym); assert(sym < ds.next.size()); assert(ds.next[sym] == root_state); ds.next[sym] = v_state; } } return rdfa; } #define MAX_GOOD_ACCEL_DEPTH 4 static bool is_slow(const raw_dfa &rdfa, const set<dstate_id_t> &accel, u32 roseQuality) { /* we consider a dfa as slow if there is no way to quickly get into an accel * state/dead state. In these cases, it is more likely that we will be * running at our unaccelerated dfa speeds so the small write engine is only * competitive over a small region where start up costs are dominant. */ if (roseQuality) { return true; } set<dstate_id_t> visited; set<dstate_id_t> next; set<dstate_id_t> curr; curr.insert(rdfa.start_anchored); u32 ialpha_size = rdfa.getImplAlphaSize(); for (u32 i = 0; i < MAX_GOOD_ACCEL_DEPTH; i++) { next.clear(); for (dstate_id_t s : curr) { if (contains(visited, s)) { continue; } visited.insert(s); if (s == DEAD_STATE || contains(accel, s)) { return false; } for (size_t j = 0; j < ialpha_size; j++) { next.insert(rdfa.states[s].next[j]); } } curr.swap(next); } return true; } static bytecode_ptr<NFA> getDfa(raw_dfa &rdfa, const CompileContext &cc, const ReportManager &rm, bool has_non_literals, set<dstate_id_t> &accel_states) { // If we determinised only literals, then we only need to consider the init // states for acceleration. bool only_accel_init = !has_non_literals; bool trust_daddy_states = !has_non_literals; bytecode_ptr<NFA> dfa = nullptr; if (cc.grey.allowSmallWriteSheng) { dfa = shengCompile(rdfa, cc, rm, only_accel_init, &accel_states); if (!dfa) { dfa = sheng32Compile(rdfa, cc, rm, only_accel_init, &accel_states); } if (!dfa) { dfa = sheng64Compile(rdfa, cc, rm, only_accel_init, &accel_states); } } if (!dfa) { dfa = mcclellanCompile(rdfa, cc, rm, only_accel_init, trust_daddy_states, &accel_states); } return dfa; } static bytecode_ptr<NFA> prepEngine(raw_dfa &rdfa, u32 roseQuality, const CompileContext &cc, const ReportManager &rm, bool has_non_literals, u32 *start_offset, u32 *small_region) { *start_offset = remove_leading_dots(rdfa); // Unleash the McClellan! set<dstate_id_t> accel_states; auto nfa = getDfa(rdfa, cc, rm, has_non_literals, accel_states); if (!nfa) { DEBUG_PRINTF("DFA compile failed for smallwrite NFA\n"); return nullptr; } if (is_slow(rdfa, accel_states, roseQuality)) { DEBUG_PRINTF("is slow\n"); *small_region = cc.grey.smallWriteLargestBufferBad; if (*small_region <= *start_offset) { return nullptr; } if (clear_deeper_reports(rdfa, *small_region - *start_offset)) { minimize_hopcroft(rdfa, cc.grey); if (rdfa.start_anchored == DEAD_STATE) { DEBUG_PRINTF("all patterns pruned out\n"); return nullptr; } nfa = getDfa(rdfa, cc, rm, has_non_literals, accel_states); if (!nfa) { DEBUG_PRINTF("DFA compile failed for smallwrite NFA\n"); assert(0); /* able to build orig dfa but not the trimmed? */ return nullptr; } } } else { *small_region = cc.grey.smallWriteLargestBuffer; } assert(isDfaType(nfa->type)); if (nfa->length > cc.grey.limitSmallWriteOutfixSize || nfa->length > cc.grey.limitDFASize) { DEBUG_PRINTF("smallwrite outfix size too large\n"); return nullptr; /* this is just a soft failure - don't build smwr */ } nfa->queueIndex = 0; /* dummy, small write API does not use queue */ return nfa; } // SmallWriteBuild factory unique_ptr<SmallWriteBuild> makeSmallWriteBuilder(size_t num_patterns, const ReportManager &rm, const CompileContext &cc) { return ue2::make_unique<SmallWriteBuildImpl>(num_patterns, rm, cc); } bytecode_ptr<SmallWriteEngine> SmallWriteBuildImpl::build(u32 roseQuality) { const bool has_literals = !is_empty(lit_trie) || !is_empty(lit_trie_nocase); const bool has_non_literals = !dfas.empty(); if (dfas.empty() && !has_literals) { DEBUG_PRINTF("no smallwrite engine\n"); poisoned = true; return nullptr; } if (poisoned) { DEBUG_PRINTF("some pattern could not be made into a smallwrite dfa\n"); return nullptr; } // We happen to know that if the rose is high quality, we're going to limit // depth further. if (roseQuality) { u32 max_depth = cc.grey.smallWriteLargestBufferBad; if (!is_empty(lit_trie)) { pruneTrie(lit_trie, max_depth); } if (!is_empty(lit_trie_nocase)) { pruneTrie(lit_trie_nocase, max_depth); } } if (!is_empty(lit_trie)) { dfas.push_back(buildDfa(lit_trie, false)); DEBUG_PRINTF("caseful literal dfa with %zu states\n", dfas.back()->states.size()); } if (!is_empty(lit_trie_nocase)) { dfas.push_back(buildDfa(lit_trie_nocase, true)); DEBUG_PRINTF("nocase literal dfa with %zu states\n", dfas.back()->states.size()); } if (dfas.empty()) { DEBUG_PRINTF("no dfa, pruned everything away\n"); return nullptr; } if (!mergeDfas(dfas, rm, cc)) { dfas.clear(); return nullptr; } assert(dfas.size() == 1); auto rdfa = std::move(dfas.front()); dfas.clear(); DEBUG_PRINTF("building rdfa %p\n", rdfa.get()); u32 start_offset; u32 small_region; auto nfa = prepEngine(*rdfa, roseQuality, cc, rm, has_non_literals, &start_offset, &small_region); if (!nfa) { DEBUG_PRINTF("some smallwrite outfix could not be prepped\n"); /* just skip the smallwrite optimization */ poisoned = true; return nullptr; } u32 size = sizeof(SmallWriteEngine) + nfa->length; auto smwr = make_zeroed_bytecode_ptr<SmallWriteEngine>(size); smwr->size = size; smwr->start_offset = start_offset; smwr->largestBuffer = small_region; /* copy in nfa after the smwr */ assert(ISALIGNED_CL(smwr.get() + 1)); memcpy(smwr.get() + 1, nfa.get(), nfa->length); DEBUG_PRINTF("smallwrite done %p\n", smwr.get()); return smwr; } set<ReportID> SmallWriteBuildImpl::all_reports() const { set<ReportID> reports; if (poisoned) { return reports; } for (const auto &rdfa : dfas) { insert(&reports, ::ue2::all_reports(*rdfa)); } insert(&reports, ::ue2::all_reports(lit_trie)); insert(&reports, ::ue2::all_reports(lit_trie_nocase)); return reports; } } // namespace ue2
13,545
14,668
// 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 "third_party/blink/public/platform/web_encrypted_media_request.h" #include "third_party/blink/public/platform/web_media_key_system_configuration.h" #include "third_party/blink/public/platform/web_security_origin.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/blink/renderer/platform/encrypted_media_request.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" namespace blink { WebEncryptedMediaRequest::WebEncryptedMediaRequest( const WebEncryptedMediaRequest& request) { Assign(request); } WebEncryptedMediaRequest::WebEncryptedMediaRequest( EncryptedMediaRequest* request) : private_(request) {} WebEncryptedMediaRequest::~WebEncryptedMediaRequest() { Reset(); } WebString WebEncryptedMediaRequest::KeySystem() const { return private_->KeySystem(); } const WebVector<WebMediaKeySystemConfiguration>& WebEncryptedMediaRequest::SupportedConfigurations() const { return private_->SupportedConfigurations(); } WebSecurityOrigin WebEncryptedMediaRequest::GetSecurityOrigin() const { return WebSecurityOrigin(private_->GetSecurityOrigin()); } void WebEncryptedMediaRequest::RequestSucceeded( std::unique_ptr<WebContentDecryptionModuleAccess> access) { private_->RequestSucceeded(std::move(access)); } void WebEncryptedMediaRequest::RequestNotSupported( const WebString& error_message) { private_->RequestNotSupported(error_message); } void WebEncryptedMediaRequest::Assign(const WebEncryptedMediaRequest& other) { private_ = other.private_; } void WebEncryptedMediaRequest::Reset() { private_.Reset(); } } // namespace blink
567
4,756
<filename>cpp/src/phonenumbers/base/memory/singleton_posix.h<gh_stars>1000+ // Copyright (C) 2013 The Libphonenumber 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. #ifndef I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_POSIX_H_ #define I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_POSIX_H_ #include <pthread.h> #include "phonenumbers/base/logging.h" namespace i18n { namespace phonenumbers { template <class T> class Singleton { public: virtual ~Singleton() {} static T* GetInstance() { const int ret = pthread_once(&once_control_, &Init); (void) ret; DCHECK_EQ(0, ret); return instance_; } private: static void Init() { instance_ = new T(); } static T* instance_; // Leaky singleton. static pthread_once_t once_control_; }; template <class T> T* Singleton<T>::instance_; template <class T> pthread_once_t Singleton<T>::once_control_ = PTHREAD_ONCE_INIT; } // namespace phonenumbers } // namespace i18n #endif // I18N_PHONENUMBERS_BASE_MEMORY_SINGLETON_POSIX_H_
534
450
<gh_stars>100-1000 /** * Locale specific code. */ package io.github.jhipster.config.locale;
35
2,706
/* Copyright (c) 2013-2015 <NAME> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GBA_OVERRIDES_H #define GBA_OVERRIDES_H #include <mgba-util/common.h> CXX_GUARD_START #include <mgba/internal/gba/savedata.h> #define IDLE_LOOP_NONE 0xFFFFFFFF struct GBACartridgeOverride { char id[4]; enum SavedataType savetype; int hardware; uint32_t idleLoop; bool mirroring; }; struct Configuration; bool GBAOverrideFind(const struct Configuration*, struct GBACartridgeOverride* override); void GBAOverrideSave(struct Configuration*, const struct GBACartridgeOverride* override); struct GBA; void GBAOverrideApply(struct GBA*, const struct GBACartridgeOverride*); void GBAOverrideApplyDefaults(struct GBA*, const struct Configuration*); CXX_GUARD_END #endif
308
4,879
<gh_stars>1000+ #ifndef MWMBottomMenuState_h #define MWMBottomMenuState_h typedef NS_ENUM(NSUInteger, MWMBottomMenuState) { MWMBottomMenuStateHidden, MWMBottomMenuStateInactive, MWMBottomMenuStateActive, MWMBottomMenuStateLayers }; #endif /* MWMBottomMenuState_h */
111
386
<reponame>ccoderJava/bus<filename>bus-image/src/main/java/org/aoju/bus/image/metric/internal/pdu/AAssociateRQAC.java<gh_stars>100-1000 /********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2021 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * * * ********************************************************************************/ package org.aoju.bus.image.metric.internal.pdu; import org.aoju.bus.core.lang.Normal; import org.aoju.bus.core.lang.Symbol; import org.aoju.bus.image.UID; import org.aoju.bus.image.galaxy.Capacity; import org.aoju.bus.image.galaxy.Property; import org.aoju.bus.image.galaxy.data.Implementation; import org.aoju.bus.image.metric.Connection; import java.util.*; /** * @author <NAME> * @version 6.3.2 * @since JDK 1.8+ */ public abstract class AAssociateRQAC { protected final ArrayList<Presentation> pcs = new ArrayList<>(); protected final Capacity<Presentation> pcidMap = new Capacity<>(); protected final LinkedHashMap<String, RoleSelection> roleSelMap = new LinkedHashMap<>(); protected final LinkedHashMap<String, ExtendedNegotiate> extNegMap = new LinkedHashMap<>(); protected final LinkedHashMap<String, CommonExtended> commonExtNegMap = new LinkedHashMap<>(); protected byte[] reservedBytes = new byte[Normal._32]; protected int protocolVersion = 1; protected int maxPDULength = Connection.DEF_MAX_PDU_LENGTH; protected int maxOpsInvoked = Connection.SYNCHRONOUS_MODE; protected int maxOpsPerformed = Connection.SYNCHRONOUS_MODE; protected String calledAET; protected String callingAET; protected String applicationContext = UID.DICOMApplicationContextName; protected String implClassUID = Implementation.getClassUID(); protected String implVersionName = Implementation.getVersionName(); protected IdentityRQ identityRQ; protected IdentityAC identityAC; public void checkCallingAET() { if (null == callingAET) throw new IllegalStateException("Calling AET not initalized"); } public void checkCalledAET() { if (null == calledAET) throw new IllegalStateException("Called AET not initalized"); } public final int getProtocolVersion() { return protocolVersion; } public final void setProtocolVersion(int protocolVersion) { this.protocolVersion = protocolVersion; } public final byte[] getReservedBytes() { return reservedBytes.clone(); } public final void setReservedBytes(byte[] reservedBytes) { if (reservedBytes.length != Normal._32) throw new IllegalArgumentException("reservedBytes.length: " + reservedBytes.length); System.arraycopy(reservedBytes, 0, this.reservedBytes, 0, Normal._32); } public final String getCalledAET() { return calledAET; } public final void setCalledAET(String calledAET) { if (calledAET.length() > Normal._16) throw new IllegalArgumentException("calledAET: " + calledAET); this.calledAET = calledAET; } public final String getCallingAET() { return callingAET; } public final void setCallingAET(String callingAET) { if (callingAET.length() > Normal._16) throw new IllegalArgumentException("callingAET: " + callingAET); this.callingAET = callingAET; } public final String getApplicationContext() { return applicationContext; } public final void setApplicationContext(String applicationContext) { if (null == applicationContext) throw new NullPointerException(); this.applicationContext = applicationContext; } public final int getMaxPDULength() { return maxPDULength; } public final void setMaxPDULength(int maxPDULength) { this.maxPDULength = maxPDULength; } public final int getMaxOpsInvoked() { return maxOpsInvoked; } public final void setMaxOpsInvoked(int maxOpsInvoked) { this.maxOpsInvoked = maxOpsInvoked; } public final int getMaxOpsPerformed() { return maxOpsPerformed; } public final void setMaxOpsPerformed(int maxOpsPerformed) { this.maxOpsPerformed = maxOpsPerformed; } public final boolean isAsyncOps() { return maxOpsInvoked != 1 || maxOpsPerformed != 1; } public final String getImplClassUID() { return implClassUID; } public final void setImplClassUID(String implClassUID) { if (null == implClassUID) throw new NullPointerException(); this.implClassUID = implClassUID; } public final String getImplVersionName() { return implVersionName; } public final void setImplVersionName(String implVersionName) { this.implVersionName = implVersionName; } public final IdentityRQ getIdentityRQ() { return identityRQ; } public void setIdentityRQ(IdentityRQ identityRQ) { this.identityRQ = identityRQ; } public final IdentityAC getIdentityAC() { return identityAC; } public void setIdentityAC(IdentityAC identityAC) { this.identityAC = identityAC; } public List<Presentation> getPresentationContexts() { return Collections.unmodifiableList(pcs); } public int getNumberOfPresentationContexts() { return pcs.size(); } public Presentation getPresentationContext(int pcid) { return pcidMap.get(pcid); } public void addPresentationContext(Presentation pc) { int pcid = pc.getPCID(); if (pcidMap.containsKey(pcid)) throw new IllegalStateException( "Already contains Presentation Context with pid: " + pcid); pcidMap.put(pcid, pc); pcs.add(pc); } public boolean removePresentationContext(Presentation pc) { if (!pcs.remove(pc)) return false; pcidMap.remove(pc.getPCID()); return true; } public Collection<RoleSelection> getRoleSelections() { return Collections.unmodifiableCollection(roleSelMap.values()); } public RoleSelection getRoleSelectionFor(String cuid) { return roleSelMap.get(cuid); } public RoleSelection addRoleSelection(RoleSelection rs) { return roleSelMap.put(rs.getSOPClassUID(), rs); } public RoleSelection removeRoleSelectionFor(String cuid) { return roleSelMap.remove(cuid); } public Collection<ExtendedNegotiate> getExtendedNegotiations() { return Collections.unmodifiableCollection(extNegMap.values()); } public ExtendedNegotiate getExtNegotiationFor(String cuid) { return extNegMap.get(cuid); } public ExtendedNegotiate addExtendedNegotiate(ExtendedNegotiate extNeg) { return extNegMap.put(extNeg.getSOPClassUID(), extNeg); } public ExtendedNegotiate removeExtendedNegotiationFor(String cuid) { return extNegMap.remove(cuid); } public Collection<CommonExtended> getCommonExtendedNegotiations() { return Collections.unmodifiableCollection(commonExtNegMap.values()); } public CommonExtended getCommonExtendedNegotiationFor(String cuid) { return commonExtNegMap.get(cuid); } public CommonExtended addCommonExtendedNegotiation( CommonExtended extNeg) { return commonExtNegMap.put(extNeg.getSOPClassUID(), extNeg); } public CommonExtended removeCommonExtendedNegotiationFor( String cuid) { return commonExtNegMap.remove(cuid); } public int length() { int len = 68; // Fix AA-RQ/AC PDU fields len += 4 + applicationContext.length(); for (Presentation pc : pcs) { len += 4 + pc.length(); } len += 4 + userInfoLength(); return len; } public int userInfoLength() { int len = 8; // 最大长度子项 len += 4 + implClassUID.length(); if (isAsyncOps()) len += 8; // 异步操作窗口子项 for (RoleSelection rs : roleSelMap.values()) { len += 4 + rs.length(); } if (null != implVersionName) len += 4 + implVersionName.length(); for (ExtendedNegotiate en : extNegMap.values()) { len += 4 + en.length(); } for (CommonExtended cen : commonExtNegMap.values()) { len += 4 + cen.length(); } if (null != identityRQ) len += 4 + identityRQ.length(); if (null != identityAC) len += 4 + identityAC.length(); return len; } protected StringBuilder promptTo(String header, StringBuilder sb) { sb.append(header) .append(Property.LINE_SEPARATOR) .append(" calledAET: ").append(calledAET) .append(Property.LINE_SEPARATOR) .append(" callingAET: ").append(callingAET) .append(Property.LINE_SEPARATOR) .append(" applicationContext: "); UID.promptTo(applicationContext, sb) .append(Property.LINE_SEPARATOR) .append(" implClassUID: ").append(implClassUID) .append(Property.LINE_SEPARATOR) .append(" implVersionName: ").append(implVersionName) .append(Property.LINE_SEPARATOR) .append(" maxPDULength: ").append(maxPDULength) .append(Property.LINE_SEPARATOR) .append(" maxOpsInvoked/maxOpsPerformed: ") .append(maxOpsInvoked).append(Symbol.SLASH).append(maxOpsPerformed) .append(Property.LINE_SEPARATOR); if (null != identityRQ) identityRQ.promptTo(sb).append(Property.LINE_SEPARATOR); if (null != identityAC) identityAC.promptTo(sb).append(Property.LINE_SEPARATOR); for (Presentation pc : pcs) pc.promptTo(sb).append(Property.LINE_SEPARATOR); for (RoleSelection rs : roleSelMap.values()) rs.promptTo(sb).append(Property.LINE_SEPARATOR); for (ExtendedNegotiate extNeg : extNegMap.values()) extNeg.promptTo(sb).append(Property.LINE_SEPARATOR); for (CommonExtended extNeg : commonExtNegMap.values()) extNeg.promptTo(sb).append(Property.LINE_SEPARATOR); return sb.append("]"); } }
5,215
722
<filename>asteroid/masknn/norms.py<gh_stars>100-1000 from functools import partial import torch from torch import nn from torch.nn.modules.batchnorm import _BatchNorm from typing import List from .. import complex_nn from ..utils.torch_utils import script_if_tracing EPS = 1e-8 def z_norm(x, dims: List[int], eps: float = 1e-8): mean = x.mean(dim=dims, keepdim=True) var2 = torch.var(x, dim=dims, keepdim=True, unbiased=False) value = (x - mean) / torch.sqrt((var2 + eps)) return value @script_if_tracing def _glob_norm(x, eps: float = 1e-8): dims: List[int] = torch.arange(1, len(x.shape)).tolist() return z_norm(x, dims, eps) @script_if_tracing def _feat_glob_norm(x, eps: float = 1e-8): dims: List[int] = torch.arange(2, len(x.shape)).tolist() return z_norm(x, dims, eps) class _LayerNorm(nn.Module): """Layer Normalization base class.""" def __init__(self, channel_size): super(_LayerNorm, self).__init__() self.channel_size = channel_size self.gamma = nn.Parameter(torch.ones(channel_size), requires_grad=True) self.beta = nn.Parameter(torch.zeros(channel_size), requires_grad=True) def apply_gain_and_bias(self, normed_x): """ Assumes input of size `[batch, chanel, *]`. """ return (self.gamma * normed_x.transpose(1, -1) + self.beta).transpose(1, -1) class GlobLN(_LayerNorm): """Global Layer Normalization (globLN).""" def forward(self, x, EPS: float = 1e-8): """Applies forward pass. Works for any input size > 2D. Args: x (:class:`torch.Tensor`): Shape `[batch, chan, *]` Returns: :class:`torch.Tensor`: gLN_x `[batch, chan, *]` """ value = _glob_norm(x, eps=EPS) return self.apply_gain_and_bias(value) class ChanLN(_LayerNorm): """Channel-wise Layer Normalization (chanLN).""" def forward(self, x, EPS: float = 1e-8): """Applies forward pass. Works for any input size > 2D. Args: x (:class:`torch.Tensor`): `[batch, chan, *]` Returns: :class:`torch.Tensor`: chanLN_x `[batch, chan, *]` """ mean = torch.mean(x, dim=1, keepdim=True) var = torch.var(x, dim=1, keepdim=True, unbiased=False) return self.apply_gain_and_bias((x - mean) / (var + EPS).sqrt()) class CumLN(_LayerNorm): """Cumulative Global layer normalization(cumLN).""" def forward(self, x, EPS: float = 1e-8): """ Args: x (:class:`torch.Tensor`): Shape `[batch, channels, length]` Returns: :class:`torch.Tensor`: cumLN_x `[batch, channels, length]` """ batch, chan, spec_len = x.size() cum_sum = torch.cumsum(x.sum(1, keepdim=True), dim=-1) cum_pow_sum = torch.cumsum(x.pow(2).sum(1, keepdim=True), dim=-1) cnt = torch.arange( start=chan, end=chan * (spec_len + 1), step=chan, dtype=x.dtype, device=x.device ).view(1, 1, -1) cum_mean = cum_sum / cnt cum_var = cum_pow_sum - cum_mean.pow(2) return self.apply_gain_and_bias((x - cum_mean) / (cum_var + EPS).sqrt()) class FeatsGlobLN(_LayerNorm): """Feature-wise global Layer Normalization (FeatsGlobLN). Applies normalization over frames for each channel.""" def forward(self, x, EPS: float = 1e-8): """Applies forward pass. Works for any input size > 2D. Args: x (:class:`torch.Tensor`): `[batch, chan, time]` Returns: :class:`torch.Tensor`: chanLN_x `[batch, chan, time]` """ value = _feat_glob_norm(x, eps=EPS) return self.apply_gain_and_bias(value) class BatchNorm(_BatchNorm): """Wrapper class for pytorch BatchNorm1D and BatchNorm2D""" def _check_input_dim(self, input): if input.dim() < 2 or input.dim() > 4: raise ValueError("expected 4D or 3D input (got {}D input)".format(input.dim())) # Aliases. gLN = GlobLN fgLN = FeatsGlobLN cLN = ChanLN cgLN = CumLN bN = BatchNorm def register_norm(custom_norm): """Register a custom norm, gettable with `norms.get`. Args: custom_norm: Custom norm to register. """ if custom_norm.__name__ in globals().keys() or custom_norm.__name__.lower() in globals().keys(): raise ValueError(f"Norm {custom_norm.__name__} already exists. Choose another name.") globals().update({custom_norm.__name__: custom_norm}) def get(identifier): """Returns a norm class from a string. Returns its input if it is callable (already a :class:`._LayerNorm` for example). Args: identifier (str or Callable or None): the norm identifier. Returns: :class:`._LayerNorm` or None """ if identifier is None: return None elif callable(identifier): return identifier elif isinstance(identifier, str): cls = globals().get(identifier) if cls is None: raise ValueError("Could not interpret normalization identifier: " + str(identifier)) return cls else: raise ValueError("Could not interpret normalization identifier: " + str(identifier)) def get_complex(identifier): """Like `.get` but returns a complex norm created with `asteroid.complex_nn.OnReIm`.""" norm = get(identifier) if norm is None: return None else: return partial(complex_nn.OnReIm, norm)
2,406
3,702
<reponame>mondeique/metatron-discovery /* * 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 app.metatron.discovery.domain.workbook.widget; import com.fasterxml.jackson.annotation.JsonTypeName; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import app.metatron.discovery.common.GlobalObjectMapper; import app.metatron.discovery.domain.workbook.DashBoard; import app.metatron.discovery.domain.workbook.configurations.WidgetConfiguration; import app.metatron.discovery.domain.workbook.configurations.widget.TextWidgetConfiguration; import app.metatron.discovery.util.PolarisUtils; /** * Created by kyungtaak on 2017. 7. 18.. */ @Entity @JsonTypeName("text") @DiscriminatorValue("text") public class TextWidget extends Widget { /** * HTML 컨텐츠 */ @Column(name = "widget_text_contents", length = 65535, columnDefinition = "TEXT") @Basic(fetch = FetchType.LAZY) String contents; /** * Default Constructor */ public TextWidget() { // Empty Constructor } @Override public Widget copyOf(DashBoard parent, boolean addPrefix) { TextWidget textWidget = new TextWidget(); textWidget.setName(addPrefix ? PolarisUtils.COPY_OF_PREFIX + name : name); textWidget.setDescription(description); textWidget.setConfiguration(configuration); if(parent == null) { textWidget.setDashBoard(dashBoard); } else { textWidget.setDashBoard(parent); } return textWidget; } @Override public WidgetConfiguration convertConfiguration() { return GlobalObjectMapper.readValue(this.configuration, TextWidgetConfiguration.class); } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } }
752
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package org.openoffice.accessibility.misc; import java.lang.Thread; import com.sun.star.awt.Rectangle; import com.sun.star.awt.XExtendedToolkit; import com.sun.star.awt.XWindow; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XChild; import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XEnumeration; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.frame.XTasksSupplier; import com.sun.star.frame.XTask; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.XServiceName; import com.sun.star.lang.XTypeProvider; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.uno.Type; import com.sun.star.drawing.XDrawView; import com.sun.star.drawing.XDrawPage; import com.sun.star.drawing.XShapes; import com.sun.star.drawing.XShape; import com.sun.star.drawing.XShapeDescriptor; import com.sun.star.accessibility.XAccessible; import com.sun.star.accessibility.XAccessibleContext; import com.sun.star.accessibility.XAccessibleComponent; import com.sun.star.accessibility.XAccessibleRelationSet; import com.sun.star.accessibility.XAccessibleStateSet; /** This singleton class tries to simplify some tasks like loading a document or getting various objects. */ public class SimpleOffice { synchronized static public SimpleOffice Instance () { if (saInstance == null) saInstance = new SimpleOffice (); return saInstance; } synchronized static public void Clear () { saInstance = null; } public XModel LoadDocument (String URL) { XModel xModel = null; try { // Load the document from the specified URL. XComponentLoader xLoader = (XComponentLoader)UnoRuntime.queryInterface( XComponentLoader.class, mxDesktop); XComponent xComponent = xLoader.loadComponentFromURL ( URL, "_blank", 0, new PropertyValue[0] ); xModel = (XModel) UnoRuntime.queryInterface( XModel.class, xComponent); } catch (java.lang.NullPointerException e) { MessageArea.println ("caught exception while loading " + URL + " : " + e); } catch (Exception e) { MessageArea.println ("caught exception while loading " + URL + " : " + e); } return xModel; } public XModel GetModel (String name) { XModel xModel = null; try { XTasksSupplier xTasksSupplier = (XTasksSupplier) UnoRuntime.queryInterface( XTasksSupplier.class, mxDesktop); XEnumerationAccess xEA = xTasksSupplier.getTasks(); XEnumeration xE = xEA.createEnumeration(); while (xE.hasMoreElements()) { XTask xTask = (XTask) UnoRuntime.queryInterface( XTask.class, xE.nextElement()); MessageArea.print (xTask.getName()); } } catch (Exception e) { MessageArea.println ("caught exception while getting Model " + name + ": " + e); } return xModel; } public XModel GetModel (XDrawView xView) { XController xController = (XController) UnoRuntime.queryInterface( XController.class, xView); if (xController != null) return xController.getModel(); else { MessageArea.println ("can't cast view to controller"); return null; } } public XDesktop GetDesktop () { if (mxDesktop != null) return mxDesktop; try { // Get the factory of the connected office. XMultiServiceFactory xMSF = OfficeConnection.Instance().GetServiceManager (); if (xMSF == null) { MessageArea.println ("can't connect to office"); return null; } else MessageArea.println ("Connected successfully."); // Create a new desktop. mxDesktop = (XDesktop) UnoRuntime.queryInterface( XDesktop.class, xMSF.createInstance ("com.sun.star.frame.Desktop") ); } catch (Exception e) { MessageArea.println ("caught exception while creating desktop: " + e); } return mxDesktop; } /** Return a reference to the extended toolkit which is a broadcaster of top window, key, and focus events. */ public XExtendedToolkit GetExtendedToolkit () { XExtendedToolkit xToolkit = null; if (this != null) try { // Get the factory of the connected office. XMultiServiceFactory xMSF = OfficeConnection.Instance().GetServiceManager (); if (xMSF != null) { xToolkit = (XExtendedToolkit) UnoRuntime.queryInterface( XExtendedToolkit.class, xMSF.createInstance ("stardiv.Toolkit.VCLXToolkit") ); } } catch (Exception e) { MessageArea.println ( "caught exception while creating extended toolkit: " + e); } return xToolkit; } static public XAccessible GetAccessibleObject (XInterface xObject) { XAccessible xAccessible = null; try { xAccessible = (XAccessible) UnoRuntime.queryInterface( XAccessible.class, xObject); } catch (Exception e) { System.err.println ( "caught exception while getting accessible object" + e); e.printStackTrace (System.err); } return xAccessible; } static public XAccessibleContext GetAccessibleContext (XInterface xObject) { XAccessible xAccessible = GetAccessibleObject (xObject); if (xAccessible != null) return xAccessible.getAccessibleContext(); else return null; } /** Return the root object of the accessibility hierarchy. */ public XAccessible GetAccessibleRoot (XAccessible xAccessible) { try { XAccessible xParent = null; do { XAccessibleContext xContext = xAccessible.getAccessibleContext(); if (xContext != null) xParent = xContext.getAccessibleParent(); if (xParent != null) xAccessible = xParent; } while (xParent != null); } catch (Exception e) { MessageArea.println ( "caught exception while getting accessible root" + e); e.printStackTrace(); } return xAccessible; } /** @descr Return the current window associated with the given model. */ public XWindow GetCurrentWindow () { return GetCurrentWindow ((XModel) UnoRuntime.queryInterface( XModel.class, GetDesktop())); } public XWindow GetCurrentWindow (XModel xModel) { XWindow xWindow = null; try { if (xModel == null) MessageArea.println ("invalid model (==null)"); XController xController = xModel.getCurrentController(); if (xController == null) MessageArea.println ("can't get controller from model"); XFrame xFrame = xController.getFrame(); if (xFrame == null) MessageArea.println ("can't get frame from controller"); xWindow = xFrame.getComponentWindow (); if (xWindow == null) MessageArea.println ("can't get window from frame"); } catch (Exception e) { MessageArea.println ("caught exception while getting current window" + e); } return xWindow; } /** @descr Return the current draw page of the given desktop. */ public XDrawPage GetCurrentDrawPage () { return GetCurrentDrawPage ( (XDrawView) UnoRuntime.queryInterface( XDrawView.class, GetCurrentView())); } public XDrawPage GetCurrentDrawPage (XDrawView xView) { XDrawPage xPage = null; try { if (xView == null) MessageArea.println ("can't get current draw page from null view"); else xPage = xView.getCurrentPage(); } catch (Exception e) { MessageArea.println ("caught exception while getting current draw page : " + e); } return xPage; } /** @descr Return the current view of the given desktop. */ public XDrawView GetCurrentView () { return GetCurrentView (GetDesktop()); } public XDrawView GetCurrentView (XDesktop xDesktop) { if (xDesktop == null) MessageArea.println ("can't get desktop to retrieve current view"); XDrawView xView = null; try { XComponent xComponent = xDesktop.getCurrentComponent(); if (xComponent == null) MessageArea.println ("can't get component to retrieve current view"); XFrame xFrame = xDesktop.getCurrentFrame(); if (xFrame == null) MessageArea.println ("can't get frame to retrieve current view"); XController xController = xFrame.getController(); if (xController == null) MessageArea.println ("can't get controller to retrieve current view"); xView = (XDrawView) UnoRuntime.queryInterface( XDrawView.class, xController); if (xView == null) MessageArea.println ("could not cast controller into view"); } catch (Exception e) { MessageArea.println ("caught exception while getting current view : " + e); } return xView; } // Return the accessible object of the document window. public static XAccessible GetAccessibleDocumentWindow (XDrawPage xPage) { XIndexAccess xShapeList = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xPage); if (xShapeList.getCount() > 0) { // All shapes return as accessible object the document window's // accessible object. This is, of course, a hack and will be // removed as soon as the missing infrastructure for obtaining // the object directly is implemented. XShape xShape = null; try{ xShape = (XShape) UnoRuntime.queryInterface( XShape.class, xShapeList.getByIndex (0)); } catch (Exception e) {} XAccessible xAccessible = (XAccessible) UnoRuntime.queryInterface ( XAccessible.class, xShape); return xAccessible; } else return null; } private SimpleOffice () { } private XDesktop mxDesktop; private static SimpleOffice saInstance = null; }
5,721
1,005
import torch from torch import nn from torch.nn import functional as F from models.networks import BaseNetwork ################################################################################## # Sequential Models ################################################################################## class ResBlocks(nn.Module): def __init__(self, num_blocks, dim, norm='in', activation='relu', pad_type='zero'): super(ResBlocks, self).__init__() self.model = [] for i in range(num_blocks): self.model += [ResBlock(dim, norm=norm, activation=activation, pad_type=pad_type)] self.model = nn.Sequential(*self.model) def forward(self, x): return self.model(x) class MLP(nn.Module): def __init__(self, input_dim, output_dim, dim, n_blk, norm='none', activ='relu'): super(MLP, self).__init__() self.model = [] self.model += [LinearBlock(input_dim, dim, norm=norm, activation=activ)] for i in range(n_blk - 2): self.model += [LinearBlock(dim, dim, norm=norm, activation=activ)] self.model += [LinearBlock(dim, output_dim, norm='none', activation='none')] # no output activations self.model = nn.Sequential(*self.model) def forward(self, x): return self.model(x.view(x.size(0), -1)) ################################################################################## # Basic Blocks ################################################################################## class ResBlock(nn.Module): def __init__(self, dim, norm='in', activation='relu', pad_type='zero'): super(ResBlock, self).__init__() model = [] model += [Conv2dBlock(dim, dim, 3, 1, 1, norm=norm, activation=activation, pad_type=pad_type)] model += [Conv2dBlock(dim, dim, 3, 1, 1, norm=norm, activation='none', pad_type=pad_type)] self.model = nn.Sequential(*model) def forward(self, x): residual = x out = self.model(x) out += residual return out class Conv2dBlock(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, stride, padding=0, norm='none', activation='relu', pad_type='zero'): super(Conv2dBlock, self).__init__() self.use_bias = True # initialize padding if pad_type == 'reflect': self.pad = nn.ReflectionPad2d(padding) elif pad_type == 'replicate': self.pad = nn.ReplicationPad2d(padding) elif pad_type == 'zero': self.pad = nn.ZeroPad2d(padding) else: assert 0, "Unsupported padding type: {}".format(pad_type) # initialize normalization norm_dim = output_dim if norm == 'bn': self.norm = nn.BatchNorm2d(norm_dim) elif norm == 'in': self.norm = nn.InstanceNorm2d(norm_dim) elif norm == 'ln': self.norm = LayerNorm(norm_dim) elif norm == 'adain': self.norm = AdaptiveInstanceNorm2d(norm_dim) elif norm == 'none' or norm == 'sn': self.norm = None else: assert 0, "Unsupported normalization: {}".format(norm) # initialize activation if activation == 'relu': self.activation = nn.ReLU(inplace=True) elif activation == 'lrelu': self.activation = nn.LeakyReLU(0.2, inplace=True) elif activation == 'prelu': self.activation = nn.PReLU() elif activation == 'selu': self.activation = nn.SELU(inplace=True) elif activation == 'tanh': self.activation = nn.Tanh() elif activation == 'none': self.activation = None else: assert 0, "Unsupported activation: {}".format(activation) # initialize convolution if norm == 'sn': self.conv = SpectralNorm(nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias)) else: self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias) def forward(self, x): x = self.conv(self.pad(x)) if self.norm: x = self.norm(x) if self.activation: x = self.activation(x) return x class LinearBlock(nn.Module): def __init__(self, input_dim, output_dim, norm='none', activation='relu'): super(LinearBlock, self).__init__() use_bias = True # initialize fully connected layer if norm == 'sn': self.fc = SpectralNorm(nn.Linear(input_dim, output_dim, bias=use_bias)) else: self.fc = nn.Linear(input_dim, output_dim, bias=use_bias) # initialize normalization norm_dim = output_dim if norm == 'bn': self.norm = nn.BatchNorm1d(norm_dim) elif norm == 'in': self.norm = nn.InstanceNorm1d(norm_dim) elif norm == 'ln': self.norm = LayerNorm(norm_dim) elif norm == 'none' or norm == 'sn': self.norm = None else: assert 0, "Unsupported normalization: {}".format(norm) # initialize activation if activation == 'relu': self.activation = nn.ReLU(inplace=True) elif activation == 'lrelu': self.activation = nn.LeakyReLU(0.2, inplace=True) elif activation == 'prelu': self.activation = nn.PReLU() elif activation == 'selu': self.activation = nn.SELU(inplace=True) elif activation == 'tanh': self.activation = nn.Tanh() elif activation == 'none': self.activation = None else: assert 0, "Unsupported activation: {}".format(activation) def forward(self, x): out = self.fc(x) if self.norm: out = self.norm(out) if self.activation: out = self.activation(out) return out ################################################################################## # Normalization layers ################################################################################## class AdaptiveInstanceNorm2d(nn.Module): def __init__(self, num_features, eps=1e-5, momentum=0.1): super(AdaptiveInstanceNorm2d, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum # weight and bias are dynamically assigned self.weight = None self.bias = None def forward(self, x): assert self.weight is not None and self.bias is not None, "Please assign weight and bias before calling AdaIN!" b, c = x.size(0), x.size(1) # Apply instance norm x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:]) out = F.batch_norm( x_reshaped, None, None, self.weight, self.bias, True, self.momentum, self.eps) return out.view(b, c, *x.size()[2:]) def __repr__(self): return self.__class__.__name__ + '(' + str(self.num_features) + ')' class LayerNorm(nn.Module): def __init__(self, num_features, eps=1e-5, affine=True): super(LayerNorm, self).__init__() self.num_features = num_features self.affine = affine self.eps = eps if self.affine: self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_()) self.beta = nn.Parameter(torch.zeros(num_features)) def forward(self, x): shape = [-1] + [1] * (x.dim() - 1) if x.size(0) == 1: # These two lines run much faster in pytorch 0.4 than the two lines listed below. mean = x.view(-1).mean().view(*shape) std = x.view(-1).std().view(*shape) else: mean = x.view(x.size(0), -1).mean(1).view(*shape) std = x.view(x.size(0), -1).std(1).view(*shape) x = (x - mean) / (std + self.eps) if self.affine: shape = [1, -1] + [1] * (x.dim() - 2) x = x * self.gamma.view(*shape) + self.beta.view(*shape) return x def l2normalize(v, eps=1e-12): return v / (v.norm() + eps) class SpectralNorm(nn.Module): """ Based on the paper "Spectral Normalization for Generative Adversarial Networks" by <NAME>, <NAME>, <NAME>, <NAME> and the Pytorch implementation https://github.com/christiancosgrove/pytorch-spectral-normalization-gan """ def __init__(self, module, name='weight', power_iterations=1): super(SpectralNorm, self).__init__() self.module = module self.name = name self.power_iterations = power_iterations if not self._made_params(): self._make_params() def _update_u_v(self): u = getattr(self.module, self.name + "_u") v = getattr(self.module, self.name + "_v") w = getattr(self.module, self.name + "_bar") height = w.data.shape[0] for _ in range(self.power_iterations): v.data = l2normalize(torch.mv(torch.t(w.view(height, -1).data), u.data)) u.data = l2normalize(torch.mv(w.view(height, -1).data, v.data)) # sigma = torch.dot(u.data, torch.mv(w.view(height,-1).data, v.data)) sigma = u.dot(w.view(height, -1).mv(v)) setattr(self.module, self.name, w / sigma.expand_as(w)) def _made_params(self): try: u = getattr(self.module, self.name + "_u") v = getattr(self.module, self.name + "_v") w = getattr(self.module, self.name + "_bar") return True except AttributeError: return False def _make_params(self): w = getattr(self.module, self.name) height = w.data.shape[0] width = w.view(height, -1).data.shape[1] u = nn.Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) v = nn.Parameter(w.data.new(width).normal_(0, 1), requires_grad=False) u.data = l2normalize(u.data) v.data = l2normalize(v.data) w_bar = nn.Parameter(w.data) del self.module._parameters[self.name] self.module.register_parameter(self.name + "_u", u) self.module.register_parameter(self.name + "_v", v) self.module.register_parameter(self.name + "_bar", w_bar) def forward(self, *args): self._update_u_v() return self.module.forward(*args) ################################################################################## # Generator ################################################################################## class AdaINGenerator(BaseNetwork): # AdaIN auto-encoder architecture def __init__(self, opt): super(AdaINGenerator, self).__init__() self.opt = opt input_dim = opt.input_nc dim = opt.ngf style_dim = opt.style_dim n_downsample = opt.n_downsample n_res = opt.n_res activ = opt.activ pad_type = opt.pad_type mlp_dim = opt.mlp_dim no_style_encoder = opt.no_style_encoder if not no_style_encoder: self.enc_style = StyleEncoder(4, input_dim, dim, style_dim, norm='none', activ=activ, pad_type=pad_type) # content encoder self.enc_content = ContentEncoder(n_downsample, n_res, input_dim, dim, 'in', activ, pad_type=pad_type) self.dec = Decoder(n_downsample, n_res, self.enc_content.output_dim, input_dim, res_norm='adain', activ=activ, pad_type=pad_type) # MLP to generate AdaIN parameters self.mlp = MLP(style_dim, self.get_num_adain_params(self.dec), mlp_dim, 3, norm='none', activ=activ) def forward(self, images, z=None): # reconstruct an image if z is None: content, style_fake = self.encode(images) else: content, _ = self.encode(images, need_style=False) style_fake = z images_recon = self.decode(content, style_fake) return images_recon def encode(self, images, need_content=True, need_style=True): # encode an image to its content and style codes if need_style: assert hasattr(self, 'enc_style') style_fake = self.enc_style(images) else: style_fake = None if need_content: content = self.enc_content(images) else: content = None return content, style_fake def decode(self, content, style): # decode content and style codes to an image adain_params = self.mlp(style) self.assign_adain_params(adain_params, self.dec) images = self.dec(content) return images def assign_adain_params(self, adain_params, model): # assign the adain_params to the AdaIN layers in model for m in model.modules(): if m.__class__.__name__ == "AdaptiveInstanceNorm2d": mean = adain_params[:, :m.num_features] std = adain_params[:, m.num_features:2 * m.num_features] m.bias = mean.contiguous().view(-1) m.weight = std.contiguous().view(-1) if adain_params.size(1) > 2 * m.num_features: adain_params = adain_params[:, 2 * m.num_features:] def get_num_adain_params(self, model): # return the number of AdaIN parameters needed by the model num_adain_params = 0 for m in model.modules(): if m.__class__.__name__ == "AdaptiveInstanceNorm2d": num_adain_params += 2 * m.num_features return num_adain_params ################################################################################## # Encoder and Decoders ################################################################################## class StyleEncoder(nn.Module): def __init__(self, n_downsample, input_dim, dim, style_dim, norm, activ, pad_type): super(StyleEncoder, self).__init__() self.model = [] self.model += [Conv2dBlock(input_dim, dim, 7, 1, 3, norm=norm, activation=activ, pad_type=pad_type)] for i in range(2): self.model += [Conv2dBlock(dim, 2 * dim, 4, 2, 1, norm=norm, activation=activ, pad_type=pad_type)] dim *= 2 for i in range(n_downsample - 2): self.model += [Conv2dBlock(dim, dim, 4, 2, 1, norm=norm, activation=activ, pad_type=pad_type)] self.model += [nn.AdaptiveAvgPool2d(1)] # global average pooling self.model += [nn.Conv2d(dim, style_dim, 1, 1, 0)] self.model = nn.Sequential(*self.model) self.output_dim = dim def forward(self, x): return self.model(x) class ContentEncoder(nn.Module): def __init__(self, n_downsample, n_res, input_dim, dim, norm, activ, pad_type): super(ContentEncoder, self).__init__() self.model = [] self.model += [Conv2dBlock(input_dim, dim, 7, 1, 3, norm=norm, activation=activ, pad_type=pad_type)] # downsampling blocks for i in range(n_downsample): self.model += [Conv2dBlock(dim, 2 * dim, 4, 2, 1, norm=norm, activation=activ, pad_type=pad_type)] dim *= 2 # residual blocks self.model += [ResBlocks(n_res, dim, norm=norm, activation=activ, pad_type=pad_type)] self.model = nn.Sequential(*self.model) self.output_dim = dim def forward(self, x): return self.model(x) class Decoder(nn.Module): def __init__(self, n_upsample, n_res, dim, output_dim, res_norm='adain', activ='relu', pad_type='zero'): super(Decoder, self).__init__() self.model = [] # AdaIN residual blocks self.model += [ResBlocks(n_res, dim, res_norm, activ, pad_type=pad_type)] # upsampling blocks for i in range(n_upsample): self.model += [nn.Upsample(scale_factor=2), Conv2dBlock(dim, dim // 2, 5, 1, 2, norm='ln', activation=activ, pad_type=pad_type)] dim //= 2 # use reflection padding in the last conv layer self.model += [Conv2dBlock(dim, output_dim, 7, 1, 3, norm='none', activation='tanh', pad_type=pad_type)] self.model = nn.Sequential(*self.model) def forward(self, x): return self.model(x)
7,185
734
<reponame>adamnemecek/tracktion_engine<gh_stars>100-1000 /* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { //============================================================================== /** Holds a list of TempoSetting objects, to form a sequence of tempo changes. You can query this at particular points, but it's wise to use a TempoSequencePosition object to iterate it. */ class TempoSequence : public Selectable, private juce::AsyncUpdater { public: //============================================================================== TempoSequence (Edit&); ~TempoSequence() override; Edit& getEdit() const { return edit; } const juce::ValueTree& getState() const { return state; } void setState (const juce::ValueTree&, bool remapEdit); void createEmptyState(); void copyFrom (const TempoSequence&); void freeResources(); //============================================================================== juce::UndoManager* getUndoManager() const noexcept; //============================================================================== const juce::Array<TimeSigSetting*>& getTimeSigs() const; int getNumTimeSigs() const; TimeSigSetting* getTimeSig (int index) const; TimeSigSetting& getTimeSigAt (double time) const; TimeSigSetting& getTimeSigAtBeat (double beat) const; int indexOfTimeSigAt (double time) const; int indexOfTimeSig (const TimeSigSetting*) const; //============================================================================== const juce::Array<TempoSetting*>& getTempos() const; int getNumTempos() const; TempoSetting* getTempo (int index) const; TempoSetting& getTempoAt (double time) const; TempoSetting& getTempoAtBeat (double beat) const; double getBpmAt (double time) const; // takes ramping into account double getBeatsPerSecondAt (double time, bool lengthOfOneBeatDependsOnTimeSignature = false) const; bool isTripletsAtTime (double time) const; int indexOfTempoAt (double t) const; int indexOfNextTempoAt (double t) const; int indexOfTempo (const TempoSetting*) const; int countTemposInRegion (EditTimeRange range) const; juce::int64 createHashForTemposInRange (EditTimeRange) const; /** inserts a tempo break that can be edited later. */ TempoSetting::Ptr insertTempo (double time); TempoSetting::Ptr insertTempo (double beatNum, double bpm, float curve); TimeSigSetting::Ptr insertTimeSig (double time); void removeTempo (int index, bool remapEdit); void removeTemposBetween (EditTimeRange, bool remapEdit); void removeTimeSig (int index); void removeTimeSigsBetween (EditTimeRange); void moveTempoStart (int index, double deltaBeats, bool snapToBeat); void moveTimeSigStart (int index, double deltaBeats, bool snapToBeat); /** Inserts space in to a sequence, shifting TempoSettings and TimeSigs. */ void insertSpaceIntoSequence (double time, double amountOfSpaceInSeconds, bool snapToBeat); /** Removes a region in a sequence, shifting TempoSettings and TimeSigs. */ void deleteRegion (EditTimeRange); //============================================================================== double timeToBeats (double time) const; juce::Range<double> timeToBeats (EditTimeRange timeRange) const; struct BarsAndBeats { int bars; double beats; int getWholeBeats() const; double getFractionalBeats() const; }; BarsAndBeats timeToBarsBeats (double time) const; double barsBeatsToTime (BarsAndBeats) const; double barsBeatsToBeats (BarsAndBeats) const; double beatsToTime (double beats) const; EditTimeRange beatsToTime (juce::Range<double> beatsRange) const; //============================================================================== struct SectionDetails { double bpm; double startTime; double startBeatInEdit; double secondsPerBeat, beatsPerSecond, ppqAtStart; double timeOfFirstBar, beatsUntilFirstBar; int barNumberOfFirstBar, numerator, prevNumerator, denominator; bool triplets; }; struct TempoSections { int size() const; const SectionDetails& getReference (int i) const; double timeToBeats (double time) const; double beatsToTime (double beats) const; /** The only modifying operation */ void swapWith (juce::Array<SectionDetails>& newTempos); /** Compare to cheaply determine if any changes have been made. */ juce::uint32 getChangeCount() const; private: juce::uint32 changeCounter = 0; juce::Array<SectionDetails> tempos; }; const TempoSections& getTempoSections() { return internalTempos; } //============================================================================== juce::String getSelectableDescription() override; //============================================================================== Edit& edit; void updateTempoData(); // internal private: //============================================================================== friend class TempoSetting; friend class TimeSigSetting; //============================================================================== juce::ValueTree state; struct TempoSettingList; struct TimeSigList; std::unique_ptr<TempoSettingList> tempos; std::unique_ptr<TimeSigList> timeSigs; friend class TempoSequencePosition; TempoSections internalTempos; //============================================================================== void updateTempoDataIfNeeded() const; void handleAsyncUpdate() override; TempoSetting::Ptr insertTempo (double beatNum, double bpm, float curve, juce::UndoManager*); TempoSetting::Ptr insertTempo (double time, juce::UndoManager*); TimeSigSetting::Ptr insertTimeSig (double time, juce::UndoManager*); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TempoSequence) }; //============================================================================== /** Iterates a TempoSequence. One of these lets you take a position in a tempo sequence, and skip forwards/backwards either by absolute times, or by bar/beat amounts. */ class TempoSequencePosition { public: //============================================================================== TempoSequencePosition (const TempoSequence&); TempoSequencePosition (const TempoSequencePosition&); ~TempoSequencePosition(); //============================================================================== double getTime() const { return time; } TempoSequence::BarsAndBeats getBarsBeatsTime() const; const TempoSequence::SectionDetails& getCurrentTempo() const; double getPPQTime() const noexcept; double getPPQTimeOfBarStart() const noexcept; //============================================================================== void setTime (double time); void addBars (int bars); void addBeats (double beats); void addSeconds (double seconds); void setBarsBeats (TempoSequence::BarsAndBeats); void setPPQTime (double ppq); private: //============================================================================== const TempoSequence& sequence; double time = 0.0; int index = 0; TempoSequencePosition& operator= (const TempoSequencePosition&); }; //============================================================================== /** Takes a copy of all the beat related things in an edit in terms of bars/beats and then remaps these after a tempo change. */ struct EditTimecodeRemapperSnapshot { void savePreChangeState (Edit&); void remapEdit (Edit&); private: struct ClipPos { Selectable::WeakRef clip; double startBeat = 0.0, endBeat = 0.0, contentStartBeat = 0.0; }; struct AutomationPos { AutomationCurve& curve; juce::Array<double> beats; }; juce::Array<ClipPos> clips; juce::Array<AutomationPos> automation; juce::Range<double> loopPositionBeats; }; } // namespace tracktion_engine
2,862
6,449
<gh_stars>1000+ /* * Copyright 2009-2016 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.api.motan.transport; import java.net.InetSocketAddress; import java.util.Collection; import com.weibo.api.motan.codec.Codec; import com.weibo.api.motan.common.ChannelState; import com.weibo.api.motan.common.URLParamType; import com.weibo.api.motan.core.extension.ExtensionLoader; import com.weibo.api.motan.exception.MotanFrameworkException; import com.weibo.api.motan.rpc.URL; /** * @author maijunsheng * @version 创建时间:2013-5-21 * */ public abstract class AbstractServer implements Server { protected InetSocketAddress localAddress; protected InetSocketAddress remoteAddress; protected URL url; protected Codec codec; protected volatile ChannelState state = ChannelState.UNINIT; public AbstractServer() {} public AbstractServer(URL url) { this.url = url; this.codec = ExtensionLoader.getExtensionLoader(Codec.class).getExtension( url.getParameter(URLParamType.codec.getName(), URLParamType.codec.getValue())); } @Override public InetSocketAddress getLocalAddress() { return localAddress; } @Override public InetSocketAddress getRemoteAddress() { return remoteAddress; } public void setLocalAddress(InetSocketAddress localAddress) { this.localAddress = localAddress; } public void setRemoteAddress(InetSocketAddress remoteAddress) { this.remoteAddress = remoteAddress; } @Override public Collection<Channel> getChannels() { throw new MotanFrameworkException(this.getClass().getName() + " getChannels() method unsupport " + url); } @Override public Channel getChannel(InetSocketAddress remoteAddress) { throw new MotanFrameworkException(this.getClass().getName() + " getChannel(InetSocketAddress) method unsupport " + url); } public void setUrl(URL url) { this.url = url; } public void setCodec(Codec codec) { this.codec = codec; } }
937
1,186
<gh_stars>1000+ from werkzeug import BaseRequest, BaseResponse, run_simple, wrap_file import meinheld def view_file(req): if not 'uploaded_file' in req.files: return BaseResponse('no file uploaded') f = req.files['uploaded_file'] return BaseResponse(wrap_file(req.environ, f), mimetype=f.content_type, direct_passthrough=True) def upload_file(req): return BaseResponse(''' <h1>Upload File</h1> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"> <input type="submit" value="Upload"> </form> ''', mimetype='text/html') def application(environ, start_response): req = BaseRequest(environ) if req.method == 'POST': resp = view_file(req) else: resp = upload_file(req) return resp(environ, start_response) meinheld.set_max_content_length(1024 * 1024 * 1024) meinheld.listen(("0.0.0.0", 8000)) meinheld.run(application)
404
380
<gh_stars>100-1000 from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS with InfluxDBClient(url="http://localhost:8086", token="<PASSWORD>", org="my-org") as client: """ Prepare data """ _point1 = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3) _point2 = Point("my_measurement").tag("location", "New York").field("temperature", 24.3) client.write_api(write_options=SYNCHRONOUS).write(bucket="my-bucket", record=[_point1, _point2]) """ Query: using Table structure """ tables = client.query_api().query('from(bucket:"my-bucket") |> range(start: -10m)') """ Serialize to JSON """ import json from influxdb_client.client.flux_table import FluxStructureEncoder output = json.dumps(tables, cls=FluxStructureEncoder, indent=2) print(output)
333
5,937
<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_transform // $Keywords: // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" using namespace dxlayer; MtDefine(AxisAngleRotation3DResource, MILRender, "AxisAngleRotation3D Resource"); MtDefine(CMilAxisAngleRotation3DDuce, AxisAngleRotation3DResource, "CMilAxisAngleRotation3DDuce"); CMilAxisAngleRotation3DDuce::~CMilAxisAngleRotation3DDuce() { UnRegisterNotifiers(); } /* override */ HRESULT CMilAxisAngleRotation3DDuce::GetRealization( __out_ecount(1) CMILMatrix *pRealization ) { HRESULT hr = S_OK; vector3 axis; IFC(SynchronizeAnimatedFields()); axis = { m_data.m_axis.X, m_data.m_axis.Y, m_data.m_axis.Z }; C_ASSERT(sizeof(axis) == sizeof(m_data.m_axis)); // // // D3DXMatrixRotationAxis (which is part of the deprecated DirectX 9 Extension API's) that // this code was originally written to depend on) has the behavior that if the length^2 of // axis <= FLT_MIN, then the returned matrix will be a uniform scale of cos(angle). // // This threshold needs to match the one we used in D3DXVec3Normalize (d3dxmath9.cpp) // and in managed code. See also AxisAngleRotation3D.cs. if (axis.length_sq() > FLT_MIN) { *pRealization = matrix::rotation_axis(axis, DegToRadF(m_data.m_angle)); } else { // If we have a zero-length axis we set pRealization to identity (i.e., // we consider this to be no rotation.) pRealization->SetToIdentity(); } Cleanup: RRETURN(hr); }
707
3,702
<filename>discovery-server/src/main/java/app/metatron/discovery/query/druid/filters/BoundFilter.java<gh_stars>1000+ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.metatron.discovery.query.druid.filters; import com.fasterxml.jackson.annotation.JsonTypeName; import app.metatron.discovery.query.druid.Filter; /** * Created by hsp on 2016. 3. 9.. */ @JsonTypeName("bound") public class BoundFilter implements Filter { String dimension; String lower; Boolean lowerStrict; String upper; Boolean upperStrict; Boolean alphaNumeric; public BoundFilter(String dimension, String lower, Boolean lowerStrict, String upper, Boolean upperStrict, Boolean alphaNumeric) { this.dimension = dimension; this.lower = lower; this.lowerStrict = lowerStrict; this.upper = upper; this.upperStrict = upperStrict; this.alphaNumeric = alphaNumeric; } public String getDimension() { return dimension; } public void setDimension(String dimension) { this.dimension = dimension; } public String getLower() { return lower; } public void setLower(String lower) { this.lower = lower; } public Boolean getLowerStrict() { return lowerStrict; } public void setLowerStrict(Boolean lowerStrict) { this.lowerStrict = lowerStrict; } public String getUpper() { return upper; } public void setUpper(String upper) { this.upper = upper; } public Boolean getUpperStrict() { return upperStrict; } public void setUpperStrict(Boolean upperStrict) { this.upperStrict = upperStrict; } public Boolean getAlphaNumeric() { return alphaNumeric; } public void setAlphaNumeric(Boolean alphaNumeric) { this.alphaNumeric = alphaNumeric; } }
724
14,668
<gh_stars>1000+ // 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. // This is a shim that injects Chrome's ICU initialization sequence into // SQLite's shell. BUILD.gn uses this instead of building the sqlite_shell.c // file in the amalgamation directly. #include "third_party/sqlite/sqlite_shell_icu_helper.h" // On Windows, SQLite's shell.c defines wmain() instead of main() by default. // This preprocessor macro causes it to use main(). #define SQLITE_SHELL_IS_UTF8 1 // While processing shell.c, rename main() to sqlite_shell_main(). #define main sqlite_shell_main #include "third_party/sqlite/src/amalgamation/shell/shell.c" #undef main int main(int argc, char** argv) { InitializeICUForSqliteShell(); return sqlite_shell_main(argc, argv); }
276
739
<gh_stars>100-1000 #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk class UIManagerExample: ui = '''<ui> <menubar name="MenuBar"> <menu action="File"> <menuitem action="Quit"/> </menu> <menu action="Sound"> <menuitem action="Mute"/> </menu> <menu action="RadioBand"> <menuitem action="AM"/> <menuitem action="FM"/> <menuitem action="SSB"/> </menu> </menubar> <toolbar name="Toolbar"> <toolitem action="Quit"/> <separator/> <toolitem action="Mute"/> <separator/> <placeholder name="RadioBandItems"> <toolitem action="AM"/> <toolitem action="FM"/> <toolitem action="SSB"/> </placeholder> </toolbar> </ui>''' def __init__(self): # Create the toplevel window window = gtk.Window() window.connect('destroy', lambda w: gtk.main_quit()) window.set_size_request(300, -1) vbox = gtk.VBox() window.add(vbox) # Create a UIManager instance uimanager = gtk.UIManager() # Add the accelerator group to the toplevel window accelgroup = uimanager.get_accel_group() window.add_accel_group(accelgroup) # Create an ActionGroup actiongroup = gtk.ActionGroup('UIManagerExample') self.actiongroup = actiongroup # Create a ToggleAction, etc. actiongroup.add_toggle_actions([('Mute', None, '_Mute', '<Control>m', 'Mute the volume', self.mute_cb)]) # Create actions actiongroup.add_actions([('Quit', gtk.STOCK_QUIT, '_Quit me!', None, 'Quit the Program', self.quit_cb), ('File', None, '_File'), ('Sound', None, '_Sound'), ('RadioBand', None, '_Radio Band')]) actiongroup.get_action('Quit').set_property('short-label', '_Quit') # Create some RadioActions actiongroup.add_radio_actions([('AM', None, '_AM', '<Control>a', 'AM Radio', 0), ('FM', None, '_FM', '<Control>f', 'FM Radio', 1), ('SSB', None, '_SSB', '<Control>s', 'SSB Radio', 2), ], 0, self.radioband_cb) # Add the actiongroup to the uimanager uimanager.insert_action_group(actiongroup, 0) # Add a UI description uimanager.add_ui_from_string(self.ui) # Create a MenuBar menubar = uimanager.get_widget('/MenuBar') vbox.pack_start(menubar, False) # Create a Toolbar toolbar = uimanager.get_widget('/Toolbar') vbox.pack_start(toolbar, False) # Create and pack two Labels label = gtk.Label('Sound is not muted') vbox.pack_start(label) self.mutelabel = label label = gtk.Label('Radio band is AM') vbox.pack_start(label) self.bandlabel = label # Create buttons to control visibility and sensitivity of actions buttonbox = gtk.HButtonBox() sensitivebutton = gtk.CheckButton('Sensitive') sensitivebutton.set_active(True) sensitivebutton.connect('toggled', self.toggle_sensitivity) visiblebutton = gtk.CheckButton('Visible') visiblebutton.set_active(True) visiblebutton.connect('toggled', self.toggle_visibility) # add them to buttonbox buttonbox.pack_start(sensitivebutton, False) buttonbox.pack_start(visiblebutton, False) vbox.pack_start(buttonbox) window.show_all() return def mute_cb(self, action): # action has not toggled yet text = ('muted', 'not muted')[action.get_active()==False] self.mutelabel.set_text('Sound is %s' % text) return def radioband_cb(self, action, current): text = ('AM', 'FM', 'SSB')[action.get_current_value()] self.bandlabel.set_text('Radio band is %s' % text) return def quit_cb(self, b): print 'Quitting program' gtk.main_quit() def toggle_sensitivity(self, b): self.actiongroup.set_sensitive(b.get_active()) return def toggle_visibility(self, b): self.actiongroup.set_visible(b.get_active()) return if __name__ == '__main__': ba = UIManagerExample() gtk.main()
2,253
2,564
<reponame>WakeHao/CainCamera<gh_stars>1000+ package com.cgfay.caincamera.activity; import android.Manifest; import android.app.Dialog; import android.app.ProgressDialog; import android.graphics.SurfaceTexture; import android.opengl.GLSurfaceView; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import androidx.annotation.NonNull; import android.os.Bundle; import com.cgfay.caincamera.R; import com.cgfay.caincamera.presenter.RecordPresenter; import com.cgfay.caincamera.renderer.DuetRecordRenderer; import com.cgfay.caincamera.renderer.DuetType; import com.cgfay.caincamera.widget.GLRecordView; import com.cgfay.camera.widget.RecordButton; import com.cgfay.camera.widget.RecordProgressView; import com.cgfay.picker.model.MediaData; import com.cgfay.uitls.utils.NotchUtils; import com.cgfay.uitls.utils.PermissionUtils; import com.cgfay.uitls.utils.StatusBarUtils; /** * 同框录制 */ public class DuetRecordActivity extends BaseRecordActivity implements View.OnClickListener { public static final String DUET_MEDIA = "DUET_MEDIA"; private GLRecordView mGLRecordView; private RecordProgressView mProgressView; private RecordButton mRecordButton; private DuetRecordRenderer mRenderer; private RecordPresenter mPresenter; private View mBtnSwitch; private Button mBtnNext; private Button mBtnDelete; private Button mBtnDuet; private Button mBtnDuetFlip; private LinearLayout mLayoutDuetType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_duet_record); mPresenter = new RecordPresenter(this); mPresenter.setRecordSeconds(15); mRenderer = new DuetRecordRenderer(mPresenter); MediaData duetMedia = getIntent().getParcelableExtra(DUET_MEDIA); if (duetMedia != null) { mRenderer.setDuetVideo(duetMedia); } // 录制预览 mGLRecordView = (GLRecordView) findViewById(R.id.gl_record_view); mGLRecordView.setEGLContextClientVersion(3); mGLRecordView.setRenderer(mRenderer); mGLRecordView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // 进度条 mProgressView = (RecordProgressView) findViewById(R.id.record_progress_view); // 录制按钮 mRecordButton = (RecordButton) findViewById(R.id.btn_record); mRecordButton.addRecordStateListener(new RecordButton.RecordStateListener() { @Override public void onRecordStart() { mPresenter.startRecord(); mRenderer.playVideo(); } @Override public void onRecordStop() { mPresenter.stopRecord(); mRenderer.stopVideo(); } @Override public void onZoom(float percent) { } }); // 切换相机 mBtnSwitch = findViewById(R.id.btn_switch); mBtnSwitch.setOnClickListener(this); // 下一步 mBtnNext = findViewById(R.id.btn_next); mBtnNext.setOnClickListener(this); // 删除按钮 mBtnDelete = findViewById(R.id.btn_delete); mBtnDelete.setOnClickListener(this); // 选择同框类型 mBtnDuet = findViewById(R.id.btn_next_duet); mBtnDuet.setOnClickListener(this); // 翻转同框 mBtnDuetFlip = findViewById(R.id.btn_duet_flip); mBtnDuetFlip.setOnClickListener(this); mBtnDuetFlip.setVisibility(duetMedia != null ? View.VISIBLE : View.GONE); // 同框类型 mLayoutDuetType = findViewById(R.id.layout_duet_type); mLayoutDuetType.findViewById(R.id.btn_duet_left_right).setOnClickListener(this); mLayoutDuetType.findViewById(R.id.btn_duet_up_down).setOnClickListener(this); mLayoutDuetType.findViewById(R.id.btn_duet_big_small).setOnClickListener(this); // 判断是否存在刘海屏 if (NotchUtils.hasNotchScreen(this)) { View view = findViewById(R.id.view_safety_area); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = StatusBarUtils.getStatusBarHeight(this); view.setLayoutParams(params); } showViews(); } @Override protected void onResume() { super.onResume(); handleFullScreen(); mGLRecordView.onResume(); mPresenter.onResume(); mPresenter.setAudioEnable(PermissionUtils.permissionChecking(this, Manifest.permission.RECORD_AUDIO)); } @Override protected void onPause() { super.onPause(); mGLRecordView.onPause(); mPresenter.onPause(); mRenderer.clear(); } @Override protected void onDestroy() { mPresenter.release(); mPresenter = null; super.onDestroy(); } private void handleFullScreen() { getWindow().setFlags(LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // 是否全面屏 if (NotchUtils.hasNotchScreen(this)) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); LayoutParams lp = getWindow().getAttributes(); if (VERSION.SDK_INT >= VERSION_CODES.P) { lp.layoutInDisplayCutoutMode = LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } getWindow().setAttributes(lp); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_switch) { mPresenter.switchCamera(); } else if (id == R.id.btn_delete) { mPresenter.deleteLastVideo(); } else if (id == R.id.btn_next) { mPresenter.mergeAndEdit(); } else if (id == R.id.btn_next_duet) { mLayoutDuetType.setVisibility(View.VISIBLE); mBtnDuet.setVisibility(View.GONE); mBtnDuetFlip.setVisibility(View.GONE); } else if (id == R.id.btn_duet_flip) { mRenderer.flip(); } else if (id == R.id.btn_duet_left_right) { mRenderer.setDuetType(DuetType.DUET_TYPE_LEFT_RIGHT); hidDuetTypeViews(); } else if (id == R.id.btn_duet_up_down) { mRenderer.setDuetType(DuetType.DUET_TYPE_UP_DOWN); hidDuetTypeViews(); } else if (id == R.id.btn_duet_big_small) { mRenderer.setDuetType(DuetType.DUET_TYPE_BIG_SMALL); hidDuetTypeViews(); } } private void hidDuetTypeViews() { if (mLayoutDuetType != null) { mLayoutDuetType.setVisibility(View.GONE); } if (mBtnDuet != null) { mBtnDuet.setVisibility(View.VISIBLE); } if (mBtnDuetFlip != null) { mBtnDuetFlip.setVisibility(View.VISIBLE); } } /** * 隐藏控件 */ @Override public void hideViews() { runOnUiThread(() -> { if (mBtnDelete != null) { mBtnDelete.setVisibility(View.GONE); } if (mBtnNext != null) { mBtnNext.setVisibility(View.GONE); } if (mBtnSwitch != null) { mBtnSwitch.setVisibility(View.GONE); } }); } /** * 显示控件 */ @Override public void showViews() { runOnUiThread(() -> { boolean showEditEnable = mPresenter.getRecordVideoSize() > 0; if (mBtnDelete != null) { mBtnDelete.setVisibility(showEditEnable ? View.VISIBLE : View.GONE); } if (mBtnNext != null) { mBtnNext.setVisibility(showEditEnable ? View.VISIBLE : View.GONE); } if (mBtnSwitch != null) { mBtnSwitch.setVisibility(View.VISIBLE); } if (mRecordButton != null) { mRecordButton.reset(); } }); } /** * 设置进度 * @param progress */ @Override public void setRecordProgress(float progress) { runOnUiThread(() -> { mProgressView.setProgress(progress); }); } /** * 添加一段进度 * @param progress */ @Override public void addProgressSegment(float progress) { runOnUiThread(() -> { mProgressView.addProgressSegment(progress); }); } /** * 删除一段进度 */ @Override public void deleteProgressSegment() { runOnUiThread(() -> { mProgressView.deleteProgressSegment(); }); } /** * 绑定相机输出的SurfaceTexture * @param surfaceTexture */ @Override public void bindSurfaceTexture(@NonNull SurfaceTexture surfaceTexture) { mGLRecordView.queueEvent(() -> mRenderer.bindSurfaceTexture(surfaceTexture)); } /** * 更新预览纹理大小 * @param width * @param height */ @Override public void updateTextureSize(int width, int height) { if (mRenderer != null) { mRenderer.setTextureSize(width, height); } } /** * 刷新画面 */ @Override public void onFrameAvailable() { if (mGLRecordView != null) { mGLRecordView.requestRender(); } } private Dialog mProgressDialog; /** * 显示合成进度 */ @Override public void showProgressDialog() { runOnUiThread(() -> { mProgressDialog = ProgressDialog.show(this, "正在合成", "正在合成"); }); } /** * 隐藏合成进度 */ @Override public void hideProgressDialog() { runOnUiThread(() -> { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } }); } private Toast mToast; /** * 显示Toast提示 * @param msg */ @Override public void showToast(String msg) { runOnUiThread(() -> { if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); mToast.show(); }); } }
5,189
2,908
<filename>socket-common-interface/src/main/java/com/xuhao/didi/socket/common/interfaces/common_interfacies/client/ISender.java package com.xuhao.didi.socket.common.interfaces.common_interfacies.client; import com.xuhao.didi.core.iocore.interfaces.ISendable; /** * Created by xuhao on 2017/5/16. */ public interface ISender<T> { /** * 在当前的连接上发送数据 * * @param sendable 具有发送能力的Bean {@link ISendable} * @return T */ T send(ISendable sendable); }
227
1,521
/** Copyright 2020 Alibaba Group Holding Limited. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ANALYTICAL_ENGINE_APPS_DFS_DFS_H_ #define ANALYTICAL_ENGINE_APPS_DFS_DFS_H_ #include <tuple> #include <utility> #include <vector> #include "grape/grape.h" #include "core/config.h" #include "dfs/dfs_context.h" namespace gs { /** * @brief Depth-first search. The predecessor or successor will be found and * hold in the context. The behavior of the algorithm can be controlled by a * source vertex. * @tparam FRAG_T */ template <typename FRAG_T> class DFS : public AppBase<FRAG_T, DFSContext<FRAG_T>>, public grape::Communicator { public: INSTALL_DEFAULT_WORKER(DFS<FRAG_T>, DFSContext<FRAG_T>, FRAG_T) static constexpr grape::MessageStrategy message_strategy = grape::MessageStrategy::kAlongEdgeToOuterVertex; static constexpr grape::LoadStrategy load_strategy = grape::LoadStrategy::kBothOutIn; using vertex_t = typename fragment_t::vertex_t; using vid_t = typename fragment_t::vid_t; using oid_t = typename fragment_t::oid_t; void PEval(const fragment_t& frag, context_t& ctx, message_manager_t& messages) { messages.ForceContinue(); } void IncEval(const fragment_t& frag, context_t& ctx, message_manager_t& messages) { auto vertices = frag.Vertices(); auto inner_vertices = frag.InnerVertices(); auto& is_in_frag = ctx.is_in_frag; if (ctx.output_stage == false) { std::tuple<std::pair<vid_t, vid_t>, int, bool> msg; while (messages.GetMessage(msg)) { if (std::get<1>(msg) == -1) { std::vector<std::pair<oid_t, int>> send_msg; send_msg.reserve(frag.GetInnerVerticesNum()); for (auto v : inner_vertices) { send_msg.emplace_back(std::make_pair(frag.GetId(v), ctx.rank[v])); } messages.SendToFragment(0, send_msg); ctx.output_stage = true; break; } is_in_frag = true; vid_t gid = std::get<0>(msg).second; vertex_t v; frag.Gid2Vertex(gid, v); if (ctx.is_visited[v] == false) { ctx.max_rank = std::get<1>(msg) + 1; ctx.rank[v] = ctx.max_rank; ctx.is_visited[v] = true; ctx.current_vertex = v; ctx.parent[v] = std::get<0>(msg).first; vertex_t parent_v; frag.Gid2Vertex(std::get<0>(msg).first, parent_v); ctx.is_visited[parent_v] = true; } else if (ctx.is_visited[v] == true && std::get<2>(msg) == false) { ctx.current_vertex = v; ctx.max_rank = std::get<1>(msg); } else { is_in_frag = false; std::tuple<std::pair<vid_t, vid_t>, int, bool> send_msg; send_msg = std::make_tuple( std::make_pair(std::get<0>(msg).second, std::get<0>(msg).first), std::get<1>(msg), false); vertex_t tmp_v; frag.Gid2Vertex(std::get<0>(msg).first, tmp_v); fid_t fid = frag.GetFragId(tmp_v); messages.SendToFragment(fid, send_msg); } } } else if (ctx.output_stage == true) { std::vector<std::pair<oid_t, int>> msg; while (messages.GetMessage(msg)) { for (size_t i = 0; i < msg.size(); i++) { if (msg[i].second != -1) { ctx.results[msg[i].second] = msg[i].first; ctx.total_num++; } } } } if (is_in_frag) { auto current_vertex = ctx.current_vertex; while (true) { bool message_send = false; int num_visited = 0; auto es = frag.GetOutgoingAdjList(current_vertex); for (auto& e : es) { auto u = e.neighbor; if (ctx.is_visited[u] == true) { num_visited++; } } if (num_visited == frag.GetLocalOutDegree(current_vertex) && frag.Vertex2Gid(current_vertex) != ctx.source_gid) { vid_t gid = ctx.parent[current_vertex]; vertex_t parent_vertex; frag.Gid2Vertex(gid, parent_vertex); if (frag.IsInnerVertex(parent_vertex)) { current_vertex = parent_vertex; } else { std::tuple<std::pair<vid_t, vid_t>, int, bool> msg = std::make_tuple( std::make_pair(frag.Vertex2Gid(current_vertex), gid), ctx.max_rank, false); fid_t fid = frag.GetFragId(parent_vertex); messages.SendToFragment(fid, msg); break; } } else if (num_visited == frag.GetLocalOutDegree(current_vertex) && frag.Vertex2Gid(current_vertex) == ctx.source_gid) { std::tuple<std::pair<vid_t, vid_t>, int, bool> msg = std::make_tuple(std::make_pair(0, 0), -1, false); for (fid_t fid = 0; fid < frag.fnum(); fid++) { messages.SendToFragment(fid, msg); } break; } else { auto es = frag.GetOutgoingAdjList(current_vertex); for (auto& e : es) { auto u = e.neighbor; if (ctx.is_visited[u] == false) { ctx.is_visited[u] = true; if (frag.IsInnerVertex(u)) { ctx.parent[u] = frag.Vertex2Gid(current_vertex); ctx.rank[u] = ctx.max_rank + 1; ctx.max_rank++; current_vertex = u; } else { vid_t gid = frag.Vertex2Gid(u); std::tuple<std::pair<vid_t, vid_t>, int, bool> msg = std::make_tuple( std::make_pair(frag.Vertex2Gid(current_vertex), gid), ctx.max_rank, true); fid_t fid = frag.GetFragId(u); messages.SendToFragment(fid, msg); message_send = true; } break; } } if (message_send) { break; } } } ctx.is_in_frag = false; } auto& output_format = ctx.output_format; auto total_num = ctx.total_num; if (output_format == "edges" || output_format == "successors") { if (frag.fid() == 0) { auto& results = ctx.results; std::vector<size_t> shape{(size_t) total_num - 1, 2}; ctx.set_shape(shape); auto* data = ctx.tensor().data(); size_t idx = 0; for (int i = 0; i < total_num - 1; i++) { data[idx++] = results[i]; data[idx++] = results[i + 1]; } } } else if (output_format == "predecessors") { if (frag.fid() == 0) { auto& results = ctx.results; std::vector<size_t> shape{(size_t) total_num - 1, 2}; ctx.set_shape(shape); auto* data = ctx.tensor().data(); size_t idx = 0; for (int i = 1; i < total_num; i++) { data[idx++] = results[i]; data[idx++] = results[i + 1]; } } } else { auto& rank = ctx.rank; std::vector<size_t> shape{inner_vertices.size(), 2}; ctx.set_shape(shape); auto* data = ctx.tensor().data(); size_t idx = 0; for (auto& u : inner_vertices) { data[idx++] = frag.GetId(u); data[idx++] = rank[u]; } } } }; }; // namespace gs #endif // ANALYTICAL_ENGINE_APPS_DFS_DFS_H_
3,981
393
<reponame>cosmin-ionita/rxjava2-jdbc package org.davidmoten.rx.jdbc; import static org.junit.Assert.assertEquals; import java.util.Collections; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; public class SqlInfoTest { @Test public void testExpansionNoParameters() { SqlInfo s = SqlInfo.parse("? ?", Collections.emptyList()); assertEquals("? ?", s.sql()); } @Test public void testExpansionEmpty() { SqlInfo s = SqlInfo.parse("", Collections.emptyList()); assertEquals("", s.sql()); } @Test public void testExpansionWithParametersNoCollections() { Parameter p = new Parameter(12); SqlInfo s = SqlInfo.parse("? hello ?", Lists.newArrayList(p, p)); assertEquals("? hello ?", s.sql()); } @Test public void testExpansionWithParametersCollectionPresent() { Parameter p1 = new Parameter(12); Parameter p2 = new Parameter(Lists.newArrayList(1, 2, 3)); SqlInfo s = SqlInfo.parse("? hello ?", Lists.newArrayList(p1, p2)); assertEquals("? hello ?,?,?", s.sql()); } }
467
2,151
<gh_stars>1000+ // Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef sw_Math_hpp #define sw_Math_hpp #include "Types.hpp" #include "Half.hpp" #include <cmath> #if defined(_MSC_VER) #include <intrin.h> #endif namespace sw { using std::abs; #undef min #undef max template<class T> inline T max(T a, T b) { return a > b ? a : b; } template<class T> inline T min(T a, T b) { return a < b ? a : b; } template<class T> inline T max(T a, T b, T c) { return max(max(a, b), c); } template<class T> inline T min(T a, T b, T c) { return min(min(a, b), c); } template<class T> inline T max(T a, T b, T c, T d) { return max(max(a, b), max(c, d)); } template<class T> inline T min(T a, T b, T c, T d) { return min(min(a, b), min(c, d)); } template<class T> inline void swap(T &a, T &b) { T t = a; a = b; b = t; } template <typename destType, typename sourceType> destType bitCast(const sourceType &source) { union { sourceType s; destType d; } sd; sd.s = source; return sd.d; } inline int iround(float x) { return (int)floor(x + 0.5f); // return _mm_cvtss_si32(_mm_load_ss(&x)); // FIXME: Demands SSE support } inline int ifloor(float x) { return (int)floor(x); } inline int ceilFix4(int x) { return (x + 0xF) & 0xFFFFFFF0; } inline int ceilInt4(int x) { return (x + 0xF) >> 4; } #define BITS(x) ( \ !!((x) & 0x80000000) + \ !!((x) & 0xC0000000) + \ !!((x) & 0xE0000000) + \ !!((x) & 0xF0000000) + \ !!((x) & 0xF8000000) + \ !!((x) & 0xFC000000) + \ !!((x) & 0xFE000000) + \ !!((x) & 0xFF000000) + \ !!((x) & 0xFF800000) + \ !!((x) & 0xFFC00000) + \ !!((x) & 0xFFE00000) + \ !!((x) & 0xFFF00000) + \ !!((x) & 0xFFF80000) + \ !!((x) & 0xFFFC0000) + \ !!((x) & 0xFFFE0000) + \ !!((x) & 0xFFFF0000) + \ !!((x) & 0xFFFF8000) + \ !!((x) & 0xFFFFC000) + \ !!((x) & 0xFFFFE000) + \ !!((x) & 0xFFFFF000) + \ !!((x) & 0xFFFFF800) + \ !!((x) & 0xFFFFFC00) + \ !!((x) & 0xFFFFFE00) + \ !!((x) & 0xFFFFFF00) + \ !!((x) & 0xFFFFFF80) + \ !!((x) & 0xFFFFFFC0) + \ !!((x) & 0xFFFFFFE0) + \ !!((x) & 0xFFFFFFF0) + \ !!((x) & 0xFFFFFFF8) + \ !!((x) & 0xFFFFFFFC) + \ !!((x) & 0xFFFFFFFE) + \ !!((x) & 0xFFFFFFFF)) #define MAX(x, y) ((x) > (y) ? (x) : (y)) #define MIN(x, y) ((x) < (y) ? (x) : (y)) inline float exp2(float x) { return exp2f(x); } inline int exp2(int x) { return 1 << x; } inline unsigned long log2(int x) { #if defined(_MSC_VER) unsigned long y; _BitScanReverse(&y, x); return y; #else return 31 - __builtin_clz(x); #endif } inline int ilog2(float x) { unsigned int y = *(unsigned int*)&x; return ((y & 0x7F800000) >> 23) - 127; } inline float log2(float x) { return logf(x) * 1.44269504f; // 1.0 / log[e](2) } inline bool isPow2(int x) { return (x & -x) == x; } template<class T> inline T clamp(T x, T a, T b) { if(x < a) x = a; if(x > b) x = b; return x; } inline float clamp01(float x) { return clamp(x, 0.0f, 1.0f); } inline int ceilPow2(int x) { int i = 1; while(i < x) { i <<= 1; } return i; } inline int floorDiv(int a, int b) { return a / b + ((a % b) >> 31); } inline int floorMod(int a, int b) { int r = a % b; return r + ((r >> 31) & b); } inline int ceilDiv(int a, int b) { return a / b - (-(a % b) >> 31); } inline int ceilMod(int a, int b) { int r = a % b; return r - ((-r >> 31) & b); } template<const int n> inline unsigned int unorm(float x) { static const unsigned int max = 0xFFFFFFFF >> (32 - n); static const float maxf = static_cast<float>(max); if(x >= 1.0f) { return max; } else if(x <= 0.0f) { return 0; } else { return static_cast<unsigned int>(maxf * x + 0.5f); } } template<const int n> inline int snorm(float x) { static const unsigned int min = 0x80000000 >> (32 - n); static const unsigned int max = 0xFFFFFFFF >> (32 - n + 1); static const float maxf = static_cast<float>(max); static const unsigned int range = 0xFFFFFFFF >> (32 - n); if(x >= 0.0f) { if(x >= 1.0f) { return max; } else { return static_cast<int>(maxf * x + 0.5f); } } else { if(x <= -1.0f) { return min; } else { return static_cast<int>(maxf * x - 0.5f) & range; } } } template<const int n> inline unsigned int ucast(float x) { static const unsigned int max = 0xFFFFFFFF >> (32 - n); static const float maxf = static_cast<float>(max); if(x >= maxf) { return max; } else if(x <= 0.0f) { return 0; } else { return static_cast<unsigned int>(x + 0.5f); } } template<const int n> inline int scast(float x) { static const unsigned int min = 0x80000000 >> (32 - n); static const unsigned int max = 0xFFFFFFFF >> (32 - n + 1); static const float maxf = static_cast<float>(max); static const float minf = static_cast<float>(min); static const unsigned int range = 0xFFFFFFFF >> (32 - n); if(x > 0.0f) { if(x >= maxf) { return max; } else { return static_cast<int>(x + 0.5f); } } else { if(x <= -minf) { return min; } else { return static_cast<int>(x - 0.5f) & range; } } } inline float sRGBtoLinear(float c) { if(c <= 0.04045f) { return c * 0.07739938f; // 1.0f / 12.92f; } else { return powf((c + 0.055f) * 0.9478673f, 2.4f); // 1.0f / 1.055f } } inline float linearToSRGB(float c) { if(c <= 0.0031308f) { return c * 12.92f; } else { return 1.055f * powf(c, 0.4166667f) - 0.055f; // 1.0f / 2.4f } } unsigned char sRGB8toLinear8(unsigned char value); uint64_t FNV_1a(const unsigned char *data, int size); // Fowler-Noll-Vo hash function // Round up to the next multiple of alignment template<typename T> inline T align(T value, unsigned int alignment) { return ((value + alignment - 1) / alignment) * alignment; } template<unsigned int alignment, typename T> inline T align(T value) { return ((value + alignment - 1) / alignment) * alignment; } inline int clampToSignedInt(unsigned int x) { return static_cast<int>(min(x, 0x7FFFFFFFu)); } } #endif // sw_Math_hpp
3,198
32,544
<reponame>DBatOWL/tutorials package com.baeldung.systemrules; import static org.junit.Assert.assertEquals; import java.util.Scanner; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.TextFromStandardInputStream; import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream; public class SystemInWithRuleUnitTest { @Rule public final TextFromStandardInputStream systemInMock = emptyStandardInputStream(); @Test public void givenTwoNames_whenSystemInMock_thenNamesJoinedTogether() { systemInMock.provideLines("Jonathan", "Cook"); assertEquals("Names should be concatenated", "<NAME>", getFullname()); } private String getFullname() { try (Scanner scanner = new Scanner(System.in)) { String firstName = scanner.next(); String surname = scanner.next(); return String.join(" ", firstName, surname); } } }
355
1,006
/**************************************************************************** * arch/renesas/src/rx65n/rx65n_definitions.h * * 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. * ****************************************************************************/ #ifndef __ARCH_RENESAS_SRC_RX65N_RX65N_DEFINITIONS_H #define __ARCH_RENESAS_SRC_RX65N_RX65N_DEFINITIONS_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include "arch/rx65n/iodefine.h" #include "arch/board/board.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Memory-mapped register addresses *****************************************/ #define RX65N_SCI0_BASE (uint32_t)&SCI0 #define RX65N_SCI1_BASE (uint32_t)&SCI1 #define RX65N_SCI2_BASE (uint32_t)&SCI2 #define RX65N_SCI3_BASE (uint32_t)&SCI3 #define RX65N_SCI4_BASE (uint32_t)&SCI4 #define RX65N_SCI5_BASE (uint32_t)&SCI5 #define RX65N_SCI6_BASE (uint32_t)&SCI6 #define RX65N_SCI7_BASE (uint32_t)&SCI7 #define RX65N_SCI8_BASE (uint32_t)&SCI8 #define RX65N_SCI9_BASE (uint32_t)&SCI9 #define RX65N_SCI10_BASE (uint32_t)&SCI10 #define RX65N_SCI11_BASE (uint32_t)&SCI11 #define RX65N_SCI12_BASE (uint32_t)&SCI12 /* Serial Communications interface (SCI) */ #define RX_SCISMR_CKSMASK (0x03) /* Bit 0-1: Internal clock source */ #define RX_SCISMR_DIV1 (0x00) /* System clock (phi) */ #define RX_SCISMR_DIV4 (0x01) /* phi/4 */ #define RX_SCISMR_DIV16 (0x02) /* phi/16 */ #define RX_SCISMR_DIV64 (0x03) /* phi/64 */ #define RX_SCISMR_MP (0x04) /* Bit 2: Multiprocessor select */ #define RX_SCISMR_STOP (0x08) /* Bit 3: 0:One stop bit, 1:Two stop bits */ #define RX_SCISMR_OE (0x10) /* Bit 4: 0:Even parity, 1:Odd parity */ #define RX_SCISMR_PE (0x20) /* Bit 5: Parity enable */ #define RX_SCISMR_CHR (0x40) /* Bit 6: 0:8-bit data, 1:7-bit data */ #define RX_SCISMR_CA (0x80) /* Bit 7: 0:Asynchronous, 1:clocked synchronous */ #define RX_SCISCR_CKEMASK (0x03) /* Bit 0-1: Internal clock source */ /* Asynchronous mode: */ /* Internal clock, SCK pin used for input pin */ #define RX_SCISCR_AISIN (0x00) /* Internal clock, SCK pin used for clock output */ #define RX_SCISCR_AISOUT (0x01) /* External clock, SCK pin used for clock input */ #define RX_SCISCR_AXSIN1 (0x02) /* External clock, SCK pin used for clock input */ #define RX_SCISCR_AXSIN2 (0x03) /* Synchronous mode: */ /* Internal clock, SCK pin used for clock output */ #define RX_SCISCR_SISOUT2 (0x01) /* External clock, SCK pin used for clock input */ #define RX_SCISCR_SXSIN1 (0x02) /* External clock, SCK pin used for clock input */ #define RX_SCISCR_SXSIN2 (0x03) /* Bit 2: 1=Transmit end interrupt enable */ #define RX_SCISCR_TEIE (0x04) /* Bit 3: 1=Multiprocessor interrupt enable */ #define RX_SCISCR_MPIE (0x08) #define RX_SCISCR_RE (0x10) /* Bit 4: 1=Receiver enable */ #define RX_SCISCR_TE (0x20) /* Bit 5: 1=Transmitter enable */ /* Bit 6: 1=Recieve-data-full interrupt enable */ #define RX_SCISCR_RIE (0x40) /* Bit 7: 1=Transmit-data-empty interrupt enable */ #define RX_SCISCR_TIE (0x80) #define RX_SCISCR_ALLINTS (0xcc) /* Bit 0: Multi-processor Bit in Transmit data */ #define RX_SCISSR_MPBT (0x01) /* Bit 1: Multi-processor Bit in receive data */ #define RX_SCISSR_MPB (0x02) #define RX_SCISSR_TEND (0x04) /* Bit 2: End of transmission */ #define RX_SCISSR_PER (0x08) /* Bit 3: Receive parity error */ #define RX_SCISSR_FER (0x10) /* Bit 4: Receive framing error */ #define RX_SCISSR_ORER (0x20) /* Bit 5: Receive overrun error */ /* Bit 6: RDR contains valid received data */ #define RX_SCISSR_RDRF (0x40) /* Bit 7: TDR does not contain valid transmit data */ #define RX_SCISSR_TDRE (0x80) #define RX65N_CMT_CMSTR0_ADDR (0x00088000) /* 8-bits wide */ #define RX65N_CMT0_CMCNT_ADDR (0x00088004) #define RX65N_CMT0_CMCOR_ADDR (0x00088006) #define RX65N_CMT0_CMCR_ADDR (0x00088002) /* CMTW0 used for Ethernet TX polling and TX timeout */ #define RX65N_CMTW0_CMWSTR_ADDR (0x00094200) #define RX65N_CMTW0_CMWCR_ADDR (0x00094204) #define RX65N_CMTW0_CMWIOR_ADDR (0x00094208) #define RX65N_CMTW0_CMWCNT_ADDR (0x00094210) #define RX65N_CMTW0_CMWCOR_ADDR (0x00094214) #define RX65N_CMTW0_CMWICR0_ADDR (0x00094218) #define RX65N_CMTW0_CMWICR1_ADDR (0x0009421c) #define RX65N_CMTW0_CMWOCR0_ADDR (0x00094220) #define RX65N_CMTW0_CMWOCR1_ADDR (0x00094224) #define RX65N_CMTW0_TICKFREQ (1) /* 1Hz tick frequency */ #define RX65N_CMTW0_DIV_VALUE (32) #define RX65N_CMTW0_COUNT_VALUE_FOR_TXPOLL ((RX_PCLKB / RX65N_CMTW0_DIV_VALUE)/(RX65N_CMTW0_TICKFREQ)) #define RX65N_CMTW0_COUNT_VALUE_FOR_TXTIMEOUT (((RX_PCLKB / RX65N_CMTW0_DIV_VALUE)/(RX65N_CMTW0_TICKFREQ))*60) #define rx65n_cmtw0_txpoll 1 #define rx65n_cmtw0_timeout 2 #define RX65N_MSTPCRA_ADDR (0x00080010) #define RX65N_MSTPCRB_ADDR (0x00080014) #define RX65N_CMT0_TICKFREQ (100) /* 100Hz tick frequency */ #define RX65N_CMT_DIV32 (0x0001) #define RX65N_CMT0_DIV_VALUE (32) #define RX65N_CMT0_COUNT_VALUE ((RX_PCLKB / RX65N_CMT0_DIV_VALUE)/(RX65N_CMT0_TICKFREQ)) #define RX65N_CMT_CMCR_INIT (RX65N_CMT_DIV32 |\ RX65N_CMT_CMCR_CMIE_ENABLE |\ RX65N_CMT_CMCR_DEFAULT) #define RX65N_CMTW_DIV32 (0x0001) #define RX65N_CMTW_CMWCR_INIT (RX65N_CMTW_DIV32 |\ RX65N_CMTW_CMWCR_CMWIE_ENABLE |\ RX65N_CMTW_CMWCR_DEFAULT) #define RX65N_CMTW_CMWCR_DEFAULT (0x0000) #define RX65N_CMTW_CMWCR_CMWIE_ENABLE (0x0008) #define RX65N_CMT_CMCR_DEFAULT (0x0080) #define RX65N_CMT_CMCR_CMIE_ENABLE (0x0040) #define RX65N_CMT_MSTPCRA_STOP (0x00008000) /* Release unit0(CMT0 and CMT1) from module stop state */ #define RX65N_CMT_UNIT1_MSTPCRA_STOP (0x00004000) /* Release unit1(CMT2 and CMT3) from module stop state */ #define RX65N_CMTW_UNIT1_MSTPCRA_STOP (0x00000001) /* Release CMTW unit1 from module stop state */ #define RX65N_CMTW_UNIT0_MSTPCRA_STOP (0x00000002) /* Release CMTW unit0 from module stop state */ #define RX65N_CMTCMSTR0_STR0 (0x0001) /* Bit 0: TCNT0 is counting */ #define RX65N_CMTCMSTR0_STR1 (0x0002) /* Bit 1: TCNT1 is counting */ #define RX65N_CMTCMSTR1_STR2 (0x0001) /* Bit 0: TCNT0 is counting */ #define RX65N_CMTCMSTR1_STR3 (0x0002) /* Bit 1: TCNT1 is counting */ #define RX65N_PRCR_ADDR (0x000803fe) #define RX65N_PRCR_VALUE (0xa50b) #define RX65N_GRPBE0_ADDR (0x00087600) #define RX65N_GRPBL0_ADDR (0x00087630) #define RX65N_GRPBL1_ADDR (0x00087634) #define RX65N_GRPBL2_ADDR (0x00087638) #define RX65N_GRPAL0_ADDR (0x00087830) #define RX65N_GRPAL1_ADDR (0x00087834) #define RX65N_GENBE0_ADDR (0x00087640) #define RX65N_GENBL0_ADDR (0x00087670) #define RX65N_GENBL1_ADDR (0x00087674) #define RX65N_GENBL2_ADDR (0x00087678) #define RX65N_GENAL0_ADDR (0x00087870) #define RX65N_GENAL1_ADDR (0x00087874) #define RX65N_GRPBL0_TEI0_MASK (1U << 0) /* (0x00000001) */ #define RX65N_GRPBL0_ERI0_MASK (1U << 1) /* (0x00000002) */ #define RX65N_GRPBL0_TEI1_MASK (1U << 2) /* (0x00000004) */ #define RX65N_GRPBL0_ERI1_MASK (1U << 3) /* (0x00000008) */ #define RX65N_GRPBL0_TEI2_MASK (1U << 4) /* (0x00000010) */ #define RX65N_GRPBL0_ERI2_MASK (1U << 5) /* (0x00000020) */ #define RX65N_GRPBL0_TEI3_MASK (1U << 6) /* (0x00000040) */ #define RX65N_GRPBL0_ERI3_MASK (1U << 7) /* (0x00000080) */ #define RX65N_GRPBL0_TEI4_MASK (1U << 8) /* (0x00000100) */ #define RX65N_GRPBL0_ERI4_MASK (1U << 9) /* (0x00000200) */ #define RX65N_GRPBL0_TEI5_MASK (1U << 10) /* (0x00000400) */ #define RX65N_GRPBL0_ERI5_MASK (1U << 11) /* (0x00000800) */ #define RX65N_GRPBL0_TEI6_MASK (1U << 12) /* (0x00001000) */ #define RX65N_GRPBL0_ERI6_MASK (1U << 13) /* (0x00002000) */ #define RX65N_GRPBL0_TEI7_MASK (1U << 14) /* (0x00004000) */ #define RX65N_GRPBL0_ERI7_MASK (1U << 15) /* (0x00008000) */ #define RX65N_GRPBL1_TEI0_MASK (1U << 13) #define RX65N_GRPBL1_EEI0_MASK (1U << 14) #define RX65N_GRPBL1_TEI2_MASK (1U << 15) #define RX65N_GRPBL1_EEI2_MASK (1U << 16) #define RX65N_GRPBL1_TEI8_MASK (1U << 24) #define RX65N_GRPBL1_ERI8_MASK (1U << 25) #define RX65N_GRPBL1_TEI9_MASK (1U << 26) #define RX65N_GRPBL1_ERI9_MASK (1U << 27) #define RX65N_GRPBL1_TEI1_MASK (1U << 28) #define RX65N_GRPBL1_EEI1_MASK (1U << 29) #define RX65N_GRPAL0_TEI10_MASK (1U << 8) #define RX65N_GRPAL0_ERI10_MASK (1U << 9) #define RX65N_GRPAL0_TEI11_MASK (1U << 12) #define RX65N_GRPAL0_ERI11_MASK (1U << 13) #define RX65N_GRPAL0_SPII0_MASK (1U << 16) #define RX65N_GRPAL0_SPEI0_MASK (1U << 17) #define RX65N_GRPAL0_SPII1_MASK (1U << 18) #define RX65N_GRPAL0_SPEI1_MASK (1U << 19) #define RX65N_GRPAL0_SPII2_MASK (1U << 20) #define RX65N_GRPAL0_SPEI2_MASK (1U << 21) #define RX65N_GRPBL0_TEI12_MASK (1U << 16) #define RX65N_GRPBL0_ERI12_MASK (1U << 17) /* Start Ethernet and EDMAC Interface */ /* ETHERC and EDMAC base Addresses */ #define RX65N_EDMAC0_BASE (0x000c0000) /* EDMAC base address */ #define RX65N_ETHERC0_BASE (0x000c0100) /* Ethernet MAC base address */ /* Ethernet Addresses */ /* Register Offsets */ /* MAC Registers */ #define RX65N_ETH_ECMR_OFFSET (0x0000) /* ETHERC Mode register */ #define RX65N_ETH_RFLR_OFFSET (0x0008) /* Receive Frame Maximum Length Register */ #define RX65N_ETH_ECSR_OFFSET (0x0010) /* ETHERC Status Register */ #define RX65N_ETH_ECSIPR_OFFSET (0x0018) /* ETHERC Interrupt Enable Register */ #define RX65N_ETH_PIR_OFFSET (0x0020) /* PHY Interface Register */ #define RX65N_ETH_PSR_OFFSET (0x0028) /* PHY Status Register */ #define RX65N_ETH_RDMLR_OFFSET (0x0040) /* Random Number Generation Counter Limit Setting Register */ #define RX65N_ETH_IPGR_OFFSET (0x0050) /* Interpacket Gap Register */ #define RX65N_ETH_APR_OFFSET (0x0054) /* Automatic PAUSE Frame Register */ #define RX65N_ETH_MPR_OFFSET (0x0058) /* Manual PAUSE Frame Register */ #define RX65N_ETH_RFCF_OFFSET (0x0060) /* Received PAUSE Frame Counter */ #define RX65N_ETH_TPAUSER_OFFSET (0x0064) /* PAUSE Frame Retransmit Count Setting Register */ #define RX65N_ETH_TPAUSECR_OFFSET (0x0068) /* PAUSE Frame Retransmit Counter */ #define RX65N_ETH_BCFRR_OFFSET (0x006c) /* Broadcast Frame Receive Count Setting Register */ #define RX65N_ETH_MAHR_OFFSET (0x00c0) /* MAC Address Upper Bit Register */ #define RX65N_ETH_MALR_OFFSET (0x00c8) /* MAC Address Lower Bit Register */ #define RX65N_ETH_TROCR_OFFSET (0x00d0) /* Transmit Retry Over Counter Register */ #define RX65N_ETH_CDCR_OFFSET (0x00d4) /* Late Collision Detect Counter Register */ #define RX65N_ETH_LCCR_OFFSET (0x00d8) /* Lost Carrier Counter Register */ #define RX65N_ETH_CNDCR_OFFSET (0x00dc) /* Carrier Not Detect Counter Register */ #define RX65N_ETH_CEFCR_OFFSET (0x00e4) /* CRC Error Frame Receive Counter Register */ #define RX65N_ETH_FRECR_OFFSET (0x00e8) /* Frame Receive Error Counter Register */ #define RX65N_ETH_TSFRCR_OFFSET (0x00ec) /* Too-Short Frame Receive Counter Register */ #define RX65N_ETH_TLFRCR_OFFSET (0x00f0) /* Too-Long Frame Receive Counter Register */ #define RX65N_ETH_RFCR_OFFSET (0x00f4) /* Received Alignment Error Frame Counter Register */ #define RX65N_ETH_MAFCR_OFFSET (0x00f8) /* Multicast Address Frame Receive Counter Register */ /* DMA Registers */ #define RX65N_ETHD_EDMR_OFFSET (0x0000) /* EDMAC Mode Register */ #define RX65N_ETHD_EDTRR_OFFSET (0x0008) /* EDMAC Transmit Request Register */ #define RX65N_ETHD_EDRRR_OFFSET (0x0010) /* EDMAC Receive Request Register */ #define RX65N_ETHD_TDLAR_OFFSET (0x0018) /* Transmit Descriptor List Start Address Register */ #define RX65N_ETHD_RDLAR_OFFSET (0x0020) /* Receive Descriptor List Start Address Register */ #define RX65N_ETHD_EESR_OFFSET (0x0028) /* ETHERC/EDMAC Status Register */ #define RX65N_ETHD_EESIPR_OFFSET (0x0030) /* ETHERC/EDMAC Status Interrupt Enable Register */ #define RX65N_ETHD_TRSCER_OFFSET (0x0038) /* ETHERC/EDMAC Transmit/Receive Status Copy Enable Register */ #define RX65N_ETHD_RMFCR_OFFSET (0x0040) /* Missed-Frame Counter Register */ #define RX65N_ETHD_TFTR_OFFSET (0x0048) /* Transmit FIFO Threshold Register */ #define RX65N_ETHD_FDR_OFFSET (0x0050) /* FIFO Depth Register */ #define RX65N_ETHD_RMCR_OFFSET (0x0058) /* Receive Method Control Register */ #define RX65N_ETHD_TFUCR_OFFSET (0x0064) /* Transmit FIFO Underflow Counter */ #define RX65N_ETHD_RFOCR_OFFSET (0x0068) /* Receive FIFO Overflow Counter */ #define RX65N_ETHD_IOSR_OFFSET (0x006c) /* Independent Output Signal Setting Register */ #define RX65N_ETHD_FCFTR_OFFSET (0x0070) /* Flow Control Start FIFO Threshold Setting Register */ #define RX65N_ETHD_RPADIR_OFFSET (0x0078) /* Receive Data Padding Insert Register */ #define RX65N_ETHD_TRIMD_OFFSET (0x007c) /* Transmit Interrupt Setting Register */ #define RX65N_ETHD_RBWAR_OFFSET (0x00c8) /* Receive Buffer Write Address Register */ #define RX65N_ETHD_RDFAR_OFFSET (0x00cc) /* Receive Descriptor Fetch Address Register */ #define RX65N_ETHD_TBRAR_OFFSET (0x00d4) /* Transmit Buffer Read Address Register */ #define RX65N_ETHD_TDFAR_OFFSET (0x00d8) /* Transmit Descriptor Fetch Address Register */ /* Register Base Addresses */ /* MAC Registers */ #define RX65N_ETH_ECMR (RX65N_ETHERC0_BASE+RX65N_ETH_ECMR_OFFSET) #define RX65N_ETH_RFLR (RX65N_ETHERC0_BASE+RX65N_ETH_RFLR_OFFSET) #define RX65N_ETH_ECSR (RX65N_ETHERC0_BASE+RX65N_ETH_ECSR_OFFSET) #define RX65N_ETH_ECSIPR (RX65N_ETHERC0_BASE+RX65N_ETH_ECSIPR_OFFSET) #define RX65N_ETH_PIR (RX65N_ETHERC0_BASE+RX65N_ETH_PIR_OFFSET) #define RX65N_ETH_PSR (RX65N_ETHERC0_BASE+RX65N_ETH_PSR_OFFSET) #define RX65N_ETH_RDMLR (RX65N_ETHERC0_BASE+RX65N_ETH_RDMLR_OFFSET) #define RX65N_ETH_IPGR (RX65N_ETHERC0_BASE+RX65N_ETH_IPGR_OFFSET) #define RX65N_ETH_APR (RX65N_ETHERC0_BASE+RX65N_ETH_APR_OFFSET) #define RX65N_ETH_MPR (RX65N_ETHERC0_BASE+RX65N_ETH_MPR_OFFSET) #define RX65N_ETH_RFCF (RX65N_ETHERC0_BASE+RX65N_ETH_RFCF_OFFSET) #define RX65N_ETH_TPAUSER (RX65N_ETHERC0_BASE+RX65N_ETH_TPAUSER_OFFSET) #define RX65N_ETH_TPAUSECR (RX65N_ETHERC0_BASE+RX65N_ETH_TPAUSECR_OFFSET) #define RX65N_ETH_BCFRR (RX65N_ETHERC0_BASE+RX65N_ETH_BCFRR_OFFSET) #define RX65N_ETH_MAHR (RX65N_ETHERC0_BASE+RX65N_ETH_MAHR_OFFSET) #define RX65N_ETH_MALR (RX65N_ETHERC0_BASE+RX65N_ETH_MALR_OFFSET) #define RX65N_ETH_TROCR (RX65N_ETHERC0_BASE+RX65N_ETH_TROCR_OFFSET) #define RX65N_ETH_CDCR (RX65N_ETHERC0_BASE+RX65N_ETH_CDCR_OFFSET) #define RX65N_ETH_LCCR (RX65N_ETHERC0_BASE+RX65N_ETH_LCCR_OFFSET) #define RX65N_ETH_CNDCR (RX65N_ETHERC0_BASE+RX65N_ETH_CNDCR_OFFSET) #define RX65N_ETH_CEFCR (RX65N_ETHERC0_BASE+RX65N_ETH_CEFCR_OFFSET) #define RX65N_ETH_FRECR (RX65N_ETHERC0_BASE+RX65N_ETH_FRECR_OFFSET) #define RX65N_ETH_TSFRCR (RX65N_ETHERC0_BASE+RX65N_ETH_TSFRCR_OFFSET) #define RX65N_ETH_TLFRCR (RX65N_ETHERC0_BASE+RX65N_ETH_TLFRCR_OFFSET) #define RX65N_ETH_RFCR (RX65N_ETHERC0_BASE+RX65N_ETH_RFCR_OFFSET) #define RX65N_ETH_MAFCR (RX65N_ETHERC0_BASE+RX65N_ETH_MAFCR_OFFSET) /* DMA Registers */ #define RX65N_ETHD_EDMR (RX65N_EDMAC0_BASE+RX65N_ETHD_EDMR_OFFSET) #define RX65N_ETHD_EDTRR (RX65N_EDMAC0_BASE+RX65N_ETHD_EDTRR_OFFSET) #define RX65N_ETHD_EDRRR (RX65N_EDMAC0_BASE+RX65N_ETHD_EDRRR_OFFSET) #define RX65N_ETHD_TDLAR (RX65N_EDMAC0_BASE+RX65N_ETHD_TDLAR_OFFSET) #define RX65N_ETHD_RDLAR (RX65N_EDMAC0_BASE+RX65N_ETHD_RDLAR_OFFSET) #define RX65N_ETHD_EESR (RX65N_EDMAC0_BASE+RX65N_ETHD_EESR_OFFSET) #define RX65N_ETHD_EESIPR (RX65N_EDMAC0_BASE+RX65N_ETHD_EESIPR_OFFSET) #define RX65N_ETHD_TRSCER (RX65N_EDMAC0_BASE+RX65N_ETHD_TRSCER_OFFSET) #define RX65N_ETHD_RMFCR (RX65N_EDMAC0_BASE+RX65N_ETHD_RMFCR_OFFSET) #define RX65N_ETHD_TFTR (RX65N_EDMAC0_BASE+RX65N_ETHD_TFTR_OFFSET) #define RX65N_ETHD_FDR (RX65N_EDMAC0_BASE+RX65N_ETHD_FDR_OFFSET) #define RX65N_ETHD_RMCR (RX65N_EDMAC0_BASE+RX65N_ETHD_RMCR_OFFSET) #define RX65N_ETHD_TFUCR (RX65N_EDMAC0_BASE+RX65N_ETHD_TFUCR_OFFSET) #define RX65N_ETHD_RFOCR (RX65N_EDMAC0_BASE+RX65N_ETHD_RFOCR_OFFSET) #define RX65N_ETHD_IOSR (RX65N_EDMAC0_BASE+RX65N_ETHD_IOSR_OFFSET) #define RX65N_ETHD_FCFTR (RX65N_EDMAC0_BASE+RX65N_ETHD_FCFTR_OFFSET) #define RX65N_ETHD_RPADIR (RX65N_EDMAC0_BASE+RX65N_ETHD_RPADIR_OFFSET) #define RX65N_ETHD_TRIMD (RX65N_EDMAC0_BASE+RX65N_ETHD_TRIMD_OFFSET) #define RX65N_ETHD_RBWAR (RX65N_EDMAC0_BASE+RX65N_ETHD_RBWAR_OFFSET) #define RX65N_ETHD_RDFAR (RX65N_EDMAC0_BASE+RX65N_ETHD_RDFAR_OFFSET) #define RX65N_ETHD_TBRAR (RX65N_EDMAC0_BASE+RX65N_ETHD_TBRAR_OFFSET) #define RX65N_ETHD_TDFAR (RX65N_EDMAC0_BASE+RX65N_ETHD_TDFAR_OFFSET) /* MPC (Multifunction pin controller) Registers for Ethernet */ #define RX65N_MPC_PFENET (0x0008c10e) #define RX65N_MPC_PWPR (0x0008c11f) /* (Module control Registers) for Ethernet */ #define RX65N_MSTP_CRB (0x00080014) /* Register Bit-Field Definitions */ /* MAC Registers */ #define ETH_ECSR_LCHNG (1 << 2) /* Bit 2: Link Signal Change Flag */ /* Bit 2: LINK Signal Change Interrupt enable/disable */ #define ETH_ECSIPR_LCHNGIP (1 << 2) #define ETH_ECMR_CLR (0x00000000) /* Clear all ETHERC status BFR, PSRTO, LCHNG, MPD, ICD */ #define ETH_ECSR_CLR (0x00000037) #define ETH_ECMR_RE (1 << 6) /* Transmit function is enabled */ #define ETH_ECMR_TE (1 << 5) /* Receive function is enabled */ #define ETH_ECMR_DM (1 << 1) /* Duplex Mode */ #define ETH_ECMR_RTM (1 << 2) /* Bit Rate */ /* Bit 4:0:Interpacket Gap 96 bit time (initial value) */ #define ETH_IPGR_IPG_INITIAL (0x00000014) /* Receive Frame Maximum Length */ #define ETH_RFLR_RFL (1518) /* EDMA Registers */ /* Bit 22: ETHERC status interrupt request is enable/disabled. */ #define ETHD_EDMR_SWR (1 << 0) /* Bit 6: Big Endian Mode/Little Endian Mode */ #define ETHD_EDMR_DE (1 << 6) /* Clear all EDMAC status bits */ #define ETHD_EESR_EDMAC (0x47ff0f9f) /* Frame transfer Complete status Flag check */ #define ETHD_EESR_TC (1 << 21) /* ETHERC/EDMAC Status Register Source Flag */ #define ETHD_EESR_ECI (1 << 22) #define ETHD_EESR_FR (1 << 18) /* Frame Receive Flag */ /* Frame Receive Interrupt Request Enable */ #define ETHD_EESIPR_FRIP (1 << 18) /* Frame Transfer Complete Interrupt Request Enable */ #define ETHD_EESIPR_TCIP (1 << 21) /* ETHERC/EDMAC Status Register Source Interrupt Request Enable */ #define ETHD_EESIPR_ECIIP (1 << 22) /* ETHERC/EDMAC Write-Back Complete Interrupt Request Enable */ #define ETHD_EESIPR_TWBIP (1 << 30) /* Bit 0:10: Transmit FIFO Threshold */ #define ETHD_TFTR_TFT (0x00000000) /* Bit: 20: Transmit Descriptor Empty Flag */ #define ETHD_EESR_TDE (1 << 20) /* Ether PSR register */ #define ETH_PSR_LMON (1) /* EDMAC Transmit Request Register's bit */ #define ETHD_EDRRR_TR (1) /* Transmit Request */ /* EDMAC Receive Request Register's bit */ #define ETHD_EDRRR_RR (1) /* Receive descriptor read, * and receive function is enabled */ /* Transmit Interrupt Setting Register's bit */ #define ETHD_TRIMD_TIS (1) /* Transmit Interrupt is enabled */ #define ETHD_TRIMD_TIM (1 << 4) /* Write-back complete interrupt mode */ /* Receive Method Control Register's bit */ /* Receive Method Control Register's bit */ #define ETHD_RMCR_RNR (1) /* EDRRR.RR bit (receive request bit) is not * set to 0 when one frame has been received */ /* FIFO Depth Register's bit */ #define ETHD_FDR_RFD (7) /* Receive FIFO Depth */ #define ETHD_FDR_TFD (7 << 8) /* Transmit FIFO Depth */ /* ETHERC/EDMAC Transmit/Receive Status Copy Enable Register's bit */ #define ETHD_TRSCER_RRFCE (1 << 4) /* RRF Flag Copy Enable */ #define ETHD_TRSCER_RMAFCE (1 << 7) /* RMAF Flag Copy Enable */ /* Broadcast Frame Receive Count Setting Register's field */ #define ETH_BCFRR_BCF (0x0000) /* Broadcast Frame Continuous Receive Count Setting */ /* PHY Interface Register's bit and values */ #define ETH_PIR_MDC (1) /* MII/RMII Management Data Clock */ #define ETH_PIR_MMD (1 << 1) /* MII/RMII Management Mode */ #define ETH_PIR_MDO (1 << 2) /* MII/RMII Management Data-Out */ #define ETH_PIR_MDI (1 << 3) /* MII/RMII Management Data-In */ #define ETH_PIR_RESET_ALL (0x00000000) /* Reset All Flags of PIR */ #define ETH_PIR_SET_MDC (0x00000001) /* Setting MDC of PIR */ #define ETH_PIR_SET_MMD (0x00000002) /* Setting MMD of PIR */ #define ETH_PIR_SET_MMD_MDC (0x00000003) /* Setting MMD and MDC */ #define ETH_PIR_SET_MDO_MMD (0x00000006) /* Setting MDO and MMD */ #define ETH_PIR_SET_MDO_MMD_MDC (0x00000007) /* Setting MDO, MMD and MDC */ /* Ethernet Control Register's bit and value */ #define ETH_PFENET_MII_MODE (0x10) #define ETH_PFENET_RMII_MODE (0x00) /* End Ethernet and EDMAC Interface */ /* Bit Set Values */ #define SET_BIT_HIGH (1) #define SET_BIT_LOW (0) #define SET_BYTE_HIGH (0xff) #define SET_BYTE_LOW (0x00) /* RTC Register Offsets */ #define RX65N_RTC_R64CNT_OFFSET (0x0000) #define RX65N_RTC_RSECCNT_OFFSET (0x0002) #define RX65N_RTC_RMINCNT_OFFSET (0x0004) #define RX65N_RTC_RHRCNT_OFFSET (0x0006) #define RX65N_RTC_RWKCNT_OFFSET (0x0008) #define RX65N_RTC_RDAYCNT_OFFSET (0x000a) #define RX65N_RTC_RMONCNT_OFFSET (0x000c) #define RX65N_RTC_RYRCNT_OFFSET (0x000e) #define RX65N_RTC_RSECAR_OFFSET (0x0010) #define RX65N_RTC_RMINAR_OFFSET (0x0012) #define RX65N_RTC_RHRAR_OFFSET (0x0014) #define RX65N_RTC_RWKAR_OFFSET (0x0016) #define RX65N_RTC_RDAYAR_OFFSET (0x0018) #define RX65N_RTC_RMONAR_OFFSET (0x001a) #define RX65N_RTC_RYRAR_OFFSET (0x001c) #define RX65N_RTC_RYRAREN_OFFSET (0x001e) #define RX65N_RTC_RCR1_OFFSET (0x0022) #define RX65N_RTC_RCR2_OFFSET (0x0024) #define RX65N_RTC_RCR3_OFFSET (0x0026) #define RX65N_RTC_RCR4_OFFSET (0x0028) #define RX65N_RTC_RADJ_OFFSET (0x002e) #define RX65N_RTC_BASE (0x0008c400) #define RX65N_RTC_R64CNT (RX65N_RTC_BASE + RX65N_RTC_R64CNT_OFFSET) #define RX65N_RTC_RSECCNT (RX65N_RTC_BASE + RX65N_RTC_RSECCNT_OFFSET) #define RX65N_RTC_RMINCNT (RX65N_RTC_BASE + RX65N_RTC_RMINCNT_OFFSET) #define RX65N_RTC_RHRCNT (RX65N_RTC_BASE + RX65N_RTC_RHRCNT_OFFSET) #define RX65N_RTC_RWKCNT (RX65N_RTC_BASE + RX65N_RTC_RWKCNT_OFFSET) #define RX65N_RTC_RDAYCNT (RX65N_RTC_BASE + RX65N_RTC_RDAYCNT_OFFSET) #define RX65N_RTC_RMONCNT (RX65N_RTC_BASE + RX65N_RTC_RMONCNT_OFFSET) #define RX65N_RTC_RYRCNT (RX65N_RTC_BASE + RX65N_RTC_RYRCNT_OFFSET) #define RX65N_RTC_RSECAR (RX65N_RTC_BASE + RX65N_RTC_RSECAR_OFFSET) #define RX65N_RTC_RMINAR (RX65N_RTC_BASE + RX65N_RTC_RMINAR_OFFSET) #define RX65N_RTC_RHRAR (RX65N_RTC_BASE + RX65N_RTC_RHRAR_OFFSET) #define RX65N_RTC_RWKAR (RX65N_RTC_BASE + RX65N_RTC_RWKAR_OFFSET) #define RX65N_RTC_RDAYAR (RX65N_RTC_BASE + RX65N_RTC_RDAYAR_OFFSET) #define RX65N_RTC_RMONAR (RX65N_RTC_BASE + RX65N_RTC_RMONAR_OFFSET) #define RX65N_RTC_RYRAR (RX65N_RTC_BASE + RX65N_RTC_RYRAR_OFFSET) #define RX65N_RTC_RYRAREN (RX65N_RTC_BASE + RX65N_RTC_RYRAREN_OFFSET) #define RX65N_RTC_RCR1 (RX65N_RTC_BASE + RX65N_RTC_RCR1_OFFSET) #define RX65N_RTC_RCR2 (RX65N_RTC_BASE + RX65N_RTC_RCR2_OFFSET) #define RX65N_RTC_RCR3 (RX65N_RTC_BASE + RX65N_RTC_RCR3_OFFSET) #define RX65N_RTC_RCR4 (RX65N_RTC_BASE + RX65N_RTC_RCR4_OFFSET) #define RX65N_RTC_RADJ (RX65N_RTC_BASE + RX65N_RTC_RADJ_OFFSET) #define RTC_RTC_ALRDIS (0x00) #define RTC_RCR4_RCKSEL (0x00) #define RTC_RCR3_RTCEN (0x01) #define RTC_RCR3_RTCDV (0x02) #define RTC_RCR2_START (0x01) #define RTC_RCR2_CNTMD (0x00) #define RTC_RCR2_RESET (0x01) #define RTC_ALARM_INT_ENABLE (0x01) #define RTC_CARRY_INT_ENABLE (0x02) #define RTC_PERIOD_INT_ENABLE (0x04) #define RTC_PERIODIC_INT_PERIOD_1 (0xe0) #define _04_FOUR_READ_COUNT (0x04) #define RTC_1_64_SEC_CYCLE (0x0005b8d9) #define _0F_RTC_PRIORITY_LEVEL15 (0x0f) #define RTC_RCR1_CUP (0x02) #define RX65N_SUBCLKOSC_SOSCCR (0x00080033) #define SUBCLKOSC_SOSCCR_SOSTP (0x01) #define RX65N_SUBCLKOSC_SOSCWTCR (0x0008c293) #define RTC_SOSCWTCR_VALUE (0x21) #define RTC_DUMMY_READ (3) #define _00_RTC_PRIORITY_LEVEL0 (0) #define _04_RTC_PERIOD_INT_ENABLE (0x04) #define RTC_RTC_CARRYDIS (0xe5) #define RTC_RTC_PERDIS (0xe3) #define RTC_RADJ_INITVALUE (0x0) #define RTC_RCR2_AADJE (0x10) #define RTC_RCR2_AADJP (0x20) #if defined(CONFIG_RTC) || defined(CONFIG_RTC_DRIVER) #define HAVE_RTC_DRIVER 1 #endif /* Constant values used in RTC */ #define RX65N_RTC_WAIT_PERIOD 184 #define RTC_RCR2_HR24 (0x40) #define RTC_PERIODIC_INTERRUPT_2_SEC (0xf) /* StandBy RAM Address */ #define RX65N_SBRAM_BASE 0x000a4000 /* USB Related definitions */ #define RX65N_NUSBHOST 1 /* USB Registers */ /* USB Peripheral base address */ #define RX65N_MSTPCRB_START_STOP_USB (1 << 19) #define RX65N_USB_BASE (0x000a0000UL) /* Different USB registers with corresponding offset */ /* USB System Configuration register and its bit fields */ #define RX65N_USB_SYSCFG ((volatile short *) (RX65N_USB_BASE + 0x0000UL)) #define RX65N_USB_SYSCFG_SCKE (1U << 10) #define RX65N_USB_SYSCFG_DCFM (1U << 6) #define RX65N_USB_SYSCFG_DRPD (1U << 5) #define RX65N_USB_SYSCFG_DPRPU (1U << 4) #define RX65N_USB_SYSCFG_USBE (1U << 0) #define RX65N_USB_SYSSTS0 ((volatile short *) (RX65N_USB_BASE + 0x0004UL)) #define USB_FS_JSTS (0x0001u) /* Full-Speed J State */ #define USB_LNST (0x0003u) /* b1-0: D+, D- line status */ #define RX65N_USB_SYSSTS0_LNST (3) #define RX65N_USB_SYSSTS0_IDMON (1U << 2) #define RX65N_USB_SYSSTS0_SOFEA (1U << 5) #define RX65N_USB_SYSSTS0_HTACT (1U << 6) #define RX65N_USB_SYSSTS0_OVCMON (0xc000U) /* SE1 */ #define RX65N_USB_SYSSTS0_LNST_SE1 (0x3u) /* Full speed K state */ #define RX65N_USB_SYSSTS0_LNST_FS_KSTS (0x2u) /* Full speed J State */ #define RX65N_USB_SYSSTS0_LNST_FS_JSTS (0x1u) /* Low speed K state */ #define RX65N_USB_SYSSTS0_LNST_LS_KSTS (0x2u) /* Low speed J State */ #define RX65N_USB_SYSSTS0_LNST_LS_JSTS (0x2u) /* SE0 */ #define RX65N_USB_SYSSTS0_LNST_SE0 (0x0u) #define USB_ATTACH (0x0040) #define USB_ATTACHL (0x0041) #define USB_ATTACHF (0x0042) #define USB_DETACH (0x0043) #define USB_RESUME (0x0044) #define USB_SUSPEND (0x0045) /* Definitions used to pass on the information from interrupt to worker * function */ #define USB_PROCESS_ATTACHED_INT (0x0050) #define USB_PROCESS_DETACHED_INT (0x0051) #define USB_PROCESS_BRDY_INT (0x0052) #define USB_PROCESS_BEMP_INT (0x0053) #define USB_PROCESS_NRDY_INT (0x0054) #define USB_PROCESS_SACK_INT (0x0055) #define USB_PROCESS_SIGN_INT (0x0056) #define USB_UACTON (1) #define USB_UACTOFF (0) #define USB_VBON (1) #define USB_VBOFF (0) #define USB_UNDECID (0x0000U) /* Undecided */ /* USB Device State Control register 0 and its bit fields */ #define RX65N_USB_DVSTCTR0 ((volatile short *) (RX65N_USB_BASE + 0x0008UL)) #define RX65N_USB_DVSTCTR0_HNPBTOA (1U << 11) #define RX65N_USB_DVSTCTR0_EXICEN (1U << 10) #define RX65N_USB_DVSTCTR0_VBUSEN (1U << 9) #define RX65N_USB_DVSTCTR0_WKUP (1U << 8) #define RX65N_USB_DVSTCTR0_RWUPE (1U << 7) #define RX65N_USB_DVSTCTR0_USBRST (1U << 6) #define RX65N_USB_DVSTCTR0_RESUME (1U << 5) #define RX65N_USB_DVSTCTR0_UACT (1U << 4) #define RX65N_USB_DVSTCTR0_RHST (0x7U) #define USB_RHST (RX65N_USB_DVSTCTR0_RHST) #define RX65N_USB_DVSTCTR0_SPEED_LOW (1) #define RX65N_USB_DVSTCTR0_SPEED_FULL (2) #define RX65N_USB_DVSTCTR0_RESET_IN_PROGRESS (4) /* USB CFIFO Port Register and its bit fields */ #define RX65N_USB_CFIFO ((volatile short *) (RX65N_USB_BASE + 0x0014UL)) /* USB D0FIFO Port Register and its bit fields */ #define RX65N_USB_D0FIFO ((volatile short *) (RX65N_USB_BASE + 0x0018UL)) /* USB D1FIFO Port Register and its bit fields */ #define RX65N_USB_D1FIFO ((volatile short *) (RX65N_USB_BASE + 0x001cUL)) /* USB CFIFO Port Select Register and its bit fields */ #define RX65N_USB_CFIFOSEL ((volatile short *) (RX65N_USB_BASE + 0x0020UL)) #define RX65N_USB_CFIFOSEL_RCNT (1U << 15) #define USB_RCNT (RX65N_USB_CFIFOSEL_RCNT) #define RX65N_USB_CFIFOSEL_REW (1U << 14) #define RX65N_USB_CFIFOSEL_MBW_8 (0U << 10) #define RX65N_USB_CFIFOSEL_MBW_16 (1U << 10) #define RX65N_USB_CFIFOSEL_BIGEND (1U << 8) #define RX65N_USB_CFIFOSEL_ISEL (1U << 5) #define USB_ISEL (RX65N_USB_CFIFOSEL_ISEL) #define RX65N_USB_CFIFOSEL_CURPIPE_MASK (0xfU) #define USB_CURPIPE (RX65N_USB_CFIFOSEL_CURPIPE_MASK) /* USB CFIFO Port Control Register */ #define RX65N_USB_CFIFOCTR ((volatile short *) (RX65N_USB_BASE + 0x0022UL)) /* Common bit field values for CFIFOCTR, D0FIFOCTR and D1FIFOCTR registers */ #define RX65N_USB_FIFOCTR_BVAL (1U << 15) #define USB_BVAL (RX65N_USB_FIFOCTR_BVAL) #define RX65N_USB_FIFOCTR_BCLR (1U << 14) #define RX65N_USB_FIFOCTR_FRDY (1U << 13) #define RX65N_USB_FIFOCTR_DTLN (0xfff) /* USB D0FIFO and D1FIFO port select and control registers */ #define RX65N_USB_D0FIFOSEL ((volatile short *) (RX65N_USB_BASE + 0x0028UL)) #define RX65N_USB_D0FIFOSEL_MBW_16 (1U << 10) #define RX65N_USB_D0FIFOCTR ((volatile short *) (RX65N_USB_BASE + 0x002aUL)) #define RX65N_USB_D1FIFOSEL ((volatile short *) (RX65N_USB_BASE + 0x002cUL)) #define RX65N_USB_D1FIFOSEL_MBW_16 (1U << 10) #define RX65N_USB_D1FIFOCTR ((volatile short *) (RX65N_USB_BASE + 0x002eUL)) #define RX65N_USB_USING_CFIFO (0) #define RX65N_USB_USING_D0FIFO (1) #define RX65N_USB_USING_D1FIFO (2) #define USB_CUSE (RX65N_USB_USING_CFIFO) #define USB_D0USE (RX65N_USB_USING_D0FIFO) #define USB_D1USE (RX65N_USB_USING_D1FIFO) #define USB_ERROR (0xffUL) #define RX65N_USB_FIFO_ERROR (0xffUL) #define USB_TRUE (1UL) #define USB_FALSE (0UL) #define USB_YES (1UL) #define USB_NO (0UL) /* FIFO read / write result */ #define USB_FIFOERROR (USB_ERROR) /* FIFO not ready */ #define USB_WRITEEND (0x0000u) /* End of write (but packet may not be outputting) */ #define USB_WRITESHRT (0x0001u) /* End of write (send short packet) */ #define USB_WRITING (0x0002u) /* Write continues */ #define USB_READEND (0x0000u) /* End of read */ #define USB_READSHRT (0x0001u) /* Insufficient (receive short packet) */ #define USB_READING (0x0002u) /* Read continues */ #define USB_READOVER (0x0003u) /* Buffer size over */ /* Pipe define table end code */ #define USB_PDTBLEND (0xffffu) /* End of table */ /* Transfer status Type */ #define USB_CTRL_END (0u) #define USB_DATA_NONE (1u) #define USB_DATA_WAIT (2u) #define USB_DATA_OK (3u) #define USB_DATA_SHT (4u) #define USB_DATA_OVR (5u) #define USB_DATA_STALL (6u) #define USB_DATA_ERR (7u) #define USB_DATA_STOP (8u) #define USB_DATA_TMO (9u) #define USB_CTRL_READING (17u) #define USB_CTRL_WRITING (18u) #define USB_DATA_READING (19u) #define USB_DATA_WRITING (20u) /* Utr member (segment) */ #define USB_TRAN_CONT (0x00u) #define USB_TRAN_END (0x80u) /* USB common bit fields for D0 and D1 FIFO select register */ #define RX65N_USB_DFIFOSEL_RCNT (1U << 15) #define RX65N_USB_DFIFOSEL_REW (1U << 14) #define RX65N_USB_DFIFOSEL_DCLRM (1U << 13) #define RX65N_USB_DFIFOSEL_DREQE (1U << 12) #define RX65N_USB_DFIFOSEL_MBW_8 (0U << 10) #define USB_MBW_8 (RX65N_USB_DFIFOSEL_MBW_8) #define RX65N_USB_DFIFOSEL_MBW_16 (1U << 10) #define USB_MBW_16 (RX65N_USB_DFIFOSEL_MBW_16) #define USB0_CFIFO_MBW (USB_MBW_16) #define USB0_D0FIFO_MBW (USB_MBW_16) #define USB0_D1FIFO_MBW (USB_MBW_16) #define RX65N_USB_DFIFOSEL_BIGEND (1U << 8) #define RX65N_USB_DFIFOSEL_CURPIPE_MASK (0xf) /* USB Interrupt Enable Register 0 and its bit fields */ #define RX65N_USB_INTENB0 ((volatile short *) (RX65N_USB_BASE + 0x0030UL)) #define RX65N_USB_INTENB0_BEMPE (1U << 10) #define RX65N_USB_INTENB0_BRDYE (1U << 8) #define RX65N_USB_INTENB0_VBSE (1U << 15) #define RX65N_USB_INTENB0_RSME (1U << 14) #define RX65N_USB_INTENB0_SOFE (1U << 13) #define RX65N_USB_INTENB0_DVSE (1U << 12) #define RX65N_USB_INTENB0_CTRE (1U << 11) #define RX65N_USB_INTENB0_BEMPE (1U << 10) #define RX65N_USB_INTENB0_NRDYE (1U << 9) #define RX65N_USB_INTENB0_BRDYE (1U << 8) /* USB Interrupt Enable Register 1 and its bit fields */ #define RX65N_USB_INTENB1 ((volatile short *) (RX65N_USB_BASE + 0x0032UL)) #define RX65N_USB_INTENB1_OVRCRE (1U << 15) #define RX65N_USB_INTENB1_BCHGE (1U << 14) #define RX65N_USB_INTENB1_DTCHE (1U << 12) #define RX65N_USB_INTENB1_ATTCHE (1U << 11) #define RX65N_USB_INTENB1_EOFERRE (1U << 6) #define RX65N_USB_INTENB1_SIGNE (1U << 5) #define RX65N_USB_INTENB1_SACKE (1U << 4) /* BRDY Interrupt Enable Register */ #define RX65N_USB_BRDYENB ((volatile short *) (RX65N_USB_BASE + 0x0036UL)) /* Bit fields of pipe selection/ control registers. These bit fields are * generic */ #define USB_PIPE1 (1) #define USB_PIPE2 (2) #define USB_PIPE3 (3) #define USB_PIPE4 (4) #define USB_PIPE5 (5) #define USB_PIPE6 (6) #define USB_PIPE7 (7) #define USB_PIPE8 (8) #define USB_PIPE9 (9) #define USB_MIN_PIPE_NO (1u) #define USB_MAX_PIPE_NO (9) /* Details of pipe number for obtaining the pipe */ /* Start Pipe No */ #define USB_MIN_PIPE_NUM (1u) /* Max device */ #define USB_MAXPIPE_BULK (5u) #define USB_MAXPIPE_ISO (2u) #define USB_MAX_PIPE_NUM (9u) #define USB_BULK_PIPE_START (1u) #define USB_BULK_PIPE_END (5u) #define USB_INT_PIPE_START (6u) #define USB_INT_PIPE_END (9u) #define USB_ISO_PIPE_START (1u) #define USB_ISO_PIPE_END (2u) /* Endpoint Descriptor Define */ #define USB_EP_IN (0x80u) /* In Endpoint */ #define USB_EP_OUT (0x00u) /* Out Endpoint */ #define USB_EP_CTRL (0x00u) #define USB_EP_ISO (0x01u) /* Isochronous Transfer */ #define USB_EP_BULK (0x02u) /* Bulk Transfer */ #define USB_EP_INT (0x03u) /* Interrupt Transfer */ #define USB_BITSET(x) ((uint16_t)((uint16_t)1 << (x))) /* BRDY Interrupt Enable/Status Register */ #define USB_BRDY9 (0x0200u) /* b9: PIPE9 */ #define USB_BRDY8 (0x0100u) /* b8: PIPE8 */ #define USB_BRDY7 (0x0080u) /* b7: PIPE7 */ #define USB_BRDY6 (0x0040u) /* b6: PIPE6 */ #define USB_BRDY5 (0x0020u) /* b5: PIPE5 */ #define USB_BRDY4 (0x0010u) /* b4: PIPE4 */ #define USB_BRDY3 (0x0008u) /* b3: PIPE3 */ #define USB_BRDY2 (0x0004u) /* b2: PIPE2 */ #define USB_BRDY1 (0x0002u) /* b1: PIPE1 */ #define USB_BRDY0 (0x0001u) /* b1: PIPE0 */ /* NRDY Interrupt Enable/Status Register */ #define USB_NRDY9 (0x0200u) /* b9: PIPE9 */ #define USB_NRDY8 (0x0100u) /* b8: PIPE8 */ #define USB_NRDY7 (0x0080u) /* b7: PIPE7 */ #define USB_NRDY6 (0x0040u) /* b6: PIPE6 */ #define USB_NRDY5 (0x0020u) /* b5: PIPE5 */ #define USB_NRDY4 (0x0010u) /* b4: PIPE4 */ #define USB_NRDY3 (0x0008u) /* b3: PIPE3 */ #define USB_NRDY2 (0x0004u) /* b2: PIPE2 */ #define USB_NRDY1 (0x0002u) /* b1: PIPE1 */ #define USB_NRDY0 (0x0001u) /* b1: PIPE0 */ /* BEMP Interrupt Enable/Status Register */ #define USB_BEMP9 (0x0200u) /* b9: PIPE9 */ #define USB_BEMP8 (0x0100u) /* b8: PIPE8 */ #define USB_BEMP7 (0x0080u) /* b7: PIPE7 */ #define USB_BEMP6 (0x0040u) /* b6: PIPE6 */ #define USB_BEMP5 (0x0020u) /* b5: PIPE5 */ #define USB_BEMP4 (0x0010u) /* b4: PIPE4 */ #define USB_BEMP3 (0x0008u) /* b3: PIPE3 */ #define USB_BEMP2 (0x0004u) /* b2: PIPE2 */ #define USB_BEMP1 (0x0002u) /* b1: PIPE1 */ #define USB_BEMP0 (0x0001u) /* b0: PIPE0 */ /* Control Transfer Stage */ #define USB_IDLEST (0u) /* Idle */ #define USB_SETUPNDC (1u) /* Setup Stage No Data Control */ #define USB_SETUPWR (2u) /* Setup Stage Control Write */ #define USB_SETUPRD (3u) /* Setup Stage Control Read */ #define USB_DATAWR (4u) /* Data Stage Control Write */ #define USB_DATARD (5u) /* Data Stage Control Read */ #define USB_STATUSRD (6u) /* Status stage */ #define USB_STATUSWR (7u) /* Status stage */ #define USB_SETUPWRCNT (17u) /* Setup Stage Control Write */ #define USB_SETUPRDCNT (18u) /* Setup Stage Control Read */ #define USB_DATAWRCNT (19u) /* Data Stage Control Write */ #define USB_DATARDCNT (20u) /* Data Stage Control Read */ #define RX65N_USB_PIPE_ALL (0x3ff) /* USB NRDY Interrupt Enable Register */ #define RX65N_USB_NRDYENB ((volatile short *) (RX65N_USB_BASE + 0x0038UL)) /* USB BEMP Interrupt Enable Register */ #define RX65N_USB_BEMPENB ((volatile short *) (RX65N_USB_BASE + 0x003aUL)) /* USB SOF Output Configuration Register and its bit fields */ #define RX65N_USB_SOFCFG ((volatile short *) (RX65N_USB_BASE + 0x003cUL)) #define RX65N_USB_SOFCFG_TRNENSEL (1U << 8) #define RX65N_USB_SOFCFG_BRDYM (1U << 6) #define USB_SUREQ (0x4000u) /* b14: Send USB request */ #define RX65N_USB_SOFCFG_EDGESTS (1U << 4) /* USB Interrupt Status Register 0 and its bit fields */ #define RX65N_USB_INTSTS0 ((volatile short *) (RX65N_USB_BASE + 0x0040UL)) #define RX65N_USB_INTSTS0_VBINT (1U << 15) #define RX65N_USB_INTSTS0_RESM (1U << 14) #define RX65N_USB_INTSTS0_SOFR (1U << 13) #define RX65N_USB_INTSTS0_DVST (1U << 12) #define USB_DVSQ (0x0070u) /* b6-4: Device state */ #define RX65N_USB_INTSTS0_CTRT (1U << 11) #define USB_CTSQ (0x0007u) /* b2-0: Control transfer stage */ #define USB_CS_SQER (0x0006u) /* Sequence error */ #define USB_CS_WRND (0x0005u) /* Ctrl write nodata status stage */ #define USB_CS_WRSS (0x0004u) /* Ctrl write status stage */ #define USB_CS_WRDS (0x0003u) /* Ctrl write data stage */ #define USB_CS_RDSS (0x0002u) /* Ctrl read status stage */ #define USB_CS_RDDS (0x0001u) /* Ctrl read data stage */ #define USB_CS_IDST (0x0000u) /* Idle or setup stage */ #define USB_DS_SPD_CNFG (0x0070u) /* Suspend Configured */ #define USB_DS_SPD_ADDR (0x0060u) /* Suspend Address */ #define USB_DS_SPD_DFLT (0x0050u) /* Suspend Default */ #define USB_DS_SPD_POWR (0x0040u) /* Suspend Powered */ #define USB_DS_SUSP (0x0040u) /* Suspend */ #define USB_DS_CNFG (0x0030u) /* Configured */ #define USB_DS_ADDS (0x0020u) /* Address */ #define USB_DS_DFLT (0x0010u) /* Default */ #define USB_DS_POWR (0x0000u) /* Powered */ #define RX65N_USB_INTSTS0_CTRT (1U << 11) #define RX65N_USB_INTSTS0_BEMP (1U << 10) #define RX65N_USB_INTSTS0_NRDY (1U << 9) #define RX65N_USB_INTSTS0_BRDY (1U << 8) #define RX65N_USB_INTSTS0_VBSTS (1U << 7) #define RX65N_USB_INTSTS0_VALID (1U << 3) #define RX65N_USB_INTSTS0_DVSQ_MASK (7U << 4) #define RX65N_USB_INTSTS0_CTSQ_MASK (7) #define RX65N_USB_INTSTS0_ALL_CLEAR (0U) #define INTSTS0_BIT_VALUES_TO_DETECT (0x9d00) #define USB_DATA_STOP (8u) #define USB_MIN_PIPE_NO (1u) #define USB_MAXPIPE_NUM (9u) #define USB_ACLRM (0x0200u) #define USB_PID_BUF (0x0001u) /* BUF */ #define USB_PIPE0 (0x0u) #define USB_PBUSY (0x0020u) /* b5: pipe busy */ #define USB_TRENB (0x0200u) #define USB_TRCLR (0x0100u) #define USB_NULL (0x0u) #define USB_RSME (0x4000u) #define USB_RESM (0x4000u) /* b14: Resume interrupt */ #define USB_VALID (0x0008u) /* b3: Setup packet detect flag */ #define USB_BMREQUESTTYPETYPE (0x0060u) /* b6-5: Type */ #define USB_CLASS (0x0020u) #define USB_MBW (0x0C00u) /* b10: Maximum bit width for FIFO access */ #define USB0_CFIFO_MBW (USB_MBW_16) #define USB_DATA_ERR (7u) #define USB_DATA_OVR (5u) #define USB_PID (0x0003u) /* b1-0: Response PID */ #define USB_CCPL (0x0004u) /* b2: Enable control transfer complete */ #define USB_BCLR (0x4000u) /* b14: Buffer clear */ #define USB_FRDY (0x2000u) /* b13: FIFO ready */ #define USB_MAXP (0x007Fu) /* b6-0: Maxpacket size of default control pipe */ #define USB_MXPS (0x07FFu) /* b10-0: Maxpacket size */ #define USB_WRITESHRT (0x0001u) /* End of write (send short packet) */ #define USB_WRITING (0x0002u) /* Write continues */ #define USB0_CFIFO8 (USB0.CFIFO.BYTE.L) #define USB0_D0FIFO8 (USB0.D0FIFO.BYTE.L) #define USB0_D1FIFO8 (USB0.D1FIFO.BYTE.L) #define USB0_CFIFO16 (USB0.CFIFO.WORD) #define USB0_D0FIFO16 (USB0.D0FIFO.WORD) #define USB0_D1FIFO16 (USB0.D1FIFO.WORD) #define USB_WRITEEND (0x0000u) #define USB_CTRL_END (0u) #define USB_BREQUEST (0xFF00u) #define USB_BRDY0 (0x0001u) /* b1: PIPE0 */ #define USB_READEND (0x0000u) /* End of read */ #define USB_READSHRT (0x0001u) /* Insufficient (receive short packet) */ #define USB_READING (0x0002u) /* Read continues */ #define USB_READOVER (0x0003u) /* Buffer size over */ #define USB_DTLN (0x0FFFu) /* b11-0: FIFO data length */ #define USB_VENDOR (0x0040u) #define USB_WRITE (1) #define USB_QOVR (0xd5) #define USB_DIRFIELD (0x0010u) /* Transfer direction select */ #define USB_DIR_H_OUT (0x0010u) #define USB_BEMP0 (0x0001u) /* b0: PIPE0 */ #define BEMPSTS_MASK (0x03FFu) /* BEMPSTS Reserved bit mask */ #define USB_BEMP (0x0400u) /* b10: Buffer empty interrupt */ #define USB_BUF2FIFO (0x0010u) /* Buffer --> FIFO */ #define USB_FIFO2BUF (0x0000u) #define USB_BITSET(x) ((uint16_t)((uint16_t)1 << (x))) #define USB_READ (0) #define USB_DATA_STALL (6u) #define USB_INBUFM (0x4000u) /* b14: IN buffer monitor (Only for PIPE1 to 5) */ #define USB_DATA_NONE (1u) #define USB_DATA_OK (3u) #define USB_DATA_SHT (4u) #define USB_GS_REMOTEWAKEUP (0x0002u) #define USB_EPNUMFIELD (0x000Fu) /* Endpoint number select */ #define USB_GS_HALT (0x0001u) #define USB_GS_SELFPOWERD (1) #define USB_GS_BUSPOWERD (0) #define USB_MAX_EP_NO (15u) /* EP0 EP1 ... EP15 */ #define USB_ENDPOINT_HALT (0x0000u) #define USB_OVRN (0x8000u) /* b15: Overrun error */ #define USB_DREQE (0x1000u) /* b12: DREQ output enable */ /* USB Interrupt Status Register 0 and its bit fields */ #define RX65N_USB_INTSTS1 ((volatile short *) (RX65N_USB_BASE + 0x0042UL)) #define RX65N_USB_INTSTS1_OVRCRE (1U << 15) #define RX65N_USB_INTSTS1_BCHG (1U << 14) #define RX65N_USB_INTSTS1_DTCH (1U << 12) #define RX65N_USB_INTSTS1_ATTCH (1U << 11) #define RX65N_USB_INTSTS1_EOFERR (1U << 6) #define RX65N_USB_INTSTS1_SIGN (1U << 5) #define RX65N_USB_INTSTS1_SACK (1U << 4) #define RX65N_USB_INTSTS1_ALL_CLEAR (0U) /* USB DCP Control Register and its bit fields */ #define RX65N_USB_DCPCTR ((volatile short *) (RX65N_USB_BASE + 0x0060UL)) #define RX65N_USB_DCPCTR_BSTS (1U << 15) #define RX65N_USB_DCPCTR_SUREQ (1U << 14) #define RX65N_USB_DCPCTR_SUREQCLR (1U << 11) #define USB_SUREQCLR (RX65N_USB_DCPCTR_SUREQCLR) #define RX65N_USB_DCPCTR_SQCLR (1U << 8) #define USB_SQCLR (RX65N_USB_DCPCTR_SQCLR) #define RX65N_USB_DCPCTR_SQSET (1U << 7) #define RX65N_USB_DCPCTR_SQMON (1U << 6) #define RX65N_USB_DCPCTR_PBUSY (1U << 5) #define RX65N_USB_DCPCTR_CCPL (1U << 2) #define RX65N_USB_DCPCTR_PID_MASK (3UL) #define RX65N_USB_DCPCTR_PIDNAK (0UL) #define RX65N_USB_DCPCTR_PIDBUF (1UL) #define RX65N_USB_DCPCTR_PIDSTALL (2UL) #define RX65N_USB_DCPCTR_PIDSTALL2 (3UL) /* USB PIPE 1 to 9 Control Registers */ #define RX65N_USB_PIPE1CTR ((volatile short *) (RX65N_USB_BASE + 0x0070UL)) #define RX65N_USB_PIPE2CTR ((volatile short *) (RX65N_USB_BASE + 0x0072UL)) #define RX65N_USB_PIPE3CTR ((volatile short *) (RX65N_USB_BASE + 0x0074UL)) #define RX65N_USB_PIPE4CTR ((volatile short *) (RX65N_USB_BASE + 0x0076UL)) #define RX65N_USB_PIPE5CTR ((volatile short *) (RX65N_USB_BASE + 0x0078UL)) #define RX65N_USB_PIPE6CTR ((volatile short *) (RX65N_USB_BASE + 0x007aUL)) #define RX65N_USB_PIPE7CTR ((volatile short *) (RX65N_USB_BASE + 0x007cUL)) #define RX65N_USB_PIPE8CTR ((volatile short *) (RX65N_USB_BASE + 0x007eUL)) #define RX65N_USB_PIPE9CTR ((volatile short *) (RX65N_USB_BASE + 0x0080UL)) /* USB Pipe 1 to 9 control register bit fields */ #define RX65N_USB_PIPECTR_BSTS (1U << 15) #define RX65N_USB_PIPECTR_INBUFM (1U << 14) #define RX65N_USB_PIPECTR_ATREPM (1U << 10) #define RX65N_USB_PIPECTR_ACLRM (1U << 9) #define RX65N_USB_PIPECTR_SQCLR (1U << 8) #define RX65N_USB_PIPECTR_SQSET (1U << 7) #define RX65N_USB_PIPECTR_SQMON (1U << 6) #define RX65N_USB_PIPECTR_PBUSY (1U << 5) #define RX65N_USB_PIPECTR_PID_MASK (3) #define RX65N_USB_PIPECTR_PIDNAK (0) #define RX65N_USB_PIPECTR_PIDBUF (1) #define RX65N_USB_PIPECTR_PIDSTALL (2) #define RX65N_USB_PIPECTR_PIDSTALL2 (3) #define RX65N_USB_PIPECTR_DATA1 (1U << 7) #define RX65N_USB_PIPECTR_DATA0 (1U << 8) /* USB PIPE 1 to 5 (Transaction Counter Enable) and * (Transaction Counter Register) Registers */ #define RX65N_USB_PIPE1TRE ((volatile short *) (RX65N_USB_BASE + 0x0090UL)) #define RX65N_USB_PIPE1TRN ((volatile short *) (RX65N_USB_BASE + 0x0092UL)) #define RX65N_USB_PIPE2TRE ((volatile short *) (RX65N_USB_BASE + 0x0094UL)) #define RX65N_USB_PIPE2TRN ((volatile short *) (RX65N_USB_BASE + 0x0096UL)) #define RX65N_USB_PIPE3TRE ((volatile short *) (RX65N_USB_BASE + 0x0098UL)) #define RX65N_USB_PIPE3TRN ((volatile short *) (RX65N_USB_BASE + 0x009aUL)) #define RX65N_USB_PIPE4TRE ((volatile short *) (RX65N_USB_BASE + 0x009cUL)) #define RX65N_USB_PIPE4TRN ((volatile short *) (RX65N_USB_BASE + 0x009eUL)) #define RX65N_USB_PIPE5TRE ((volatile short *) (RX65N_USB_BASE + 0x00a0UL)) #define RX65N_USB_PIPE5TRN ((volatile short *) (RX65N_USB_BASE + 0x00a2UL)) /* USB PIPE 1 to 5 Transaction Counter Enable register bit fields */ #define RX65N_USB_PIPETRE_TRENB (1U << 9) #define RX65N_USB_PIPETRE_TRCLR (1U << 8) /* USB Device Address 0 to 5 Configuration Register */ #define RX65N_USB_DEVADD0 ((volatile short *) (RX65N_USB_BASE + 0x00d0UL)) #define RX65N_USB_DEVADD1 ((volatile short *) (RX65N_USB_BASE + 0x00d2UL)) #define RX65N_USB_DEVADD2 ((volatile short *) (RX65N_USB_BASE + 0x00d4UL)) #define RX65N_USB_DEVADD3 ((volatile short *) (RX65N_USB_BASE + 0x00d6UL)) #define RX65N_USB_DEVADD4 ((volatile short *) (RX65N_USB_BASE + 0x00d8UL)) #define RX65N_USB_DEVADD5 ((volatile short *) (RX65N_USB_BASE + 0x00daUL)) #define RX65N_USB_DEVSPD (3 << 6) #define USB_MAXDEVADDR (5u) #define USB_DEVICE_0 (0x0000u) /* Device address 0 */ #define USB_DEVICE_1 (0x1000u) /* Device address 1 */ #define USB_DEVICE_2 (0x2000u) /* Device address 2 */ #define USB_DEVICE_3 (0x3000u) /* Device address 3 */ #define USB_DEVICE_4 (0x4000u) /* Device address 4 */ #define USB_DEVICE_5 (0x5000u) /* Device address 5 */ #define USB_DEVICE_6 (0x6000u) /* Device address 6 */ #define USB_DEVICE_7 (0x7000u) /* Device address 7 */ #define USB_DEVICE_8 (0x8000u) /* Device address 8 */ #define USB_DEVICE_9 (0x9000u) /* Device address 9 */ #define USB_DEVICE_A (0xa000u) /* Device address A */ #define USB_NODEVICE (0xf000u) /* No device */ #define USB_DEVADDRBIT (12u) #define USB_DEFPACKET (0x0040) /* Device Address bit fields */ #define RX65N_USB_DEVADD_SPEED_LOW (1U << 6) #define RX65N_USB_DEVADD_SPEED_FULL (2U << 6) #define RX65N_USB_DEVADD_SPEED_HIGH (3U << 6) /* USB PHY Cross Point Adjustment Register and its bit fields */ #define RX65N_USB_PHYSLEW ((volatile int *) (RX65N_USB_BASE + 0x00f0UL)) /* PHY Cross Point Adjustment, note that Hardware Manual to be * updated(0xe->0x5) */ #define RX65N_USB_PHYSLEW_SLEW_SLEWR00 (1U << 0) #define RX65N_USB_PHYSLEW_SLEW_SLEWR01 (1U << 1) #define RX65N_USB_PHYSLEW_SLEW_SLEWF00 (1U << 2) #define RX65N_USB_PHYSLEW_SLEW_SLEWF01 (1U << 3) /* USB Deep Standby USB Transceiver Control/Pin Monitoring Register */ #define RX65N_USB_DPUSR0R ((volatile int *)(RX65N_USB_BASE + 0x0400UL)) /* USB Deep Standby USB Suspend/Resume Interrupt Register */ #define RX65N_USB_DPUSR1R ((volatile int *)(RX65N_USB_BASE + 0x0404UL)) #define RX65N_USB_BRDYENB ((volatile short *) (RX65N_USB_BASE + 0x0036UL)) #define RX65N_USB_NRDYENB ((volatile short *) (RX65N_USB_BASE + 0x0038UL)) /* USB BEMP Interrupt Enable Register */ #define RX65N_USB_BEMPENB ((volatile short *) (RX65N_USB_BASE + 0x003aUL)) /* USB Frame Number Register and its bit fields */ #define RX65N_USB_FRMNUM ((volatile short *) (RX65N_USB_BASE + 0x004cUL)) #define RX65N_USB_FRMNUM_OVRN (1U << 15) #define RX65N_USB_FRMNUM_CRCE (1U << 14) #define RX65N_USB_FRMNUM_FRNM_MASK (0x7ffU) /* USB Device State Change Register and its bit fields */ #define RX65N_USB_DVCHGR ((volatile short *) (RX65N_USB_BASE + 0x004eUL)) #define RX65N_USB_PIPESEL ((volatile short *) (RX65N_USB_BASE + 0x0064UL)) #define RX65N_USB_PIPESEL_NO_PIPE (0x000fUL) #define RX65N_USB_PIPECFG ((volatile short *) (RX65N_USB_BASE + 0x0068UL)) #define RX65N_USB_PIPECFG_TYPE_MASK (0xc000) #define RX65N_USB_PIPECFG_TYPE_BIT_USED (0) #define RX65N_USB_PIPECFG_TYPE_BULK (1U << 14) #define RX65N_USB_PIPECFG_TYPE_INTERRUPT (2U << 14) #define RX65N_USB_PIPECFG_TYPE_ISOCHRONOUS (3U << 14) #define RX65N_USB_PIPECFG_BFRE (1U << 10) #define RX65N_USB_PIPECFG_DBLB (1U << 9) #define RX65N_USB_PIPECFG_SHTNAK (1U << 7) #define RX65N_USB_PIPECFG_DIR (1U << 4) #define RX65N_USB_PIPECFG_EPNUM_MASK (0xfU) #define RX65N_USB_PIPEMAXP ((volatile short *) (RX65N_USB_BASE + 0x006cUL)) #define RX65N_USB_PIPEMAXP_DEVSELMASK (0xfU << 12) #define RX65N_USB_PIPEMAXP_DEVSEL_SHIFT (12U) #define RX65N_USB_PIPEMAXP_MXPSMASK (0x1ff) #define RX65N_USB_PIPEPERI ((volatile short *) (RX65N_USB_BASE + 0x006eUL)) /* USB BRDY Interrupt Status Register */ #define RX65N_USB_BRDYSTS ((volatile short *) (RX65N_USB_BASE + 0x0046UL)) /* USB NRDY Interrupt Status Register */ #define RX65N_USB_NRDYSTS ((volatile short *) (RX65N_USB_BASE + 0x0048UL)) /* USB BEMP Interrupt Status Register */ #define RX65N_USB_BEMPSTS ((volatile short *) (RX65N_USB_BASE + 0x004aUL)) #define RX65N_USB_DVSTCTR0 ((volatile short *) (RX65N_USB_BASE + 0x0008UL)) #define USB_HSMODE (0x0003u) /* Hi-Speed mode */ #define USB_FSMODE (0x0002u) /* Full-Speed mode */ #define USB_LSMODE (0x0001u) /* Low-Speed mode */ #define USB_HSPROC (0x0004u) /* HS handshake processing */ #define USB_HSCONNECT (0x00C0u) /* Hi-Speed connect */ #define USB_FSCONNECT (0x0080u) /* Full-Speed connect */ #define USB_LSCONNECT (0x0040u) /* Low-Speed connect */ #define USB_NOCONNECT (0x0000u) #define RX65N_USB_DCPCFG ((volatile short *) (RX65N_USB_BASE + 0x005cUL)) #define RX65N_USB_DCPCFG_DIR (1U << 4) #define RX65N_USB_DCPMAXP ((volatile short *) (RX65N_USB_BASE + 0x005eUL)) #define RX65N_USB_DCPMAXP_DEVADDR_SHIFT (12U) #define RX65N_USB_DCPMAXP_DEVADDR_MASK (0xf000U) #define RX65N_USB_DCPMAXP_MXPS_MASK (0x007fU) #define USB_DCPMAXP (64u) #define RX65N_USB_USBREQ ((volatile short *) (RX65N_USB_BASE + 0x0054UL)) /* USB Request Value Register */ #define RX65N_USB_USBVAL ((volatile short *) (RX65N_USB_BASE + 0x0056UL)) /* USB Request Index Register */ #define RX65N_USB_USBINDX ((volatile short *) (RX65N_USB_BASE + 0x0058UL)) /* USB Request Length Register */ #define RX65N_USB_USBLENG ((volatile short *) (RX65N_USB_BASE + 0x005aUL)) /* Endpoint Descriptor Define */ #define USB_EP_IN (0x80u) /* In Endpoint */ #define USB_EP_OUT (0x00u) /* Out Endpoint */ #define USB_EP_ISO (0x01u) /* Isochronous Transfer */ #define USB_EP_BULK (0x02u) /* Bulk Transfer */ #define USB_EP_INT (0x03u) /* Interrupt Transfer */ #define USB_PIPE_DIR_IN (0u) #define USB_PIPE_DIR_OUT (1u) #define USB_PIPE_DIR_MAX (2u) #define USB_CFG_PCDC_BULK_IN (USB_PIPE1) #define USB_CFG_PCDC_BULK_OUT (USB_PIPE2) #define USB_CFG_PCDC_INT_IN (USB_PIPE6) /* USB pipe number */ #define USB_PIPE0 (0x0u) /* Pipe configuration table define */ #define USB_EPL (6u) /* Pipe configuration table length */ #define USB_TYPFIELD (0xC000u) /* Transfer type */ #define USB_PERIODIC (0x8000u) /* Periodic pipe */ #define USB_TYPFIELD_ISO (0xC000u) /* Isochronous */ #define USB_TYPFIELD_INT (0x8000u) /* Interrupt */ #define USB_TYPFIELD_BULK (0x4000u) /* Bulk */ #define USB_NOUSE (0x0000u) /* Not configuration */ #define USB_BFREFIELD (0x0400u) /* Buffer ready interrupt mode select */ #define USB_BFREON (0x0400u) #define USB_BFREOFF (0x0000u) #define USB_DBLBFIELD (0x0200u) /* Double buffer mode select */ #define USB_CFG_DBLBON (0x0200u) #define USB_CFG_DBLBOFF (0x0000u) #define USB_CNTMDFIELD (0x0100u) /* Continuous transfer mode select */ #define USB_CFG_CNTMDON (0x0100u) #define USB_CFG_CNTMDOFF (0x0000u) #define USB_CFG_DBLB (USB_CFG_DBLBON) #define USB_DIR_P_IN (0x0010u) /* PERI IN */ #define USB_DIR_H_IN (0x0000u) #define USB_SHTNAKFIELD (0x0080u) /* Transfer end NAK */ #define USB_DIR_P_OUT (0x0000u) /* PERI OUT */ #define USB_BRDY (0x0100u) /* b8: Buffer ready interrupt */ #define BRDYSTS_MASK (0x03FFu) /* BRDYSTS Reserved bit mask */ #define RX65N_USB_INTSTS0_NRDY (1U << 9) #define RX65N_PIPENUM_WRITE (1) #define RX65N_USB_MAXP (64) #define RX65N_USBI0_SOURCE (0x3eu) #define RX65N_USBI0_PRIORITY (0x0f) #define RX65N_PHYSLEW_VALUE (0x5) #define RX65N_USB_PFKUSB_ENABLED (1U << 4) #define RX65N_USB_PFKUSB_MODE_HOST (1) #define RX65N_USB_INTERRUPT_STATUS_MASK (0x3ffU) /* Supported USBMCLK frequency for S7G2 and S5D9. */ #define RX65N_USB_MAIN_OSC_24MHz (24000000U) #define RX65N_USB_MAIN_OSC_20MHz (20000000U) #define RX65N_USB_MAIN_OSC_12MHz (12000000U) /* Bit fields */ #define RX65N_USB_SYSSTS0_LNST_J_STATE_FS (1U) #define RX65N_USB_SYSSTS0_LNST_J_STATE_LS (2U) #define RX65N_USB_PLLSTA_PLLLOCK (1U << 0) #define RX65N_USB_PHYSET_HSEB (1U << 15) #define RX65N_USB_PHYSET_REPSTART (1U << 11) #define RX65N_USB_PHYSET_REPSEL (1U << 8) #define RX65N_USB_PHYSET_CLKSEL_1 (1U << 5) #define RX65N_USB_PHYSET_CLKSEL_0 (1U << 4) #define RX65N_USB_PHYSET_CDPEN (1U << 3) #define RX65N_USB_PHYSET_PLLRESET (1U << 1) #define RX65N_USB_PHYSET_DIRPD (1U << 0) #define RX65N_USB_PIPEBUF_SIZEMASK (0x1fU << 10) #define RX65N_USB_PIPEBUF_BUFNMBMASK (0xffU << 10) #define RX65N_USB_PIPEBUF_SHIFT (10U) /* Possibly below are used for differentiating Control/ D0 or D1 pipe... */ #define RX65N_USB_FIFO_D0 (0UL) #define RX65N_USB_FIFO_D1 (1UL) #define RX65N_USB_FIFO_C (2UL) #define RX65N_USB_DEVADD_UPPHUB_SHIFT (11U) #define RX65N_USB_DEVADD_HUBPORT_SHIFT (8U) #define RX65N_USB_USBMC_VDCEN (1U << 7) /* Define Synergy HCOR command/status bitmaps. */ #define RX65N_USB_DCP (0) #define RX65N_USB_DCPCTR_DATA1 (1U << 7) #define RX65N_USB_DCPCTR_DATA0 (1U << 8) /* Define Synergy fifo definition. */ #define RX65N_USB_PIPE0_SIZE (256) #define RX65N_USB_PIPE_NB_BUFFERS (64) /* Define Synergy static definition. */ #define RX65N_USB_AVAILABLE_BANDWIDTH (2304UL) /* The macro above is used for checking the available bandwidth for periodic * transfers(Isochronous and Interrupt) * Maximum bandwidth is calculated as * {2048byes(2x ISO PIPEs) + 256bytes(4x INT PIPEs)} for high-speed operation */ #define RX65N_USB_INIT_DELAY (1000) #define RX65N_USB_RESET_RETRY (1000) #define RX65N_USB_RESET_DELAY (10) #define RX65N_USB_PORT_RESET_RETRY (50) #define RX65N_USB_FORCE_PORT_RESET_RETRY (50) #define RX65N_USB_FORCE_PORT_RESET_DELAY (1) #define RX65N_USB_CHECK_PORT_RESET_RETRY (500) #define RX65N_USB_PORT_RESET_DELAY (300) #define RX65N_USB_PORT_RESET_RECOVERY_DELAY (100) /* Define Synergy initialization values. */ #define RX65N_USB_COMMAND_STATUS_RESET (0) #define RX65N_USB_INIT_RESET_DELAY (10) #define RX65N_USB_MAX_BUF_SIZE (64) #define RX65N_USB_BUF_BLOCK_SIZE (64) #define RX65N_USB_MAX_BUF_SIZE_PIPE1_to_2_FS (256) #define RX65N_USB_MAX_BUF_SIZE_PIPE3_to_9_FS (64) #define RX65N_USB_MAX_BUF_SIZE_PIPE1_to_2_HS (1024) #define RX65N_USB_MAX_BUF_SIZE_PIPE3_to_5_HS (512) #define RX65N_USB_MAX_BUF_SIZE_PIPE6_to_9_HS (64) #define RX65N_USB_MAX_BUF_NUM (135) #define RX65N_USB_PIPE1_BUF_START_NUM (8) /* Define Synergy FIFO write completion code. */ #define RX65N_USB_FIFO_WRITING (2) #define RX65N_USB_FIFO_WRITE_END (3) #define RX65N_USB_FIFO_WRITE_SHORT (4) #define RX65N_USB_FIFO_WRITE_DMA (5) #define RX65N_USB_FIFO_WRITE_ERROR (6) /* Define Synergy FIFO read completion code. */ #define RX65N_USB_FIFO_READING (2) #define RX65N_USB_FIFO_READ_END (3) #define RX65N_USB_FIFO_READ_SHORT (4) #define RX65N_USB_FIFO_READ_DMA (5) #define RX65N_USB_FIFO_READ_ERROR (6) #define RX65N_USB_FIFO_READ_OVER (7) #define RX65N_USB_ED_BRDY (0x00000001U) #define RX65N_USB_ED_NRDY (0x00000002U) #define RX65N_USB_ED_BEMP (0x00000004U) #define RX65N_USB_ED_EOFERR (0x00000010U) #define RX65N_USB_ED_SIGN (0x00000020U) #define RX65N_USB_ED_SACK (0x00000040U) #define RX65N_USB_ED_TIMEOUT (0x00000080U) #define RX65N_USB_LPSTS_SUSPENDM (1U << 14) /* Define Synergy Root hub states. */ #define RX65N_USB_PORT_ENABLED (1) #define RX65N_USB_PORT_DISABLED (0) #define RX65N_USB_PORT_INEOFERR (3) #define RX65N_USB_FRMNUM_VAL (0x1111111111) #define USB_INT_BRDY (0x0001u) #define USB_BMREQUESTTYPERECIP (0x001Fu) /* b4-0: Recipient */ #define HUB_PORT1 (1) #define HUB_PORT2 (2) #define HUB_PORT3 (3) #define HUB_PORT4 (4) /* StandBy RAM Address */ #define RX65N_SBRAM_BASE 0x000a4000 /* Start of RSPI interface related definitions */ #if defined(CONFIG_SPI) || defined(CONFIG_SPI_DRIVER) #define HAVE_RSPI_DRIVER 1 #endif #define RX65N_RSPI0_BASE (0x000D0100) #define RX65N_RSPI1_BASE (0x000D0140) #define RX65N_RSPI2_BASE (0x000D0300) /* Tx and Rx vector number */ #define RX65N_RSPI0_RXVECT (38) #define RX65N_RSPI0_TXVECT (39) #define RX65N_RSPI1_RXVECT (40) #define RX65N_RSPI1_TXVECT (41) #define RX65N_RSPI2_RXVECT (108) #define RX65N_RSPI2_TXVECT (109) #define RX65N_PCLK_FREQUENCY RX_PCLKA /* RSPI Register offsets */ #define RX65N_RSPI_SPCR_OFFSET (0x0000) /* RSPI Control Register */ #define RX65N_RSPI_SSLP_OFFSET (0x0001) /* RSPI Slave Select Polarity Register */ #define RX65N_RSPI_SPPCR_OFFSET (0x0002) /* RSPI Pin Control Register */ #define RX65N_RSPI_SPSR_OFFSET (0x0003) /* RSPI Status Register */ #define RX65N_RSPI_SPDR_OFFSET (0x0004) /* RSPI Data Register */ #define RX65N_RSPI_SPSCR_OFFSET (0x0008) /* RSPI Sequence Control Register */ #define RX65N_RSPI_SPSSR_OFFSET (0x0009) /* RSPI Sequence Status Register */ #define RX65N_RSPI_SPBR_OFFSET (0x000A) /* RSPI Bit Rate Register */ #define RX65N_RSPI_SPDCR_OFFSET (0x000B) /* RSPI Data Control Register */ #define RX65N_RSPI_SPCKD_OFFSET (0x000C) /* RSPI Clock Delay Register */ #define RX65N_RSPI_SSLND_OFFSET (0x000D) /* RSPI Slave Select Negation Delay Register */ #define RX65N_RSPI_SPND_OFFSET (0x000E) /* RSPI Next-Access Delay Register */ #define RX65N_RSPI_SPCR2_OFFSET (0x000F) /* RSPI Control Register 2 */ #define RX65N_RSPI_SPCMD0_OFFSET (0x0010) /* RSPI Command Registers 0 */ #define RX65N_RSPI_SPCMD1_OFFSET (0x0012) /* RSPI Command Registers 1 */ #define RX65N_RSPI_SPCMD2_OFFSET (0x0014) /* RSPI Command Registers 2 */ #define RX65N_RSPI_SPCMD3_OFFSET (0x0016) /* RSPI Command Registers 3 */ #define RX65N_RSPI_SPCMD4_OFFSET (0x0018) /* RSPI Command Registers 4 */ #define RX65N_RSPI_SPCMD5_OFFSET (0x001A) /* RSPI Command Registers 5 */ #define RX65N_RSPI_SPCMD6_OFFSET (0x001C) /* RSPI Command Registers 6 */ #define RX65N_RSPI_SPCMD7_OFFSET (0x001E) /* RSPI Command Registers 7 */ #define RX65N_RSPI_SPDCR2_OFFSET (0x0020) /* RSPI Data Control Register 2 */ /* RSPI Control Register bits */ #define RSPI_SPCR_SMPS (1 << 0) /* RSPI Mode Select */ #define RSPI_SPCR_TXMD (1 << 1) /* Communications Operating Mode Select */ #define RSPI_SPCR_MODFEN (1 << 2) /* Mode Fault Error Detection Enable */ #define RSPI_SPCR_MSTR (1 << 3) /* RSPI Master/Slave Mode Select */ #define RSPI_SPCR_SPEIE (1 << 4) /* RSPI Error Interrupt Enable */ #define RSPI_SPCR_SPTIE (1 << 5) /* Transmit Buffer Empty Interrupt Enable */ #define RSPI_SPCR_SPE (1 << 6) /* RSPI Function Enable */ #define RSPI_SPCR_SPRIE (1 << 7) /* RSPI Receive Buffer Full Interrupt Enable */ /* RSPI Slave Select Polarity Register bits */ #define RSPI_SSLP_SSL0P (1 << 0) /* SSL0 Signal Polarity Setting */ #define RSPI_SSLP_SSL1P (1 << 1) /* SSL0 Signal Polarity Setting */ #define RSPI_SSLP_SSL2P (1 << 2) /* SSL0 Signal Polarity Setting */ #define RSPI_SSLP_SSL3P (1 << 3) /* SSL0 Signal Polarity Setting */ /* RSPI Pin Control Register bits */ #define RSPI_SPPCR_SPLP (1 << 0) /* 0: Normal mode. 1: Loopback mode (reversed transmit data = receive). */ #define RSPI_SPPCR_SPLP2 (1 << 1) /* 0: Normal mode. 1: Loopback mode (transmit data = receive data). */ #define RSPI_SPPCR_MOIFV (1 << 4) /* 0: MOSI pin idles low. 1: MOSI pin idles high. */ #define RSPI_SPPCR_MOIFE (1 << 5) /* 0: MOSI pin idles at final previous data. 1: MOSI pin idles at MOIFV. */ /* RSPI status register bits */ #define RSPI_SPSR_OVRF (1 << 0) /* Overrun Error Flag */ #define RSPI_SPSR_IDLNF (1 << 1) /* RSPI Idle Flag */ #define RSPI_SPSR_MODF (1 << 2) /* Mode Fault Error Flag */ #define RSPI_SPSR_PERF (1 << 3) /* Parity Error Flag */ #define RSPI_SPSR_UDRF (1 << 4) /* Underrun Error Flag */ #define RSPI_SPSR_SPTEF (1 << 5) /* Transmit Buffer Empty Flag */ #define RSPI_SPSR_SPRF (1 << 7) /* Receive Buffer Full Flag */ #define RSPI_SPSR_MODF_UDRF_MASK (0xAB) /* Protect reserved bits. */ /* RSPI Data Control Register bit and mask */ #define RSPI_SPDCR_MASK (0x73) /* Mask for SPDCR*/ #define RSPI_SPDCR_SPFC0 (1 << 0) /* b0 used for number of frame calculation with b1 */ #define RSPI_SPDCR_SPFC1 (1 << 1) /* b1 used for number of frame calculation with b0 */ #define RSPI_SPDCR_SPRDTD (1 << 4) /* RSPI Receive/Transmit Data Select*/ #define RSPI_SPDCR_SPLW (1 << 5) /* RSPI Longword Access Word Access Specification */ #define RSPI_SPDCR_SPBYT (1 << 6) /* RSPI Byte Access Specification*/ #define RSPI_SPDCR_SPFC_MASK (0x3) /* SPFC mask */ /* RSPI command register bits */ #define RSPI_SPCMD_MASK (0xFF << 0) /* RSPI Command Register mask */ #define RSPI_SPCMD_PHA (1 << 0) /* RSPCK Phase Setting */ #define RSPI_SPCMD_POL (1 << 1) /* RSPCK Polarity Setting */ #define RSPI_SPCMD_BRDV0 (1 << 2) /* Bit Rate Division Setting bit b2 */ #define RSPI_SPCMD_BRDV1 (1 << 3) /* Bit Rate Division Setting bit b3 */ #define RSPI_SPCMD_SSLA0 (1 << 4) /* SSL Signal Assertion Setting bit b4 */ #define RSPI_SPCMD_SSLA1 (1 << 5) /* SSL Signal Assertion Setting bit b5 */ #define RSPI_SPCMD_SSLA2 (1 << 6) /* SSL Signal Assertion Setting bit b6 */ #define RSPI_SPCMD_SSLKP (1 << 7) /* SSL Signal Level Keeping bit b7 */ #define RSPI_SPCMD_SPB0 (1 << 8) /* RSPI Data Length Setting bit b8 */ #define RSPI_SPCMD_SPB1 (1 << 9) /* RSPI Data Length Setting bit b9 */ #define RSPI_SPCMD_SPB2 (1 << 10) /* RSPI Data Length Setting bit b10 */ #define RSPI_SPCMD_SPB3 (1 << 11) /* RSPI Data Length Setting bit b11 */ #define RSPI_SPCMD_LSBF (1 << 12) /* RSPI LSB First bit b12 */ #define RSPI_SPCMD_SPNDEN (1 << 13) /* RSPI Next-Access Delay Enable bit */ #define RSPI_SPCMD_SLNDEN (1 << 14) /* SSL Negation Delay Setting Enable bit */ #define RSPI_SPCMD_SCKDEN (1 << 15) /* SCKDEN RSPCK Delay Setting Enable bit */ #define RSPI_SPCMD_BRDV_MASK (3 << 2) /* Bit Rate Division Setting mask */ #define RSPI_SPCMD_SPB_MASK (15 << 8) /* RSPI Data Length Setting */ /* RSPI clock delay register bit */ #define RSPI_SPCKD_MASK (7 << 0) /* RSPCK Delay Setting mask */ #define RSPI_SPCKD_SCKDL0 (1 << 0) /* SCKDL0 bit */ #define RSPI_SPCKD_SCKDL1 (1 << 1) /* SCKDL1 bit */ #define RSPI_SPCKD_SCKDL2 (1 << 2) /* SCKDL2 bit */ /* RSPI Slave Select Negation Delay Register bit */ #define RSPI_SSLND_MASK (7 << 0) /* SSL Negation Delay Setting mask */ #define RSPI_SSLND_SLNDL0 (1 << 0) /* SLNDL0 bit */ #define RSPI_SSLND_SLNDL1 (1 << 1) /* SLNDL1 bit */ #define RSPI_SSLND_SLNDL2 (1 << 2) /* SLNDL2 bit */ /* RSPI clock delay register bit */ #define RSPI_SPND_MASK (7 << 0) /* RSPI Next-Access Delay mask */ #define RSPI_SPND_SPNDL0 (1 << 0) /* SPNDL0 bit */ #define RSPI_SPND_SPNDL1 (1 << 1) /* SPNDL1 bit */ #define RSPI_SPND_SPNDL2 (1 << 2) /* SPNDL2 bit */ /* RSPI RSPI Control Register 2 bit */ #define RSPI_SPCR2_MASK (0x1F << 0) /* RSPI Control Register 2 mask */ #define RSPI_SPCR2_SPPE (1 << 0) /* Parity Enable bit */ #define RSPI_SPCR2_SPOE (1 << 1) /* Parity Mode bit */ #define RSPI_SPCR2_SPIIE (1 << 2) /* RSPI Idle Interrupt Enable */ #define RSPI_SPCR2_PTE (1 << 3) /* Parity Self-Diagnosis bit */ #define RSPI_SPCR2_SCKASE (1 << 4) /* RSPCK Auto-Stop Function Enable bit */ /* RSPI Sequence Control Register 2 bit */ #define RSPI_SPSCR_MASK (7 << 0) /* RSPI Sequence Control Register mask */ #define RSPI_SPSCR_SPSLN0 (1 << 0) /* SPSLN0 bit */ #define RSPI_SPSCR_SPSLN1 (1 << 1) /* SPSLN1 bit */ #define RSPI_SPSCR_SPSLN2 (1 << 2) /* SPSLN2 bit */ /* Set RSPI data control register 2 bit */ #define RSPI_SPDCR2_BYSW (1 << 0) /* RSPI Byte Swap */ /* End of RSPI interface related definitions */ /* RIIC related definitions */ #if defined(CONFIG_I2C) || defined(CONFIG_I2C_DRIVER) #define HAVE_RIIC_DRIVER 1 #endif /* RIIC Channel Base Address definitions */ #define RX65N_RIIC0_BASE (uint32_t)&RIIC0 #define RX65N_RIIC1_BASE (uint32_t)&RIIC1 #define RX65N_RIIC2_BASE (uint32_t)&RIIC2 /* RIIC Register Offset definitions */ #define RX65N_RIIC_ICCR1_OFFSET (0x0000) #define RX65N_RIIC_ICCR2_OFFSET (0x0001) #define RX65N_RIIC_ICMR1_OFFSET (0x0002) #define RX65N_RIIC_ICMR2_OFFSET (0x0003) #define RX65N_RIIC_ICMR3_OFFSET (0x0004) #define RX65N_RIIC_ICFER_OFFSET (0x0005) #define RX65N_RIIC_ICSER_OFFSET (0x0006) #define RX65N_RIIC_ICIER_OFFSET (0x0007) #define RX65N_RIIC_ICSR1_OFFSET (0x0008) #define RX65N_RIIC_ICSR2_OFFSET (0x0009) #define RX65N_RIIC_SARL0_OFFSET (0x000a) #define RX65N_RIIC_SARU0_OFFSET (0x000b) #define RX65N_RIIC_SARL1_OFFSET (0x000c) #define RX65N_RIIC_SARU1_OFFSET (0x000d) #define RX65N_RIIC_SARL2_OFFSET (0x000e) #define RX65N_RIIC_SARU2_OFFSET (0x000f) #define RX65N_RIIC_ICBRL_OFFSET (0x0010) #define RX65N_RIIC_ICBRH_OFFSET (0x0011) #define RX65N_RIIC_ICDRT_OFFSET (0x0012) #define RX65N_RIIC_ICDRR_OFFSET (0x0013) /* RIIC register address definitions */ #define RX65N_RIIC0_ICCR1 (RX65N_RIIC0_BASE + RX65N_RIIC_ICCR1_OFFSET) #define RX65N_RIIC0_ICCR2 (RX65N_RIIC0_BASE + RX65N_RIIC_ICCR2_OFFSET) #define RX65N_RIIC0_ICMR1 (RX65N_RIIC0_BASE + RX65N_RIIC_ICMR1_OFFSET) #define RX65N_RIIC0_ICMR2 (RX65N_RIIC0_BASE + RX65N_RIIC_ICMR2_OFFSET) #define RX65N_RIIC0_ICMR3 (RX65N_RIIC0_BASE + RX65N_RIIC_ICMR3_OFFSET) #define RX65N_RIIC0_ICFER (RX65N_RIIC0_BASE + RX65N_RIIC_ICFER_OFFSET) #define RX65N_RIIC0_ICSER (RX65N_RIIC0_BASE + RX65N_RIIC_ICSER_OFFSET) #define RX65N_RIIC0_ICIER (RX65N_RIIC0_BASE + RX65N_RIIC_ICIER_OFFSET) #define RX65N_RIIC0_ICSR1 (RX65N_RIIC0_BASE + RX65N_RIIC_ICSR1_OFFSET) #define RX65N_RIIC0_ICSR2 (RX65N_RIIC0_BASE + RX65N_RIIC_ICSR2_OFFSET) #define RX65N_RIIC0_SARL0 (RX65N_RIIC0_BASE + RX65N_RIIC_SARL0_OFFSET) #define RX65N_RIIC0_SARU0 (RX65N_RIIC0_BASE + RX65N_RIIC_SARU0_OFFSET) #define RX65N_RIIC0_SARL1 (RX65N_RIIC0_BASE + RX65N_RIIC_SARL1_OFFSET) #define RX65N_RIIC0_SARU1 (RX65N_RIIC0_BASE + RX65N_RIIC_SARU1_OFFSET) #define RX65N_RIIC0_SARL2 (RX65N_RIIC0_BASE + RX65N_RIIC_SARL2_OFFSET) #define RX65N_RIIC0_SARU2 (RX65N_RIIC0_BASE + RX65N_RIIC_SARU2_OFFSET) #define RX65N_RIIC0_ICBRL (RX65N_RIIC0_BASE + RX65N_RIIC_ICBRL_OFFSET) #define RX65N_RIIC0_ICBRH (RX65N_RIIC0_BASE + RX65N_RIIC_ICBRH_OFFSET) #define RX65N_RIIC0_ICDRT (RX65N_RIIC0_BASE + RX65N_RIIC_ICDRT_OFFSET) #define RX65N_RIIC0_ICDRR (RX65N_RIIC0_BASE + RX65N_RIIC_ICDRR_OFFSET) #define RX65N_RIIC1_ICCR1 (RX65N_RIIC1_BASE + RX65N_RIIC_ICCR1_OFFSET) #define RX65N_RIIC1_ICCR2 (RX65N_RIIC1_BASE + RX65N_RIIC_ICCR2_OFFSET) #define RX65N_RIIC1_ICMR1 (RX65N_RIIC1_BASE + RX65N_RIIC_ICMR1_OFFSET) #define RX65N_RIIC1_ICMR2 (RX65N_RIIC1_BASE + RX65N_RIIC_ICMR2_OFFSET) #define RX65N_RIIC1_ICMR3 (RX65N_RIIC1_BASE + RX65N_RIIC_ICMR3_OFFSET) #define RX65N_RIIC1_ICFER (RX65N_RIIC1_BASE + RX65N_RIIC_ICFER_OFFSET) #define RX65N_RIIC1_ICSER (RX65N_RIIC1_BASE + RX65N_RIIC_ICSER_OFFSET) #define RX65N_RIIC1_ICIER (RX65N_RIIC1_BASE + RX65N_RIIC_ICIER_OFFSET) #define RX65N_RIIC1_ICSR1 (RX65N_RIIC1_BASE + RX65N_RIIC_ICSR1_OFFSET) #define RX65N_RIIC1_ICSR2 (RX65N_RIIC1_BASE + RX65N_RIIC_ICSR2_OFFSET) #define RX65N_RIIC1_SARL0 (RX65N_RIIC1_BASE + RX65N_RIIC_SARL0_OFFSET) #define RX65N_RIIC1_SARU0 (RX65N_RIIC1_BASE + RX65N_RIIC_SARU0_OFFSET) #define RX65N_RIIC1_SARL1 (RX65N_RIIC1_BASE + RX65N_RIIC_SARL1_OFFSET) #define RX65N_RIIC1_SARU1 (RX65N_RIIC1_BASE + RX65N_RIIC_SARU1_OFFSET) #define RX65N_RIIC1_SARL2 (RX65N_RIIC1_BASE + RX65N_RIIC_SARL2_OFFSET) #define RX65N_RIIC1_SARU2 (RX65N_RIIC1_BASE + RX65N_RIIC_SARU2_OFFSET) #define RX65N_RIIC1_ICBRL (RX65N_RIIC1_BASE + RX65N_RIIC_ICBRL_OFFSET) #define RX65N_RIIC1_ICBRH (RX65N_RIIC1_BASE + RX65N_RIIC_ICBRH_OFFSET) #define RX65N_RIIC1_ICDRT (RX65N_RIIC1_BASE + RX65N_RIIC_ICDRT_OFFSET) #define RX65N_RIIC1_ICDRR (RX65N_RIIC1_BASE + RX65N_RIIC_ICDRR_OFFSET) #define RX65N_RIIC2_ICCR1 (RX65N_RIIC2_BASE + RX65N_RIIC_ICCR1_OFFSET) #define RX65N_RIIC2_ICCR2 (RX65N_RIIC2_BASE + RX65N_RIIC_ICCR2_OFFSET) #define RX65N_RIIC2_ICMR1 (RX65N_RIIC2_BASE + RX65N_RIIC_ICMR1_OFFSET) #define RX65N_RIIC2_ICMR2 (RX65N_RIIC2_BASE + RX65N_RIIC_ICMR2_OFFSET) #define RX65N_RIIC2_ICMR3 (RX65N_RIIC2_BASE + RX65N_RIIC_ICMR3_OFFSET) #define RX65N_RIIC2_ICFER (RX65N_RIIC2_BASE + RX65N_RIIC_ICFER_OFFSET) #define RX65N_RIIC2_ICSER (RX65N_RIIC2_BASE + RX65N_RIIC_ICSER_OFFSET) #define RX65N_RIIC2_ICIER (RX65N_RIIC2_BASE + RX65N_RIIC_ICIER_OFFSET) #define RX65N_RIIC2_ICSR1 (RX65N_RIIC2_BASE + RX65N_RIIC_ICSR1_OFFSET) #define RX65N_RIIC2_ICSR2 (RX65N_RIIC2_BASE + RX65N_RIIC_ICSR2_OFFSET) #define RX65N_RIIC2_SARL0 (RX65N_RIIC2_BASE + RX65N_RIIC_SARL0_OFFSET) #define RX65N_RIIC2_SARU0 (RX65N_RIIC2_BASE + RX65N_RIIC_SARU0_OFFSET) #define RX65N_RIIC2_SARL1 (RX65N_RIIC2_BASE + RX65N_RIIC_SARL1_OFFSET) #define RX65N_RIIC2_SARU1 (RX65N_RIIC2_BASE + RX65N_RIIC_SARU1_OFFSET) #define RX65N_RIIC2_SARL2 (RX65N_RIIC2_BASE + RX65N_RIIC_SARL2_OFFSET) #define RX65N_RIIC2_SARU2 (RX65N_RIIC2_BASE + RX65N_RIIC_SARU2_OFFSET) #define RX65N_RIIC2_ICBRL (RX65N_RIIC2_BASE + RX65N_RIIC_ICBRL_OFFSET) #define RX65N_RIIC2_ICBRH (RX65N_RIIC2_BASE + RX65N_RIIC_ICBRH_OFFSET) #define RX65N_RIIC2_ICDRT (RX65N_RIIC2_BASE + RX65N_RIIC_ICDRT_OFFSET) #define RX65N_RIIC2_ICDRR (RX65N_RIIC2_BASE + RX65N_RIIC_ICDRR_OFFSET) /* RIIC register field/bit value definitions */ #define RX65N_RIIC_ICCR1_ICE_RST (0x7f) #define RX65N_RIIC_ICCR1_IICRST_SET (0x40) #define RX65N_RIIC_ICCR2_ST_SET (0x02) #define RX65N_RIIC_ICCR2_SP_SET (0x08) #define RX65N_RIIC_ICCR2_RS_SET (0x04) #define RX65N_RIIC_ICSR2_STOP_SET (0x08) #define RX65N_RIIC_ICSR2_START_SET (0x04) #define RX65N_RIIC_ICMR1_CKS_MASK (0x8f) #define RX65N_RIIC_ICMR2_SDDL0 (0x06) #define RX65N_RIIC_ICMR2_SDDL1 (0x16) #define RX65N_RIIC_ICMR2_SDDL2 (0x26) #define RX65N_RIIC_ICMR2_SDDL3 (0x36) #define RX65N_RIIC_ICMR2_SDDL4 (0x46) #define RX65N_RIIC_ICMR2_SDDL5 (0x56) #define RX65N_RIIC_ICMR2_SDDL6 (0x66) #define RX65N_RIIC_ICMR2_SDDL7 (0x76) #define RX65N_RIIC_ICMR3_NF1 (0x00) #define RX65N_RIIC_ICMR3_NF2 (0x01) #define RX65N_RIIC_ICMR3_NF3 (0x02) #define RX65N_RIIC_ICMR3_NF4 (0x03) #define RX65N_RIIC_ICMR3_WAIT_SET (0x40) #define RX65N_RIIC_ICMR3_ACKWP_SET (0x10) #define RX65N_RIIC_ICMR3_ACKBT_SET (0x08) #define RX65N_RIIC_ICMR3_ACKWP_CLR (0xEF) #define RX65N_RIIC_ICMR3_RDRFS_SET (0x20) #define RX65N_RIIC_ICIER_ALIE (0x02) #define RX65N_RIIC_ICIER_ST_NAK_AL (0x16) #define RX65N_RIIC_ICIER_SP_NAK_AL (0x1a) #define RX65N_RIIC_ICIER_SP_AL (0x0a) #define RX65N_RIIC_ICIER_TMO (0x01) #define RX65N_RIIC_ICIER_TEND_NAK_AL (0x52) #define RX65N_RIIC_ICIER_RX_NAK_AL (0x32) #define RX65N_RIIC_ICFER_TMOE_SET (0x01) #define RX65N_RIIC_ICFER_NFE_SET (0x20) #define RX65N_RIIC_ICFER_NFE_RST (0xdf) #define RX65N_RIIC_ICSER_SET (0x00) #define RX65N_RIIC_ICBRL_MASK (0xe0) #define RX65N_RIIC_ICBRH_MASK (0xe0) #define RX65N_I2C_SLV_ADDR (0x80) #define RX65N_RIIC_READ_MASK (0x01) #define RX65N_RIIC_10BIT_SARU_MASK (0x0300) #define RX65N_RIIC_10BIT_SARL_MASK (0x00ff) #define BUS_CHECK_COUNTER (1000) #define RIIC_REG_INIT (0x00) #define RIIC_BUS_BUSY ((bool)(1)) #define RIIC_BUS_FREE ((bool)(0)) /* End of RIIC related definitions */ /* Start of DTC interface related definitions */ #if defined(CONFIG_RX65N_DTC) #define HAVE_DTC_DRIVER 1 #endif #define RX65N_DTC_BASE (uint32_t)&DTC #define DTC_DTCCR_OFFSET (0x0000) /* DTC Control Register */ #define DTC_DTCVBR_OFFSET (0x0004) /* DTC Vector Base Register */ #define DTC_DTCADMOD_OFFSET (0x0008) /* DTC Address Mode Register */ #define DTC_DTCST_OFFSET (0x000C) /* DTC Control Register */ #define DTC_DTCSTS_OFFSET (0x000E) /* DTC Status Register */ #define DTC_DTCIBR_OFFSET (0x0010) /* DTC Index Table Base Register */ #define DTC_DTCOR_OFFSET (0x0014) /* DTC Operation Register */ #define DTC_DTCSQE_OFFSET (0x0016) /* DTC Sequence Transfer Enable Register */ #define DTC_DTCDISP_OFFSET (0x0018) /* DTC Address Displacement Register */ /* Bits of register DTCCR */ #define DTC_DTCCR_RRS (1 << 4) /* DTC Transfer Information Read Skip Enable*/ /* Bits of register DTCST */ #define DTC_DTCST_DTCST (1 << 0) /* DTC Transfer Information Read Skip Enable*/ /* End of DTC related defeinitions */ /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ #ifndef __ASSEMBLER__ /* Serial Communications interface (SCI) */ enum E_RX_SCI { RX_SCI_SMR_OFFSET = 0, RX_SCI_BRR_OFFSET, RX_SCI_SCR_OFFSET, RX_SCI_TDR_OFFSET, RX_SCI_SSR_OFFSET, RX_SCI_RDR_OFFSET, RX_SCI_SCMR_OFFSET, RX_SCI_SEMR_OFFSET, RX_SCI_SNFR_OFFSET, RX_SCI_SIMR1_OFFSET, RX_SCI_SIMR2_OFFSET, RX_SCI_SIMR3_OFFSET, RX_SCI_SISR_OFFSET, RX_SCI_SPMR_OFFSET, RX_SCI_THRHL_OFFSET, RX_SCI_THRL_OFFSET, RX_SCI_RDRHL_OFFSET, RX_SCI_RDRL_OFFSET, RX_SCI_MDDR_OFFSET }; #endif /* __ASSEMBLER__ */ #endif /* __ARCH_RENESAS_SRC_RX65N_RX65N_DEFINITIONS_H */
48,941
311
<gh_stars>100-1000 /* * Copyright (c) 2009-2020, <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 software 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 GPICK_DYNV_VARIABLE_H_ #define GPICK_DYNV_VARIABLE_H_ #include "MapFwd.h" #include "Color.h" #include "common/Ref.h" #include <string> #include <vector> #include <cstdint> #include <boost/variant.hpp> namespace dynv { struct Map; struct Variable { using Data = boost::variant<bool, float, int32_t, Color, std::string, Ref, std::vector<bool>, std::vector<float>, std::vector<int32_t>, std::vector<Color>, std::vector<std::string>, std::vector<Ref>>; Variable(const std::string &name, bool value); Variable(const std::string &name, float value); Variable(const std::string &name, int32_t value); Variable(const std::string &name, const Color &value); Variable(const std::string &name, const std::string &value); Variable(const std::string &name, const char *value); Variable(const std::string &name, const Ref &value); Variable(const std::string &name, const std::vector<bool> &value); Variable(const std::string &name, const std::vector<float> &value); Variable(const std::string &name, const std::vector<int32_t> &value); Variable(const std::string &name, const std::vector<Color> &value); Variable(const std::string &name, const std::vector<std::string> &value); Variable(const std::string &name, const std::vector<const char *> &value); Variable(const std::string &name, const std::vector<Ref> &value); void assign(bool value); void assign(float value); void assign(int32_t value); void assign(const Color &value); void assign(const std::string &value); void assign(const char *value); void assign(const Ref &value); template<typename T> void assign(const std::vector<T> &value); ~Variable(); const std::string &name() const; const Data &data() const; Data &data(); private: std::string m_name; Data m_data; }; } #endif /* GPICK_DYNV_VARIABLE_H_ */
1,028
367
<filename>C++/Using a DLL/print.h #ifndef PRINT_H #define PRINT_H #include <iostream> using namespace std; // Here is our slightly modified "print.h" from the "PrintDLL" project // __declspec() "declare special" -- Is a Microsoft specific keyword that allows you // to "specify specific information" about a // variable or function // __declspec(dllimport) -- By passing "dllimport" into __declspec() we are saying // "The function declaration that follows is to be IMPORTED // from a .dll file". __declspec(dllimport) void printMessage(); /* Now the "void printMessage()" is just like a normal function declaration. The return parameter is void and the function takes no parameters. */ #endif
244
335
{ "word": "Xhosa", "definitions": [ "a member of a South African people traditionally living in the province of Eastern Cape. They form the second largest ethnic group in South Africa after the Zulus." ], "parts-of-speech": "Noun" }
73
512
/* * Copyright 2017 XBMC Foundation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xbmc.kore.jsonrpc.method; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.xbmc.kore.jsonrpc.ApiException; import org.xbmc.kore.jsonrpc.ApiList; import org.xbmc.kore.jsonrpc.ApiMethod; import org.xbmc.kore.jsonrpc.type.FavouriteType; import org.xbmc.kore.jsonrpc.type.ListType; import java.util.ArrayList; import java.util.Collections; /** * All JSON RPC methods in Favourites.* */ public class Favourites { /** * Retrieves the Details of the Favourites. */ public static class GetFavourites extends ApiMethod<ApiList<FavouriteType.DetailsFavourite>> { public static final String METHOD_NAME = "Favourites.GetFavourites"; private static final String LIST_NODE = "favourites"; /** * Default ctor, gets all the properties by default. */ public GetFavourites() { addParameterToRequest("properties", new String[]{ FavouriteType.DetailsFavourite.WINDOW, FavouriteType.DetailsFavourite.WINDOW_PARAMETER, FavouriteType.DetailsFavourite.THUMBNAIL, FavouriteType.DetailsFavourite.PATH }); } @Override public String getMethodName() { return METHOD_NAME; } @Override public ApiList<FavouriteType.DetailsFavourite> resultFromJson(ObjectNode jsonObject) throws ApiException { ListType.LimitsReturned limits = new ListType.LimitsReturned(jsonObject); JsonNode resultNode = jsonObject.get(RESULT_NODE); ArrayNode items = resultNode.has(LIST_NODE) && !resultNode.get(LIST_NODE).isNull() ? (ArrayNode) resultNode.get(LIST_NODE) : null; if (items == null) { return new ApiList<>(Collections.<FavouriteType.DetailsFavourite>emptyList(), limits); } ArrayList<FavouriteType.DetailsFavourite> result = new ArrayList<>(items.size()); for (JsonNode item : items) { result.add(new FavouriteType.DetailsFavourite(item)); } return new ApiList<>(result, limits); } } }
1,142
634
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.util.dataholder; import javax.annotation.Nonnull; import java.util.function.Supplier; /** * @author peter */ public final class KeyWithDefaultValue<T> extends Key<T> { @Nonnull public static <T> KeyWithDefaultValue<T> create(@Nonnull String name, final T defValue) { return new KeyWithDefaultValue<T>(name, () -> defValue); } @Nonnull public static <T> KeyWithDefaultValue<T> create(@Nonnull String name, final Supplier<? extends T> supplier) { return new KeyWithDefaultValue<T>(name, supplier); } @Nonnull private final Supplier<? extends T> myValueGetter; @SuppressWarnings("deprecation") private KeyWithDefaultValue(@Nonnull String name, @Nonnull Supplier<? extends T> valueGetter) { super(name); myValueGetter = valueGetter; } public T getDefaultValue() { return myValueGetter.get(); } }
445
3,756
package com.imooc.interview.questions.java.concurrency.thread; import java.io.IOException; public class ProcessCreationQuestion { public static void main(String[] args) throws IOException { // 获取 Java Runtime Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd /k start http://www.baidu.com"); process.exitValue(); } }
137
324
/* * 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.jclouds.ec2.features; import static com.google.common.collect.Iterables.getOnlyElement; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.Properties; import org.jclouds.Constants; import org.jclouds.ec2.EC2Api; import org.jclouds.ec2.domain.PublicIpInstanceIdPair; import org.jclouds.ec2.internal.BaseEC2ApiExpectTest; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.rest.internal.BaseRestApiExpectTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; /** * * @see org.jclouds.ec2.features.ElasticIPAddressApi */ @Test(groups = "unit") public class ElasticIPAddressApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> { protected Properties setupProperties() { Properties props = super.setupProperties(); props.put(Constants.PROPERTY_API_VERSION, "2010-08-31"); return props; } HttpRequest filter = HttpRequest.builder() .method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .payload(BaseRestApiExpectTest.payloadFromStringWithContentType( "Action=DescribeAddresses" + "&Filter.1.Name=instance-id" + "&Filter.1.Value.1=i-f15ebb98" + "&Signature=dJbTUsBGHSrarQQAwmLm8LLI255R/lzdE7ZcYJucOzI%3D" + "&SignatureMethod=HmacSHA256" + "&SignatureVersion=2" + "&Timestamp=2012-04-16T15%3A54%3A08.897Z" + "&Version=2010-08-31" + "&AWSAccessKeyId=identity", "application/x-www-form-urlencoded")) .build(); public void testFilterWhenResponseIs2xx() throws Exception { HttpResponse filterResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResourceWithContentType("/describe_addresses_single.xml", "text/xml")).build(); EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse); PublicIpInstanceIdPair address = getOnlyElement(apiWhenExist.getElasticIPAddressApi() .get().describeAddressesInRegionWithFilter("us-east-1", ImmutableMultimap.<String, String>builder() .put("instance-id", "i-f15ebb98") .build())); assertNotNull(address, "address should not be null"); assertEquals(address.getPublicIp(), "192.168.127.12"); } public void testFilterWhenResponseIs404() throws Exception { HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build(); EC2Api apiWhenDontExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse); assertEquals(apiWhenDontExist.getElasticIPAddressApi() .get().describeAddressesInRegionWithFilter("us-east-1", ImmutableMultimap.<String, String>builder() .put("instance-id", "i-f15ebb98") .build()), ImmutableSet.of()); } }
1,883
5,852
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Memory.h> #include <folly/dynamic.h> #include <memory> #include <proxygen/lib/http/HTTPMessage.h> #include <proxygen/lib/http/codec/compress/HPACKHeader.h> #include <string> #include <vector> namespace proxygen { class HTTPArchive { public: std::vector<HTTPMessage> requests; std::vector<HTTPMessage> responses; static std::vector<std::vector<HPACKHeader>> convertToHPACK( const std::vector<HTTPMessage>& msgs); static std::unique_ptr<HTTPArchive> fromFile(const std::string& filename); static std::unique_ptr<HTTPArchive> fromPublicFile(const std::string& fname); static uint32_t getSize(const HTTPMessage& msg); static uint32_t getSize(const std::vector<HPACKHeader>& headers); }; } // namespace proxygen
326
2,308
/** * Copyright 2016 vip.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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. * </p> **/ package com.vip.saturn.job.console.domain; /** * 禁用作业超时告警对象 */ public class DisabledTimeoutAlarmJob extends AbstractAlarmJob { /** * 禁用作业的时间 */ private long disableTime; /** * 字符串格式的禁用作业时间 */ private String disableTimeStr; /** * 设置的禁用超时秒数 */ private int disableTimeoutSeconds; public DisabledTimeoutAlarmJob() { } public DisabledTimeoutAlarmJob(String jobName, String domainName, String nns, String degree) { super(jobName, domainName, nns, degree); } public long getDisableTime() { return disableTime; } public void setDisableTime(long disableTime) { this.disableTime = disableTime; } public String getDisableTimeStr() { return disableTimeStr; } public void setDisableTimeStr(String disableTimeStr) { this.disableTimeStr = disableTimeStr; } public int getDisableTimeoutSeconds() { return disableTimeoutSeconds; } public void setDisableTimeoutSeconds(int disableTimeoutSeconds) { this.disableTimeoutSeconds = disableTimeoutSeconds; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DisabledTimeoutAlarmJob that = (DisabledTimeoutAlarmJob) o; if (!jobName.equals(that.jobName)) { return false; } return domainName.equals(that.domainName); } @Override public int hashCode() { return (int) (disableTime ^ (disableTime >>> 32)); } }
704
1,142
#ifndef APP_GEOMEAN_H #define APP_GEOMEAN_H #include <cmath> template <typename It, typename Op> double geomean(It begin, It end, Op op) { double sum = 0.0; size_t count = 0; while (begin != end) { sum += std::log(op(*begin)); ++begin; ++count; } sum /= static_cast<double>(count); return std::exp(sum); } template <typename Container, typename Op> double geomean(Container&& c, Op op) { return geomean(std::begin(c), std::end(c), std::move(op)); } #endif
225
556
<reponame>danra/scnlib #!/usr/bin/env python3 import subprocess import sys import os import math import shutil def convert_size(size_bytes): if size_bytes == 0: return '0 B' size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return '{} {}'.format(s, size_name[i]) out = sys.argv[1] stripped = out + '.stripped' size_out = os.path.getsize(out) hsize_out = convert_size(size_out) print('{} {}'.format(size_out, hsize_out)) shutil.copyfile(out, stripped) subprocess.run(['strip', stripped]) size_stripped = os.path.getsize(stripped) hsize_stripped = convert_size(size_stripped) print('{} {}'.format(size_stripped, hsize_stripped)) os.remove(stripped)
338
5,411
<reponame>thorium-cfx/fivem // 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 MOJO_PUBLIC_CPP_BINDINGS_LIB_TRACING_HELPER_H_ #define MOJO_PUBLIC_CPP_BINDINGS_LIB_TRACING_HELPER_H_ #define MANGLE_MESSAGE_ID(id) (id ^ ::mojo::internal::kMojoMessageMangleMask) namespace mojo { namespace internal { // Mojo message id is 32-bit, but for tracing we ensure that mojo messages // don't collide with other trace events. constexpr uint64_t kMojoMessageMangleMask = 0x655b2a8e8efdf27f; } // namespace internal } // namespace mojo #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_TRACING_HELPER_H_
266
313
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.histogram; import java.util.List; import com.google.common.primitives.Longs; public class Histogram { private final List<Long> counters; private final HistogramDescriptor histogramDescriptor; private Histogram(List<Long> counters, HistogramDescriptor histogramDescriptor) { this.counters = counters; this.histogramDescriptor = histogramDescriptor; } public List<Long> getCounters() { return counters; } public HistogramDescriptor getHistogramDescriptor() { return histogramDescriptor; } public static Builder newBuilder(HistogramDescriptor histogramDescriptor) { return new Builder(histogramDescriptor); } public static class Builder { private final HistogramDescriptor histogramDescriptor; private final long[] counters; private Builder(HistogramDescriptor histogramDescriptor) { this.histogramDescriptor = histogramDescriptor; this.counters = histogramDescriptor.newCounters(); } public Builder increment(long value) { return add(value, 1); } public Builder add(long value, long count) { int position = histogramDescriptor.positionOf(value); counters[position] = counters[position] + count; return this; } public Histogram build() { return new Histogram(Longs.asList(counters), histogramDescriptor); } } }
740
488
<reponame>ouankou/rose<gh_stars>100-1000 #include <vector> #include <cstdint> #include <iostream> // DQ (10/18/2017): Added string support. #include<string> class Container { private: std::vector<int> m_Values; public: Container(){} void storeValue(int value) { m_Values.push_back(value); } void dump() { for(auto &i : m_Values) { std::cout << i << std::endl; } } }; //Entry point for C++ // extern "C" void process(void); extern "C" void process(char* top_builddir, char* sourceFileNameWithPath); //Used by C# to store the results extern "C" void storeResults(uint64_t container, int value);
379
785
<filename>app/src/main/java/com/ozj/baby/event/IncrementEvent.java package com.ozj.baby.event; /** * Created by YX201603-6 on 2016/5/26. */ public class IncrementEvent { public int position; public int count; public IncrementEvent(int count, int position) { this.count = count; this.position = position; } }
134
3,508
<reponame>PraneshASP/Leetcode<gh_stars>1000+ package com.fishercoder.solutions; public class _900 { public static class Solution1 { public static class RLEIterator { int index; int[] array; public RLEIterator(int[] A) { index = 0; array = A; } public int next(int n) { int lastElement = -1; while (n > 0 && index < array.length) { if (array[index] > n) { array[index] -= n; lastElement = array[index + 1]; break; } else if (array[index] == n) { array[index] = 0; lastElement = array[index + 1]; index += 2; break; } else { n -= array[index]; index += 2; } } return lastElement; } } } }
682
301
/* * Copyright (c) 2018-2019 "Neo4j, Inc." [https://neo4j.com] * * 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.opencypher.gremlin.queries; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.opencypher.gremlin.test.GremlinExtractors.byElementProperty; import static org.opencypher.gremlin.test.TestCommons.DELETE_ALL; import static org.opencypher.gremlin.translation.ReturnProperties.LABEL; import java.util.List; import java.util.Map; import java.util.Objects; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.opencypher.gremlin.groups.SkipExtensions; import org.opencypher.gremlin.groups.SkipWithCosmosDB; import org.opencypher.gremlin.rules.GremlinServerExternalResource; import org.opencypher.gremlin.test.TestCommons; public class ComplexExamplesTest { @ClassRule public static final GremlinServerExternalResource gremlinServer = new GremlinServerExternalResource(); @Before public void setUp() { submitAndGet(DELETE_ALL); } private List<Map<String, Object>> submitAndGet(String cypher) { return gremlinServer.cypherGremlinClient().submit(cypher).all(); } @Test public void returnDuplicateNode() throws Exception { submitAndGet( "CREATE (x:root)-[:r]->(y)\n" + "CREATE (x)-[:r]->(z)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (x:root)-[:r]->()\n" + "RETURN x" ); List<Map<String, Object>> distinctResults = submitAndGet( "MATCH (x:root)-[:r]->()\n" + "RETURN DISTINCT x" ); assertThat(results) .hasSize(2) .matches(rows -> { Object first = rows.get(0); Object second = rows.get(1); return Objects.equals(first, second); }); assertThat(distinctResults) .hasSize(1) .extracting("x") .extracting(LABEL) .containsExactly("root"); } @Test public void filterOutBasedOnNodePropName() throws Exception { submitAndGet("CREATE ({name: 'Someone'})<-[:X]-()-[:X]->({name: 'Andres'})"); List<Map<String, Object>> results = submitAndGet( "MATCH ()-[rel:X]-(a)\n" + "WHERE a.name = 'Andres'\n" + "RETURN a" ); assertThat(results) .hasSize(1) .extracting("a") .extracting(byElementProperty("name")) .containsExactly("Andres"); } @Test public void returnTwoSubgraphsWithBoundUndirectedRelationship() throws Exception { submitAndGet("CREATE (a:A {value: 1})-[:REL {name: 'r'}]->(b:B {value: 2})"); List<Map<String, Object>> results = submitAndGet( "MATCH (a)-[r {name: 'r'}]-(b)\n" + "RETURN a.value, b.value" ); assertThat(results) .hasSize(2) .extracting("a.value", "b.value") .containsExactlyInAnyOrder( tuple(1L, 2L), tuple(2L, 1L) ); } @Test public void returnChildrenPairsWithoutSelfPairs() throws Exception { submitAndGet( "CREATE (ss:StarSystem {name: 'Sirius'})\n" + "CREATE (s1:Star {name: '<NAME>'})-[:MEMBER_OF]->(ss)\n" + "CREATE (s2:Star {name: '<NAME>'})-[:MEMBER_OF]->(ss)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (s1:Star)-->(:StarSystem {name: 'Sirius'})<--(s2:Star)\n" + "RETURN s1.name, s2.name" ); assertThat(results) .hasSize(2) .extracting("s1.name", "s2.name") .containsExactlyInAnyOrder( tuple("Sirius A", "Sirius B"), tuple("Sirius B", "Sirius A") ); } @Test public void matchInvalidProp() throws Exception { submitAndGet( "CREATE (a {name: 'A'}), (b {name: 'B'}), (c {name: 'C'})\n" + "CREATE (a)-[:KNOWS]->(b)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (a {name: 'A'}), (c {name: 'C'})\n" + "MATCH (a)-->(b)\n" + "RETURN a.name, b.name, c.name" ); assertThat(results) .hasSize(1) .extracting("a.name", "b.name", "c.name") .containsExactly(tuple("A", "B", "C")); } @Test @Category(SkipExtensions.CustomFunctions.class) public void returnExpressionUnrelatedToMatch() throws Exception { submitAndGet("CREATE ()-[:T]->()"); List<Map<String, Object>> results = submitAndGet( "MATCH (n)-[r:T]->()\n" + "RETURN toString(1) AS x" ); assertThat(results) .extracting("x") .containsExactly("1"); } @Test public void selfReferentialNode() throws Exception { submitAndGet("CREATE (n:N {n: 1})-[:R]->(n)"); List<Map<String, Object>> results = submitAndGet( "MATCH (a)-[r]->(a) RETURN a.n" ); assertThat(results) .extracting("a.n") .containsExactly(1L); } @Test public void selfReferentialNodeChained() throws Exception { submitAndGet("CREATE (a:A {n: 1})-[:R]->(b:B {n: 2})-[:R]->(b)"); List<Map<String, Object>> results = submitAndGet( "MATCH (a)-[r1]->(b)-[r2]->(b) RETURN a.n, b.n" ); assertThat(results) .extracting("a.n", "b.n") .containsExactly(tuple(1L, 2L)); } @Test public void selfReferentialNodeInTwoPatterns() throws Exception { submitAndGet("CREATE (a:A {n: 1})-[:R]->(b:B {n: 2})-[:R]->(b)"); List<Map<String, Object>> results = submitAndGet( "MATCH (a)-[r1]->(b), (b)-[r2]->(b) RETURN a.n, b.n" ); assertThat(results) .extracting("a.n", "b.n") .containsExactly(tuple(1L, 2L)); } @Test public void selfReferentialNodeUndirected() throws Exception { submitAndGet( "CREATE " + "(a:A {name: 'a'})-[:R]->(l:Looper {name: 'l'}), " + "(l)-[:LOOP]->(l)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (a)--(b) " + "RETURN a.name, b.name" ); assertThat(results) .extracting("a.name", "b.name") .containsExactlyInAnyOrder( tuple("a", "l"), tuple("l", "a"), tuple("l", "l") ); } @Test public void selfReferentialNodeWithUndirectedSegment() throws Exception { submitAndGet( "CREATE (:A {name: 'a'})-[:T1]->(l:Looper {name: 'l'}), " + "(l)-[:LOOP]->(l), " + "(l)-[:T2]->(:B {name: 'b'})" ); List<Map<String, Object>> results = submitAndGet( "MATCH (a)--(b)--(c) " + "RETURN a.name, b.name, c.name" ); assertThat(results) .extracting("a.name", "b.name", "c.name") .containsExactlyInAnyOrder( tuple("a", "l", "l"), tuple("a", "l", "b"), tuple("l", "l", "a"), tuple("l", "l", "b"), tuple("b", "l", "l"), tuple("b", "l", "a") ); } @Test public void biDirectionalPath() throws Exception { submitAndGet( "CREATE " + "(a:A {name: 'a'}), (b:B {name: 'b'}), " + "(a)-[:R1 {name: 'r1'}]->(b), " + "(b)-[:R2 {name: 'r2'}]->(a)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (a)-[r1]-(b)-[r2]-(c) " + "RETURN a.name, r1.name, b.name, r2.name, c.name" ); assertThat(results) .extracting("a.name", "r1.name", "b.name", "r2.name", "c.name") .containsExactlyInAnyOrder( tuple("a", "r1", "b", "r2", "a"), tuple("a", "r2", "b", "r1", "a"), tuple("b", "r1", "a", "r2", "b"), tuple("b", "r2", "a", "r1", "b") ); } @Test @Category(SkipWithCosmosDB.Truncate4096.class) public void matchAndReverseOptionalMatch() throws Exception { submitAndGet("CREATE (:A {name: 'A'})-[:T {name: 'T'}]->(:B {name: 'B'})"); List<Map<String, Object>> results = submitAndGet( "MATCH (a1)-[r]->() " + "WITH r, a1 " + "OPTIONAL MATCH (a1)<-[r]-(b2) " + "RETURN a1.name, r.name, b2.name" ); assertThat(results) .extracting("a1.name", "r.name", "b2.name") .containsExactly(tuple("A", "T", null)); } @Test public void matchRhsAliases() throws Exception { submitAndGet("CREATE (h1:House {name: 'house1', animal:'cat'}), " + "(h2:House {name: 'house2', animal:'dog'}), " + "(h3:House {name: 'house3', animal:'cat'}), " + "(h4:House {name: 'house4', animal:'cat'}), " + "(h1)-[:KNOWS]->(h2), " + "(h1)-[:KNOWS]->(h3), " + "(h1)-[:KNOWS]->(h4)"); List<Map<String, Object>> results = submitAndGet( "MATCH (n)-[rel]->(x)\n" + "WHERE n.animal = x.animal\n" + "RETURN n.name, x.name" ); assertThat(results) .extracting("n.name", "x.name") .containsExactlyInAnyOrder(tuple("house1", "house3"), tuple("house1", "house4")); } @Test public void stringInequality() { submitAndGet( "CREATE (root:Root {name: 'x'}), " + "(child1:TextNode {prop2: 'text'}), " + "(child2:IntNode {prop2: 0}), " + "(root)-[:T]->(child1), " + "(root)-[:T]->(child2)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (:Root {name: 'x'})-->(i:TextNode) " + "WHERE i.prop2 > 'te' " + "RETURN i.prop2 as prop" ); assertThat(results) .extracting("prop") .containsExactly("text"); } @Test public void optionalMatchOnEmptyGraph() throws Exception { List<Map<String, Object>> results = submitAndGet( "OPTIONAL MATCH (n) " + "RETURN n" ); assertThat(results) .extracting("n") .containsExactly((Object) null); } @Test @Category(SkipWithCosmosDB.Choose.class) public void doubleWithMerge() throws Exception { submitAndGet("CREATE ({id: 0})"); List<Map<String, Object>> results = submitAndGet( "MATCH (n) " + "WITH n AS a, n AS b " + "WITH a AS x " + "MERGE (a) " + "RETURN x.id AS x" ); assertThat(results) .extracting("x") .containsExactly(0L); } @Test public void multipleUndirectedMatches() throws Exception { submitAndGet(TestCommons.DELETE_ALL); submitAndGet( "CREATE (org1:org {name: 'org1'}), " + "(org2:org {name: 'org2'})," + "(p1:person {name: 'foo'})," + "(p2:person {name: 'boo'})," + "(doc:doc {title: 'doc1'})," + "(org1)-[:e]->(p1)," + "(org1)-[:e]->(p2)," + "(org2)-[:e]->(p1)," + "(org2)-[:e]->(p2)," + "(org1)-[:e]->(doc)," + "(org2)-[:e]->(doc)" ); List<Map<String, Object>> results = submitAndGet( "MATCH (org1:org)--(p:person)--(org2:org)\n" + "MATCH (org1:org)--(doc:doc)--(org2:org)\n" + "WHERE org1.name = 'org1' AND id(org1) <> id(org2)\n" + "RETURN p.name AS personName, org2.name AS orgName"); assertThat(results) .extracting("personName", "orgName") .containsExactly( tuple("foo", "org2"), tuple("boo", "org2") ); } }
6,842
310
{ "name": "<NAME> 2 (iOS)", "description": "A two-player strategy game for iOS.", "url": "http://shauninman.com/horrorvacui2/" }
52
1,979
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qihoo.qsql.org.apache.calcite.adapter.druid; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.qihoo.qsql.org.apache.calcite.config.CalciteConnectionConfig; import com.qihoo.qsql.org.apache.calcite.plan.*; import com.qihoo.qsql.org.apache.calcite.rel.RelFieldCollation; import com.qihoo.qsql.org.apache.calcite.rel.RelNode; import com.qihoo.qsql.org.apache.calcite.rel.core.*; import com.qihoo.qsql.org.apache.calcite.rel.logical.LogicalFilter; import com.qihoo.qsql.org.apache.calcite.rel.rules.*; import com.qihoo.qsql.org.apache.calcite.rel.type.RelDataType; import com.qihoo.qsql.org.apache.calcite.rel.type.RelDataTypeFactory; import com.qihoo.qsql.org.apache.calcite.rex.*; import com.qihoo.qsql.org.apache.calcite.runtime.PredicateImpl; import com.qihoo.qsql.org.apache.calcite.sql.SqlKind; import com.qihoo.qsql.org.apache.calcite.sql.fun.SqlStdOperatorTable; import com.qihoo.qsql.org.apache.calcite.sql.type.SqlTypeFamily; import com.qihoo.qsql.org.apache.calcite.sql.type.SqlTypeName; import com.qihoo.qsql.org.apache.calcite.tools.RelBuilder; import com.qihoo.qsql.org.apache.calcite.tools.RelBuilderFactory; import com.qihoo.qsql.org.apache.calcite.util.ImmutableBitSet; import com.qihoo.qsql.org.apache.calcite.util.Pair; import com.qihoo.qsql.org.apache.calcite.util.Util; import com.qihoo.qsql.org.apache.calcite.util.trace.CalciteTrace; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.joda.time.Interval; import org.slf4j.Logger; import java.util.*; /** * Rules and relational operators for {@link DruidQuery}. */ public class DruidRules { private DruidRules() {} protected static final Logger LOGGER = CalciteTrace.getPlannerTracer(); public static final DruidFilterRule FILTER = new DruidFilterRule(RelFactories.LOGICAL_BUILDER); public static final DruidProjectRule PROJECT = new DruidProjectRule(RelFactories.LOGICAL_BUILDER); public static final DruidAggregateRule AGGREGATE = new DruidAggregateRule(RelFactories.LOGICAL_BUILDER); public static final DruidAggregateProjectRule AGGREGATE_PROJECT = new DruidAggregateProjectRule(RelFactories.LOGICAL_BUILDER); public static final DruidSortRule SORT = new DruidSortRule(RelFactories.LOGICAL_BUILDER); public static final DruidSortProjectTransposeRule SORT_PROJECT_TRANSPOSE = new DruidSortProjectTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidProjectSortTransposeRule PROJECT_SORT_TRANSPOSE = new DruidProjectSortTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidProjectFilterTransposeRule PROJECT_FILTER_TRANSPOSE = new DruidProjectFilterTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidFilterProjectTransposeRule FILTER_PROJECT_TRANSPOSE = new DruidFilterProjectTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidAggregateFilterTransposeRule AGGREGATE_FILTER_TRANSPOSE = new DruidAggregateFilterTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidFilterAggregateTransposeRule FILTER_AGGREGATE_TRANSPOSE = new DruidFilterAggregateTransposeRule(RelFactories.LOGICAL_BUILDER); public static final DruidPostAggregationProjectRule POST_AGGREGATION_PROJECT = new DruidPostAggregationProjectRule(RelFactories.LOGICAL_BUILDER); public static final DruidAggregateExtractProjectRule PROJECT_EXTRACT_RULE = new DruidAggregateExtractProjectRule(RelFactories.LOGICAL_BUILDER); public static final List<RelOptRule> RULES = ImmutableList.of(FILTER, PROJECT_FILTER_TRANSPOSE, AGGREGATE_FILTER_TRANSPOSE, AGGREGATE_PROJECT, PROJECT_EXTRACT_RULE, PROJECT, POST_AGGREGATION_PROJECT, AGGREGATE, FILTER_AGGREGATE_TRANSPOSE, FILTER_PROJECT_TRANSPOSE, PROJECT_SORT_TRANSPOSE, SORT, SORT_PROJECT_TRANSPOSE); /** Predicate that returns whether Druid can not handle an aggregate. */ private static final Predicate<Triple<Aggregate, RelNode, DruidQuery>> BAD_AGG = new PredicateImpl<Triple<Aggregate, RelNode, DruidQuery>>() { public boolean test(Triple<Aggregate, RelNode, DruidQuery> triple) { final Aggregate aggregate = triple.getLeft(); final RelNode node = triple.getMiddle(); final DruidQuery query = triple.getRight(); final CalciteConnectionConfig config = query.getConnectionConfig(); for (AggregateCall aggregateCall : aggregate.getAggCallList()) { switch (aggregateCall.getAggregation().getKind()) { case COUNT: // Druid count aggregator can handle 3 scenarios: // 1. count(distinct col) when approximate results // are acceptable and col is not a metric. // Note that exact count(distinct column) is handled // by being rewritten into group by followed by count // 2. count(*) // 3. count(column) if (checkAggregateOnMetric(ImmutableBitSet.of(aggregateCall.getArgList()), node, query)) { return true; } // case count(*) if (aggregateCall.getArgList().isEmpty()) { continue; } // case count(column) if (aggregateCall.getArgList().size() == 1 && !aggregateCall.isDistinct()) { continue; } // case count(distinct and is approximate) if (aggregateCall.isDistinct() && (aggregateCall.isApproximate() || config.approximateDistinctCount())) { continue; } return true; case SUM: case SUM0: case MIN: case MAX: final RelDataType type = aggregateCall.getType(); final SqlTypeName sqlTypeName = type.getSqlTypeName(); if (SqlTypeFamily.APPROXIMATE_NUMERIC.getTypeNames().contains(sqlTypeName) || SqlTypeFamily.INTEGER.getTypeNames().contains(sqlTypeName)) { continue; } else if (SqlTypeFamily.EXACT_NUMERIC.getTypeNames().contains(sqlTypeName)) { // Decimal assert sqlTypeName == SqlTypeName.DECIMAL; if (type.getScale() == 0 || config.approximateDecimal()) { // If scale is zero or we allow approximating decimal, we can proceed continue; } } // Cannot handle this aggregate function return true; default: // Cannot handle this aggregate function return true; } } return false; } }; /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Filter} into a {@link DruidQuery}. */ public static class DruidFilterRule extends RelOptRule { /** * Creates a DruidFilterRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidFilterRule(RelBuilderFactory relBuilderFactory) { super(operand(Filter.class, operand(DruidQuery.class, none())), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final DruidQuery query = call.rel(1); final RelOptCluster cluster = filter.getCluster(); final RelBuilder relBuilder = call.builder(); final RexBuilder rexBuilder = cluster.getRexBuilder(); if (!DruidQuery.isValidSignature(query.signature() + 'f')) { return; } final List<RexNode> validPreds = new ArrayList<>(); final List<RexNode> nonValidPreds = new ArrayList<>(); final RexExecutor executor = Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR); final RelOptPredicateList predicates = call.getMetadataQuery().getPulledUpPredicates(filter.getInput()); final RexSimplify simplify = new RexSimplify(rexBuilder, predicates, true, executor); final RexNode cond = simplify.simplify(filter.getCondition()); for (RexNode e : RelOptUtil.conjunctions(cond)) { if (query.isValidFilter(e)) { validPreds.add(e); } else { nonValidPreds.add(e); } } // Timestamp int timestampFieldIdx = -1; for (int i = 0; i < query.getRowType().getFieldCount(); i++) { if (query.druidTable.timestampFieldName.equals( query.getRowType().getFieldList().get(i).getName())) { timestampFieldIdx = i; break; } } final Triple<List<RexNode>, List<RexNode>, List<RexNode>> triple = splitFilters(rexBuilder, query, validPreds, nonValidPreds, timestampFieldIdx); if (triple.getLeft().isEmpty() && triple.getMiddle().isEmpty()) { // We can't push anything useful to Druid. return; } final List<RexNode> residualPreds = new ArrayList<>(triple.getRight()); List<Interval> intervals = null; if (!triple.getLeft().isEmpty()) { final String timeZone = cluster.getPlanner().getContext() .unwrap(CalciteConnectionConfig.class).timeZone(); assert timeZone != null; intervals = DruidDateTimeUtils.createInterval( RexUtil.composeConjunction(rexBuilder, triple.getLeft(), false), timeZone); if (intervals == null || intervals.isEmpty()) { // Case we have an filter with extract that can not be written as interval push down triple.getMiddle().addAll(triple.getLeft()); } } RelNode newDruidQuery = query; if (!triple.getMiddle().isEmpty()) { final RelNode newFilter = filter.copy(filter.getTraitSet(), Util.last(query.rels), RexUtil.composeConjunction(rexBuilder, triple.getMiddle(), false)); newDruidQuery = DruidQuery.extendQuery(query, newFilter); } if (intervals != null && !intervals.isEmpty()) { newDruidQuery = DruidQuery.extendQuery((DruidQuery) newDruidQuery, intervals); } if (!residualPreds.isEmpty()) { newDruidQuery = relBuilder .push(newDruidQuery) .filter(residualPreds) .build(); } call.transformTo(newDruidQuery); } /** * Given a list of conditions that contain Druid valid operations and * a list that contains those that contain any non-supported operation, * it outputs a triple with three different categories: * 1-l) condition filters on the timestamp column, * 2-m) condition filters that can be pushed to Druid, * 3-r) condition filters that cannot be pushed to Druid. */ private static Triple<List<RexNode>, List<RexNode>, List<RexNode>> splitFilters( final RexBuilder rexBuilder, final DruidQuery input, final List<RexNode> validPreds, final List<RexNode> nonValidPreds, final int timestampFieldIdx) { final List<RexNode> timeRangeNodes = new ArrayList<>(); final List<RexNode> pushableNodes = new ArrayList<>(); final List<RexNode> nonPushableNodes = new ArrayList<>(nonValidPreds); // Number of columns with the dimensions and timestamp for (RexNode conj : validPreds) { final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor(); conj.accept(visitor); if (visitor.inputPosReferenced.contains(timestampFieldIdx)) { if (visitor.inputPosReferenced.size() != 1) { // Complex predicate, transformation currently not supported nonPushableNodes.add(conj); } else { timeRangeNodes.add(conj); } } else { pushableNodes.add(conj); } } return ImmutableTriple.of(timeRangeNodes, pushableNodes, nonPushableNodes); } } /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} into a {@link DruidQuery}. */ public static class DruidProjectRule extends RelOptRule { /** * Creates a DruidProjectRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidProjectRule(RelBuilderFactory relBuilderFactory) { super(operand(Project.class, operand(DruidQuery.class, none())), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Project project = call.rel(0); final DruidQuery query = call.rel(1); final RelOptCluster cluster = project.getCluster(); final RexBuilder rexBuilder = cluster.getRexBuilder(); if (!DruidQuery.isValidSignature(query.signature() + 'p')) { return; } if (canProjectAll(project.getProjects())) { // All expressions can be pushed to Druid in their entirety. final RelNode newProject = project.copy(project.getTraitSet(), ImmutableList.of(Util.last(query.rels))); RelNode newNode = DruidQuery.extendQuery(query, newProject); call.transformTo(newNode); return; } final Pair<List<RexNode>, List<RexNode>> pair = splitProjects(rexBuilder, query, project.getProjects()); if (pair == null) { // We can't push anything useful to Druid. return; } final List<RexNode> above = pair.left; final List<RexNode> below = pair.right; final RelDataTypeFactory.Builder builder = cluster.getTypeFactory().builder(); final RelNode input = Util.last(query.rels); for (RexNode e : below) { final String name; if (e instanceof RexInputRef) { name = input.getRowType().getFieldNames().get(((RexInputRef) e).getIndex()); } else { name = null; } builder.add(name, e.getType()); } final RelNode newProject = project.copy(project.getTraitSet(), input, below, builder.build()); final DruidQuery newQuery = DruidQuery.extendQuery(query, newProject); final RelNode newProject2 = project.copy(project.getTraitSet(), newQuery, above, project.getRowType()); call.transformTo(newProject2); } private static boolean canProjectAll(List<RexNode> nodes) { for (RexNode e : nodes) { if (!(e instanceof RexInputRef)) { return false; } } return true; } private static Pair<List<RexNode>, List<RexNode>> splitProjects(final RexBuilder rexBuilder, final RelNode input, List<RexNode> nodes) { final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor(); for (RexNode node : nodes) { node.accept(visitor); } if (visitor.inputPosReferenced.size() == input.getRowType().getFieldCount()) { // All inputs are referenced return null; } final List<RexNode> belowNodes = new ArrayList<>(); final List<RelDataType> belowTypes = new ArrayList<>(); final List<Integer> positions = Lists.newArrayList(visitor.inputPosReferenced); for (int i : positions) { final RexNode node = rexBuilder.makeInputRef(input, i); belowNodes.add(node); belowTypes.add(node.getType()); } final List<RexNode> aboveNodes = new ArrayList<>(); for (RexNode node : nodes) { aboveNodes.add( node.accept( new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef ref) { final int index = positions.indexOf(ref.getIndex()); return rexBuilder.makeInputRef(belowTypes.get(index), index); } })); } return Pair.of(aboveNodes, belowNodes); } } /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} into a {@link DruidQuery} as a * Post aggregator. */ public static class DruidPostAggregationProjectRule extends RelOptRule { /** * Creates a DruidPostAggregationProjectRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidPostAggregationProjectRule( RelBuilderFactory relBuilderFactory) { super( operand(Project.class, operand(DruidQuery.class, none())), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { Project project = call.rel(0); DruidQuery query = call.rel(1); final RelOptCluster cluster = project.getCluster(); final RexBuilder rexBuilder = cluster.getRexBuilder(); if (!DruidQuery.isValidSignature(query.signature() + 'o')) { return; } Pair<ImmutableMap<String, String>, Boolean> scanned = scanProject(query, project); // Only try to push down Project when there will be Post aggregators in result DruidQuery if (scanned.right) { Pair<Project, Project> splitProjectAggregate = splitProject(rexBuilder, query, project, scanned.left, cluster); Project inner = splitProjectAggregate.left; Project outer = splitProjectAggregate.right; DruidQuery newQuery = DruidQuery.extendQuery(query, inner); // When all project get pushed into DruidQuery, the project can be replaced by DruidQuery. if (outer != null) { Project newProject = outer.copy(outer.getTraitSet(), newQuery, outer.getProjects(), outer.getRowType()); call.transformTo(newProject); } else { call.transformTo(newQuery); } } } /** * Similar to split Project in DruidProjectRule. It used the name mapping from scanProject * to render the correct field names of inner project so that the outer project can correctly * refer to them. For RexNode that can be parsed into post aggregator, they will get pushed in * before input reference, then outer project can simply refer to those pushed in RexNode to * get result. * @param rexBuilder builder from cluster * @param query matched Druid Query * @param project matched project takes in druid * @param nameMap Result nameMapping from scanProject * @param cluster cluster that provide builder for row type. * @return Triple object contains inner project, outer project and required * Json Post Aggregation objects to be pushed down into Druid Query. */ public Pair<Project, Project> splitProject(final RexBuilder rexBuilder, DruidQuery query, Project project, ImmutableMap<String, String> nameMap, final RelOptCluster cluster) { //Visit & Build Inner Project final List<RexNode> innerRex = new ArrayList<>(); final RelDataTypeFactory.Builder typeBuilder = cluster.getTypeFactory().builder(); final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor(); final List<Integer> positions = new ArrayList<>(); final List<RelDataType> innerTypes = new ArrayList<>(); // Similar logic to splitProject in DruidProject Rule // However, post aggregation will also be output of DruidQuery and they will be // added before other input. int offset = 0; for (Pair<RexNode, String> pair : project.getNamedProjects()) { RexNode rex = pair.left; String name = pair.right; String fieldName = nameMap.get(name); if (fieldName == null) { rex.accept(visitor); } else { final RexNode node = rexBuilder.copy(rex); innerRex.add(node); positions.add(offset++); typeBuilder.add(nameMap.get(name), node.getType()); innerTypes.add(node.getType()); } } // Other referred input will be added into the inner project rex list. positions.addAll(visitor.inputPosReferenced); for (int i : visitor.inputPosReferenced) { final RexNode node = rexBuilder.makeInputRef(Util.last(query.rels), i); innerRex.add(node); typeBuilder.add(query.getRowType().getFieldNames().get(i), node.getType()); innerTypes.add(node.getType()); } Project innerProject = project.copy(project.getTraitSet(), Util.last(query.rels), innerRex, typeBuilder.build()); // If the whole project is pushed, we do not need to do anything else. if (project.getNamedProjects().size() == nameMap.size()) { return new Pair<>(innerProject, null); } // Build outer Project when some projects are left in outer project. offset = 0; final List<RexNode> outerRex = new ArrayList<>(); for (Pair<RexNode, String> pair : project.getNamedProjects()) { RexNode rex = pair.left; String name = pair.right; if (!nameMap.containsKey(name)) { outerRex.add( rex.accept( new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef ref) { final int j = positions.indexOf(ref.getIndex()); return rexBuilder.makeInputRef(innerTypes.get(j), j); } })); } else { outerRex.add( rexBuilder.makeInputRef(rex.getType(), positions.indexOf(offset++))); } } Project outerProject = project.copy(project.getTraitSet(), innerProject, outerRex, project.getRowType()); return new Pair<>(innerProject, outerProject); } /** * Scans the project. * * <p>Takes Druid Query as input to figure out which expression can be * pushed down. Also returns a map to show the correct field name in Druid * Query for columns get pushed in. * * @param query matched Druid Query * @param project Matched project that takes in Druid Query * @return Pair that shows how name map with each other. */ public Pair<ImmutableMap<String, String>, Boolean> scanProject( DruidQuery query, Project project) { List<String> aggNamesWithGroup = query.getRowType().getFieldNames(); final ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder(); int j = 0; boolean ret = false; for (Pair<RexNode, String> namedProject : project.getNamedProjects()) { RexNode rex = namedProject.left; String name = namedProject.right; // Find out the corresponding fieldName for DruidQuery to fetch result // in DruidConnectionImpl, give specific name for post aggregator if (rex instanceof RexCall) { if (checkPostAggregatorExist(rex)) { String postAggName = "postagg#" + j++; mapBuilder.put(name, postAggName); ret = true; } } else if (rex instanceof RexInputRef) { String fieldName = aggNamesWithGroup.get(((RexInputRef) rex).getIndex()); mapBuilder.put(name, fieldName); } } return new Pair<>(mapBuilder.build(), ret); } /** * Recursively check whether the rexNode can be parsed into post aggregator in druid query * Have to fulfill conditions below: * 1. Arithmetic operation +, -, /, * or CAST in SQL * 2. Simple input reference refer to the result of Aggregate or Grouping * 3. A constant * 4. All input referred should also be able to be parsed * @param rexNode input RexNode to be recursively checked * @return a boolean shows whether this rexNode can be parsed or not. */ public boolean checkPostAggregatorExist(RexNode rexNode) { if (rexNode instanceof RexCall) { for (RexNode ele : ((RexCall) rexNode).getOperands()) { boolean inputRex = checkPostAggregatorExist(ele); if (!inputRex) { return false; } } switch (rexNode.getKind()) { case PLUS: case MINUS: case DIVIDE: case TIMES: //case CAST: return true; default: return false; } } else if (rexNode instanceof RexInputRef || rexNode instanceof RexLiteral) { // Do not have to check the source of input because the signature checking ensure // the input of project must be Aggregate. return true; } return false; } } /** * Rule to push an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Aggregate} into a {@link DruidQuery}. */ public static class DruidAggregateRule extends RelOptRule { /** * Creates a DruidAggregateRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidAggregateRule(RelBuilderFactory relBuilderFactory) { super(operand(Aggregate.class, operand(DruidQuery.class, none())), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final DruidQuery query = call.rel(1); if (!DruidQuery.isValidSignature(query.signature() + 'a')) { return; } if (aggregate.indicator || aggregate.getGroupSets().size() != 1 || BAD_AGG.apply(ImmutableTriple.of(aggregate, (RelNode) aggregate, query)) || !validAggregate(aggregate, query)) { return; } final RelNode newAggregate = aggregate.copy(aggregate.getTraitSet(), ImmutableList.of(Util.last(query.rels))); call.transformTo(DruidQuery.extendQuery(query, newAggregate)); } /* Check whether agg functions reference timestamp */ private static boolean validAggregate(Aggregate aggregate, DruidQuery query) { ImmutableBitSet.Builder builder = ImmutableBitSet.builder(); for (AggregateCall aggCall : aggregate.getAggCallList()) { builder.addAll(aggCall.getArgList()); } return !checkTimestampRefOnQuery(builder.build(), query.getTopNode(), query); } } /** * Rule to push an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Aggregate} and * {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} into a {@link DruidQuery}. */ public static class DruidAggregateProjectRule extends RelOptRule { /** * Creates a DruidAggregateProjectRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidAggregateProjectRule(RelBuilderFactory relBuilderFactory) { super( operand(Aggregate.class, operand(Project.class, operand(DruidQuery.class, none()))), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final Project project = call.rel(1); final DruidQuery query = call.rel(2); if (!DruidQuery.isValidSignature(query.signature() + 'p' + 'a')) { return; } int timestampIdx = validProject(project, query); List<Integer> filterRefs = getFilterRefs(aggregate.getAggCallList()); if (timestampIdx == -1 && filterRefs.size() == 0) { return; } // Check that the filters that the Aggregate calls refer to are valid filters can be pushed // into Druid for (Integer i : filterRefs) { RexNode filterNode = project.getProjects().get(i); if (!query.isValidFilter(filterNode) || filterNode.isAlwaysFalse()) { return; } } if (aggregate.indicator || aggregate.getGroupSets().size() != 1 || BAD_AGG.apply(ImmutableTriple.of(aggregate, (RelNode) project, query)) || !validAggregate(aggregate, timestampIdx, filterRefs.size())) { return; } final RelNode newProject = project.copy(project.getTraitSet(), ImmutableList.of(Util.last(query.rels))); final RelNode newAggregate = aggregate.copy(aggregate.getTraitSet(), ImmutableList.of(newProject)); final DruidQuery query2; if (filterRefs.size() > 0) { query2 = optimizeFilteredAggregations(call, query, (Project) newProject, (Aggregate) newAggregate); } else { final DruidQuery query1 = DruidQuery.extendQuery(query, newProject); query2 = DruidQuery.extendQuery(query1, newAggregate); } call.transformTo(query2); } /** * Returns an array of unique filter references from * the given list of {@link com.qihoo.qsql.org.apache.calcite.rel.core.AggregateCall} * */ private Set<Integer> getUniqueFilterRefs(List<AggregateCall> calls) { Set<Integer> refs = new HashSet<>(); for (AggregateCall call : calls) { if (call.hasFilter()) { refs.add(call.filterArg); } } return refs; } /** * Attempts to optimize any aggregations with filters in the DruidQuery. * Uses the following steps: * * <ol> * <li>Tries to abstract common filters out into the "filter" field; * <li>Eliminates expressions that are always true or always false when * possible; * <li>ANDs aggregate filters together with the outer filter to allow for * pruning of data. * </ol> * * <p>Should be called before pushing both the aggregate and project into * Druid. Assumes that at least one aggregate call has a filter attached to * it. */ private DruidQuery optimizeFilteredAggregations(RelOptRuleCall call, DruidQuery query, Project project, Aggregate aggregate) { Filter filter = null; final RexBuilder builder = query.getCluster().getRexBuilder(); final RexExecutor executor = Util.first(query.getCluster().getPlanner().getExecutor(), RexUtil.EXECUTOR); final RelNode scan = query.rels.get(0); // first rel is the table scan final RelOptPredicateList predicates = call.getMetadataQuery().getPulledUpPredicates(scan); final RexSimplify simplify = new RexSimplify(builder, predicates, true, executor); // if the druid query originally contained a filter boolean containsFilter = false; for (RelNode node : query.rels) { if (node instanceof Filter) { filter = (Filter) node; containsFilter = true; break; } } // if every aggregate call has a filter arg reference boolean allHaveFilters = allAggregatesHaveFilters(aggregate.getAggCallList()); Set<Integer> uniqueFilterRefs = getUniqueFilterRefs(aggregate.getAggCallList()); // One of the pre-conditions for this method assert uniqueFilterRefs.size() > 0; List<AggregateCall> newCalls = new ArrayList<>(); // OR all the filters so that they can ANDed to the outer filter List<RexNode> disjunctions = new ArrayList<>(); for (Integer i : uniqueFilterRefs) { disjunctions.add(stripFilter(project.getProjects().get(i))); } RexNode filterNode = RexUtil.composeDisjunction(builder, disjunctions); // Erase references to filters for (AggregateCall aggCall : aggregate.getAggCallList()) { int newFilterArg = aggCall.filterArg; if (!aggCall.hasFilter() || (uniqueFilterRefs.size() == 1 && allHaveFilters) // filters get extracted || project.getProjects().get(newFilterArg).isAlwaysTrue()) { newFilterArg = -1; } newCalls.add(aggCall.copy(aggCall.getArgList(), newFilterArg)); } aggregate = aggregate.copy(aggregate.getTraitSet(), aggregate.getInput(), aggregate.indicator, aggregate.getGroupSet(), aggregate.getGroupSets(), newCalls); if (containsFilter) { // AND the current filterNode with the filter node inside filter filterNode = builder.makeCall(SqlStdOperatorTable.AND, filterNode, filter.getCondition()); } // Simplify the filter as much as possible RexNode tempFilterNode = filterNode; filterNode = simplify.simplify(filterNode); // It's possible that after simplification that the expression is now always false. // Druid cannot handle such a filter. // This will happen when the below expression (f_n+1 may not exist): // f_n+1 AND (f_1 OR f_2 OR ... OR f_n) simplifies to be something always false. // f_n+1 cannot be false, since it came from a pushed filter rel node // and each f_i cannot be false, since DruidAggregateProjectRule would have caught that. // So, the only solution is to revert back to the un simplified version and let Druid // handle a filter that is ultimately unsatisfiable. if (filterNode.isAlwaysFalse()) { filterNode = tempFilterNode; } filter = LogicalFilter.create(scan, filterNode); boolean addNewFilter = !filter.getCondition().isAlwaysTrue() && allHaveFilters; // Assumes that Filter nodes are always right after // TableScan nodes (which are always present) int startIndex = containsFilter && addNewFilter ? 2 : 1; List<RelNode> newNodes = constructNewNodes(query.rels, addNewFilter, startIndex, filter, project, aggregate); return DruidQuery.create(query.getCluster(), aggregate.getTraitSet().replace(query.getConvention()), query.getTable(), query.druidTable, newNodes); } // Returns true if and only if every AggregateCall in calls has a filter argument. private static boolean allAggregatesHaveFilters(List<AggregateCall> calls) { for (AggregateCall call : calls) { if (!call.hasFilter()) { return false; } } return true; } /** * Returns a new List of RelNodes in the order of the given order of the oldNodes, * the given {@link Filter}, and any extra nodes. */ private static List<RelNode> constructNewNodes(List<RelNode> oldNodes, boolean addFilter, int startIndex, RelNode filter, RelNode... trailingNodes) { List<RelNode> newNodes = new ArrayList<>(); // The first item should always be the Table scan, so any filter would go after that newNodes.add(oldNodes.get(0)); if (addFilter) { newNodes.add(filter); // This is required so that each RelNode is linked to the one before it if (startIndex < oldNodes.size()) { RelNode next = oldNodes.get(startIndex); newNodes.add(next.copy(next.getTraitSet(), Collections.singletonList(filter))); startIndex++; } } // Add the rest of the nodes from oldNodes for (int i = startIndex; i < oldNodes.size(); i++) { newNodes.add(oldNodes.get(i)); } // Add the trailing nodes (need to link them) for (RelNode node : trailingNodes) { newNodes.add(node.copy(node.getTraitSet(), Collections.singletonList(Util.last(newNodes)))); } return newNodes; } // Removes the IS_TRUE in front of RexCalls, if they exist private static RexNode stripFilter(RexNode node) { if (node.getKind() == SqlKind.IS_TRUE) { return ((RexCall) node).getOperands().get(0); } return node; } private static List<Integer> getFilterRefs(List<AggregateCall> calls) { List<Integer> refs = new ArrayList<>(); for (AggregateCall call : calls) { if (call.hasFilter()) { refs.add(call.filterArg); } } return refs; } /* To be a valid Project, we allow it to contain references, and a single call * to a FLOOR function on the timestamp column OR valid time EXTRACT on the timestamp column. * Returns the reference to the timestamp, if any. */ private static int validProject(Project project, DruidQuery query) { List<RexNode> nodes = project.getProjects(); int idxTimestamp = -1; boolean hasFloor = false; for (int i = 0; i < nodes.size(); i++) { final RexNode e = nodes.get(i); if (e instanceof RexCall) { // It is a call, check that it is EXTRACT and follow-up conditions final RexCall call = (RexCall) e; final String timeZone = query.getCluster().getPlanner().getContext() .unwrap(CalciteConnectionConfig.class).timeZone(); assert timeZone != null; if (DruidDateTimeUtils.extractGranularity(call, timeZone) == null) { return -1; } if (idxTimestamp != -1 && hasFloor) { // Already one usage of timestamp column return -1; } switch (call.getKind()) { case FLOOR: hasFloor = true; if (!(call.getOperands().get(0) instanceof RexInputRef)) { return -1; } final RexInputRef ref = (RexInputRef) call.getOperands().get(0); if (!(checkTimestampRefOnQuery(ImmutableBitSet.of(ref.getIndex()), query.getTopNode(), query))) { return -1; } idxTimestamp = i; break; case EXTRACT: idxTimestamp = RelOptUtil.InputFinder.bits(call).asList().get(0); break; default: throw new AssertionError(); } continue; } if (!(e instanceof RexInputRef)) { // It needs to be a reference return -1; } final RexInputRef ref = (RexInputRef) e; if (checkTimestampRefOnQuery(ImmutableBitSet.of(ref.getIndex()), query.getTopNode(), query)) { if (idxTimestamp != -1) { // Already one usage of timestamp column return -1; } idxTimestamp = i; } } return idxTimestamp; } private static boolean validAggregate(Aggregate aggregate, int idx, int numFilterRefs) { if (numFilterRefs > 0 && idx < 0) { return true; } if (!aggregate.getGroupSet().get(idx)) { return false; } for (AggregateCall aggCall : aggregate.getAggCallList()) { if (aggCall.getArgList().contains(idx)) { return false; } } return true; } } /** * Rule to push an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Sort} through a * {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project}. Useful to transform * to complex Druid queries. */ public static class DruidSortProjectTransposeRule extends SortProjectTransposeRule { /** * Creates a DruidSortProjectTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidSortProjectTransposeRule(RelBuilderFactory relBuilderFactory) { super( operand(Sort.class, operand(Project.class, operand(DruidQuery.class, none()))), relBuilderFactory, null); } } /** * Rule to push back {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} through a * {@link com.qihoo.qsql.org.apache.calcite.rel.core.Sort}. Useful if after pushing Sort, * we could not push it inside DruidQuery. */ public static class DruidProjectSortTransposeRule extends ProjectSortTransposeRule { /** * Creates a DruidProjectSortTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidProjectSortTransposeRule(RelBuilderFactory relBuilderFactory) { super( operand(Project.class, operand(Sort.class, operand(DruidQuery.class, none()))), relBuilderFactory, null); } } /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Sort} * into a {@link DruidQuery}. */ public static class DruidSortRule extends RelOptRule { /** * Creates a DruidSortRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidSortRule(RelBuilderFactory relBuilderFactory) { super(operand(Sort.class, operand(DruidQuery.class, none())), relBuilderFactory, null); } public void onMatch(RelOptRuleCall call) { final Sort sort = call.rel(0); final DruidQuery query = call.rel(1); if (!DruidQuery.isValidSignature(query.signature() + 'l')) { return; } // Either it is: // - a sort and limit on a dimension/metric part of the druid group by query or // - a sort without limit on the time column on top of // Agg operator (transformable to timeseries query), or // - a simple limit on top of other operator than Agg if (!validSortLimit(sort, query)) { return; } final RelNode newSort = sort.copy(sort.getTraitSet(), ImmutableList.of(Util.last(query.rels))); call.transformTo(DruidQuery.extendQuery(query, newSort)); } /** Checks whether sort is valid. */ private static boolean validSortLimit(Sort sort, DruidQuery query) { if (sort.offset != null && RexLiteral.intValue(sort.offset) != 0) { // offset not supported by Druid return false; } // Use a different logic to push down Sort RelNode because the top node could be a Project now RelNode topNode = query.getTopNode(); Aggregate topAgg; if (topNode instanceof Project && ((Project) topNode).getInput() instanceof Aggregate) { topAgg = (Aggregate) ((Project) topNode).getInput(); } else if (topNode instanceof Aggregate) { topAgg = (Aggregate) topNode; } else { // If it is going to be a Druid select operator, we push the limit if // it does not contain a sort specification (required by Druid) return RelOptUtil.isPureLimit(sort); } final ImmutableBitSet.Builder positionsReferenced = ImmutableBitSet.builder(); for (RelFieldCollation col : sort.collation.getFieldCollations()) { int idx = col.getFieldIndex(); if (idx >= topAgg.getGroupCount()) { continue; } //has the indexes of the columns used for sorts positionsReferenced.set(topAgg.getGroupSet().nth(idx)); } // Case it is a timeseries query if (checkIsFlooringTimestampRefOnQuery(topAgg.getGroupSet(), topAgg.getInput(), query) && topAgg.getGroupCount() == 1) { // do not push if it has a limit or more than one sort key or we have sort by // metric/dimension return !RelOptUtil.isLimit(sort) && sort.collation.getFieldCollations().size() == 1 && checkTimestampRefOnQuery(positionsReferenced.build(), topAgg.getInput(), query); } return true; } } /** Returns true if any of the grouping key is a floor operator over the timestamp column. */ private static boolean checkIsFlooringTimestampRefOnQuery(ImmutableBitSet set, RelNode top, DruidQuery query) { if (top instanceof Project) { ImmutableBitSet.Builder newSet = ImmutableBitSet.builder(); final Project project = (Project) top; for (int index : set) { RexNode node = project.getProjects().get(index); if (node instanceof RexCall) { RexCall call = (RexCall) node; final String timeZone = query.getCluster().getPlanner().getContext() .unwrap(CalciteConnectionConfig.class).timeZone(); assert timeZone != null; assert DruidDateTimeUtils.extractGranularity(call, timeZone) != null; if (call.getKind() == SqlKind.FLOOR) { newSet.addAll(RelOptUtil.InputFinder.bits(call)); } } } top = project.getInput(); set = newSet.build(); } // Check if any references the timestamp column for (int index : set) { if (query.druidTable.timestampFieldName.equals( top.getRowType().getFieldNames().get(index))) { return true; } } return false; } /** Checks whether any of the references leads to the timestamp column. */ private static boolean checkTimestampRefOnQuery(ImmutableBitSet set, RelNode top, DruidQuery query) { if (top instanceof Project) { ImmutableBitSet.Builder newSet = ImmutableBitSet.builder(); final Project project = (Project) top; for (int index : set) { RexNode node = project.getProjects().get(index); if (node instanceof RexInputRef) { newSet.set(((RexInputRef) node).getIndex()); } else if (node instanceof RexCall) { RexCall call = (RexCall) node; final String timeZone = query.getCluster().getPlanner().getContext() .unwrap(CalciteConnectionConfig.class).timeZone(); assert timeZone != null; assert DruidDateTimeUtils.extractGranularity(call, timeZone) != null; // when we have extract from time column the rexCall is of the form // "/Reinterpret$0" newSet.addAll(RelOptUtil.InputFinder.bits(call)); } } top = project.getInput(); set = newSet.build(); } // Check if any references the timestamp column for (int index : set) { if (query.druidTable.timestampFieldName.equals( top.getRowType().getFieldNames().get(index))) { return true; } } return false; } /** Checks whether any of the references leads to a metric column. */ private static boolean checkAggregateOnMetric(ImmutableBitSet set, RelNode topProject, DruidQuery query) { if (topProject instanceof Project) { ImmutableBitSet.Builder newSet = ImmutableBitSet.builder(); final Project project = (Project) topProject; for (int index : set) { RexNode node = project.getProjects().get(index); ImmutableBitSet setOfBits = RelOptUtil.InputFinder.bits(node); newSet.addAll(setOfBits); } set = newSet.build(); } for (int index : set) { if (query.druidTable.isMetric(query.getTopNode().getRowType().getFieldNames().get(index))) { return true; } } return false; } /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} * past a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Filter} * when {@code Filter} is on top of a {@link DruidQuery}. */ public static class DruidProjectFilterTransposeRule extends ProjectFilterTransposeRule { /** * Creates a DruidProjectFilterTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidProjectFilterTransposeRule( RelBuilderFactory relBuilderFactory) { super( operand(Project.class, operand(Filter.class, operand(DruidQuery.class, none()))), PushProjector.ExprCondition.FALSE, relBuilderFactory); } } /** * Rule to push a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Filter} * past a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} * when {@code Project} is on top of a {@link DruidQuery}. */ public static class DruidFilterProjectTransposeRule extends FilterProjectTransposeRule { /** * Creates a DruidFilterProjectTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidFilterProjectTransposeRule( RelBuilderFactory relBuilderFactory) { super( operand(Filter.class, operand(Project.class, operand(DruidQuery.class, none()))), true, true, relBuilderFactory); } } /** * Rule to push an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Aggregate} * past a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Filter} * when {@code Filter} is on top of a {@link DruidQuery}. */ public static class DruidAggregateFilterTransposeRule extends AggregateFilterTransposeRule { /** * Creates a DruidAggregateFilterTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidAggregateFilterTransposeRule( RelBuilderFactory relBuilderFactory) { super( operand(Aggregate.class, operand(Filter.class, operand(DruidQuery.class, none()))), relBuilderFactory); } } /** * Rule to push an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Filter} * past an {@link com.qihoo.qsql.org.apache.calcite.rel.core.Aggregate} * when {@code Aggregate} is on top of a {@link DruidQuery}. */ public static class DruidFilterAggregateTransposeRule extends FilterAggregateTransposeRule { /** * Creates a DruidFilterAggregateTransposeRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidFilterAggregateTransposeRule( RelBuilderFactory relBuilderFactory) { super( operand(Filter.class, operand(Aggregate.class, operand(DruidQuery.class, none()))), relBuilderFactory); } } /** * Rule to extract a {@link com.qihoo.qsql.org.apache.calcite.rel.core.Project} from * {@link com.qihoo.qsql.org.apache.calcite.rel.core.Aggregate} on top of * {@link com.qihoo.qsql.org.apache.calcite.adapter.druid.DruidQuery} based on the fields * used in the aggregate. */ public static class DruidAggregateExtractProjectRule extends AggregateExtractProjectRule { /** * Creates a DruidAggregateExtractProjectRule. * * @param relBuilderFactory Builder for relational expressions */ public DruidAggregateExtractProjectRule( RelBuilderFactory relBuilderFactory) { super( operand(Aggregate.class, operand(DruidQuery.class, none())), relBuilderFactory); } } } // End DruidRules.java
20,838
504
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1997. All rights reserved. GEOWORKS CONFIDENTIAL PROJECT: PCGEOS MODULE: swat - ntcurses FILE: attrib.c AUTHOR: <NAME>, Apr 08, 1997 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- dbaumann 4/08/97 Initial version DESCRIPTION: $Id: attrib.c,v 1.1 97/04/18 11:17:03 dbaumann Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /****************************************************************/ /* Character attribute routines of the PCcurses package */ /* */ /****************************************************************/ /* This version of curses is based on ncurses, a curses version */ /* originally written by <NAME> at Cornell University. */ /* I have made substantial changes to make it run on IBM PC's, */ /* and therefore consider myself free make it public domain. */ /* <NAME> (<EMAIL>) */ /****************************************************************/ /* 1.4: Portability improvements: 900114 */ /* 1.3: MSC -W3, Turbo'C' -w -w-pro checkes: 881005 */ /* 1.2: Rcsid[] string for maintenance: 881002 */ /* 1.0: Release: 870515 */ /****************************************************************/ #include <curses.h> #include <curspriv.h> char _curses_attrib_rcsid[] = "@(#)attrib.c v.1.4 - 900114"; /****************************************************************/ /* Wstandout() starts standout mode in window 'win'. */ /****************************************************************/ void wstandout(WINDOW *win) { win->_flags |= _STANDOUT; } /* wstandout */ /****************************************************************/ /* Wstandend() ends standout mode in window 'win'. */ /****************************************************************/ void wstandend(WINDOW *win) { win->_flags &= ~_STANDOUT; } /* wstandend */ /****************************************************************/ /* Standout() starts standout mode in stdscr. */ /****************************************************************/ void standout(void) { wstandout(stdscr); } /* standout */ /****************************************************************/ /* Standend() ends standout mode in stdscr */ /****************************************************************/ void standend(void) { wstandend(stdscr); } /* standend */
737
346
#include "assert.h" int main() { typedef struct { int x, y, z; } A; int i = 1; A a[3]; a[i].x = 1; a[i+1].z = 2; a[i-1].y = 3; assert(a[1].x == 1); assert(a[0].y == 3); assert(a[2].z == 2); return 0; }
128
372
import re import argparse import matplotlib.pyplot as plt import numpy as np def running_mean(x, n): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[n:] - cumsum[:-n]) / float(n) def main(): parser = argparse.ArgumentParser() parser.add_argument('log_files', type=str, nargs='+') parser.add_argument('--plot_sr', default=False, action='store_true') parser.add_argument('--plot_cr', default=False, action='store_true') parser.add_argument('--plot_time', default=False, action='store_true') parser.add_argument('--plot_reward', default=True, action='store_true') parser.add_argument('--plot_train', default=True, action='store_true') parser.add_argument('--plot_val', default=False, action='store_true') parser.add_argument('--window_size', type=int, default=200) args = parser.parse_args() # define the names of the models you want to plot and the longest episodes you want to show models = ['LSTM-RL', 'SARL', 'OM-SARL'] max_episodes = 10000 ax1 = ax2 = ax3 = ax4 = None ax1_legends = [] ax2_legends = [] ax3_legends = [] ax4_legends = [] for i, log_file in enumerate(args.log_files): with open(log_file, 'r') as file: log = file.read() val_pattern = r"VAL in episode (?P<episode>\d+) has success rate: (?P<sr>[0-1].\d+), " \ r"collision rate: (?P<cr>[0-1].\d+), nav time: (?P<time>\d+.\d+), " \ r"total reward: (?P<reward>[-+]?\d+.\d+)" val_episode = [] val_sr = [] val_cr = [] val_time = [] val_reward = [] for r in re.findall(val_pattern, log): val_episode.append(int(r[0])) val_sr.append(float(r[1])) val_cr.append(float(r[2])) val_time.append(float(r[3])) val_reward.append(float(r[4])) train_pattern = r"TRAIN in episode (?P<episode>\d+) has success rate: (?P<sr>[0-1].\d+), " \ r"collision rate: (?P<cr>[0-1].\d+), nav time: (?P<time>\d+.\d+), " \ r"total reward: (?P<reward>[-+]?\d+.\d+)" train_episode = [] train_sr = [] train_cr = [] train_time = [] train_reward = [] for r in re.findall(train_pattern, log): train_episode.append(int(r[0])) train_sr.append(float(r[1])) train_cr.append(float(r[2])) train_time.append(float(r[3])) train_reward.append(float(r[4])) train_episode = train_episode[:max_episodes] train_sr = train_sr[:max_episodes] train_cr = train_cr[:max_episodes] train_time = train_time[:max_episodes] train_reward = train_reward[:max_episodes] # smooth training plot train_sr_smooth = running_mean(train_sr, args.window_size) train_cr_smooth = running_mean(train_cr, args.window_size) train_time_smooth = running_mean(train_time, args.window_size) train_reward_smooth = running_mean(train_reward, args.window_size) # plot sr if args.plot_sr: if ax1 is None: _, ax1 = plt.subplots() if args.plot_train: ax1.plot(range(len(train_sr_smooth)), train_sr_smooth) ax1_legends.append(models[i]) if args.plot_val: ax1.plot(val_episode, val_sr) ax1_legends.append(models[i]) ax1.legend(ax1_legends) ax1.set_xlabel('Episodes') ax1.set_ylabel('Success Rate') ax1.set_title('Success rate') # plot time if args.plot_time: if ax2 is None: _, ax2 = plt.subplots() if args.plot_train: ax2.plot(range(len(train_time_smooth)), train_time_smooth) ax2_legends.append(models[i]) if args.plot_val: ax2.plot(val_episode, val_time) ax2_legends.append(models[i]) ax2.legend(ax2_legends) ax2.set_xlabel('Episodes') ax2.set_ylabel('Time(s)') ax2.set_title("Robot's Time to Reach Goal") # plot cr if args.plot_cr: if ax3 is None: _, ax3 = plt.subplots() if args.plot_train: ax3.plot(range(len(train_cr_smooth)), train_cr_smooth) ax3_legends.append(models[i]) if args.plot_val: ax3.plot(val_episode, val_cr) ax3_legends.append(models[i]) ax3.legend(ax3_legends) ax3.set_xlabel('Episodes') ax3.set_ylabel('Collision Rate') ax3.set_title('Collision Rate') # plot reward if args.plot_reward: if ax4 is None: _, ax4 = plt.subplots() if args.plot_train: ax4.plot(range(len(train_reward_smooth)), train_reward_smooth) ax4_legends.append(models[i]) if args.plot_val: ax4.plot(val_episode, val_reward) ax4_legends.append(models[i]) ax4.legend(ax4_legends) ax4.set_xlabel('Episodes') ax4.set_ylabel('Reward') ax4.set_title('Cumulative Discounted Reward') plt.show() if __name__ == '__main__': main()
2,814
587
// // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) Contributors to the OpenEXR Project. // //----------------------------------------------------------------------------- // // ACES image file I/O. // //----------------------------------------------------------------------------- #include <Iex.h> #include <ImfAcesFile.h> #include <ImfRgbaFile.h> #include <ImfStandardAttributes.h> #include <algorithm> using namespace std; using namespace IMATH_NAMESPACE; using namespace IEX_NAMESPACE; #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER const Chromaticities& acesChromaticities () { static const Chromaticities acesChr ( V2f (0.73470f, 0.26530f), // red V2f (0.00000f, 1.00000f), // green V2f (0.00010f, -0.07700f), // blue V2f (0.32168f, 0.33767f)); // white return acesChr; } class AcesOutputFile::Data { public: Data (); ~Data (); Data (const Data& other) = delete; Data& operator= (const Data& other) = delete; Data (Data&& other) = delete; Data& operator= (Data&& other) = delete; RgbaOutputFile* rgbaFile; }; AcesOutputFile::Data::Data () : rgbaFile (0) { // empty } AcesOutputFile::Data::~Data () { delete rgbaFile; } namespace { void checkCompression (Compression compression) { // // Not all compression methods are allowed in ACES files. // switch (compression) { case NO_COMPRESSION: case PIZ_COMPRESSION: case B44A_COMPRESSION: break; default: throw ArgExc ("Invalid compression type for ACES file."); } } } // namespace AcesOutputFile::AcesOutputFile ( const std::string& name, const Header& header, RgbaChannels rgbaChannels, int numThreads) : _data (new Data) { checkCompression (header.compression ()); Header newHeader = header; addChromaticities (newHeader, acesChromaticities ()); addAdoptedNeutral (newHeader, acesChromaticities ().white); _data->rgbaFile = new RgbaOutputFile (name.c_str (), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile ( OPENEXR_IMF_INTERNAL_NAMESPACE::OStream& os, const Header& header, RgbaChannels rgbaChannels, int numThreads) : _data (new Data) { checkCompression (header.compression ()); Header newHeader = header; addChromaticities (newHeader, acesChromaticities ()); addAdoptedNeutral (newHeader, acesChromaticities ().white); _data->rgbaFile = new RgbaOutputFile (os, header, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile ( const std::string& name, const IMATH_NAMESPACE::Box2i& displayWindow, const IMATH_NAMESPACE::Box2i& dataWindow, RgbaChannels rgbaChannels, float pixelAspectRatio, const IMATH_NAMESPACE::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _data (new Data) { checkCompression (compression); Header newHeader ( displayWindow, dataWindow.isEmpty () ? displayWindow : dataWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); addChromaticities (newHeader, acesChromaticities ()); addAdoptedNeutral (newHeader, acesChromaticities ().white); _data->rgbaFile = new RgbaOutputFile (name.c_str (), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile ( const std::string& name, int width, int height, RgbaChannels rgbaChannels, float pixelAspectRatio, const IMATH_NAMESPACE::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _data (new Data) { checkCompression (compression); Header newHeader ( width, height, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); addChromaticities (newHeader, acesChromaticities ()); addAdoptedNeutral (newHeader, acesChromaticities ().white); _data->rgbaFile = new RgbaOutputFile (name.c_str (), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::~AcesOutputFile () { delete _data; } void AcesOutputFile::setFrameBuffer ( const Rgba* base, size_t xStride, size_t yStride) { _data->rgbaFile->setFrameBuffer (base, xStride, yStride); } void AcesOutputFile::writePixels (int numScanLines) { _data->rgbaFile->writePixels (numScanLines); } int AcesOutputFile::currentScanLine () const { return _data->rgbaFile->currentScanLine (); } const Header& AcesOutputFile::header () const { return _data->rgbaFile->header (); } const IMATH_NAMESPACE::Box2i& AcesOutputFile::displayWindow () const { return _data->rgbaFile->displayWindow (); } const IMATH_NAMESPACE::Box2i& AcesOutputFile::dataWindow () const { return _data->rgbaFile->dataWindow (); } float AcesOutputFile::pixelAspectRatio () const { return _data->rgbaFile->pixelAspectRatio (); } const IMATH_NAMESPACE::V2f AcesOutputFile::screenWindowCenter () const { return _data->rgbaFile->screenWindowCenter (); } float AcesOutputFile::screenWindowWidth () const { return _data->rgbaFile->screenWindowWidth (); } LineOrder AcesOutputFile::lineOrder () const { return _data->rgbaFile->lineOrder (); } Compression AcesOutputFile::compression () const { return _data->rgbaFile->compression (); } RgbaChannels AcesOutputFile::channels () const { return _data->rgbaFile->channels (); } void AcesOutputFile::updatePreviewImage (const PreviewRgba pixels[]) { _data->rgbaFile->updatePreviewImage (pixels); } class AcesInputFile::Data { public: Data (); ~Data (); Data (const Data& other) = delete; Data& operator= (const Data& other) = delete; Data (Data&& other) = delete; Data& operator= (Data&& other) = delete; void initColorConversion (); RgbaInputFile* rgbaFile; Rgba* fbBase; size_t fbXStride; size_t fbYStride; int minX; int maxX; bool mustConvertColor; M44f fileToAces; }; AcesInputFile::Data::Data () : rgbaFile (0) , fbBase (0) , fbXStride (0) , fbYStride (0) , minX (0) , maxX (0) , mustConvertColor (false) { // empty } AcesInputFile::Data::~Data () { delete rgbaFile; } void AcesInputFile::Data::initColorConversion () { const Header& header = rgbaFile->header (); Chromaticities fileChr; if (hasChromaticities (header)) fileChr = chromaticities (header); V2f fileNeutral = fileChr.white; if (hasAdoptedNeutral (header)) { fileNeutral = adoptedNeutral (header); fileChr.white = fileNeutral; // for RGBtoXYZ() purposes. } const Chromaticities acesChr = acesChromaticities (); V2f acesNeutral = acesChr.white; if (fileChr.red == acesChr.red && fileChr.green == acesChr.green && fileChr.blue == acesChr.blue && fileChr.white == acesChr.white) { // // The file already contains ACES data, // color conversion is not necessary. return; } mustConvertColor = true; minX = header.dataWindow ().min.x; maxX = header.dataWindow ().max.x; // // Create a matrix that transforms colors from the // RGB space of the input file into the ACES space // using a color adaptation transform to move the // white point. // // // We'll need the Bradford cone primary matrix and its inverse // static const M44f bradfordCPM ( 0.895100f, -0.750200f, 0.038900f, 0.000000f, 0.266400f, 1.713500f, -0.068500f, 0.000000f, -0.161400f, 0.036700f, 1.029600f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 1.000000f); const static M44f inverseBradfordCPM ( 0.986993f, 0.432305f, -0.008529f, 0.000000f, -0.147054f, 0.518360f, 0.040043f, 0.000000f, 0.159963f, 0.049291f, 0.968487f, 0.000000f, 0.000000f, 0.000000f, 0.000000f, 1.000000f); // // Convert the white points of the two RGB spaces to XYZ // float fx = fileNeutral.x; float fy = fileNeutral.y; V3f fileNeutralXYZ (fx / fy, 1, (1 - fx - fy) / fy); float ax = acesNeutral.x; float ay = acesNeutral.y; V3f acesNeutralXYZ (ax / ay, 1, (1 - ax - ay) / ay); // // Compute the Bradford transformation matrix // V3f ratio ((acesNeutralXYZ * bradfordCPM) / (fileNeutralXYZ * bradfordCPM)); M44f ratioMat ( ratio[0], 0, 0, 0, 0, ratio[1], 0, 0, 0, 0, ratio[2], 0, 0, 0, 0, 1); M44f bradfordTrans = bradfordCPM * ratioMat * inverseBradfordCPM; // // Build a combined file-RGB-to-ACES-RGB conversion matrix // fileToAces = RGBtoXYZ (fileChr, 1) * bradfordTrans * XYZtoRGB (acesChr, 1); } AcesInputFile::AcesInputFile (const std::string& name, int numThreads) : _data (new Data) { _data->rgbaFile = new RgbaInputFile (name.c_str (), numThreads); _data->initColorConversion (); } AcesInputFile::AcesInputFile (IStream& is, int numThreads) : _data (new Data) { _data->rgbaFile = new RgbaInputFile (is, numThreads); _data->initColorConversion (); } AcesInputFile::~AcesInputFile () { delete _data; } void AcesInputFile::setFrameBuffer (Rgba* base, size_t xStride, size_t yStride) { _data->rgbaFile->setFrameBuffer (base, xStride, yStride); _data->fbBase = base; _data->fbXStride = xStride; _data->fbYStride = yStride; } void AcesInputFile::readPixels (int scanLine1, int scanLine2) { // // Copy the pixels from the RgbaInputFile into the frame buffer. // _data->rgbaFile->readPixels (scanLine1, scanLine2); // // If the RGB space of the input file is not the same as the ACES // RGB space, then the pixels in the frame buffer must be transformed // into the ACES RGB space. // if (!_data->mustConvertColor) return; int minY = min (scanLine1, scanLine2); int maxY = max (scanLine1, scanLine2); for (int y = minY; y <= maxY; ++y) { Rgba* base = _data->fbBase + _data->fbXStride * _data->minX + _data->fbYStride * y; for (int x = _data->minX; x <= _data->maxX; ++x) { V3f aces = V3f (base->r, base->g, base->b) * _data->fileToAces; base->r = aces[0]; base->g = aces[1]; base->b = aces[2]; base += _data->fbXStride; } } } void AcesInputFile::readPixels (int scanLine) { readPixels (scanLine, scanLine); } const Header& AcesInputFile::header () const { return _data->rgbaFile->header (); } const IMATH_NAMESPACE::Box2i& AcesInputFile::displayWindow () const { return _data->rgbaFile->displayWindow (); } const IMATH_NAMESPACE::Box2i& AcesInputFile::dataWindow () const { return _data->rgbaFile->dataWindow (); } float AcesInputFile::pixelAspectRatio () const { return _data->rgbaFile->pixelAspectRatio (); } const IMATH_NAMESPACE::V2f AcesInputFile::screenWindowCenter () const { return _data->rgbaFile->screenWindowCenter (); } float AcesInputFile::screenWindowWidth () const { return _data->rgbaFile->screenWindowWidth (); } LineOrder AcesInputFile::lineOrder () const { return _data->rgbaFile->lineOrder (); } Compression AcesInputFile::compression () const { return _data->rgbaFile->compression (); } RgbaChannels AcesInputFile::channels () const { return _data->rgbaFile->channels (); } const char* AcesInputFile::fileName () const { return _data->rgbaFile->fileName (); } bool AcesInputFile::isComplete () const { return _data->rgbaFile->isComplete (); } int AcesInputFile::version () const { return _data->rgbaFile->version (); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
5,615
5,964
<reponame>wenfeifei/miniblink49 /* * 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 "StringConcatenate.h" // This macro is helpful for testing how many intermediate Strings are created while evaluating an // expression containing operator+. #ifndef WTF_STRINGTYPEADAPTER_COPIED_WTF_STRING #define WTF_STRINGTYPEADAPTER_COPIED_WTF_STRING() ((void)0) #endif void WTF::StringTypeAdapter<char*>::writeTo(LChar* destination) { for (unsigned i = 0; i < m_length; ++i) destination[i] = static_cast<LChar>(m_buffer[i]); } void WTF::StringTypeAdapter<char*>::writeTo(UChar* destination) { for (unsigned i = 0; i < m_length; ++i) { unsigned char c = m_buffer[i]; destination[i] = c; } } WTF::StringTypeAdapter<LChar*>::StringTypeAdapter(LChar* buffer) : m_buffer(buffer) , m_length(strlen(reinterpret_cast<char*>(buffer))) { } void WTF::StringTypeAdapter<LChar*>::writeTo(LChar* destination) { memcpy(destination, m_buffer, m_length * sizeof(LChar)); } void WTF::StringTypeAdapter<LChar*>::writeTo(UChar* destination) { StringImpl::copyChars(destination, m_buffer, m_length); } WTF::StringTypeAdapter<const UChar*>::StringTypeAdapter(const UChar* buffer) : m_buffer(buffer) { size_t len = 0; while (m_buffer[len] != UChar(0)) ++len; RELEASE_ASSERT(len <= std::numeric_limits<unsigned>::max()); m_length = len; } void WTF::StringTypeAdapter<const UChar*>::writeTo(UChar* destination) { memcpy(destination, m_buffer, m_length * sizeof(UChar)); } WTF::StringTypeAdapter<const char*>::StringTypeAdapter(const char* buffer) : m_buffer(buffer) , m_length(strlen(buffer)) { } void WTF::StringTypeAdapter<const char*>::writeTo(LChar* destination) { memcpy(destination, m_buffer, static_cast<size_t>(m_length) * sizeof(LChar)); } void WTF::StringTypeAdapter<const char*>::writeTo(UChar* destination) { for (unsigned i = 0; i < m_length; ++i) { unsigned char c = m_buffer[i]; destination[i] = c; } } WTF::StringTypeAdapter<const LChar*>::StringTypeAdapter(const LChar* buffer) : m_buffer(buffer) , m_length(strlen(reinterpret_cast<const char*>(buffer))) { } void WTF::StringTypeAdapter<const LChar*>::writeTo(LChar* destination) { memcpy(destination, m_buffer, static_cast<size_t>(m_length) * sizeof(LChar)); } void WTF::StringTypeAdapter<const LChar*>::writeTo(UChar* destination) { StringImpl::copyChars(destination, m_buffer, m_length); } void WTF::StringTypeAdapter<Vector<char>>::writeTo(LChar* destination) { for (size_t i = 0; i < m_buffer.size(); ++i) destination[i] = static_cast<unsigned char>(m_buffer[i]); } void WTF::StringTypeAdapter<Vector<char>>::writeTo(UChar* destination) { for (size_t i = 0; i < m_buffer.size(); ++i) destination[i] = static_cast<unsigned char>(m_buffer[i]); } void WTF::StringTypeAdapter<Vector<LChar>>::writeTo(LChar* destination) { for (size_t i = 0; i < m_buffer.size(); ++i) destination[i] = m_buffer[i]; } void WTF::StringTypeAdapter<Vector<LChar>>::writeTo(UChar* destination) { for (size_t i = 0; i < m_buffer.size(); ++i) destination[i] = m_buffer[i]; } void WTF::StringTypeAdapter<String>::writeTo(LChar* destination) { unsigned length = m_buffer.length(); ASSERT(is8Bit()); const LChar* data = m_buffer.characters8(); for (unsigned i = 0; i < length; ++i) destination[i] = data[i]; WTF_STRINGTYPEADAPTER_COPIED_WTF_STRING(); } void WTF::StringTypeAdapter<String>::writeTo(UChar* destination) { unsigned length = m_buffer.length(); if (is8Bit()) { const LChar* data = m_buffer.characters8(); for (unsigned i = 0; i < length; ++i) destination[i] = data[i]; } else { const UChar* data = m_buffer.characters16(); for (unsigned i = 0; i < length; ++i) destination[i] = data[i]; } WTF_STRINGTYPEADAPTER_COPIED_WTF_STRING(); }
1,636
3,459
package io.requery.test.model; import io.requery.Column; import io.requery.Entity; import io.requery.Key; /** * Created by mluchi on 03/08/2017. */ @Entity(cacheable = false) public abstract class AbstractChildOneToOneNoCascade { @Key long id; @Column String attribute; }
108
1,883
# Simple script to convert files from the FDDB format into sigsets # Author: <NAME> import os import sys from xml.dom.minidom import Document if len(sys.argv) < 3: print 'Usage: fddbtoSigset.py fddbFileIn xmlSigsetFileOut' sys.exit(-1) inFileName = sys.argv[1] outFileName = sys.argv[2] assert(os.path.exists(inFileName)) ini = open(inFileName) lines = ini.readlines() ini.close() xmlDoc = Document() xmlRoot = xmlDoc.createElement('biometric-signature-set') i = 0 cnt = 0 while True: if not i < len(lines): break cnt += 1 line = lines[i] xmlImg = xmlDoc.createElement('biometric-signature') xmlImg.setAttribute('name','img%05d' % cnt) xmlPres = xmlDoc.createElement('presentation') xmlPres.setAttribute('file-name',line[:-1]) xmlPres.setAttribute('Label','pos') cnt = int(lines[i+1][:-1]) for j in range(cnt): node = xmlDoc.createElement('data:bbox') s = lines[i+2+j][:-1].split() radius = float(s[1]) x = float(s[3]) y = float(s[4]) node.setAttribute('x',str(x - radius)) node.setAttribute('y',str(y - radius)) node.setAttribute('width',str(radius * 2.0)) node.setAttribute('height',str(radius * 2.0)) xmlPres.appendChild(node) xmlImg.appendChild(xmlPres) xmlRoot.appendChild(xmlImg) i += (2 + cnt) out = open(outFileName,'w') print >> out, xmlRoot.toprettyxml() out.close()
619
2,759
<filename>src/yb/util/split.cc // Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/util/split.h" #include "yb/util/status.h" using std::string; namespace yb { namespace util { using yb::Status; using yb::Slice; template<class Out> Status SplitArgsImpl(const Slice& line, Out* out_vector) { out_vector->clear(); // Points to the current position we are looking at. const char* current_position = line.cdata(); // Points to the end. const char* ptr_end = line.cend(); while (current_position != ptr_end) { // Skip blanks. while (current_position != ptr_end && isspace(*current_position)) { current_position++; } if (current_position != ptr_end) { const char* current_token = current_position; int current_token_length = 0; // Get a token. if (*current_position == '"' || *current_position == '\'') { const char quotation = *current_position; current_token++; // Skip the begining quote. current_position++; while (true) { if (current_position == ptr_end) { // Unterminated quotes. out_vector->clear(); return STATUS(Corruption, "Unterminated quotes."); } if (quotation == *current_position) { // Reached the end of the quoted token. // // Closing quote must be followed by a space or nothing at all. current_position++; if (current_position != ptr_end && !isspace(*current_position)) { out_vector->clear(); return STATUS(Corruption, "A closing quote must be followed by a white space " "or end of input"); } break; } current_token_length++; current_position++; } } else { // Token is not begining with quotes. Process until the next space character. while (current_position != ptr_end && !isspace(*current_position)) { if (*current_position == '"' || *current_position == '\'') { out_vector->clear(); return STATUS(Corruption, "A closing quote must be followed by a white space " "or end of input"); } current_token_length++; current_position++; } } // Save the token. Get ready for the next one. out_vector->emplace_back(current_token, current_token_length); } } return Status::OK(); } Status SplitArgs(const Slice& line, std::vector<Slice>* out_vector) { return SplitArgsImpl(line, out_vector); } Status SplitArgs(const Slice& line, boost::container::small_vector_base<Slice>* out_vector) { return SplitArgsImpl(line, out_vector); } } // namespace util } // namespace yb
1,266
2,568
<filename>entries/r/recurly.com.json { "Recurly": { "domain": "recurly.com", "url": "https://www.recurly.com/", "tfa": [ "sms", "custom-software" ], "documentation": "https://docs.recurly.com/docs/two-factor-authentication", "keywords": [ "payments" ] } }
150
12,718
<filename>lib/libc/musl/arch/arm/atomic_arch.h #include "libc.h" #if __ARM_ARCH_4__ || __ARM_ARCH_4T__ || __ARM_ARCH == 4 #define BLX "mov lr,pc\n\tbx" #else #define BLX "blx" #endif extern hidden uintptr_t __a_cas_ptr, __a_barrier_ptr; #if ((__ARM_ARCH_6__ || __ARM_ARCH_6K__ || __ARM_ARCH_6KZ__ || __ARM_ARCH_6ZK__) && !__thumb__) \ || __ARM_ARCH_6T2__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH >= 7 #define a_ll a_ll static inline int a_ll(volatile int *p) { int v; __asm__ __volatile__ ("ldrex %0, %1" : "=r"(v) : "Q"(*p)); return v; } #define a_sc a_sc static inline int a_sc(volatile int *p, int v) { int r; __asm__ __volatile__ ("strex %0,%2,%1" : "=&r"(r), "=Q"(*p) : "r"(v) : "memory"); return !r; } #if __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH >= 7 #define a_barrier a_barrier static inline void a_barrier() { __asm__ __volatile__ ("dmb ish" : : : "memory"); } #endif #define a_pre_llsc a_barrier #define a_post_llsc a_barrier #else #define a_cas a_cas static inline int a_cas(volatile int *p, int t, int s) { for (;;) { register int r0 __asm__("r0") = t; register int r1 __asm__("r1") = s; register volatile int *r2 __asm__("r2") = p; register uintptr_t r3 __asm__("r3") = __a_cas_ptr; int old; __asm__ __volatile__ ( BLX " r3" : "+r"(r0), "+r"(r3) : "r"(r1), "r"(r2) : "memory", "lr", "ip", "cc" ); if (!r0) return t; if ((old=*p)!=t) return old; } } #endif #ifndef a_barrier #define a_barrier a_barrier static inline void a_barrier() { register uintptr_t ip __asm__("ip") = __a_barrier_ptr; __asm__ __volatile__( BLX " ip" : "+r"(ip) : : "memory", "cc", "lr" ); } #endif #define a_crash a_crash static inline void a_crash() { __asm__ __volatile__( #ifndef __thumb__ ".word 0xe7f000f0" #else ".short 0xdeff" #endif : : : "memory"); } #if __ARM_ARCH >= 5 && (!__thumb__ || __thumb2__) #define a_clz_32 a_clz_32 static inline int a_clz_32(uint32_t x) { __asm__ ("clz %0, %1" : "=r"(x) : "r"(x)); return x; } #if __ARM_ARCH_6T2__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH >= 7 #define a_ctz_32 a_ctz_32 static inline int a_ctz_32(uint32_t x) { uint32_t xr; __asm__ ("rbit %0, %1" : "=r"(xr) : "r"(x)); return a_clz_32(xr); } #endif #endif
1,097
1,594
/* * Copyright 2014 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. */ package net.nogotofail; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.text.TextUtils; import android.widget.Toast; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * {@link PreferenceFragment} with advanced/miscellaneous preferences. */ public class AdvancedPreferenceFragment extends PreferenceFragment { private static final Object sInstallationIdLock = new Object(); private static final int MIN_TCP_PORT_NUMBER = 1; private static final int MAX_TCP_PORT_NUMBER = 65535; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.advanced_settings); Preference mitmServerHost = findPreference(getString(R.string.mitm_server_host_pref_key)); mitmServerHost.setSummary(getMitmServerHost(getActivity())); mitmServerHost.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String host = (String) newValue; preference.setSummary(getMitmServerHost(preference.getContext(), host)); return true; } }); Preference mitmServerPort = findPreference(getString(R.string.mitm_server_port_pref_key)); mitmServerPort.setSummary(String.valueOf(getMitmServerPort(getActivity()))); mitmServerPort.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String portString = (String) newValue; if (portString != null) { portString = portString.trim(); } if (!TextUtils.isEmpty(portString)) { // Port is not empty -- alert the user if the port invalid. int port = -1; try { port = Integer.parseInt(portString); } catch (NumberFormatException ignored) {} if ((port < MIN_TCP_PORT_NUMBER) || (port > MAX_TCP_PORT_NUMBER)) { new AlertDialog.Builder(preference.getContext()) .setMessage(R.string.mitm_server_port_invalid_alert) .setPositiveButton(android.R.string.ok, null) .show(); return false; } } preference.setSummary( String.valueOf(getMitmServerPort(preference.getContext(), portString))); return true; } }); Preference revokeMitmServerAuth = findPreference(getString(R.string.mitm_server_revoke_auth_pref_key)); revokeMitmServerAuth.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { new AlertDialog.Builder(preference.getContext()) .setMessage(R.string.mitm_server_revoke_auth_prompt_message) .setPositiveButton( R.string.mitm_server_revoke_auth_prompt_positive_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new PreferencesBackedPinningX509TrustManager(preference.getContext()).clear(); getRouterSocketClient().restart(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } }); final Preference displayInstallationIdPreference = findPreference(getString(R.string.install_id_display_pref_key)); displayInstallationIdPreference.setSummary(getInstallationId(getActivity())); displayInstallationIdPreference.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setPrimaryClip(ClipData.newPlainText( "nogotofail installation ID", getInstallationId(getActivity()))); Toast.makeText( getActivity(), getString(R.string.install_id_copied_to_clipboard_toast), Toast.LENGTH_SHORT).show(); return true; } }); Preference resetInstallationIdPreference = findPreference(getString(R.string.install_id_reset_pref_key)); resetInstallationIdPreference.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { resetInstallationId(getActivity()); displayInstallationIdPreference.setSummary(getInstallationId(getActivity())); getRouterSocketClient().restart(); return true; } }); } public static String getMitmServerHost(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefKey = context.getString(R.string.mitm_server_host_pref_key); String prefValue = preferences.getString(prefKey, null); return getMitmServerHost(context, prefValue); } private static String getMitmServerHost(Context context, String prefValue) { if (prefValue != null) { prefValue = prefValue.trim(); } if (!TextUtils.isEmpty(prefValue)) { return prefValue; } // null or empty -- use default return context.getString(R.string.mitm_server_host_pref_default_value); } public static int getMitmServerPort(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefKey = context.getString(R.string.mitm_server_port_pref_key); String prefValue = preferences.getString(prefKey, null); return getMitmServerPort(context, prefValue); } private static int getMitmServerPort(Context context, String prefValue) { if (prefValue != null) { prefValue = prefValue.trim(); } if (!TextUtils.isEmpty(prefValue)) { try { int port = Integer.parseInt(prefValue); if ((port >= MIN_TCP_PORT_NUMBER) && (port <= MAX_TCP_PORT_NUMBER)) { return port; } } catch (NumberFormatException ignored) {} } // null, empty, doesn't parse, or out of range -- use default. return Integer.parseInt(context.getString(R.string.mitm_server_port_pref_default_value)); } public static String getInstallationId(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefKey = context.getString(R.string.install_id_pref_key); String installationId; synchronized (sInstallationIdLock) { installationId = preferences.getString(prefKey, null); if (installationId == null) { installationId = generateInstallationId(); preferences.edit().putString(prefKey, installationId).apply(); } } return installationId; } private static void resetInstallationId(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefKey = context.getString(R.string.install_id_pref_key); synchronized (sInstallationIdLock) { preferences.edit().putString(prefKey, generateInstallationId()).apply(); } } private static final Set<String> PREF_KEYS_NEEDING_RECONNECT = new HashSet<String>(); public static boolean isReconnectRequiredToApplyPreference(Context context, String key) { if (key == null) { return false; } synchronized (PREF_KEYS_NEEDING_RECONNECT) { if (PREF_KEYS_NEEDING_RECONNECT.isEmpty()) { PREF_KEYS_NEEDING_RECONNECT.add(context.getString(R.string.mitm_server_host_pref_key)); PREF_KEYS_NEEDING_RECONNECT.add(context.getString(R.string.mitm_server_port_pref_key)); PREF_KEYS_NEEDING_RECONNECT.add(context.getString(R.string.install_id_pref_key)); } return PREF_KEYS_NEEDING_RECONNECT.contains(key); } } private static String generateInstallationId() { return UUID.randomUUID().toString(); } private RouterSocketClient getRouterSocketClient() { return ((NoGotoFailApplication) getActivity().getApplication()).getRouterSocketClient(); } }
3,398
5,249
<reponame>KaliberAI/TensorRT from polygraphy.tools.base.tool import *
26
5,169
{ "name": "LCText", "version": "0.0.3", "summary": "文本相关的工具类。", "homepage": "https://github.com/mlcldh/LCText", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "mlcldh": "<EMAIL>" }, "platforms": { "ios": "6.0" }, "source": { "git": "https://github.com/mlcldh/LCText.git", "tag": "0.0.3" }, "source_files": "LCText/**/*.{h,m}", "frameworks": [ "UIKit", "Foundation" ], "requires_arc": true, "static_framework": true, "subspecs": [ { "name": "LabelCategory", "source_files": "LCText/LabelCategory/*.{h,m,mm}", "public_header_files": "LCText/LabelCategory/*.h" }, { "name": "TextDidChange", "source_files": "LCText/TextDidChange/*.{h,m,mm}", "public_header_files": "LCText/TextDidChange/*.h" } ] }
424
303
<reponame>didindinn/database-as-a-service import os REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379') REDIS_HOST = os.getenv('REDIS_HOST', 'localhost') BROKER_URL = os.getenv( 'DBAAS_NOTIFICATION_BROKER_URL', 'redis://{}:{}/0'.format(REDIS_HOST, REDIS_PORT) ) CELERYD_TASK_TIME_LIMIT = 10800 CELERY_TRACK_STARTED = True CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend' CELERYBEAT_MAX_LOOP_INTERVAL = 5 CELERY_TIMEZONE = os.getenv('DJANGO_TIME_ZONE', 'America/Sao_Paulo') CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYD_LOG_FORMAT = ("[%(asctime)s: %(processName)s %(name)s %(levelname)s] " "%(message)s") CELERY_ALWAYS_EAGER = False CELERYD_LOG_COLOR = False CELERYD_PREFETCH_MULTIPLIER = 1
386
5,169
<reponame>ftapp/cocoapods { "name": "YJTableViewFactory", "version": "3.1.0", "summary": "UITableView工厂,可自动填充数据源,填充Cell,缓存高。", "homepage": "https://github.com/937447974/YJTableViewFactory", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "阳君": "<EMAIL>" }, "source": { "git": "https://github.com/937447974/YJTableViewFactory.git", "tag": "v3.1.0" }, "preserve_paths": "Documentation/*.*", "prepare_command": "sh Documentation/docset-installed.sh", "platforms": { "ios": "6.0" }, "frameworks": [ "UIKit", "Foundation" ], "requires_arc": true, "dependencies": { "YJCocoa/CocoaTouchLayer/UIKit/TableView": [ ] } }
360
317
<gh_stars>100-1000 /*! * Copyright (c) 2016 by Contributors * \file MxNetCpp.h * \brief meta include file for mxnet.cpp * \author <NAME>, <NAME> */ #ifndef MXNETCPP_H_ #define MXNETCPP_H_ #include "executor.h" #include "symbol.h" #include "ndarray.h" #include "operator.h" #include "optimizer.h" #include "kvstore.h" #include "op.h" #include "op_suppl.h" #include "io.h" #include "metric.h" #endif // MXNETCPP_H_
187
2,209
import unittest from test import test_support as support from test.test_support import import_module # Skip test if _thread or _tkinter wasn't built or idlelib was deleted. import_module('threading') # imported by idlelib.PyShell, imports _thread tk = import_module('Tkinter') # imports _tkinter idletest = import_module('idlelib.idle_test') # Without test_main present, regrtest.runtest_inner (line1219) calls # unittest.TestLoader().loadTestsFromModule(this_module) which calls # load_tests() if it finds it. (Unittest.main does the same.) load_tests = idletest.load_tests # pre-3.3 regrtest does not support the load_tests protocol. use test_main def test_main(): support.run_unittest(unittest.TestLoader().loadTestsFromModule(idletest)) if __name__ == '__main__': unittest.main(verbosity=2, exit=False)
270
534
package mekanism.client.jei.machine; import com.mojang.blaze3d.matrix.MatrixStack; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import javax.annotation.Nullable; import mekanism.api.chemical.pigment.Pigment; import mekanism.api.chemical.pigment.PigmentStack; import mekanism.api.recipes.PaintingRecipe; import mekanism.client.gui.element.bar.GuiVerticalPowerBar; import mekanism.client.gui.element.gauge.GaugeType; import mekanism.client.gui.element.gauge.GuiGauge; import mekanism.client.gui.element.gauge.GuiPigmentGauge; import mekanism.client.gui.element.progress.ProgressType; import mekanism.client.gui.element.slot.GuiSlot; import mekanism.client.gui.element.slot.SlotType; import mekanism.client.jei.BaseRecipeCategory; import mekanism.client.jei.JEIColorDetails; import mekanism.client.jei.MekanismJEI; import mekanism.common.inventory.container.slot.SlotOverlay; import mekanism.common.registries.MekanismBlocks; import mekanism.common.tile.component.config.DataType; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.gui.ingredient.IGuiIngredient; import mezz.jei.api.gui.ingredient.IGuiIngredientGroup; import mezz.jei.api.gui.ingredient.IGuiItemStackGroup; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.ingredients.IIngredients; public class PaintingRecipeCategory extends BaseRecipeCategory<PaintingRecipe> { //Note: We use a weak hashmap so that when the recipe stops existing either due to disconnecting from the server // or because of a reload, then it can be properly garbage collected, but until then we keep track of the pairing // between the recipe and the ingredient group JEI has so that we can ensure the arrows are the proper color private final Map<PaintingRecipe, IGuiIngredientGroup<PigmentStack>> ingredients = new WeakHashMap<>(); private final PigmentColorDetails colorDetails; private final GuiGauge<?> inputPigment; private final GuiSlot inputSlot; private final GuiSlot output; public PaintingRecipeCategory(IGuiHelper helper) { super(helper, MekanismBlocks.PAINTING_MACHINE, 25, 13, 146, 60); inputSlot = addSlot(SlotType.INPUT, 45, 35); addSlot(SlotType.POWER, 144, 35).with(SlotOverlay.POWER); output = addSlot(SlotType.OUTPUT, 116, 35); addElement(new GuiVerticalPowerBar(this, FULL_BAR, 164, 15)); inputPigment = addElement(GuiPigmentGauge.getDummy(GaugeType.STANDARD.with(DataType.INPUT), this, 25, 13)); addSimpleProgress(ProgressType.LARGE_RIGHT, 64, 39).colored(colorDetails = new PigmentColorDetails()); } @Override public Class<? extends PaintingRecipe> getRecipeClass() { return PaintingRecipe.class; } @Override public void draw(PaintingRecipe recipe, MatrixStack matrixStack, double mouseX, double mouseY) { //Set what the "current" recipe is for our color details, before bothering to draw the arrow IGuiIngredientGroup<PigmentStack> group = ingredients.get(recipe); if (group != null) { colorDetails.ingredient = group.getGuiIngredients().get(0); } super.draw(recipe, matrixStack, mouseX, mouseY); colorDetails.ingredient = null; } @Override public void setIngredients(PaintingRecipe recipe, IIngredients ingredients) { ingredients.setInputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getItemInput().getRepresentations())); ingredients.setOutputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getOutputDefinition())); ingredients.setInputLists(MekanismJEI.TYPE_PIGMENT, Collections.singletonList(recipe.getChemicalInput().getRepresentations())); } @Override public void setRecipe(IRecipeLayout recipeLayout, PaintingRecipe recipe, IIngredients ingredients) { IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); initItem(itemStacks, 0, true, inputSlot, recipe.getItemInput().getRepresentations()); initItem(itemStacks, 1, false, output, recipe.getOutputDefinition()); IGuiIngredientGroup<PigmentStack> pigmentStacks = recipeLayout.getIngredientsGroup(MekanismJEI.TYPE_PIGMENT); initChemical(pigmentStacks, 0, true, inputPigment, recipe.getChemicalInput().getRepresentations()); this.ingredients.put(recipe, pigmentStacks); } private static class PigmentColorDetails extends JEIColorDetails<Pigment, PigmentStack> { @Nullable private IGuiIngredient<PigmentStack> ingredient; private PigmentColorDetails() { super(PigmentStack.EMPTY); } @Override public int getColorFrom() { return getColor(ingredient); } @Override public int getColorTo() { return 0xFFFFFFFF; } } }
1,771
348
{"nom":"Bellegarde-en-Forez","circ":"6ème circonscription","dpt":"Loire","inscrits":1344,"abs":795,"votants":549,"blancs":31,"nuls":14,"exp":504,"res":[{"nuance":"LR","nom":"<NAME>","voix":269},{"nuance":"REM","nom":"<NAME>","voix":235}]}
94