code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// <copyright file="Driver.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet 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. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using System; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace ObserverDesignPatternEventsDelegates { public static class Driver { private static WebDriverWait _browserWait; private static IWebDriver _browser; public static IWebDriver Browser { get { if (_browser == null) { throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method Start."); } return _browser; } private set { _browser = value; } } public static WebDriverWait BrowserWait { get { if (_browserWait == null || _browser == null) { throw new NullReferenceException("The WebDriver browser wait instance was not initialized. You should first call the method Start."); } return _browserWait; } private set { _browserWait = value; } } public static void StartBrowser(BrowserTypes browserType = BrowserTypes.Firefox, int defaultTimeOut = 30) { switch (browserType) { case BrowserTypes.Firefox: Browser = new FirefoxDriver(); break; case BrowserTypes.InternetExplorer: break; case BrowserTypes.Chrome: break; default: break; } BrowserWait = new WebDriverWait(Browser, TimeSpan.FromSeconds(defaultTimeOut)); } public static void StopBrowser() { Browser.Quit(); Browser = null; BrowserWait = null; } } }
angelovstanton/AutomateThePlanet
dotnet/Design-Architecture-Series/ObserverDesignPatternEventsDelegates/Driver.cs
C#
apache-2.0
2,745
// // Copyright (c) 2014 Limit Point Systems, 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. // /// @file /// Implementation for class at2_e2 #include "SheafSystem/at2_e2.impl.h" #include "SheafSystem/abstract_poset_member.impl.h" #include "SheafSystem/assert_contract.h" #include "SheafSystem/at0.h" #include "SheafSystem/at1_space.h" #include "SheafSystem/fiber_bundles_namespace.h" #include "SheafSystem/schema_poset_member.h" #include "SheafSystem/wsv_block.h" using namespace std; using namespace fiber_bundle; // Workaround for MS C++ bug. //============================================================================== // CLASS AT2_E2_LITE //============================================================================== //============================================================================== // AT2_E2 FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::at2_e2_lite:: at2_e2_lite() { // Preconditions: // Body: // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite:: at2_e2_lite(const at2_e2_lite& xother) { // Preconditions: // Body: *this = xother; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const at2_e2_lite& xother) { // Preconditions: // Body: if(this == &xother) return *this; _row_dofs = xother._row_dofs; // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xother[0])); // Exit: return *this; } fiber_bundle::at2_e2_lite:: ~at2_e2_lite() { // Preconditions: // Body: // Postconditions: // Exit: } fiber_bundle::at2_e2_lite:: at2_e2_lite(const row_dofs_type& xrow_dofs) { // Preconditions: // Body: *this = xrow_dofs; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const row_dofs_type& xrow_dofs) { // Preconditions: // Body: _row_dofs = xrow_dofs; // Postconditions: ensure(invariant()); // Exit: return *this; } fiber_bundle::at2_e2_lite:: at2_e2_lite(const matrix_type& xmatrix) { // Preconditions: // Body: *this = xmatrix; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const matrix_type& xmatrix) { // Preconditions: // Body: _row_dofs = reinterpret_cast<const row_dofs_type&>(xmatrix); // Postconditions: ensure(invariant()); // Exit: return *this; } fiber_bundle::at2_e2_lite:: operator at2_e2_lite::matrix_type& () { // Preconditions: // Body: matrix_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator const at2_e2_lite::matrix_type& () const { // Preconditions: // Body: const matrix_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator at2_e2_lite::row_dofs_type& () { // Preconditions: // Body: row_dofs_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator const at2_e2_lite::row_dofs_type& () const { // Preconditions: // Body: const row_dofs_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: at2_e2_lite(const value_type& xy) { // Preconditions: // Body: put_component(xy); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy)); // Exit: } void fiber_bundle::at2_e2_lite:: put_component(value_type xy) { // Preconditions: // Body: put_component(0, xy); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy)); // Exit: } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TENSOR ALGEBRA (TP) FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS int fiber_bundle::at2_e2_lite:: dd() const { // Preconditions: // Body: int result = 2; // Postconditions: ensure(invariant()); ensure(result == 2); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // VECTOR ALGEBRA (VD) FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS const fiber_bundle::tp_lite& fiber_bundle::at2_e2_lite:: tp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_tp_prototype(xp))); // Body: const tp_lite& result = e2_lite::static_tp_prototype(xp); // Postconditions: ensure(postcondition_of(e2_lite::static_tp_prototype(xp))); // Exit: return result; } const fiber_bundle::atp_lite& fiber_bundle::at2_e2_lite:: atp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_atp_prototype(xp))); // Body: const atp_lite& result = e2_lite::static_atp_prototype(xp); // Postconditions: ensure(postcondition_of(e2_lite::static_atp_prototype(xp))); // Exit: return result; } const fiber_bundle::stp_lite& fiber_bundle::at2_e2_lite:: stp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_stp_prototype(xp))); // Body: const stp_lite& result = e2_lite::static_stp_prototype(xp); // Postconditions: ensure(postcondition_of(e2_lite::static_stp_prototype(xp))); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TUPLE FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ABSTRACT POSET MEMBER FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS const std::string& fiber_bundle::at2_e2_lite:: class_name() const { // Preconditions: // Body: const string& result = static_class_name(); // Postconditions: ensure(!result.empty()); // Exit: return result; } const std::string& fiber_bundle::at2_e2_lite:: static_class_name() { // Preconditions: // Body: static const string result("at2_e2_lite"); // Postconditions: ensure(!result.empty()); // Exit: return result; } fiber_bundle::at2_e2_lite* fiber_bundle::at2_e2_lite:: clone() const { at2_e2_lite* result = 0; // Preconditions: // Body: result = new at2_e2_lite(); // Postconditions: ensure(result != 0); ensure(is_same_type(*result)); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ANY FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS bool fiber_bundle::at2_e2_lite:: is_ancestor_of(const any_lite& xother) const { // Preconditions: require(&xother != 0); // Body: // True if other conforms to this. bool result = dynamic_cast<const at2_e2_lite*>(&xother) != 0; // Postconditions: return result; } bool fiber_bundle::at2_e2_lite:: invariant() const { bool result = true; if(invariant_check()) { // Prevent recursive calls to invariant. disable_invariant_check(); // Must satisfy base class invariant. invariance(at2_lite::invariant()); // Invariances for this class: // Finished, turn invariant checking back on. enable_invariant_check(); } // Exit return result; } void* fiber_bundle::at2_e2_lite:: row_dofs() { return &_row_dofs; } const void* fiber_bundle::at2_e2_lite:: row_dofs() const { return &_row_dofs; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // CLASS AT2_E2 //============================================================================== // =========================================================== // HOST FACTORY FACET OF CLASS AT2_E2 // =========================================================== // PUBLIC MEMBER FUNCTIONS const sheaf::poset_path& fiber_bundle::at2_e2:: standard_schema_path() { // Preconditions: // Body: static const poset_path result(standard_schema_poset_name(), "at2_e2_schema"); // Postconditions: // Exit: return result; } void fiber_bundle::at2_e2:: make_standard_schema(namespace_poset& xns) { // Preconditions: require(xns.state_is_read_write_accessible()); require(xns.contains_poset(standard_schema_poset_name())); require(!xns.contains_poset_member(standard_schema_path())); // Body: string lmember_names = "xy DOUBLE false"; schema_poset_member lschema(xns, standard_schema_path().member_name(), at2::standard_schema_path(), lmember_names, false); lschema.detach_from_state(); // Postconditions: ensure(xns.contains_poset_member(standard_schema_path())); // Exit: return; } fiber_bundle::at2_e2::host_type& fiber_bundle::at2_e2:: new_host(namespace_type& xns, const poset_path& xhost_path, const poset_path& xschema_path, const poset_path& xvector_space_path, bool xauto_access) { // cout << endl << "Entering at2_e2::new_host." << endl; // Preconditions: require(xns.state_is_auto_read_write_accessible(xauto_access)); require(!xhost_path.empty()); require(!xns.contains_path(xhost_path, xauto_access)); require(xschema_path.full()); require(xns.path_is_auto_read_accessible(xschema_path, xauto_access)); require(schema_poset_member::conforms_to(xns, xschema_path, standard_schema_path())); require(schema_poset_member::row_dof_ct(xns, xschema_path, xauto_access) == 1); require(xns.path_is_auto_read_accessible(xvector_space_path, xauto_access)); require(xns.contains_poset<vector_space_type::host_type>(xvector_space_path, xauto_access)); require(xns.member_poset(xvector_space_path, xauto_access).schema(xauto_access).conforms_to(vector_space_type::standard_schema_path())); require(xns.member_poset<vector_space_type::host_type>(xvector_space_path, xauto_access).d(xauto_access) == 2); // Body: host_type& result = host_type::new_table(xns, xhost_path, xschema_path, 2, xvector_space_path, xauto_access); // Postconditions: ensure(xns.owns(result, xauto_access)); ensure(result.path(true) == xhost_path); ensure(result.state_is_not_read_accessible()); ensure(result.schema(true).path(xauto_access) == xschema_path); ensure(result.factor_ct(true) == 1); ensure(result.d(true) == 1); ensure(result.scalar_space_path(true) == xns.member_poset<vector_space_type::host_type>(xvector_space_path, xauto_access).scalar_space_path()); ensure(result.p(true) == 2); ensure(result.dd(true) == 2); ensure(result.vector_space_path(true) == xvector_space_path); // Exit: // cout << "Leaving at2_e2::new_host." << endl; return result; } fiber_bundle::at2_e2::host_type& fiber_bundle::at2_e2:: standard_host(namespace_type& xns, const std::string& xsuffix, bool xauto_access) { // cout << endl << "Entering at2_e2::new_host." << endl; // Preconditions: require(xns.state_is_auto_read_write_accessible(xauto_access)); require(xsuffix.empty() || poset_path::is_valid_name(xsuffix)); require(standard_host_is_available<at2_e2>(xns, xsuffix, xauto_access)); require(xns.path_is_auto_read_accessible(standard_schema_path(), xauto_access)); require(xns.path_is_auto_read_available(standard_host_path<vector_space_type>(xsuffix), xauto_access)); // Body: // Create the vector space if necessary. poset_path lvector_space_path = vector_space_type::standard_host(xns, xsuffix, xauto_access).path(true); poset_path lpath(standard_host_path<at2_e2>(xsuffix)); host_type* result_ptr; if(xns.contains_path(lpath, xauto_access)) { result_ptr = &xns.member_poset<host_type>(lpath, xauto_access); } else { result_ptr = &new_host(xns, lpath, standard_schema_path(), lvector_space_path, xauto_access); } host_type& result = *result_ptr; // Postconditions: ensure(xns.owns(result, xauto_access)); ensure(result.path(true) == standard_host_path<at2_e2>(xsuffix)); ensure(result.state_is_not_read_accessible()); ensure(result.schema(true).path(xauto_access) == standard_schema_path()); ensure(result.factor_ct(true) == 1); ensure(result.d(true) == 1); ensure(result.scalar_space_path(true) == standard_host_path<vector_space_type::scalar_type>(xsuffix) ); ensure(result.p(true) == 2); ensure(result.dd(true) == 2); ensure(result.vector_space_path(true) == standard_host_path<vector_space_type>(xsuffix) ); // Exit: // cout << "Leaving at2_e2::new_host." << endl; return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // AT2_E2 FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::at2_e2:: at2_e2() { // Preconditions: // Body: // Postconditions: ensure(invariant()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, pod_index_type xhub_id) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(xhost->contains_member(xhub_id)); // Body: attach_to_state(xhost, xhub_id); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(index() == xhub_id); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, const scoped_index& xid) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(xhost->contains_member(xid)); // Body: attach_to_state(xhost, xid.hub_pod()); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(index() ==~ xid); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, const std::string& xname) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(!xname.empty()); require(xhost->contains_member(xname)); // Body: attach_to_state(xhost, xname); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(name() == xname); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(abstract_poset_member* xother) { // Preconditions: require(xother != 0); // Body: attach_to_state(xother); // Postconditions: ensure(invariant()); ensure(is_attached()); ensure(is_same_state(xother)); } fiber_bundle::at2_e2:: at2_e2(poset_state_handle* xhost, bool xauto_access) { // Preconditions: require(precondition_of(new_jim_state(xhost, 0, false, xauto_access))); // Body: new_jim_state(xhost, 0, false, xauto_access); // Postconditions: ensure(postcondition_of(new_jim_state(xhost, 0, false, xauto_access))); // Exit: return; } fiber_bundle::at2_e2:: at2_e2(poset_state_handle& xhost, const row_dofs_type& xrdt, bool xauto_access) { // Preconditions: require(precondition_of(new_jim_state(&xhost, 0, false, xauto_access))); // Body: new_jim_state(&xhost, 0, false, xauto_access); if(xauto_access) { xhost.get_read_write_access(); } *this = xrdt; if(xauto_access) { xhost.release_access(); } // Postconditions: ensure(postcondition_of(new_jim_state(&xhost, 0, false, xauto_access))); // Exit: return; } fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const row_dofs_type& xrdt) { // Preconditions: require(state_is_read_write_accessible()); // Body: sheaf::row_dofs(*this) = xrdt; // Postconditions: ensure(isunordered_or_equals(component(0), xrdt.components[0])); // Exit: return *this; } /// fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const abstract_poset_member& xother) { // Preconditions: require(is_ancestor_of(&xother)); require(precondition_of(attach_to_state(&xother))); // Body: attach_to_state(&xother); // Postconditions: ensure(postcondition_of(attach_to_state(&xother))); // Exit: return *this; } /// fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const at2_e2& xother) { // Preconditions: require(precondition_of(attach_to_state(&xother))); // Body: attach_to_state(&xother); // Postconditions: ensure(postcondition_of(attach_to_state(&xother))); // Exit: return *this; } fiber_bundle::at2_e2:: ~at2_e2() { // Preconditions: // Body: // Postconditions: // Exit: } const fiber_bundle::at2_e2::volatile_type& fiber_bundle::at2_e2:: lite_prototype() const { // Preconditions: // Body: static const volatile_type result; // Postconditions: // Exit: return result; } /// fiber_bundle::at2_e2::volatile_type* fiber_bundle::at2_e2:: lite_type() const { // Preconditions: // Body: volatile_type* result = new volatile_type(sheaf::row_dofs(*this)); // Postconditions: // Exit: return result; } void fiber_bundle::at2_e2:: put_components(dof_type xy_comp) { // Preconditions: require(state_is_read_write_accessible()); // Body: put_component(0, xy_comp); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy_comp)); // Exit: return; } fiber_bundle::at2_e2:: operator at2_e2::row_dofs_type& () //operator row_dofs_type& () { // Preconditions: // Body: row_dofs_type& result = sheaf::row_dofs(*this); // Postconditions: // Exit: return result; } fiber_bundle::at2_e2:: operator const at2_e2::row_dofs_type& () const //operator const row_dofs_type& () const { // Preconditions: // Body: const row_dofs_type& result = sheaf::row_dofs(*this); // Postconditions: // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // AT2 FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ATP FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TP FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // VD FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TUPLE FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::tp* fiber_bundle::at2_e2:: new_tp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_tp(vector_space(xauto_access), xp))); // Body: tp* result = e2::new_tp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_tp(vector_space(xauto_access), xp))); // Exit: return result; } fiber_bundle::atp* fiber_bundle::at2_e2:: new_atp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_atp(vector_space(xauto_access), xp))); // Body: atp* result = e2::new_atp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_atp(vector_space(xauto_access), xp))); // Exit: return result; } fiber_bundle::stp* fiber_bundle::at2_e2:: new_stp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_stp(vector_space(xauto_access), xp))); // Body: stp* result = e2::new_stp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_stp(vector_space(xauto_access), xp))); // Exit: return result; } //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ABSTRACT POSET MEMBER FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS const std::string& fiber_bundle::at2_e2:: class_name() const { // Preconditions: // Body: const string& result = static_class_name(); // Postconditions: ensure(!result.empty()); // Exit: return result; } const std::string& fiber_bundle::at2_e2:: static_class_name() { // Preconditions: // Body: static const string result("at2_e2"); // Postconditions: ensure(!result.empty()); // Exit: return result; } fiber_bundle::at2_e2* fiber_bundle::at2_e2:: clone() const { // Preconditions: // Body: // Create new handle of the current class. at2_e2* result = new at2_e2(); // Postconditions: ensure(result != 0); ensure(result->invariant()); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ANY FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS bool fiber_bundle::at2_e2:: is_ancestor_of(const any* xother) const { // Preconditions: require(xother != 0); // Body: bool result = dynamic_cast<const at2_e2*>(xother) != 0; // Postconditions: // Exit: return result; } bool fiber_bundle::at2_e2:: invariant() const { bool result = true; // Body: // Must satisfy base class invariant. invariance(at2::invariant()); if(invariant_check()) { // Prevent recursive calls to invariant. disable_invariant_check(); // Must satisfy base class invariant. invariance(at2::invariant()); // Invariances for this class: invariance((state_is_read_accessible() ? dd() == 2 : true)); // Finished, turn invariant checking back on. enable_invariant_check(); } // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // NON-MEMBER FUNCTIONS //============================================================================== #include "SheafSystem/at0.h" void fiber_bundle::atp_algebra:: hook(const e2& x0, const e2& x1, at0& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // The hook operation is essentially a contract, so here we // could call the vd facet contract function here, but we'll // reimplement it for efficiency. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b0 + a1*b1; xresult.put_component(0, lcomp); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: hook(const e2_lite& x0, const e2_lite& x1, at0_lite& xresult) { // Preconditions: // Body: // The hook operation is essentially a contract, so we // could call the vd facet contract function here, but we'll // reimplement it for efficiency. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b0 + a1*b1; xresult.put_component(0, lcomp); // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: hook(const at2_e2& x0, const e2& x1, e2& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // The hook operation is essentially a contract operation // on the first index. In 2d this is pretty simple, // so we implement it explicitly for efficiency. // at2_e2 has just 1 component. vd_value_type a = x0.component(0); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); int lrank = 2; vd_value_type lcomp0 = lrank*(-a*b1); vd_value_type lcomp1 = lrank*( a*b0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: hook(const at2_e2_lite& x0, const e2_lite& x1, e2_lite& xresult) { // Preconditions: // Body: // The hook operation is essentially a contract operation // on the first index. In 2d this is pretty simple, // so we implement it explicitly for efficiency. // at2_e2 has just 1 component. vd_value_type a = x0.component(0); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); int lrank = 2; vd_value_type lcomp0 = lrank*(-a*b1); vd_value_type lcomp1 = lrank*( a*b0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: star(const at2_e2& x0, at0& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } vd_value_type a123 = x0.component(0); xresult.put_component(0, a123); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: star(const at2_e2_lite& x0, at0_lite& xresult) { // Preconditions: // Body: vd_value_type a123 = x0.component(0); xresult.put_component(0, a123); // Postconditions: ensure(xresult.component(0) == x0.component(0)); // Exit: return; } fiber_bundle::at0_lite* fiber_bundle::atp_algebra:: star(const at2_e2_lite& x0) { // Preconditions: require(precondition_of(star(x0, *result))); // Body: at0_lite* result = new at0_lite(); star(x0, *result); // Postconditions: ///@todo Postconditions. ensure(result != 0); ensure(postcondition_of(star(x0, *result))); // Exit: return result; } void fiber_bundle::atp_algebra:: star(const at0& x0, at2_e2& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } vd_value_type lcomp123 = x0.component(0); xresult.put_component(0, lcomp123); define_old_variable(bool old_xresult_is_p_form = xresult.is_p_form(false)); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == old_xresult_is_p_form); // Exit: return; } void fiber_bundle::atp_algebra:: star(const at0_lite& x0, at2_e2_lite& xresult) { // Preconditions: // Body: vd_value_type lcomp123 = x0.component(0); xresult.put_component(0, lcomp123); // Postconditions: ensure(xresult.component(0) == x0.component(0)); // Exit: return; } fiber_bundle::at2_e2_lite* fiber_bundle::atp_algebra:: star(const at0_lite& x0) { // Preconditions: require(precondition_of(star(x0, *result))); // Body: at2_e2_lite* result = new at2_e2_lite(); star(x0, *result); // Postconditions: ///@todo Postconditions. ensure(result != 0); ensure(postcondition_of(star(x0, *result))); // Exit: return result; } void fiber_bundle::atp_algebra:: star(const e2& x0, e2& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } // In 2d the Hodge star operator maps a one-form to a new one-form represented // by orthogonal lines. So here we need to exchange the components and and // change the sign of one of them. We arbitrarily (?) change the sign on // the second component. vd_value_type lcomp0 = x0.component(1); vd_value_type lcomp1 = -x0.component(0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: star(const e2_lite& x0, e2_lite& xresult) { // Preconditions: // Body: // In 2d the Hodge star operator maps a one-form to a new one-form represented by // orthogonal lines. So here we need to exchange the components and and change // the sign of one of them. We arbitrarily (?) change the sign on the second // component. vd_value_type lcomp0 = x0.component(1); vd_value_type lcomp1 = -x0.component(0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Postconditions: ///@todo Postconditions. //ensure(); // Exit: return; } fiber_bundle::e2_lite* fiber_bundle::atp_algebra:: star(const e2_lite& x0) { // Preconditions: // Body: e2_lite* result = new e2_lite(); star(x0, *result); // Postconditions: ensure(result != 0); // Exit: return result; } void fiber_bundle::atp_algebra:: wedge(const e2& x0, const e2& x1, at2_e2& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // Access via virtual component required since // some descendants may not store components. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b1 - a1*b0; xresult.put_component(0, lcomp); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: wedge(const e2_lite& x0, const e2_lite& x1, at2_e2_lite& xresult) { // Preconditions: require(x0.is_same_type(x1)); require(x0.dd() == xresult.dd()); // Body: // Access via virtual component required since // some descendants may not store components. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b1 - a1*b0; xresult.put_component(0, lcomp); // Postconditions: ///@todo Postconditions. //ensure(); // Exit: return; }
LimitPointSystems/SheafSystem
fiber_bundles/fiber_spaces/at2_e2.cc
C++
apache-2.0
34,402
#!/usr/bin/env python3 # # Copyright (c) 2015-2017 Nest Labs, 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. # # # @file # A Happy command line utility that tests Weave Ping among Weave nodes. # # The command is executed by instantiating and running WeavePing class. # from __future__ import absolute_import from __future__ import print_function import getopt import sys import set_test_path from happy.Utils import * import WeavePing if __name__ == "__main__": options = WeavePing.option() try: opts, args = getopt.getopt(sys.argv[1:], "ho:s:c:tuwqp:i:a:e:n:CE:T:", ["help", "origin=", "server=", "count=", "tcp", "udp", "wrmp", "interval=", "quiet", "tap=", "case", "case_cert_path=", "case_key_path="]) except getopt.GetoptError as err: print(WeavePing.WeavePing.__doc__) print(hred(str(err))) sys.exit(hred("%s: Failed server parse arguments." % (__file__))) for o, a in opts: if o in ("-h", "--help"): print(WeavePing.WeavePing.__doc__) sys.exit(0) elif o in ("-q", "--quiet"): options["quiet"] = True elif o in ("-t", "--tcp"): options["tcp"] = True elif o in ("-u", "--udp"): options["udp"] = True elif o in ("-w", "--wrmp"): options["wrmp"] = True elif o in ("-o", "--origin"): options["client"] = a elif o in ("-s", "--server"): options["server"] = a elif o in ("-c", "--count"): options["count"] = a elif o in ("-i", "--interval"): options["interval"] = a elif o in ("-p", "--tap"): options["tap"] = a elif o in ("-C", "--case"): options["case"] = True elif o in ("-E", "--case_cert_path"): options["case_cert_path"] = a elif o in ("-T", "--case_key_path"): options["case_key_path"] = a else: assert False, "unhandled option" if len(args) == 1: options["origin"] = args[0] if len(args) == 2: options["client"] = args[0] options["server"] = args[1] cmd = WeavePing.WeavePing(options) cmd.start()
openweave/openweave-core
src/test-apps/happy/bin/weave-ping.py
Python
apache-2.0
2,876
package com.neko.androidexamples.recycler_view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.neko.androidexamples.R; import com.neko.androidexamples.list_view.Model; import java.util.ArrayList; /** * This class shows how to implement a List with RecyclerView and CardView components * These dependencies must be added in App build.gradle : * - 'com.android.support:recyclerview-v7:26.+' * - 'com.android.support:cardview-v7:26.+' * * @link https://developer.android.com/training/material/lists-cards.html */ public class RecyclerViewActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private RecyclerView.Adapter adapter; private RecyclerView.LayoutManager mLayoutManager; private ArrayList<Model> dataToBePopulated; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); dataToBePopulated = getDummyData(); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); // specify an adapter (see also next example) adapter = new RecyclerViewAdapter(dataToBePopulated, onDeleteButtonClickedListener); mRecyclerView.setAdapter(adapter); } /** * Callback for Delete Button * @see RecyclerViewAdapter */ RecyclerViewAdapter.OnDeleteButtonClickedListener onDeleteButtonClickedListener = new RecyclerViewAdapter.OnDeleteButtonClickedListener() { @Override public void onDeleteClicked(int position) { removeItem(position); } }; /** * Removes item at current position * * @param position */ private void removeItem(int position) { // Removing current item dataToBePopulated.remove(position); //adapter.notifyDataSetChanged(); // it doesn't show animation // Notifying with animation adapter.notifyItemRemoved(position); } /** * Adds new Item to the list */ private void addNewItem() { dataToBePopulated.add(new Model( R.mipmap.ic_launcher_round, "New Name", "New Description")); //adapter.notifyDataSetChanged(); // it doesn't show animation // Notifying with animation adapter.notifyItemInserted(dataToBePopulated.size()); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_view_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.action_add: addNewItem(); return true; default: return super.onOptionsItemSelected(item); } } /** * Retrieve dummy data to be populated into ListView * * @return List of Models */ private ArrayList<Model> getDummyData() { ArrayList<Model> dummyModels = new ArrayList<>(); for (int i = 0; i < 3; i++) { dummyModels.add(new Model( R.mipmap.ic_launcher_round, "Name: " + i, "Description: " + i)); } return dummyModels; } }
kerveros/Android-examples
app/src/main/java/com/neko/androidexamples/recycler_view/RecyclerViewActivity.java
Java
apache-2.0
3,893
var a00278 = [ [ "c_blob_comparator", "a00278.html#adf90dfe481e3980859ab92739b51caa6", null ] ];
stweil/tesseract-ocr.github.io
4.00.00dev/a00278.js
JavaScript
apache-2.0
100
'use strict'; var auth = require('../middleware/auth'); var express = require('express'); var router = express.Router(); var achievements = require('../common/achievements'); var User = require('../models').users; var Action = require('../models').actions; var Log = require('../models').logs; /** * @api {get} /user/action Get user's action list * @apiGroup User Action * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \ * http://localhost:3000/api/user/action * * @apiSuccessExample {json} Success-Response: * { * "pending": {}, * "inProgress": { * "55b230d69a8c96f177154fa1": { * "_id": "55b230d69a8c96f177154fa1", * "name": "Disable standby", * "description": "Turn off and unplug standby power of TV, stereo, computer, etc.", * "effort": 2, * "impact": 2, * "category": null, * "startedDate": "2015-08-11T10:31:39.934Z" * }, * "55b230d69a8c96f177154fa2": { * "startedDate": "2015-08-11T10:43:33.485Z", * "impact": 3, * "effort": 4, * "description": "Find and seal up leaks", * "name": "Leaks", * "_id": "55b230d69a8c96f177154fa2" * } * }, * "done": {}, * "declined": {}, * "na": {} * } */ router.get('/', auth.authenticate(), function(req, res) { res.json(req.user.actions); Log.create({ userId: req.user._id, category: 'User Action', type: 'get', data: {} }); }); /** * @api {get} /user/action/suggested Get list of suggested user actions * @apiGroup User Action * @apiDescription Returns top three most recent actions that the user has not tried * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \ * http://localhost:3000/api/user/action/suggested * * @apiSuccessExample {json} Success-Response: * [ * { * "__v": 0, * "_id": "555f0163688305b57c7cef6c", * "description": "Disabling standby can save up to 10% in total electricity costs.", * "effort": 2, * "impact": 2, * "name": "Disable standby on your devices", * "ratings": [] * }, * { * ... * } * ] * * @apiVersion 1.0.0 */ router.get('/suggested', auth.authenticate(), function(req, res) { Action.getSuggested(req.user, res.successRes); Log.create({ userId: req.user._id, category: 'User Action', type: 'getSuggested', data: res.successRes }); }); /** * @api {post} /user/action/:actionId Change state for user action * @apiGroup User Action * @apiDescription Used to start/stop actions for a user. * * @apiParam {String} actionId Action's MongoId * @apiParam {String} state Can be one of: 'pending', 'inProgress', 'alreadyDoing', * 'done', 'canceled', 'declined', 'na'. * @apiParam {Date} postponed Must be provided if state is 'pending'. Specifies * at which time the user will be reminded of the action again. * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X POST -H "Authorization: Bearer $API_TOKEN" -H "Content-Type: application/json" -d \ * '{ * "state": "inProgress" * }' \ * http://localhost:3000/api/user/action/55b230d69a8c96f177154fa1 * * @apiSuccessExample {json} Success-Response: * { * "pending": {}, * "inProgress": { * "55b230d69a8c96f177154fa1": { * "_id": "55b230d69a8c96f177154fa1", * "name": "Disable standby", * "description": "Turn off and unplug standby power of TV, stereo, computer, etc.", * "effort": 2, * "impact": 2, * "category": null, * "startedDate": "2015-08-11T10:31:39.934Z" * }, * "55b230d69a8c96f177154fa2": { * "startedDate": "2015-08-11T10:43:33.485Z", * "impact": 3, * "effort": 4, * "description": "Find and seal up leaks", * "name": "Leaks", * "_id": "55b230d69a8c96f177154fa2" * } * }, * "done": {}, * "declined": {}, * "na": {} * } */ router.post('/:actionId', auth.authenticate(), function(req, res) { User.setActionState(req.user, req.params.actionId, req.body.state, req.body.postponed, function(err, user) { if (!err) { achievements.updateAchievement(req.user, 'actionsDone', function(oldVal) { // make sure we never decerase the action count return Math.max(oldVal, user.actions ? user.actions.done.length : 0); }); } res.successRes(err, user); }); Log.create({ userId: req.user._id, category: 'User Action', type: 'update', data: req.body }); }); module.exports = router;
CIVIS-project/YouPower
backend/routes/userAction.js
JavaScript
apache-2.0
4,813
using System; using System.Linq; using JetBrains.Application.changes; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.ProjectModel.Tasks; using JetBrains.ReSharper.Plugins.Json.Psi; using JetBrains.ReSharper.Plugins.Json.Psi.Tree; using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Paths; using JetBrains.ReSharper.Psi.Transactions; using JetBrains.ReSharper.Psi.Util; using JetBrains.Util; using JetBrains.Util.dataStructures; using ProjectExtensions = JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel.ProjectExtensions; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Modules { // Listen for a module reference being added or removed, and update the source module's .asmdef file, if possible. // * The source module is the module that is being added to or removed from. It will always be a project, and it // should have an asmdef file. All generated projects will have an asmdef file apart from the predefined // Assembly-CSharp* projects, which are at the root of the dependency tree. These predefined projects // automatically reference any asmdef project that has "autoReferenced" set to true. // * The target module is the module being added or removed. It will most likely/hopefully be an asmdef project, but // could also be a predefined project (which will be an incorrect add/remove) or a plain DLL, split into external, // plugin, system or engine DLLs. // * If we're adding/removing an asmdef project, update the "references" node in the source asmdef, or set // "autoReferenced" true if source is a predefined project (notification?) // * Adding/removing a predefined project is not supported // * If we're adding/removing an engine DLL (UnityEngine* or UnityEditor*), set "noEngineReferences" to true/false // * A plugin DLL is a DLL that lives inside Assets or a package. By default, they're automatically referenced. If // "overrideReferences" is true, the plugins need to be listed manually // * Adding/removing a system DLL (System* or Microsoft*) is not supported // * Any other DLL is external and is not supported // // * ReSharper will only add a valid module, so we won't get circular references // * If we have Player projects and use Alt+Enter to add a reference from a QF, the reference is only added to the // current project context. We could update the other context's project? [SolutionComponent] public class AsmDefModuleReferenceChangeListener : IChangeProvider { private readonly UnitySolutionTracker myUnitySolutionTracker; private readonly ChangeManager myChangeManager; private readonly AsmDefCache myAsmDefCache; private readonly MetaFileGuidCache myMetaFileGuidCache; private readonly IPsiServices myPsiServices; private readonly ILogger myLogger; public AsmDefModuleReferenceChangeListener(Lifetime lifetime, ISolution solution, UnitySolutionTracker unitySolutionTracker, ChangeManager changeManager, AsmDefCache asmDefCache, MetaFileGuidCache metaFileGuidCache, ISolutionLoadTasksScheduler solutionLoadTasksScheduler, IPsiServices psiServices, ILogger logger) { myUnitySolutionTracker = unitySolutionTracker; myChangeManager = changeManager; myAsmDefCache = asmDefCache; myMetaFileGuidCache = metaFileGuidCache; myPsiServices = psiServices; myLogger = logger; solutionLoadTasksScheduler.EnqueueTask(new SolutionLoadTask("RegisterAsmDefReferenceChangeListener", SolutionLoadTaskKinds.Done, () => { changeManager.RegisterChangeProvider(lifetime, this); changeManager.AddDependency(lifetime, this, solution); })); } public object? Execute(IChangeMap changeMap) { if (!myUnitySolutionTracker.IsUnityProject.Value) return null; var changes = changeMap.GetChanges<SolutionChange>().ToList(); if (changes.IsEmpty()) return null; var collector = new ReferenceChangeCollector(); foreach (var solutionChange in changes) solutionChange.Accept(collector); collector.RemoveProblematicChangeEvents(); // We can't make changes to the PSI while we're in a change notification if (!collector.AddedReferences.IsEmpty || !collector.RemovedReferences.IsEmpty) myChangeManager.ExecuteAfterChange(() => HandleReferenceChanges(collector)); return null; } private void HandleReferenceChanges(ReferenceChangeCollector collector) { // TODO: Handle multiple add/removes foreach (var addedReference in collector.AddedReferences) { // Note that an asmdef name will usually match the name of the project being added. The only exception // is for player projects. The returned addedAsmDefName here is the asmdef name/non-player project name var ownerProject = addedReference.OwnerModule; var addedReferenceName = addedReference.Name; var (_, ownerAsmDefLocation) = GetAsmDefLocationForProject(ownerProject.Name); var (addedAsmDefName, addedAsmDefLocation) = GetAsmDefLocationForProject(addedReferenceName); switch (addedReference) { case IProjectToProjectReference: OnAddedProjectReference(ownerProject, addedReferenceName, addedAsmDefName, ownerAsmDefLocation, addedAsmDefLocation); break; case IProjectToAssemblyReference: OnAddedAssemblyReference(ownerProject, addedReferenceName, ownerAsmDefLocation); break; default: var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); if (ownerProjectKind != ProjectKind.Custom) { // This is an unexpected reference modification (COM? SDK? Unresolved assembly?) to either // a predefined or asmdef project. This change will be lost when Unity next regenerates myLogger.Warn("Unsupported reference modification: {0}", addedReference); // TODO: Notify the user that a weird/unsupported reference modification has happened } break; } } foreach (var removedReference in collector.RemovedReferences) { var ownerProject = removedReference.OwnerModule; var removedReferenceName = removedReference.Name; var (_, ownerAsmDefLocation) = GetAsmDefLocationForProject(ownerProject.Name); var (removedAsmDefName, removedAsmDefLocation) = GetAsmDefLocationForProject(removedReferenceName); switch (removedReference) { case IProjectToProjectReference: OnRemovedProjectReference(ownerProject, removedReferenceName, removedAsmDefName, ownerAsmDefLocation, removedAsmDefLocation); break; case IProjectToAssemblyReference: OnRemovedAssemblyReference(ownerProject, removedReferenceName, ownerAsmDefLocation); break; default: var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); if (ownerProjectKind != ProjectKind.Custom) { // This is an unexpected reference modification (COM? SDK? Unresolved assembly?) to either // a predefined or asmdef project. This change will be lost when Unity next regenerates myLogger.Warn("Unsupported reference modification: {0}", removedReference); // TODO: Notify the user that a weird/unsupported reference modification has happened } break; } } } private void OnAddedProjectReference(IProject ownerProject, string addedProjectName, string addedAsmDefName, VirtualFileSystemPath ownerAsmDefLocation, VirtualFileSystemPath addedAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); var addedProjectKind = GetProjectKind(addedProjectName, addedAsmDefLocation); if (ownerProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is modifying a custom project. Do nothing - Unity won't regenerate the // project that's being modified, so there will be no data loss, so there's no need to notify the user. // Unity will regenerate teh solution, which will remove the custom project. If we want to notify the // user, it would be better to notify them when initially adding the custom project. myLogger.Info("{0} project {1} added as a reference to {2} project {3}. Ignoring change", addedProjectKind, addedProjectName, ownerProjectKind, ownerProject.Name); return; } if (addedProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is trying to modify a generated project by adding a reference to a // custom project. Changes will be lost the next time Unity regenerates the projects myLogger.Warn( "Unsupported reference modification. Added reference to unknown project will be lost when Unity regenerates projects"); // TODO: Notify user that modifying a generated project will lose changes return; } if (addedProjectKind == ProjectKind.Predefined) { // Weird scenario, shouldn't happen myLogger.Warn("Adding {0} project {1} as a reference to {2} project {3}?! Weird!", addedProjectKind, addedProjectName, ownerProjectKind, ownerProject.Name); return; } switch (ownerProjectKind, addedProjectKind) { case (ProjectKind.AsmDef, ProjectKind.AsmDef): AddAsmDefReference(ownerProject, ownerAsmDefLocation, addedAsmDefName, addedAsmDefLocation); break; case (ProjectKind.Predefined, ProjectKind.AsmDef): // Predefined projects reference all asmdef projects by default. An asmdef can opt out by setting // "autoReferenced" to false. myLogger.Info( "Adding asmdef reference to predefined project. Should already be referenced. Check 'autoReferenced' value in asmdef"); // TODO: Set "autoReferenced" to true break; } } private void AddAsmDefReference(IProject ownerProject, VirtualFileSystemPath ownerAsmDefLocation, string addedAsmDefName, VirtualFileSystemPath addedAsmDefLocation) { var sourceFile = ownerProject.GetPsiSourceFileInProject(ownerAsmDefLocation); if (sourceFile?.GetDominantPsiFile<JsonNewLanguage>() is not IJsonNewFile psiFile) return; var rootObject = psiFile.GetRootObject(); if (rootObject == null) return; var guid = myMetaFileGuidCache.GetAssetGuid(addedAsmDefLocation); if (guid == null) myLogger.Warn("Cannot find asset GUID for added asmdef {0}! Can only add as name", addedAsmDefLocation); var addedAsmDefGuid = guid == null ? null : AsmDefUtils.FormatGuidReference(guid.Value); var referencesProperty = rootObject.GetFirstPropertyValue<IJsonNewArray>("references"); var existingArrayElement = FindReferenceElement(referencesProperty, addedAsmDefName, addedAsmDefGuid, out var useGuids); if (existingArrayElement.Count != 0) { myLogger.Verbose("Reference {0} already exists in asmdef {1}", addedAsmDefName, ownerAsmDefLocation); return; } using (new PsiTransactionCookie(myPsiServices, DefaultAction.Commit, "AddAsmDefReference")) { var referenceText = useGuids && addedAsmDefGuid != null ? addedAsmDefGuid : addedAsmDefName; var elementFactory = JsonNewElementFactory.GetInstance(psiFile.GetPsiModule()); if (referencesProperty == null) { referencesProperty = (IJsonNewArray)elementFactory.CreateValue($"[ \"{referenceText}\" ]"); rootObject.AddMemberBefore("references", referencesProperty, null); } else { var reference = elementFactory.CreateStringLiteral(referenceText); referencesProperty.AddArrayElementBefore(reference, null); } } } private void OnAddedAssemblyReference(IProject ownerProject, string addedAssemblyName, VirtualFileSystemPath ownerAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); switch (ownerProjectKind) { case ProjectKind.Custom: // Don't care. The user has added a custom project, and has added a reference to it. The project // will be removed the next time Unity regenerates the solution, but they won't lose the changes to // the project. We don't notify about this action - it would be better to notify when the project is // initially added myLogger.Info("Adding assembly {0} to custom project {1}. Ignoring change", addedAssemblyName, ownerProject.Name); return; case ProjectKind.Predefined: // Unsupported scenario. Custom assemblies should live in Assets and requires regenerating the // project file myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); // TODO: Notify the user return; case ProjectKind.AsmDef: // AsmDef can only reference custom assemblies if that assembly is a plugin (i.e. it's an asset, // either in Assets or a package). By default, all asmdef projects will reference all plugin // assemblies. An asmdef can opt out by setting "overrideReferences" to true and listing each // plugin individually. // This is a complex scenario: // 1. Check addedAssembly is a plugin // 2. If not, notify user that this is not supported // 3. If true, check "overrideReferences" (if false, this is a weird scenario) // 4. If true, add assembly name to "precompiledReferences" // It might be easier to notify the user to edit assembly references using Unity // TODO: All of the above ^^ myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); break; } } private void OnRemovedProjectReference(IProject ownerProject, string removedProjectName, string removedAsmDefName, VirtualFileSystemPath ownerAsmDefLocation, VirtualFileSystemPath removedAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); var removedProjectKind = GetProjectKind(removedProjectName, removedAsmDefLocation); if (ownerProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is modifying a custom project. Do nothing - Unity won't regenerate the // project that's being modified, so there will be no data loss, so there's no need to notify the user. // Unity will regenerate teh solution, which will remove the custom project. If we want to notify the // user, it's best to notify them when initially adding the custom project. myLogger.Info("{0} project {1} removed as a reference from {2} project {3}. Ignoring change", removedProjectKind, removedProjectName, ownerProjectKind, ownerProject.Name); return; } if (removedProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is trying to modify a generated project by adding a reference to a // custom project. myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); // TODO: Notify user that modifying a generated project will lose changes return; } if (removedProjectKind == ProjectKind.Predefined) { // Weird scenario, shouldn't happen myLogger.Warn("Removing {0} project {1} reference from {2} project {3}?! Weird!", removedProjectKind, removedProjectName, ownerProjectKind, ownerProject.Name); return; } switch (ownerProjectKind, removedProjectKind) { case (ProjectKind.AsmDef, ProjectKind.AsmDef): RemoveAsmDefReference(ownerProject, ownerAsmDefLocation, removedAsmDefName, removedAsmDefLocation); break; case (ProjectKind.Predefined, ProjectKind.AsmDef): myLogger.Info( "Removing asmdef reference from predefined project. Check 'autoReferenced' value in asmdef"); // TODO: Should set "autoReferenced" to false in the removed asmdef project. Should this prompt? break; } } private void RemoveAsmDefReference(IProject ownerProject, VirtualFileSystemPath ownerAsmDefLocation, string removedAsmDefName, VirtualFileSystemPath removedAsmDefLocation) { var sourceFile = ownerProject.GetPsiSourceFileInProject(ownerAsmDefLocation); var psiFile = sourceFile?.GetDominantPsiFile<JsonNewLanguage>() as IJsonNewFile; var rootObject = psiFile?.GetRootObject(); if (rootObject == null) return; var guid = myMetaFileGuidCache.GetAssetGuid(removedAsmDefLocation); if (guid == null) myLogger.Warn("Cannot find asset for added asmdef {0}! Can only add as name", removedAsmDefLocation); var removedAsmDefGuid = guid == null ? null : AsmDefUtils.FormatGuidReference(guid.Value); // "references" might be missing if we've already removed all references and Unity isn't running to refresh // the project files var referencesProperty = rootObject.GetFirstPropertyValue<IJsonNewArray>("references"); if (referencesProperty == null) { myLogger.Verbose("Cannot find 'references' property. Nothing to remove"); return; } var existingArrayElement = FindReferenceElement(referencesProperty, removedAsmDefName, removedAsmDefGuid, out _); if (existingArrayElement.Count == 0) { myLogger.Verbose("Reference {0} already removed from asmdef {1}", removedAsmDefName, ownerAsmDefLocation); return; } using (new PsiTransactionCookie(myPsiServices, DefaultAction.Commit, "AddAsmDefReference")) { foreach (var existingLiteral in existingArrayElement) referencesProperty.RemoveArrayElement(existingLiteral); } } private void OnRemovedAssemblyReference(IProject ownerProject, string removedAssemblyName, VirtualFileSystemPath ownerAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); switch (ownerProjectKind) { case ProjectKind.Custom: // Don't care. The user has added a custom project, and has removed a reference from it. The project // will be removed the next time Unity regenerates the solution, but they won't lose the changes to // the project. We don't notify about this action - it would be better to notify when the project is // initially added myLogger.Info("Removing assembly {0} to custom project {1}. Ignoring change", removedAssemblyName, ownerProject.Name); return; case ProjectKind.Predefined: // Unsupported scenario. Custom assemblies should live in Assets and requires regenerating the // project file myLogger.Warn("Unsupported reference modification. Change will be lost when Unity regenerates project files"); // TODO: Notify the user return; case ProjectKind.AsmDef: // Like adding an assembly reference to an asmdef project, removing one is only supported if we're // removing an explicit plugin reference. // 1. Check removedAssembly is a plugin // 2. If not, notify user that this is not supported // 3. If true, check "overrideReferences" (if false, this is a weird scenario) // 4. If true, remove assembly name from "precompiledReferences" // It might be easier to notify the user to edit assembly references using Unity // TODO: All of the above ^^ myLogger.Warn( "Unsupported reference modification. Changes will be lost when Unity regenerates project files"); break; } } private static ProjectKind GetProjectKind(string projectName, VirtualFileSystemPath asmDefLocation) { if (asmDefLocation.IsNotEmpty) return ProjectKind.AsmDef; if (ProjectExtensions.IsOneOfPredefinedUnityProjects(projectName, true)) return ProjectKind.Predefined; return ProjectKind.Custom; } private static FrugalLocalList<IJsonNewValue> FindReferenceElement(IJsonNewArray? array, string asmDefName, string? asmDefGuid, out bool useGuids) { useGuids = false; var count = 0; var guidCount = 0; // The user might have added more than one, even though that's an error var results = new FrugalLocalList<IJsonNewValue>(); foreach (var literal in array.ValuesAsLiteral()) { // TODO: Helper function in JsonNewUtil that doesn't allocate? var text = literal.GetUnquotedText(); if (text.Equals(asmDefName, StringComparison.OrdinalIgnoreCase)) results.Add(literal); else if (asmDefGuid != null && text.Equals(asmDefGuid, StringComparison.OrdinalIgnoreCase)) results.Add(literal); count++; if (AsmDefUtils.IsGuidReference(text)) guidCount++; } // Prefer GUIDs, unless everything else is non-guid if (count == 0 || guidCount > 0) useGuids = true; return results; } private (string, VirtualFileSystemPath) GetAsmDefLocationForProject(string projectName) { // Assembly name and project name are the same for asmdef projects, unless it's a .Player project. We want // to return the actual name of the asmdef reference we'll be adding var location = myAsmDefCache.GetAsmDefLocationByAssemblyName(projectName); if (location.IsNotEmpty) return (projectName, location); projectName = ProjectExtensions.StripPlayerSuffix(projectName); return (projectName, myAsmDefCache.GetAsmDefLocationByAssemblyName(projectName)); } private class ReferenceChangeCollector : RecursiveProjectModelChangeDeltaVisitor { public FrugalLocalList<IProjectToModuleReference> AddedReferences; public FrugalLocalList<IProjectToModuleReference> RemovedReferences; public override void VisitProjectReferenceDelta(ProjectReferenceChange change) { if (change.IsClosingSolution || change.IsOpeningSolution) return; if (change.IsAdded) AddedReferences.Add(change.ProjectToModuleReference); else if (change.IsRemoved) RemovedReferences.Add(change.ProjectToModuleReference); } public void RemoveProblematicChangeEvents() { // We will be notified of reference changes when projects are reloaded after Unity regenerates the // project files. If we added a reference to a .Player project (the "Add reference" QF might arbitrarily // pick this) then Unity will regenerate the project files with the correct reference, and we'll see // both a removal of the .Player and an addition of the proper project. Since we always add the correct // asmdef reference even for .Player references, make sure we don't process this removal! // We could also post process this list to remove any notifications for .Player projects if there are // also notifications for non-player projects. var toRemove = new FrugalLocalList<IProjectToModuleReference>(); foreach (var removedReference in RemovedReferences) { if (ProjectExtensions.IsPlayerProjectName(removedReference.Name)) { var nonPlayerProjectName = ProjectExtensions.StripPlayerSuffix(removedReference.Name); foreach (var addedReference in AddedReferences) { if (addedReference.Name.Equals(nonPlayerProjectName, StringComparison.OrdinalIgnoreCase)) toRemove.Add(removedReference); } } } foreach (var reference in toRemove) RemovedReferences.Remove(reference); } } private enum ProjectKind { Predefined, AsmDef, Custom } } }
JetBrains/resharper-unity
resharper/resharper-unity/src/Unity/AsmDef/Psi/Modules/AsmDefModuleReferenceChangeListener.cs
C#
apache-2.0
28,817
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.metrics.internal; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.Request; import com.amazonaws.metrics.AwsSdkMetrics; import com.amazonaws.metrics.ServiceMetricType; import com.amazonaws.metrics.SimpleThroughputMetricType; import com.amazonaws.metrics.ThroughputMetricType; /** * An internal helper factory for generating service specific {@link ServiceMetricType} * without causing compile time dependency on the service specific artifacts. * * There exists a S3ServiceMetricTest.java unit test in the S3 client library * that ensures this class behaves consistently with the service metric enum * defined in the S3 client library. */ public enum ServiceMetricTypeGuesser { ; /** * Returned the best-guessed throughput metric type for the given request, * or null if there is none or if metric is disabled. */ public static ThroughputMetricType guessThroughputMetricType( final Request<?> req, final String metricNameSuffix, final String byteCountMetricNameSuffix) { if (!AwsSdkMetrics.isMetricsEnabled()) return null; // metric disabled Object orig = req.getOriginalRequestObject(); if (orig.getClass().getName().startsWith("com.amazonaws.services.s3")) { return new SimpleThroughputMetricType( "S3" + metricNameSuffix, req.getServiceName(), "S3" + byteCountMetricNameSuffix); } return null; } }
jentfoo/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/metrics/internal/ServiceMetricTypeGuesser.java
Java
apache-2.0
2,121
package org.esupportail.catapp.admin.domain.config; import org.esupportail.commons.mail.CachingEmailSmtpService; import org.esupportail.commons.mail.SimpleSmtpService; import org.esupportail.commons.mail.SmtpService; import org.esupportail.commons.mail.model.SmtpServerData; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.Cache; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import javax.inject.Inject; import javax.inject.Named; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import java.io.UnsupportedEncodingException; @Configuration @Import({ CacheConfig.class }) public class SmtpConfig { @Value("${smtp.host}") private String smtpHost; @Value("${smtp.port}") private Integer smtpPort; @Value("${smtp.user}") private String smtpUser; @Value("${smtp.password}") private String smtpPwd; @Value("${smtp.fromEmail}") private String fromEmail; @Value("${smtp.fromName}") private String fromName; @Value("${smtp.interceptAll}") private boolean interceptAll; @Value("${smtp.interceptEmail}") private String interceptEmail; @Value("${smtp.interceptName}") private String interceptName; @Value("${smtp.charset}") private String charset; @Value("${exceptionHandling.email}") private String emailException; @Inject @Named("mailCache") private Cache mailCache; @Bean public SmtpServerData smtpServer() { return SmtpServerData.builder() .host(smtpHost) .port(smtpPort) .user(smtpUser) .password(smtpPwd) .build(); } @Bean public SmtpService smtpService() throws UnsupportedEncodingException { final InternetAddress from = new InternetAddress(fromEmail, fromName); final InternetAddress intercept = new InternetAddress(interceptEmail, interceptName); return CachingEmailSmtpService.create( SimpleSmtpService .builder(from, null, intercept) .interceptAll(interceptAll) .charset(charset) .server(smtpServer()) .build(), mailCache); } @Bean public InternetAddress exceptionAddress() throws AddressException { return new InternetAddress(emailException); } }
EsupPortail/esup-catapp-admin
src/main/java/org/esupportail/catapp/admin/domain/config/SmtpConfig.java
Java
apache-2.0
2,612
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd 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. */ var dispatchStorageEvent = function(key, oldValue, newValue) { var evt = document.createEvent("CustomEvent"); evt.initCustomEvent("storage", true, true); evt.key = key; evt.oldValue = oldValue; evt.newValue = newValue; evt.storageArea = window.widget.preference; document.dispatchEvent(evt); for (var i=0; i < window.frames.length; i++) { window.frames[i].document.dispatchEvent(evt); } }; var widget_info_ = requireNative('WidgetModule'); var preference_ = widget_info_['preference']; preference_.__onChanged_WRT__ = dispatchStorageEvent; function Widget() { Object.defineProperties(this, { "author": { value: widget_info_[ "author"], writable: false }, "description": { value: widget_info_["description"], writable: false }, "name": { value: widget_info_["name"], writable: false }, "shortName": { value: widget_info_["shortName"], writable: false }, "version": { value: widget_info_["version"], writable: false }, "id": { value: widget_info_["id"], writable: false }, "authorEmail": { value: widget_info_["authorEmail"], writable: false }, "authorHref": { value: widget_info_["authorHref"], writable: false }, "height": { get: function() { return window && window.innerHeight || 0; }, configurable: false }, "width": { get: function() { return window && window.innerWidth || 0; }, configurable: false }, "preferences": { value: preference_, writable: false } }); }; Widget.prototype.toString = function() { return "[object Widget]"; }; window.widget = new Widget(); exports = Widget;
sung-su/crosswalk-tizen
extensions/internal/widget/widget_api.js
JavaScript
apache-2.0
2,433
// Copyright 2005-2006 Ferdinand Prantl <prantl@users.sourceforge.net> // Copyright 2001-2004 The Apache Software 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. // // See http://ant-eclipse.sourceforge.net for the most recent version // and more information. package prantl.ant.eclipse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /** * Provides the functionality generating the file <tt>.classpath</tt> for the supplied * task object. It is expected to be used within the class EclipseTask. * * @see EclipseTask * @since Ant-Eclipse 1.0 * @author Ferdinand Prantl &lt;prantl@users.sourceforge.net&gt; */ final class ClassPathGenerator { /** * Contains a ready-to write information about a binary classpath entry - element * kinds "lib" or "var". Fields of this class match attributes of the element * <tt>classpath</tt>. * * @see ClassPathGenerator#writeProcessedBinaryClassPathEntries(XmlWriter, String, * Vector) * @since Ant-Eclipse 1.0 * @author Ferdinand Prantl &lt;prantl@users.sourceforge.net&gt; */ static class ProcessedBinaryClassPathEntry { String kind; String path; boolean exported; String sourcepath; String javadoc_location; } private EclipseTask task; /** * Creates a new instance of the generating object. * * @param parent * The parent task. * @since Ant-Eclipse 1.0 */ ClassPathGenerator(EclipseTask parent) { task = parent; } /** * Generates the file <tt>.classpath</tt> using the supplied output object. * * @since Ant-Eclipse 1.0 */ void generate() { ClassPathElement classPath = task.getEclipse().getClassPath(); if (classPath == null) { task.log("There was no description of a classpath found.", Project.MSG_WARN); return; } EclipseOutput output = task.getOutput(); if (output.isClassPathUpToDate()) { task.log("The classpath definition is up-to-date.", Project.MSG_WARN); return; } task.log("Writing the classpath definition."); XmlWriter writer = null; try { writer = new XmlWriter(new OutputStreamWriter(new BufferedOutputStream(output .createClassPath()), "UTF-8")); writer.writeXmlDeclaration("UTF-8"); writer.openElement("classpath"); checkClassPathEntries(classPath); generateContainerClassPathEntry(writer); generateSourceClassPathEntries(writer); Vector entries = new Vector(); processVariableClassPathEntries(entries, classPath.getVariables()); processLibraryClassPathEntries(entries, classPath.getLibraries()); writeProcessedBinaryClassPathEntries(writer, entries); generateOutputClassPathEntry(writer); writer.closeElement("classpath"); } catch (UnsupportedEncodingException exception) { throw new BuildException("Encoder to UTF-8 is not supported.", exception); } catch (IOException exception) { throw new BuildException("Writing the classpath definition failed.", exception); } finally { if (writer != null) try { writer.close(); } catch (IOException exception1) { throw new BuildException("Closing the classpath definition failed.", exception1); } } } private void generateContainerClassPathEntry(XmlWriter writer) throws IOException { ClassPathEntryContainerElement container = task.getEclipse().getClassPath() .getContainer(); if (container == null) { task.log("No container found, a default one added.", Project.MSG_VERBOSE); container = new ClassPathEntryContainerElement(); } container.validate(); String path = container.getPath(); if (path.indexOf('/') < 0 && !path.startsWith("org.eclipse.jdt.launching.JRE_CONTAINER")) { task.log("Prepending the container class name to the container path \"" + path + "\".", Project.MSG_VERBOSE); path = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/" + path; } task.log("Adding container \"" + path + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "con", path); writer.closeDegeneratedElement(); } private void generateSourceClassPathEntries(XmlWriter writer) throws IOException { Vector entries = task.getEclipse().getClassPath().getSources(); if (entries.size() == 0) { task .log("No source found, the current directory added.", Project.MSG_VERBOSE); entries.addElement(new ClassPathEntrySourceElement()); } for (int i = 0, size = entries.size(); i != size; ++i) { ClassPathEntrySourceElement entry = (ClassPathEntrySourceElement) entries .get(i); entry.validate(); String excluding = entry.getExcluding(); String output = entry.getOutput(); Path path = new Path(task.getProject()); Reference reference = entry.getPathRef(); String[] items = path.list(); if (reference != null) { path.setRefid(reference); items = path.list(); } else { String value = entry.getPath(); if (value.length() == 0) task.log("Using the current directory as a default source path.", Project.MSG_VERBOSE); items = new String[] { value }; } String baseDirectory = task.getProject().getBaseDir().getAbsolutePath(); for (int j = 0; j != items.length; ++j) { String item = cutBaseDirectory(items[j], baseDirectory); task.log("Adding sources from \"" + item + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "src", item); if (excluding != null) writer.appendAttribute("excluding", excluding); if (output != null) writer.appendAttribute("output", output); writer.closeDegeneratedElement(); } } } private void processVariableClassPathEntries(Vector entries, Vector paths) { processBinaryClassPathEntries(entries, "var", paths); } private void processLibraryClassPathEntries(Vector entries, Vector paths) { processBinaryClassPathEntries(entries, "lib", paths); } private void processBinaryClassPathEntries(Vector entries, String kind, Vector binaries) { for (int i = 0, size = binaries.size(); i != size; ++i) { ClassPathEntryBinaryElement entry = (ClassPathEntryBinaryElement) binaries .get(i); entry.validate(); Path path = new Path(task.getProject()); Reference reference = entry.getPathRef(); if (reference != null) path.setRefid(reference); else { String value = entry.getPath(); path.setPath(value); } processBinaryClassPathEntries(entries, kind, entry.getExported(), entry .getSource(), entry.getJavadoc(), path.list()); } } private void processBinaryClassPathEntries(Vector entries, String kind, boolean exported, String source, String javadoc_location, String[] items) { String baseDirectory = task.getProject().getBaseDir().getAbsolutePath(); for (int j = 0; j != items.length; ++j) { String item = cutBaseDirectory(items[j], baseDirectory); ProcessedBinaryClassPathEntry element = getProcessedBinaryClassPathEntry( entries, item); if (element == null) { task.log("Processing binary dependency \"" + item + "\" of the kind \"" + kind + "\".", Project.MSG_VERBOSE); element = new ProcessedBinaryClassPathEntry(); element.kind = kind; element.path = item; element.exported = exported; element.sourcepath = source; element.javadoc_location = javadoc_location; entries.addElement(element); } else { task.log("Updating binary dependency \"" + item + "\" of the kind \"" + kind + "\".", Project.MSG_VERBOSE); element.kind = kind; element.path = item; element.exported = exported; element.sourcepath = source; element.javadoc_location = javadoc_location; } } } private void writeProcessedBinaryClassPathEntries(XmlWriter writer, Vector entries) throws IOException { for (int i = 0, size = entries.size(); i != size; ++i) { ProcessedBinaryClassPathEntry element = (ProcessedBinaryClassPathEntry) entries .get(i); task.log("Adding binary dependency \"" + element.path + "\" of the kind \"" + element.kind + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, element.kind, element.path); if (element.exported) writer.appendAttribute("exported", "true"); if (element.sourcepath != null) writer.appendAttribute("sourcepath", element.sourcepath); if (element.javadoc_location != null) { writer.closeOpeningTag(); writer.openElement("attributes"); writer.openOpeningTag("attribute"); writer.appendAttribute("value", element.javadoc_location); writer.appendAttribute("name", "javadoc_location"); writer.closeDegeneratedElement(); writer.closeElement("attributes"); writer.closeElement("classpathentry"); } else writer.closeDegeneratedElement(); } } private void generateOutputClassPathEntry(XmlWriter writer) throws IOException { ClassPathEntryOutputElement output = task.getEclipse().getClassPath().getOutput(); if (output == null) { task .log("No output found, the current directory added.", Project.MSG_VERBOSE); output = new ClassPathEntryOutputElement(); } output.validate(); String path = cutBaseDirectory(output.getPath(), task.getProject().getBaseDir() .getAbsolutePath()); task.log("Adding output into \"" + path + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "output", path); writer.closeDegeneratedElement(); } private void openClassPathEntry(XmlWriter writer, String kind, String path) throws IOException { writer.openOpeningTag("classpathentry"); writer.appendAttribute("kind", kind); writer.appendAttribute("path", path); } private String cutBaseDirectory(String path, String base) { if (!path.startsWith(base)) return path; task.log("Cutting base directory \"" + base + "\" from the path \"" + path + "\".", Project.MSG_VERBOSE); return path.substring(base.length() + 1); } private void checkClassPathEntries(ClassPathElement classPath) { if (task.getEclipse().getMode().getIndex() == EclipseElement.Mode.ASPECTJ && getClassPathEntry(classPath.getVariables(), "ASPECTJRT_LIB") == null) { ClassPathEntryVariableElement variable = classPath.createVariable(); variable.setPath("ASPECTJRT_LIB"); variable.setSource("ASPECTJRT_SRC"); } } private static ClassPathEntryElement getClassPathEntry(Vector entries, String path) { for (int i = 0, size = entries.size(); i != size; ++i) { ClassPathEntryElement entry = (ClassPathEntryElement) entries.get(i); if (path.equals(entry.getPath())) return entry; } return null; } private static ProcessedBinaryClassPathEntry getProcessedBinaryClassPathEntry( Vector entries, String path) { for (int i = 0, size = entries.size(); i < size; ++i) { ProcessedBinaryClassPathEntry entry = (ProcessedBinaryClassPathEntry) entries .get(i); if (entry.path.equals(path)) return entry; } return null; } }
spidaman/ant-eclipse
src/prantl/ant/eclipse/ClassPathGenerator.java
Java
apache-2.0
14,121
/* walter: a deployment pipeline template * Copyright (C) 2014 Recruit Technologies Co., Ltd. and contributors * (see CONTRIBUTORS.md) * * 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 messengers defines clients for the messaging services such as Slack. // The clients reports the results of the pipeline stages and whole results. package messengers // FakeMessenger is a Messenger type used only for testing. type FakeMessenger struct { BaseMessenger } func (self *FakeMessenger) Post(messege string) bool { return true }
jacec/walter
messengers/fake.go
GO
apache-2.0
1,049
using System; using System.Reflection; namespace StudyServer.Areas.HelpPage.ModelDescriptions { public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); } }
hedulewei/cdm
StudyServer/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs
C#
apache-2.0
256
<?php require_once '../../includes/config.php'; $title = "Wi-Fi Topics"; $author ; //$author = "Keith Amoah"; if(!isset($date)) { $date = '26/11/2014'; } $keywords; $codeGenerator = "Dreamweaver"; ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"/> <title><?php echo $title; ?></title> <meta name="Author" content="<?php echo $author = (isset($author))? $author : ""; ?>"/> <meta name="keywords" content="<?php echo $keywords = (isset($keywords))? $keywords : ""; ?>"/> <meta name="generator" content="<?php echo $codeGenerator = (isset($codeGenerator))? $codeGenerator : ""; ?>"/> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <?php /* ********************** Stylesheets *********************************** */ ?> <link rel="stylesheet" type="text/css" href="/styles/vendors/normalize.css"> <?php //css reset ?> <link rel="stylesheet" type="text/css" href="/styles/dev/css/templateV7.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <?php //See http://fortawesome.github.io/Font-Awesome/icons/ more details on css icons ?> <style type="text/css"> </style> <?php /* ********************** Scripts *********************************** */ ?> <script type="text/javascript" src="/scripts/vendors/jquery-1.11.1.js"></script> <?php //JQuery Library ?> <script type="text/javascript"> var currentUrl = <?php echo json_encode($_SERVER['REQUEST_URI']); ?>; </script> <script type="text/javascript" src="/scripts/customV3.js"></script> </head> <body> <div id="wrapper"> <?php /* ****************** Page Header ******************* */ ?> <header id="pageHeader"> <?php require_once "../../includes/header.php"; /* ****************** Main Navigation ******************* */ ?> <nav> <div id="bar"> <div class="navButton"> <h2>Menu<span class="fa fa-bars"></span><span class="fa fa-times-circle"></span></h2> </div> </div> <?php require_once "../../includes/nav.php" ?> <div class="clearthis"></div> </nav> </header> <!-- End of Navigation Menu --> <?php /* ****************** Main Content ******************* */ ?> <!-- Start of Main Content Area --> <main> <header> <h1>Wi-Fi,WiMAX &amp; LTE Learning Aid : Wi-Fi</h1> <?php /*** Optional header - only applicable when more than one article one page */ ?> </header> <!--<p><a>Breadcrumbs</a></p>--> <article> <header> <h1>Wi-Fi Topics</h1> <ul> <li> <a href="/wifi-wimax-lte/wifi/introduction.php"> Introduction </a> </li> <li> <a href="/wifi-wimax-lte/wifi/wifi.php"> Wi-Fi </a> </li> <li> <a href="/wifi-wimax-lte/wifi/modulation-and-performance.php" > Modulation and Performance </a> </li> <li> <a href="/wifi-wimax-lte/wifi/security.php" > Security </a> </li> <li> <a href="/wifi-wimax-lte/wifi/wifi-meshes.php"> Wi-Fi Meshes </a> </li> </ul> </header> <footer> <?php // Author and date of work //Need to still this footer ?> <p>Created by <a title="" class="author" href="#"> Keith Amoah </a> , May 2011</p> </footer> </article> <div id="bottom"> <a title="Navigate to top of the current page" href="#Top"> <span class="fa fa-arrow-circle-up"></span>To the Top <span class="fa fa-arrow-circle-up"></span> </a> </div> </main> <?php /* ****************** PageFooter ******************* */ ?> <?php require_once '../../includes/footer.php'; ?> </div> </body> </html>
KKOA/portfolio-27-10-2016
wifi-wimax-lte/wifi/wifi-topics.php
PHP
apache-2.0
3,719
# encoding: UTF-8 # # Copyright 2010 Dan Wanek <dan.wanek@gmail.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. require_relative 'response_handler' module WinRM module HTTP # A generic HTTP transport that utilized HTTPClient to send messages back and forth. # This backend will maintain state for every WinRMWebService instance that is instantiated so it # is possible to use GSSAPI with Keep-Alive. class HttpTransport # Set this to an unreasonable amount because WinRM has its own timeouts DEFAULT_RECEIVE_TIMEOUT = 3600 attr_reader :endpoint def initialize(endpoint) @endpoint = endpoint.is_a?(String) ? URI.parse(endpoint) : endpoint @httpcli = HTTPClient.new(agent_name: 'Ruby WinRM Client') @httpcli.receive_timeout = DEFAULT_RECEIVE_TIMEOUT @logger = Logging.logger[self] end # Sends the SOAP payload to the WinRM service and returns the service's # SOAP response. If an error occurrs an appropriate error is raised. # # @param [String] The XML SOAP message # @returns [REXML::Document] The parsed response body def send_request(message) log_soap_message(message) hdr = { 'Content-Type' => 'application/soap+xml;charset=UTF-8', 'Content-Length' => message.length } resp = @httpcli.post(@endpoint, message, hdr) log_soap_message(resp.http_body.content) handler = WinRM::ResponseHandler.new(resp.http_body.content, resp.status) handler.parse_to_xml end # We'll need this to force basic authentication if desired def basic_auth_only! auths = @httpcli.www_auth.instance_variable_get('@authenticator') auths.delete_if { |i| i.scheme !~ /basic/i } end # Disable SSPI Auth def no_sspi_auth! auths = @httpcli.www_auth.instance_variable_get('@authenticator') auths.delete_if { |i| i.is_a? HTTPClient::SSPINegotiateAuth } end # Disable SSL Peer Verification def no_ssl_peer_verification! @httpcli.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE end # HTTP Client receive timeout. How long should a remote call wait for a # for a response from WinRM? def receive_timeout=(sec) @httpcli.receive_timeout = sec end def receive_timeout @httpcli.receive_timeout end protected def log_soap_message(message) return unless @logger.debug? xml_msg = REXML::Document.new(message) formatter = REXML::Formatters::Pretty.new(2) formatter.compact = true formatter.write(xml_msg, @logger) @logger.debug("\n") rescue StandardError => e @logger.debug("Couldn't log SOAP request/response: #{e.message} - #{message}") end end # Plain text, insecure, HTTP transport class HttpPlaintext < HttpTransport def initialize(endpoint, user, pass, opts) super(endpoint) @httpcli.set_auth(nil, user, pass) no_sspi_auth! if opts[:disable_sspi] basic_auth_only! if opts[:basic_auth_only] no_ssl_peer_verification! if opts[:no_ssl_peer_verification] end end # Uses SSL to secure the transport class HttpSSL < HttpTransport def initialize(endpoint, user, pass, ca_trust_path = nil, opts) super(endpoint) @httpcli.set_auth(endpoint, user, pass) @httpcli.ssl_config.set_trust_ca(ca_trust_path) unless ca_trust_path.nil? no_sspi_auth! if opts[:disable_sspi] basic_auth_only! if opts[:basic_auth_only] no_ssl_peer_verification! if opts[:no_ssl_peer_verification] end end # Uses Kerberos/GSSAPI to authenticate and encrypt messages # rubocop:disable Metrics/ClassLength class HttpGSSAPI < HttpTransport # @param [String,URI] endpoint the WinRM webservice endpoint # @param [String] realm the Kerberos realm we are authenticating to # @param [String<optional>] service the service name, default is HTTP # @param [String<optional>] keytab the path to a keytab file if you are using one # rubocop:disable Lint/UnusedMethodArgument def initialize(endpoint, realm, service = nil, keytab = nil, opts) # rubocop:enable Lint/UnusedMethodArgument super(endpoint) # Remove the GSSAPI auth from HTTPClient because we are doing our own thing no_sspi_auth! service ||= 'HTTP' @service = "#{service}/#{@endpoint.host}@#{realm}" init_krb end # Sends the SOAP payload to the WinRM service and returns the service's # SOAP response. If an error occurrs an appropriate error is raised. # # @param [String] The XML SOAP message # @returns [REXML::Document] The parsed response body def send_request(message) resp = send_kerberos_request(message) if resp.status == 401 @logger.debug 'Got 401 - reinitializing Kerberos and retrying one more time' init_krb resp = send_kerberos_request(message) end handler = WinRM::ResponseHandler.new(winrm_decrypt(resp.http_body.content), resp.status) handler.parse_to_xml end private # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/AbcSize # Sends the SOAP payload to the WinRM service and returns the service's # HTTP response. # # @param [String] The XML SOAP message # @returns [Object] The HTTP response object def send_kerberos_request(message) log_soap_message(message) original_length = message.length pad_len, emsg = winrm_encrypt(message) hdr = { 'Connection' => 'Keep-Alive', 'Content-Type' => 'multipart/encrypted;' \ 'protocol="application/HTTP-Kerberos-session-encrypted";' \ 'boundary="Encrypted Boundary"' } body = <<-EOF --Encrypted Boundary\r Content-Type: application/HTTP-Kerberos-session-encrypted\r OriginalContent: type=application/soap+xml;charset=UTF-8;Length=#{original_length + pad_len}\r --Encrypted Boundary\r Content-Type: application/octet-stream\r #{emsg}--Encrypted Boundary\r EOF resp = @httpcli.post(@endpoint, body, hdr) log_soap_message(resp.http_body.content) resp end def init_krb @logger.debug "Initializing Kerberos for #{@service}" @gsscli = GSSAPI::Simple.new(@endpoint.host, @service) token = @gsscli.init_context auth = Base64.strict_encode64 token hdr = { 'Authorization' => "Kerberos #{auth}", 'Connection' => 'Keep-Alive', 'Content-Type' => 'application/soap+xml;charset=UTF-8' } @logger.debug 'Sending HTTP POST for Kerberos Authentication' r = @httpcli.post(@endpoint, '', hdr) itok = r.header['WWW-Authenticate'].pop itok = itok.split.last itok = Base64.strict_decode64(itok) @gsscli.init_context(itok) end # @return [String] the encrypted request string def winrm_encrypt(str) @logger.debug "Encrypting SOAP message:\n#{str}" iov_cnt = 3 iov = FFI::MemoryPointer.new(GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * iov_cnt) iov0 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new(FFI::Pointer.new(iov.address)) iov0[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_HEADER | \ GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_FLAG_ALLOCATE) iov1 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new( FFI::Pointer.new(iov.address + (GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * 1))) iov1[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_DATA) iov1[:buffer].value = str iov2 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new( FFI::Pointer.new(iov.address + (GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * 2))) iov2[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_PADDING | \ GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_FLAG_ALLOCATE) conf_state = FFI::MemoryPointer.new :uint32 min_stat = FFI::MemoryPointer.new :uint32 GSSAPI::LibGSSAPI.gss_wrap_iov( min_stat, @gsscli.context, 1, GSSAPI::LibGSSAPI::GSS_C_QOP_DEFAULT, conf_state, iov, iov_cnt) token = [iov0[:buffer].length].pack('L') token += iov0[:buffer].value token += iov1[:buffer].value pad_len = iov2[:buffer].length token += iov2[:buffer].value if pad_len > 0 [pad_len, token] end # @return [String] the unencrypted response string def winrm_decrypt(str) @logger.debug "Decrypting SOAP message:\n#{str}" iov_cnt = 3 iov = FFI::MemoryPointer.new(GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * iov_cnt) iov0 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new(FFI::Pointer.new(iov.address)) iov0[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_HEADER | \ GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_FLAG_ALLOCATE) iov1 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new( FFI::Pointer.new(iov.address + (GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * 1))) iov1[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_DATA) iov2 = GSSAPI::LibGSSAPI::GssIOVBufferDesc.new( FFI::Pointer.new(iov.address + (GSSAPI::LibGSSAPI::GssIOVBufferDesc.size * 2))) iov2[:type] = (GSSAPI::LibGSSAPI::GSS_IOV_BUFFER_TYPE_DATA) str.force_encoding('BINARY') str.sub!(/^.*Content-Type: application\/octet-stream\r\n(.*)--Encrypted.*$/m, '\1') len = str.unpack('L').first iov_data = str.unpack("LA#{len}A*") iov0[:buffer].value = iov_data[1] iov1[:buffer].value = iov_data[2] min_stat = FFI::MemoryPointer.new :uint32 conf_state = FFI::MemoryPointer.new :uint32 conf_state.write_int(1) qop_state = FFI::MemoryPointer.new :uint32 qop_state.write_int(0) maj_stat = GSSAPI::LibGSSAPI.gss_unwrap_iov( min_stat, @gsscli.context, conf_state, qop_state, iov, iov_cnt) @logger.debug "SOAP message decrypted (MAJ: #{maj_stat}, " \ "MIN: #{min_stat.read_int}):\n#{iov1[:buffer].value}" iov1[:buffer].value end # rubocop:enable Metrics/MethodLength # rubocop:enable Metrics/AbcSize end # rubocop:enable Metrics/ClassLength end end # WinRM
ClogenyTechnologies/WinRM
lib/winrm/http/transport.rb
Ruby
apache-2.0
11,010
var a00455 = [ [ "UnicharIdArrayUtils", "a02761.html", null ], [ "AmbigSpec", "a02765.html", "a02765" ], [ "UnicharAmbigs", "a02769.html", "a02769" ], [ "MAX_AMBIG_SIZE", "a00455.html#a66b35d22667233a1566433c6dd864463", null ], [ "UnicharAmbigsVector", "a00455.html#aa63fceec9a01c185fac83c0e7d04fe08", null ], [ "UnicharIdVector", "a00455.html#a3dad1b2dad5ed3069bdb4c971116b9c5", null ], [ "AmbigType", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222", [ [ "NOT_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222af40a6c3f3fbd83ba09a6607f534349dc", null ], [ "REPLACE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a4de7fc7ae32fd87a4c53e4b6bf3322de", null ], [ "DEFINITE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a36712914249ab1d96c4f395c06bc7009", null ], [ "SIMILAR_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222aba0a03f0cccfdd9e45817623613dd740", null ], [ "CASE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a29c650e9672a75e50491fc10c0f07ec5", null ], [ "AMBIG_TYPE_COUNT", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a79854db5a6d73c698dd9b003f426918f", null ] ] ], [ "ELISTIZEH", "a00455.html#aad9b817c74cee6bd76a4912e7f54ff7b", null ] ];
stweil/tesseract-ocr.github.io
4.00.00dev/a00455.js
JavaScript
apache-2.0
1,254
<?php namespace RhubarbTests\Result; /** * @license http://www.apache.org/licenses/LICENSE-2.0 * Copyright [2012] [Robert Allen] * * 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 Rhubarb * @category Tests * @subcategory Result */ /** * @package Rhubarb * @category Tests * @subcategory Result */ class AsyncResultTest extends \PHPUnit_Framework_TestCase { public function testResult() { $this->assertTrue(true); } }
zircote/Rhubarb
tests/library/Rhubarb/Result/AsyncResultTest.php
PHP
apache-2.0
984
package org.visallo.web.clientapi.model; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.visallo.web.clientapi.VisalloClientApiException; import java.util.Map; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = DirectoryGroup.class, name = DirectoryEntity.TYPE_GROUP), @JsonSubTypes.Type(value = DirectoryPerson.class, name = DirectoryEntity.TYPE_PERSON) }) public abstract class DirectoryEntity implements ClientApiObject, Comparable<DirectoryEntity> { public static final String TYPE_GROUP = "group"; public static final String TYPE_PERSON = "person"; private final String id; private final String displayName; public DirectoryEntity(String id, String displayName) { this.id = id; this.displayName = displayName; } public String getId() { return id; } public String getDisplayName() { return displayName; } public abstract String getType(); public static DirectoryEntity fromMap(Map map) { String type = (String) map.get("type"); String id = (String) map.get("id"); String displayName = (String) map.get("displayName"); if (TYPE_GROUP.equalsIgnoreCase(type)) { return new DirectoryGroup(id, displayName); } else if (TYPE_PERSON.equalsIgnoreCase(type)) { return new DirectoryPerson(id, displayName); } else { throw new VisalloClientApiException("Unhandled type: " + type); } } public static boolean isEntity(Map map) { String id = (String) map.get("id"); String displayName = (String) map.get("displayName"); String type = (String) map.get("type"); return type != null && id != null && displayName != null && isType(type); } private static boolean isType(String type) { return type.equalsIgnoreCase(TYPE_GROUP) || type.equalsIgnoreCase(TYPE_PERSON); } @Override public int compareTo(DirectoryEntity o) { int i = getType().compareTo(o.getType()); if (i != 0) { return i; } return getId().compareTo(o.getId()); } @Override public boolean equals(Object o) { if (!(o instanceof DirectoryEntity)) { return false; } DirectoryEntity other = (DirectoryEntity)o; return id.equals(other.id) && displayName.equals(other.displayName); } @Override public int hashCode() { return id.hashCode() + 31 * displayName.hashCode(); } }
visallo/visallo
web/client-api/src/main/java/org/visallo/web/clientapi/model/DirectoryEntity.java
Java
apache-2.0
2,694
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ssmincidents.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.ssmincidents.model.*; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateIncidentRecordRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateIncidentRecordRequestMarshaller { private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("arn").build(); private static final MarshallingInfo<StructuredPojo> CHATCHANNEL_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("chatChannel").build(); private static final MarshallingInfo<String> CLIENTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientToken") .defaultValueSupplier(com.amazonaws.util.IdempotentUtils.getGenerator()).build(); private static final MarshallingInfo<Integer> IMPACT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("impact").build(); private static final MarshallingInfo<List> NOTIFICATIONTARGETS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("notificationTargets").build(); private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("status").build(); private static final MarshallingInfo<String> SUMMARY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("summary").build(); private static final MarshallingInfo<String> TITLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("title").build(); private static final UpdateIncidentRecordRequestMarshaller instance = new UpdateIncidentRecordRequestMarshaller(); public static UpdateIncidentRecordRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateIncidentRecordRequest updateIncidentRecordRequest, ProtocolMarshaller protocolMarshaller) { if (updateIncidentRecordRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateIncidentRecordRequest.getArn(), ARN_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getChatChannel(), CHATCHANNEL_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getClientToken(), CLIENTTOKEN_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getImpact(), IMPACT_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getNotificationTargets(), NOTIFICATIONTARGETS_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getSummary(), SUMMARY_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getTitle(), TITLE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-ssmincidents/src/main/java/com/amazonaws/services/ssmincidents/model/transform/UpdateIncidentRecordRequestMarshaller.java
Java
apache-2.0
4,460
<?php print _partial('header_collaborative_projects'); ?> <header id="header"> <div id="header-inner"> <?php if ($logo): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"> <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /> </a> <?php endif; ?> <?php if ($site_name || $site_slogan): ?> <div id="name-and-slogan"> <?php if ($site_name): ?> <?php if ($title): ?> <div id="site-name"> <h1><a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a></h1> </div> <?php else: /* Use h1 when the content title is empty */ ?> <h1 id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a> </h1> <?php endif; ?> <?php endif; ?> <?php if ($site_slogan): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </div> <?php endif; ?> <?php if ($page['header']): ?> <div id="header-region"> <?php print render($page['header']); ?> </div> <?php endif; ?> <?php print render($page['navigation']); ?> </div> </header> <!-- /header --> <?php if ($page['highlighted']): ?> <div id="highlighted"><?php print render($page['highlighted']) ?></div> <?php endif; ?> <div id="page" class="<?php print $classes; ?>"<?php print $attributes; ?>> <div id="page-inner"> <!-- ______________________ HEADER _______________________ --> <!-- ______________________ MAIN _______________________ --> <div id="main" class="clearfix"> <!-- ______________________ Content-top _______________________ --> <?php if ($page['content_top']): ?> <div id="content-top"><?php print render($page['content_top']) ?></div> <?php endif; ?> <section id="content"> <?php if ($breadcrumb || $title|| $messages || $tabs || $action_links): ?> <div id="content-header"> <?php print $breadcrumb; ?> <?php print render($title_prefix); ?> <?php print render($title_suffix); ?> <?php print $messages; ?> <?php print render($page['help']); ?> <?php if ($tabs): ?> <?php print render($tabs); ?> <?php endif; ?> <?php if ($action_links): ?> <ul class="action-links"><?php print render($action_links); ?></ul> <?php endif; ?> </div> <!-- /#content-header --> <?php endif; ?> <div id="content-area"> <?php print render($page['content']) ?> </div> <?php print $feed_icons; ?> </section> <!-- /content-inner /content --> <?php if ($page['sidebar_first']): ?> <aside id="sidebar-first" class="column sidebar first"> <?php print render($page['sidebar_first']); ?> </aside> <?php endif; ?> <!-- /sidebar-first --> <?php if ($page['sidebar_second']): ?> <aside id="sidebar-second" class="column sidebar second"> <?php print render($page['sidebar_second']); ?> </aside> <?php endif; ?> <!-- /sidebar-second --> <!-- ______________________ Content-bottom _______________________ --> <?php if ($page['content_bottom']): ?> <div id="content-bottom"><?php print render($page['content_bottom']) ?></div> <?php endif; ?> </div> <!-- /main --> <!-- ______________________ FOOTER _______________________ --> <?php if ($page['footer']): ?> <footer id="footer"> <?php print render($page['footer']); ?> <div class="clearfix"></div> </footer> <!-- /footer --> <?php endif; ?> </div> <!-- /page inner --> </div> <!-- /page --> <?php print _partial('footer_copyright'); ?> <?php if ($pardot_code = variable_get('pardot_code', NULL)) { print $pardot_code; } ?>
sschuberth/spdx-tools
resources/htmlTemplate/sites/all/themes/cpstandard/templates/page--front.tpl.php
PHP
apache-2.0
4,000
# # Author:: Seth Chisamore (<schisamo@opscode.com>) # Cookbook Name:: python # Attribute:: default # # Copyright 2011, Opscode, 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. # default['python']['install_method'] = 'package' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['version'] = '2.7.1' default['python']['checksum'] = '80e387bcf57eae8ce26726753584fd63e060ec11682d1145af921e85fd612292' default['python']['configure_options'] = %W{--prefix=#{python['prefix_dir']}} default['python']['pip']['prefix_dir'] = '/usr/local'
samaras/symfonyVagrant
cookbooks/python/attributes/default.rb
Ruby
apache-2.0
1,208
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/elasticache/model/Snapshot.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace ElastiCache { namespace Model { Snapshot::Snapshot() : m_snapshotNameHasBeenSet(false), m_replicationGroupIdHasBeenSet(false), m_replicationGroupDescriptionHasBeenSet(false), m_cacheClusterIdHasBeenSet(false), m_snapshotStatusHasBeenSet(false), m_snapshotSourceHasBeenSet(false), m_cacheNodeTypeHasBeenSet(false), m_engineHasBeenSet(false), m_engineVersionHasBeenSet(false), m_numCacheNodes(0), m_numCacheNodesHasBeenSet(false), m_preferredAvailabilityZoneHasBeenSet(false), m_cacheClusterCreateTimeHasBeenSet(false), m_preferredMaintenanceWindowHasBeenSet(false), m_topicArnHasBeenSet(false), m_port(0), m_portHasBeenSet(false), m_cacheParameterGroupNameHasBeenSet(false), m_cacheSubnetGroupNameHasBeenSet(false), m_vpcIdHasBeenSet(false), m_autoMinorVersionUpgrade(false), m_autoMinorVersionUpgradeHasBeenSet(false), m_snapshotRetentionLimit(0), m_snapshotRetentionLimitHasBeenSet(false), m_snapshotWindowHasBeenSet(false), m_numNodeGroups(0), m_numNodeGroupsHasBeenSet(false), m_automaticFailover(AutomaticFailoverStatus::NOT_SET), m_automaticFailoverHasBeenSet(false), m_nodeSnapshotsHasBeenSet(false), m_kmsKeyIdHasBeenSet(false) { } Snapshot::Snapshot(const XmlNode& xmlNode) : m_snapshotNameHasBeenSet(false), m_replicationGroupIdHasBeenSet(false), m_replicationGroupDescriptionHasBeenSet(false), m_cacheClusterIdHasBeenSet(false), m_snapshotStatusHasBeenSet(false), m_snapshotSourceHasBeenSet(false), m_cacheNodeTypeHasBeenSet(false), m_engineHasBeenSet(false), m_engineVersionHasBeenSet(false), m_numCacheNodes(0), m_numCacheNodesHasBeenSet(false), m_preferredAvailabilityZoneHasBeenSet(false), m_cacheClusterCreateTimeHasBeenSet(false), m_preferredMaintenanceWindowHasBeenSet(false), m_topicArnHasBeenSet(false), m_port(0), m_portHasBeenSet(false), m_cacheParameterGroupNameHasBeenSet(false), m_cacheSubnetGroupNameHasBeenSet(false), m_vpcIdHasBeenSet(false), m_autoMinorVersionUpgrade(false), m_autoMinorVersionUpgradeHasBeenSet(false), m_snapshotRetentionLimit(0), m_snapshotRetentionLimitHasBeenSet(false), m_snapshotWindowHasBeenSet(false), m_numNodeGroups(0), m_numNodeGroupsHasBeenSet(false), m_automaticFailover(AutomaticFailoverStatus::NOT_SET), m_automaticFailoverHasBeenSet(false), m_nodeSnapshotsHasBeenSet(false), m_kmsKeyIdHasBeenSet(false) { *this = xmlNode; } Snapshot& Snapshot::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode snapshotNameNode = resultNode.FirstChild("SnapshotName"); if(!snapshotNameNode.IsNull()) { m_snapshotName = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotNameNode.GetText()); m_snapshotNameHasBeenSet = true; } XmlNode replicationGroupIdNode = resultNode.FirstChild("ReplicationGroupId"); if(!replicationGroupIdNode.IsNull()) { m_replicationGroupId = Aws::Utils::Xml::DecodeEscapedXmlText(replicationGroupIdNode.GetText()); m_replicationGroupIdHasBeenSet = true; } XmlNode replicationGroupDescriptionNode = resultNode.FirstChild("ReplicationGroupDescription"); if(!replicationGroupDescriptionNode.IsNull()) { m_replicationGroupDescription = Aws::Utils::Xml::DecodeEscapedXmlText(replicationGroupDescriptionNode.GetText()); m_replicationGroupDescriptionHasBeenSet = true; } XmlNode cacheClusterIdNode = resultNode.FirstChild("CacheClusterId"); if(!cacheClusterIdNode.IsNull()) { m_cacheClusterId = Aws::Utils::Xml::DecodeEscapedXmlText(cacheClusterIdNode.GetText()); m_cacheClusterIdHasBeenSet = true; } XmlNode snapshotStatusNode = resultNode.FirstChild("SnapshotStatus"); if(!snapshotStatusNode.IsNull()) { m_snapshotStatus = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotStatusNode.GetText()); m_snapshotStatusHasBeenSet = true; } XmlNode snapshotSourceNode = resultNode.FirstChild("SnapshotSource"); if(!snapshotSourceNode.IsNull()) { m_snapshotSource = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotSourceNode.GetText()); m_snapshotSourceHasBeenSet = true; } XmlNode cacheNodeTypeNode = resultNode.FirstChild("CacheNodeType"); if(!cacheNodeTypeNode.IsNull()) { m_cacheNodeType = Aws::Utils::Xml::DecodeEscapedXmlText(cacheNodeTypeNode.GetText()); m_cacheNodeTypeHasBeenSet = true; } XmlNode engineNode = resultNode.FirstChild("Engine"); if(!engineNode.IsNull()) { m_engine = Aws::Utils::Xml::DecodeEscapedXmlText(engineNode.GetText()); m_engineHasBeenSet = true; } XmlNode engineVersionNode = resultNode.FirstChild("EngineVersion"); if(!engineVersionNode.IsNull()) { m_engineVersion = Aws::Utils::Xml::DecodeEscapedXmlText(engineVersionNode.GetText()); m_engineVersionHasBeenSet = true; } XmlNode numCacheNodesNode = resultNode.FirstChild("NumCacheNodes"); if(!numCacheNodesNode.IsNull()) { m_numCacheNodes = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(numCacheNodesNode.GetText()).c_str()).c_str()); m_numCacheNodesHasBeenSet = true; } XmlNode preferredAvailabilityZoneNode = resultNode.FirstChild("PreferredAvailabilityZone"); if(!preferredAvailabilityZoneNode.IsNull()) { m_preferredAvailabilityZone = Aws::Utils::Xml::DecodeEscapedXmlText(preferredAvailabilityZoneNode.GetText()); m_preferredAvailabilityZoneHasBeenSet = true; } XmlNode cacheClusterCreateTimeNode = resultNode.FirstChild("CacheClusterCreateTime"); if(!cacheClusterCreateTimeNode.IsNull()) { m_cacheClusterCreateTime = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(cacheClusterCreateTimeNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601); m_cacheClusterCreateTimeHasBeenSet = true; } XmlNode preferredMaintenanceWindowNode = resultNode.FirstChild("PreferredMaintenanceWindow"); if(!preferredMaintenanceWindowNode.IsNull()) { m_preferredMaintenanceWindow = Aws::Utils::Xml::DecodeEscapedXmlText(preferredMaintenanceWindowNode.GetText()); m_preferredMaintenanceWindowHasBeenSet = true; } XmlNode topicArnNode = resultNode.FirstChild("TopicArn"); if(!topicArnNode.IsNull()) { m_topicArn = Aws::Utils::Xml::DecodeEscapedXmlText(topicArnNode.GetText()); m_topicArnHasBeenSet = true; } XmlNode portNode = resultNode.FirstChild("Port"); if(!portNode.IsNull()) { m_port = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(portNode.GetText()).c_str()).c_str()); m_portHasBeenSet = true; } XmlNode cacheParameterGroupNameNode = resultNode.FirstChild("CacheParameterGroupName"); if(!cacheParameterGroupNameNode.IsNull()) { m_cacheParameterGroupName = Aws::Utils::Xml::DecodeEscapedXmlText(cacheParameterGroupNameNode.GetText()); m_cacheParameterGroupNameHasBeenSet = true; } XmlNode cacheSubnetGroupNameNode = resultNode.FirstChild("CacheSubnetGroupName"); if(!cacheSubnetGroupNameNode.IsNull()) { m_cacheSubnetGroupName = Aws::Utils::Xml::DecodeEscapedXmlText(cacheSubnetGroupNameNode.GetText()); m_cacheSubnetGroupNameHasBeenSet = true; } XmlNode vpcIdNode = resultNode.FirstChild("VpcId"); if(!vpcIdNode.IsNull()) { m_vpcId = Aws::Utils::Xml::DecodeEscapedXmlText(vpcIdNode.GetText()); m_vpcIdHasBeenSet = true; } XmlNode autoMinorVersionUpgradeNode = resultNode.FirstChild("AutoMinorVersionUpgrade"); if(!autoMinorVersionUpgradeNode.IsNull()) { m_autoMinorVersionUpgrade = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(autoMinorVersionUpgradeNode.GetText()).c_str()).c_str()); m_autoMinorVersionUpgradeHasBeenSet = true; } XmlNode snapshotRetentionLimitNode = resultNode.FirstChild("SnapshotRetentionLimit"); if(!snapshotRetentionLimitNode.IsNull()) { m_snapshotRetentionLimit = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(snapshotRetentionLimitNode.GetText()).c_str()).c_str()); m_snapshotRetentionLimitHasBeenSet = true; } XmlNode snapshotWindowNode = resultNode.FirstChild("SnapshotWindow"); if(!snapshotWindowNode.IsNull()) { m_snapshotWindow = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotWindowNode.GetText()); m_snapshotWindowHasBeenSet = true; } XmlNode numNodeGroupsNode = resultNode.FirstChild("NumNodeGroups"); if(!numNodeGroupsNode.IsNull()) { m_numNodeGroups = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(numNodeGroupsNode.GetText()).c_str()).c_str()); m_numNodeGroupsHasBeenSet = true; } XmlNode automaticFailoverNode = resultNode.FirstChild("AutomaticFailover"); if(!automaticFailoverNode.IsNull()) { m_automaticFailover = AutomaticFailoverStatusMapper::GetAutomaticFailoverStatusForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(automaticFailoverNode.GetText()).c_str()).c_str()); m_automaticFailoverHasBeenSet = true; } XmlNode nodeSnapshotsNode = resultNode.FirstChild("NodeSnapshots"); if(!nodeSnapshotsNode.IsNull()) { XmlNode nodeSnapshotsMember = nodeSnapshotsNode.FirstChild("NodeSnapshot"); while(!nodeSnapshotsMember.IsNull()) { m_nodeSnapshots.push_back(nodeSnapshotsMember); nodeSnapshotsMember = nodeSnapshotsMember.NextNode("NodeSnapshot"); } m_nodeSnapshotsHasBeenSet = true; } XmlNode kmsKeyIdNode = resultNode.FirstChild("KmsKeyId"); if(!kmsKeyIdNode.IsNull()) { m_kmsKeyId = Aws::Utils::Xml::DecodeEscapedXmlText(kmsKeyIdNode.GetText()); m_kmsKeyIdHasBeenSet = true; } } return *this; } void Snapshot::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_snapshotNameHasBeenSet) { oStream << location << index << locationValue << ".SnapshotName=" << StringUtils::URLEncode(m_snapshotName.c_str()) << "&"; } if(m_replicationGroupIdHasBeenSet) { oStream << location << index << locationValue << ".ReplicationGroupId=" << StringUtils::URLEncode(m_replicationGroupId.c_str()) << "&"; } if(m_replicationGroupDescriptionHasBeenSet) { oStream << location << index << locationValue << ".ReplicationGroupDescription=" << StringUtils::URLEncode(m_replicationGroupDescription.c_str()) << "&"; } if(m_cacheClusterIdHasBeenSet) { oStream << location << index << locationValue << ".CacheClusterId=" << StringUtils::URLEncode(m_cacheClusterId.c_str()) << "&"; } if(m_snapshotStatusHasBeenSet) { oStream << location << index << locationValue << ".SnapshotStatus=" << StringUtils::URLEncode(m_snapshotStatus.c_str()) << "&"; } if(m_snapshotSourceHasBeenSet) { oStream << location << index << locationValue << ".SnapshotSource=" << StringUtils::URLEncode(m_snapshotSource.c_str()) << "&"; } if(m_cacheNodeTypeHasBeenSet) { oStream << location << index << locationValue << ".CacheNodeType=" << StringUtils::URLEncode(m_cacheNodeType.c_str()) << "&"; } if(m_engineHasBeenSet) { oStream << location << index << locationValue << ".Engine=" << StringUtils::URLEncode(m_engine.c_str()) << "&"; } if(m_engineVersionHasBeenSet) { oStream << location << index << locationValue << ".EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&"; } if(m_numCacheNodesHasBeenSet) { oStream << location << index << locationValue << ".NumCacheNodes=" << m_numCacheNodes << "&"; } if(m_preferredAvailabilityZoneHasBeenSet) { oStream << location << index << locationValue << ".PreferredAvailabilityZone=" << StringUtils::URLEncode(m_preferredAvailabilityZone.c_str()) << "&"; } if(m_cacheClusterCreateTimeHasBeenSet) { oStream << location << index << locationValue << ".CacheClusterCreateTime=" << StringUtils::URLEncode(m_cacheClusterCreateTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_preferredMaintenanceWindowHasBeenSet) { oStream << location << index << locationValue << ".PreferredMaintenanceWindow=" << StringUtils::URLEncode(m_preferredMaintenanceWindow.c_str()) << "&"; } if(m_topicArnHasBeenSet) { oStream << location << index << locationValue << ".TopicArn=" << StringUtils::URLEncode(m_topicArn.c_str()) << "&"; } if(m_portHasBeenSet) { oStream << location << index << locationValue << ".Port=" << m_port << "&"; } if(m_cacheParameterGroupNameHasBeenSet) { oStream << location << index << locationValue << ".CacheParameterGroupName=" << StringUtils::URLEncode(m_cacheParameterGroupName.c_str()) << "&"; } if(m_cacheSubnetGroupNameHasBeenSet) { oStream << location << index << locationValue << ".CacheSubnetGroupName=" << StringUtils::URLEncode(m_cacheSubnetGroupName.c_str()) << "&"; } if(m_vpcIdHasBeenSet) { oStream << location << index << locationValue << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&"; } if(m_autoMinorVersionUpgradeHasBeenSet) { oStream << location << index << locationValue << ".AutoMinorVersionUpgrade=" << std::boolalpha << m_autoMinorVersionUpgrade << "&"; } if(m_snapshotRetentionLimitHasBeenSet) { oStream << location << index << locationValue << ".SnapshotRetentionLimit=" << m_snapshotRetentionLimit << "&"; } if(m_snapshotWindowHasBeenSet) { oStream << location << index << locationValue << ".SnapshotWindow=" << StringUtils::URLEncode(m_snapshotWindow.c_str()) << "&"; } if(m_numNodeGroupsHasBeenSet) { oStream << location << index << locationValue << ".NumNodeGroups=" << m_numNodeGroups << "&"; } if(m_automaticFailoverHasBeenSet) { oStream << location << index << locationValue << ".AutomaticFailover=" << AutomaticFailoverStatusMapper::GetNameForAutomaticFailoverStatus(m_automaticFailover) << "&"; } if(m_nodeSnapshotsHasBeenSet) { unsigned nodeSnapshotsIdx = 1; for(auto& item : m_nodeSnapshots) { Aws::StringStream nodeSnapshotsSs; nodeSnapshotsSs << location << index << locationValue << ".NodeSnapshot." << nodeSnapshotsIdx++; item.OutputToStream(oStream, nodeSnapshotsSs.str().c_str()); } } if(m_kmsKeyIdHasBeenSet) { oStream << location << index << locationValue << ".KmsKeyId=" << StringUtils::URLEncode(m_kmsKeyId.c_str()) << "&"; } } void Snapshot::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_snapshotNameHasBeenSet) { oStream << location << ".SnapshotName=" << StringUtils::URLEncode(m_snapshotName.c_str()) << "&"; } if(m_replicationGroupIdHasBeenSet) { oStream << location << ".ReplicationGroupId=" << StringUtils::URLEncode(m_replicationGroupId.c_str()) << "&"; } if(m_replicationGroupDescriptionHasBeenSet) { oStream << location << ".ReplicationGroupDescription=" << StringUtils::URLEncode(m_replicationGroupDescription.c_str()) << "&"; } if(m_cacheClusterIdHasBeenSet) { oStream << location << ".CacheClusterId=" << StringUtils::URLEncode(m_cacheClusterId.c_str()) << "&"; } if(m_snapshotStatusHasBeenSet) { oStream << location << ".SnapshotStatus=" << StringUtils::URLEncode(m_snapshotStatus.c_str()) << "&"; } if(m_snapshotSourceHasBeenSet) { oStream << location << ".SnapshotSource=" << StringUtils::URLEncode(m_snapshotSource.c_str()) << "&"; } if(m_cacheNodeTypeHasBeenSet) { oStream << location << ".CacheNodeType=" << StringUtils::URLEncode(m_cacheNodeType.c_str()) << "&"; } if(m_engineHasBeenSet) { oStream << location << ".Engine=" << StringUtils::URLEncode(m_engine.c_str()) << "&"; } if(m_engineVersionHasBeenSet) { oStream << location << ".EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&"; } if(m_numCacheNodesHasBeenSet) { oStream << location << ".NumCacheNodes=" << m_numCacheNodes << "&"; } if(m_preferredAvailabilityZoneHasBeenSet) { oStream << location << ".PreferredAvailabilityZone=" << StringUtils::URLEncode(m_preferredAvailabilityZone.c_str()) << "&"; } if(m_cacheClusterCreateTimeHasBeenSet) { oStream << location << ".CacheClusterCreateTime=" << StringUtils::URLEncode(m_cacheClusterCreateTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_preferredMaintenanceWindowHasBeenSet) { oStream << location << ".PreferredMaintenanceWindow=" << StringUtils::URLEncode(m_preferredMaintenanceWindow.c_str()) << "&"; } if(m_topicArnHasBeenSet) { oStream << location << ".TopicArn=" << StringUtils::URLEncode(m_topicArn.c_str()) << "&"; } if(m_portHasBeenSet) { oStream << location << ".Port=" << m_port << "&"; } if(m_cacheParameterGroupNameHasBeenSet) { oStream << location << ".CacheParameterGroupName=" << StringUtils::URLEncode(m_cacheParameterGroupName.c_str()) << "&"; } if(m_cacheSubnetGroupNameHasBeenSet) { oStream << location << ".CacheSubnetGroupName=" << StringUtils::URLEncode(m_cacheSubnetGroupName.c_str()) << "&"; } if(m_vpcIdHasBeenSet) { oStream << location << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&"; } if(m_autoMinorVersionUpgradeHasBeenSet) { oStream << location << ".AutoMinorVersionUpgrade=" << std::boolalpha << m_autoMinorVersionUpgrade << "&"; } if(m_snapshotRetentionLimitHasBeenSet) { oStream << location << ".SnapshotRetentionLimit=" << m_snapshotRetentionLimit << "&"; } if(m_snapshotWindowHasBeenSet) { oStream << location << ".SnapshotWindow=" << StringUtils::URLEncode(m_snapshotWindow.c_str()) << "&"; } if(m_numNodeGroupsHasBeenSet) { oStream << location << ".NumNodeGroups=" << m_numNodeGroups << "&"; } if(m_automaticFailoverHasBeenSet) { oStream << location << ".AutomaticFailover=" << AutomaticFailoverStatusMapper::GetNameForAutomaticFailoverStatus(m_automaticFailover) << "&"; } if(m_nodeSnapshotsHasBeenSet) { unsigned nodeSnapshotsIdx = 1; for(auto& item : m_nodeSnapshots) { Aws::StringStream nodeSnapshotsSs; nodeSnapshotsSs << location << ".NodeSnapshot." << nodeSnapshotsIdx++; item.OutputToStream(oStream, nodeSnapshotsSs.str().c_str()); } } if(m_kmsKeyIdHasBeenSet) { oStream << location << ".KmsKeyId=" << StringUtils::URLEncode(m_kmsKeyId.c_str()) << "&"; } } } // namespace Model } // namespace ElastiCache } // namespace Aws
cedral/aws-sdk-cpp
aws-cpp-sdk-elasticache/source/model/Snapshot.cpp
C++
apache-2.0
19,734
/* * Copyright 2016 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 com.google.schemaorg.core; import com.google.schemaorg.JsonLdContext; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.core.datatype.Date; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.PopularityScoreSpecification; import javax.annotation.Nullable; /** * Interface of <a * href="http://schema.org/MotorcycleDealer}">http://schema.org/MotorcycleDealer}</a>. */ public interface MotorcycleDealer extends AutomotiveBusiness { /** * Builder interface of <a * href="http://schema.org/MotorcycleDealer}">http://schema.org/MotorcycleDealer}</a>. */ public interface Builder extends AutomotiveBusiness.Builder { @Override Builder addJsonLdContext(@Nullable JsonLdContext context); @Override Builder addJsonLdContext(@Nullable JsonLdContext.Builder context); @Override Builder setJsonLdId(@Nullable String value); @Override Builder setJsonLdReverse(String property, Thing obj); @Override Builder setJsonLdReverse(String property, Thing.Builder builder); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(PropertyValue value); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(PropertyValue.Builder value); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(String value); /** Add a value to property additionalType. */ Builder addAdditionalType(URL value); /** Add a value to property additionalType. */ Builder addAdditionalType(String value); /** Add a value to property address. */ Builder addAddress(PostalAddress value); /** Add a value to property address. */ Builder addAddress(PostalAddress.Builder value); /** Add a value to property address. */ Builder addAddress(Text value); /** Add a value to property address. */ Builder addAddress(String value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating.Builder value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(String value); /** Add a value to property alternateName. */ Builder addAlternateName(Text value); /** Add a value to property alternateName. */ Builder addAlternateName(String value); /** Add a value to property alumni. */ Builder addAlumni(Person value); /** Add a value to property alumni. */ Builder addAlumni(Person.Builder value); /** Add a value to property alumni. */ Builder addAlumni(String value); /** Add a value to property areaServed. */ Builder addAreaServed(AdministrativeArea value); /** Add a value to property areaServed. */ Builder addAreaServed(AdministrativeArea.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(GeoShape value); /** Add a value to property areaServed. */ Builder addAreaServed(GeoShape.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(Place value); /** Add a value to property areaServed. */ Builder addAreaServed(Place.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(Text value); /** Add a value to property areaServed. */ Builder addAreaServed(String value); /** Add a value to property award. */ Builder addAward(Text value); /** Add a value to property award. */ Builder addAward(String value); /** Add a value to property awards. */ Builder addAwards(Text value); /** Add a value to property awards. */ Builder addAwards(String value); /** Add a value to property branchCode. */ Builder addBranchCode(Text value); /** Add a value to property branchCode. */ Builder addBranchCode(String value); /** Add a value to property branchOf. */ Builder addBranchOf(Organization value); /** Add a value to property branchOf. */ Builder addBranchOf(Organization.Builder value); /** Add a value to property branchOf. */ Builder addBranchOf(String value); /** Add a value to property brand. */ Builder addBrand(Brand value); /** Add a value to property brand. */ Builder addBrand(Brand.Builder value); /** Add a value to property brand. */ Builder addBrand(Organization value); /** Add a value to property brand. */ Builder addBrand(Organization.Builder value); /** Add a value to property brand. */ Builder addBrand(String value); /** Add a value to property contactPoint. */ Builder addContactPoint(ContactPoint value); /** Add a value to property contactPoint. */ Builder addContactPoint(ContactPoint.Builder value); /** Add a value to property contactPoint. */ Builder addContactPoint(String value); /** Add a value to property contactPoints. */ Builder addContactPoints(ContactPoint value); /** Add a value to property contactPoints. */ Builder addContactPoints(ContactPoint.Builder value); /** Add a value to property contactPoints. */ Builder addContactPoints(String value); /** Add a value to property containedIn. */ Builder addContainedIn(Place value); /** Add a value to property containedIn. */ Builder addContainedIn(Place.Builder value); /** Add a value to property containedIn. */ Builder addContainedIn(String value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(Place value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(Place.Builder value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(String value); /** Add a value to property containsPlace. */ Builder addContainsPlace(Place value); /** Add a value to property containsPlace. */ Builder addContainsPlace(Place.Builder value); /** Add a value to property containsPlace. */ Builder addContainsPlace(String value); /** Add a value to property currenciesAccepted. */ Builder addCurrenciesAccepted(Text value); /** Add a value to property currenciesAccepted. */ Builder addCurrenciesAccepted(String value); /** Add a value to property department. */ Builder addDepartment(Organization value); /** Add a value to property department. */ Builder addDepartment(Organization.Builder value); /** Add a value to property department. */ Builder addDepartment(String value); /** Add a value to property description. */ Builder addDescription(Text value); /** Add a value to property description. */ Builder addDescription(String value); /** Add a value to property dissolutionDate. */ Builder addDissolutionDate(Date value); /** Add a value to property dissolutionDate. */ Builder addDissolutionDate(String value); /** Add a value to property duns. */ Builder addDuns(Text value); /** Add a value to property duns. */ Builder addDuns(String value); /** Add a value to property email. */ Builder addEmail(Text value); /** Add a value to property email. */ Builder addEmail(String value); /** Add a value to property employee. */ Builder addEmployee(Person value); /** Add a value to property employee. */ Builder addEmployee(Person.Builder value); /** Add a value to property employee. */ Builder addEmployee(String value); /** Add a value to property employees. */ Builder addEmployees(Person value); /** Add a value to property employees. */ Builder addEmployees(Person.Builder value); /** Add a value to property employees. */ Builder addEmployees(String value); /** Add a value to property event. */ Builder addEvent(Event value); /** Add a value to property event. */ Builder addEvent(Event.Builder value); /** Add a value to property event. */ Builder addEvent(String value); /** Add a value to property events. */ Builder addEvents(Event value); /** Add a value to property events. */ Builder addEvents(Event.Builder value); /** Add a value to property events. */ Builder addEvents(String value); /** Add a value to property faxNumber. */ Builder addFaxNumber(Text value); /** Add a value to property faxNumber. */ Builder addFaxNumber(String value); /** Add a value to property founder. */ Builder addFounder(Person value); /** Add a value to property founder. */ Builder addFounder(Person.Builder value); /** Add a value to property founder. */ Builder addFounder(String value); /** Add a value to property founders. */ Builder addFounders(Person value); /** Add a value to property founders. */ Builder addFounders(Person.Builder value); /** Add a value to property founders. */ Builder addFounders(String value); /** Add a value to property foundingDate. */ Builder addFoundingDate(Date value); /** Add a value to property foundingDate. */ Builder addFoundingDate(String value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(Place value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(Place.Builder value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(String value); /** Add a value to property geo. */ Builder addGeo(GeoCoordinates value); /** Add a value to property geo. */ Builder addGeo(GeoCoordinates.Builder value); /** Add a value to property geo. */ Builder addGeo(GeoShape value); /** Add a value to property geo. */ Builder addGeo(GeoShape.Builder value); /** Add a value to property geo. */ Builder addGeo(String value); /** Add a value to property globalLocationNumber. */ Builder addGlobalLocationNumber(Text value); /** Add a value to property globalLocationNumber. */ Builder addGlobalLocationNumber(String value); /** Add a value to property hasMap. */ Builder addHasMap(Map value); /** Add a value to property hasMap. */ Builder addHasMap(Map.Builder value); /** Add a value to property hasMap. */ Builder addHasMap(URL value); /** Add a value to property hasMap. */ Builder addHasMap(String value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(OfferCatalog value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(OfferCatalog.Builder value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(String value); /** Add a value to property hasPOS. */ Builder addHasPOS(Place value); /** Add a value to property hasPOS. */ Builder addHasPOS(Place.Builder value); /** Add a value to property hasPOS. */ Builder addHasPOS(String value); /** Add a value to property image. */ Builder addImage(ImageObject value); /** Add a value to property image. */ Builder addImage(ImageObject.Builder value); /** Add a value to property image. */ Builder addImage(URL value); /** Add a value to property image. */ Builder addImage(String value); /** Add a value to property isicV4. */ Builder addIsicV4(Text value); /** Add a value to property isicV4. */ Builder addIsicV4(String value); /** Add a value to property legalName. */ Builder addLegalName(Text value); /** Add a value to property legalName. */ Builder addLegalName(String value); /** Add a value to property location. */ Builder addLocation(Place value); /** Add a value to property location. */ Builder addLocation(Place.Builder value); /** Add a value to property location. */ Builder addLocation(PostalAddress value); /** Add a value to property location. */ Builder addLocation(PostalAddress.Builder value); /** Add a value to property location. */ Builder addLocation(Text value); /** Add a value to property location. */ Builder addLocation(String value); /** Add a value to property logo. */ Builder addLogo(ImageObject value); /** Add a value to property logo. */ Builder addLogo(ImageObject.Builder value); /** Add a value to property logo. */ Builder addLogo(URL value); /** Add a value to property logo. */ Builder addLogo(String value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork.Builder value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(URL value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(String value); /** Add a value to property makesOffer. */ Builder addMakesOffer(Offer value); /** Add a value to property makesOffer. */ Builder addMakesOffer(Offer.Builder value); /** Add a value to property makesOffer. */ Builder addMakesOffer(String value); /** Add a value to property map. */ Builder addMap(URL value); /** Add a value to property map. */ Builder addMap(String value); /** Add a value to property maps. */ Builder addMaps(URL value); /** Add a value to property maps. */ Builder addMaps(String value); /** Add a value to property member. */ Builder addMember(Organization value); /** Add a value to property member. */ Builder addMember(Organization.Builder value); /** Add a value to property member. */ Builder addMember(Person value); /** Add a value to property member. */ Builder addMember(Person.Builder value); /** Add a value to property member. */ Builder addMember(String value); /** Add a value to property memberOf. */ Builder addMemberOf(Organization value); /** Add a value to property memberOf. */ Builder addMemberOf(Organization.Builder value); /** Add a value to property memberOf. */ Builder addMemberOf(ProgramMembership value); /** Add a value to property memberOf. */ Builder addMemberOf(ProgramMembership.Builder value); /** Add a value to property memberOf. */ Builder addMemberOf(String value); /** Add a value to property members. */ Builder addMembers(Organization value); /** Add a value to property members. */ Builder addMembers(Organization.Builder value); /** Add a value to property members. */ Builder addMembers(Person value); /** Add a value to property members. */ Builder addMembers(Person.Builder value); /** Add a value to property members. */ Builder addMembers(String value); /** Add a value to property naics. */ Builder addNaics(Text value); /** Add a value to property naics. */ Builder addNaics(String value); /** Add a value to property name. */ Builder addName(Text value); /** Add a value to property name. */ Builder addName(String value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(QuantitativeValue value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(QuantitativeValue.Builder value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(String value); /** Add a value to property openingHours. */ Builder addOpeningHours(Text value); /** Add a value to property openingHours. */ Builder addOpeningHours(String value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(OpeningHoursSpecification value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(OpeningHoursSpecification.Builder value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(String value); /** Add a value to property owns. */ Builder addOwns(OwnershipInfo value); /** Add a value to property owns. */ Builder addOwns(OwnershipInfo.Builder value); /** Add a value to property owns. */ Builder addOwns(Product value); /** Add a value to property owns. */ Builder addOwns(Product.Builder value); /** Add a value to property owns. */ Builder addOwns(String value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(Organization value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(Organization.Builder value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(String value); /** Add a value to property paymentAccepted. */ Builder addPaymentAccepted(Text value); /** Add a value to property paymentAccepted. */ Builder addPaymentAccepted(String value); /** Add a value to property photo. */ Builder addPhoto(ImageObject value); /** Add a value to property photo. */ Builder addPhoto(ImageObject.Builder value); /** Add a value to property photo. */ Builder addPhoto(Photograph value); /** Add a value to property photo. */ Builder addPhoto(Photograph.Builder value); /** Add a value to property photo. */ Builder addPhoto(String value); /** Add a value to property photos. */ Builder addPhotos(ImageObject value); /** Add a value to property photos. */ Builder addPhotos(ImageObject.Builder value); /** Add a value to property photos. */ Builder addPhotos(Photograph value); /** Add a value to property photos. */ Builder addPhotos(Photograph.Builder value); /** Add a value to property photos. */ Builder addPhotos(String value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action.Builder value); /** Add a value to property potentialAction. */ Builder addPotentialAction(String value); /** Add a value to property priceRange. */ Builder addPriceRange(Text value); /** Add a value to property priceRange. */ Builder addPriceRange(String value); /** Add a value to property review. */ Builder addReview(Review value); /** Add a value to property review. */ Builder addReview(Review.Builder value); /** Add a value to property review. */ Builder addReview(String value); /** Add a value to property reviews. */ Builder addReviews(Review value); /** Add a value to property reviews. */ Builder addReviews(Review.Builder value); /** Add a value to property reviews. */ Builder addReviews(String value); /** Add a value to property sameAs. */ Builder addSameAs(URL value); /** Add a value to property sameAs. */ Builder addSameAs(String value); /** Add a value to property seeks. */ Builder addSeeks(Demand value); /** Add a value to property seeks. */ Builder addSeeks(Demand.Builder value); /** Add a value to property seeks. */ Builder addSeeks(String value); /** Add a value to property serviceArea. */ Builder addServiceArea(AdministrativeArea value); /** Add a value to property serviceArea. */ Builder addServiceArea(AdministrativeArea.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(GeoShape value); /** Add a value to property serviceArea. */ Builder addServiceArea(GeoShape.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(Place value); /** Add a value to property serviceArea. */ Builder addServiceArea(Place.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(String value); /** Add a value to property subOrganization. */ Builder addSubOrganization(Organization value); /** Add a value to property subOrganization. */ Builder addSubOrganization(Organization.Builder value); /** Add a value to property subOrganization. */ Builder addSubOrganization(String value); /** Add a value to property taxID. */ Builder addTaxID(Text value); /** Add a value to property taxID. */ Builder addTaxID(String value); /** Add a value to property telephone. */ Builder addTelephone(Text value); /** Add a value to property telephone. */ Builder addTelephone(String value); /** Add a value to property url. */ Builder addUrl(URL value); /** Add a value to property url. */ Builder addUrl(String value); /** Add a value to property vatID. */ Builder addVatID(Text value); /** Add a value to property vatID. */ Builder addVatID(String value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article.Builder value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(String value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification.Builder value); /** Add a value to property popularityScore. */ Builder addPopularityScore(String value); /** * Add a value to property. * * @param name The property name. * @param value The value of the property. */ Builder addProperty(String name, SchemaOrgType value); /** * Add a value to property. * * @param name The property name. * @param builder The schema.org object builder for the property value. */ Builder addProperty(String name, Thing.Builder builder); /** * Add a value to property. * * @param name The property name. * @param value The string value of the property. */ Builder addProperty(String name, String value); /** Build a {@link MotorcycleDealer} object. */ MotorcycleDealer build(); } }
google/schemaorg-java
src/main/java/com/google/schemaorg/core/MotorcycleDealer.java
Java
apache-2.0
23,054
# coding=utf-8 # Copyright 2017 The DLT2T 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. """Tests for DLT2T.registry.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from DLT2T.utils import modality from DLT2T.utils import registry from DLT2T.utils import t2t_model import tensorflow as tf # pylint: disable=unused-variable class ModelRegistryTest(tf.test.TestCase): def setUp(self): registry._reset() def testT2TModelRegistration(self): @registry.register_model class MyModel1(t2t_model.T2TModel): pass model = registry.model("my_model1") self.assertTrue(model is MyModel1) def testNamedRegistration(self): @registry.register_model("model2") class MyModel1(t2t_model.T2TModel): pass model = registry.model("model2") self.assertTrue(model is MyModel1) def testNonT2TModelRegistration(self): @registry.register_model def model_fn(): pass model = registry.model("model_fn") self.assertTrue(model is model_fn) def testUnknownModel(self): with self.assertRaisesRegexp(LookupError, "never registered"): registry.model("not_registered") def testDuplicateRegistration(self): @registry.register_model def m1(): pass with self.assertRaisesRegexp(LookupError, "already registered"): @registry.register_model("m1") def m2(): pass def testListModels(self): @registry.register_model def m1(): pass @registry.register_model def m2(): pass self.assertSetEqual(set(["m1", "m2"]), set(registry.list_models())) def testSnakeCase(self): convert = registry._convert_camel_to_snake self.assertEqual("typical_camel_case", convert("TypicalCamelCase")) self.assertEqual("numbers_fuse2gether", convert("NumbersFuse2gether")) self.assertEqual("numbers_fuse2_gether", convert("NumbersFuse2Gether")) self.assertEqual("lstm_seq2_seq", convert("LSTMSeq2Seq")) self.assertEqual("starts_lower", convert("startsLower")) self.assertEqual("starts_lower_caps", convert("startsLowerCAPS")) self.assertEqual("caps_fuse_together", convert("CapsFUSETogether")) self.assertEqual("startscap", convert("Startscap")) self.assertEqual("s_tartscap", convert("STartscap")) class HParamRegistryTest(tf.test.TestCase): def setUp(self): registry._reset() def testHParamSet(self): @registry.register_hparams def my_hparams_set(): pass @registry.register_ranged_hparams def my_hparams_range(_): pass self.assertTrue(registry.hparams("my_hparams_set") is my_hparams_set) self.assertTrue( registry.ranged_hparams("my_hparams_range") is my_hparams_range) def testNamedRegistration(self): @registry.register_hparams("a") def my_hparams_set(): pass @registry.register_ranged_hparams("a") def my_hparams_range(_): pass self.assertTrue(registry.hparams("a") is my_hparams_set) self.assertTrue(registry.ranged_hparams("a") is my_hparams_range) def testUnknownHparams(self): with self.assertRaisesRegexp(LookupError, "never registered"): registry.hparams("not_registered") with self.assertRaisesRegexp(LookupError, "never registered"): registry.ranged_hparams("not_registered") def testDuplicateRegistration(self): @registry.register_hparams def hp1(): pass with self.assertRaisesRegexp(LookupError, "already registered"): @registry.register_hparams("hp1") def hp2(): pass @registry.register_ranged_hparams def rhp1(_): pass with self.assertRaisesRegexp(LookupError, "already registered"): @registry.register_ranged_hparams("rhp1") def rhp2(_): pass def testListHparams(self): @registry.register_hparams def hp1(): pass @registry.register_hparams("hp2_named") def hp2(): pass @registry.register_ranged_hparams def rhp1(_): pass @registry.register_ranged_hparams("rhp2_named") def rhp2(_): pass self.assertSetEqual(set(["hp1", "hp2_named"]), set(registry.list_hparams())) self.assertSetEqual( set(["rhp1", "rhp2_named"]), set(registry.list_ranged_hparams())) def testRangeSignatureCheck(self): with self.assertRaisesRegexp(ValueError, "must take a single argument"): @registry.register_ranged_hparams def rhp_bad(): pass with self.assertRaisesRegexp(ValueError, "must take a single argument"): @registry.register_ranged_hparams def rhp_bad2(a, b): # pylint: disable=unused-argument pass class ModalityRegistryTest(tf.test.TestCase): def setUp(self): registry._reset() def testModalityRegistration(self): @registry.register_symbol_modality class MySymbolModality(modality.Modality): pass @registry.register_audio_modality class MyAudioModality(modality.Modality): pass @registry.register_image_modality class MyImageModality(modality.Modality): pass @registry.register_class_label_modality class MyClassLabelModality(modality.Modality): pass self.assertTrue( registry.symbol_modality("my_symbol_modality") is MySymbolModality) self.assertTrue( registry.audio_modality("my_audio_modality") is MyAudioModality) self.assertTrue( registry.image_modality("my_image_modality") is MyImageModality) self.assertTrue( registry.class_label_modality("my_class_label_modality") is MyClassLabelModality) def testDefaultNameLookup(self): @registry.register_symbol_modality("default") class MyDefaultModality(modality.Modality): pass self.assertTrue(registry.symbol_modality() is MyDefaultModality) def testList(self): @registry.register_symbol_modality class MySymbolModality(modality.Modality): pass @registry.register_audio_modality class MyAudioModality(modality.Modality): pass @registry.register_image_modality class MyImageModality(modality.Modality): pass @registry.register_class_label_modality class MyClassLabelModality(modality.Modality): pass expected = [ "symbol:my_symbol_modality", "audio:my_audio_modality", "image:my_image_modality", "class_label:my_class_label_modality" ] self.assertSetEqual(set(registry.list_modalities()), set(expected)) if __name__ == "__main__": tf.test.main()
renqianluo/DLT2T
DLT2T/utils/registry_test.py
Python
apache-2.0
7,045
package xworker.swt.reacts; import org.xmeta.ActionContext; /** * 创建DataReactor的接口。 * * @author zyx * */ public interface DataReactorCreator { /** * 创建DataReactor。 * * @param control * @param action 动作 * @param actionContext * @return */ public DataReactor create(Object control, String action, ActionContext actionContext); }
x-meta/xworker
xworker_swt/src/main/java/xworker/swt/reacts/DataReactorCreator.java
Java
apache-2.0
397
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.restapi.change; import static java.util.stream.Collectors.joining; import com.google.gerrit.extensions.common.Input; import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDbUtil; import com.google.gerrit.server.CommentsUtil; import com.google.gerrit.server.change.ChangeResource; import com.google.gerrit.server.notedb.ChangeBundle; import com.google.gerrit.server.notedb.ChangeBundleReader; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.notedb.NotesMigration; import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.io.IOException; import java.util.List; import org.eclipse.jgit.errors.ConfigInvalidException; @Singleton public class Rebuild implements RestModifyView<ChangeResource, Input> { private final Provider<ReviewDb> db; private final NotesMigration migration; private final ChangeRebuilder rebuilder; private final ChangeBundleReader bundleReader; private final CommentsUtil commentsUtil; private final ChangeNotes.Factory notesFactory; @Inject Rebuild( Provider<ReviewDb> db, NotesMigration migration, ChangeRebuilder rebuilder, ChangeBundleReader bundleReader, CommentsUtil commentsUtil, ChangeNotes.Factory notesFactory) { this.db = db; this.migration = migration; this.rebuilder = rebuilder; this.bundleReader = bundleReader; this.commentsUtil = commentsUtil; this.notesFactory = notesFactory; } @Override public BinaryResult apply(ChangeResource rsrc, Input input) throws ResourceNotFoundException, IOException, OrmException, ConfigInvalidException, ResourceConflictException { if (!migration.commitChangeWrites()) { throw new ResourceNotFoundException(); } if (!migration.readChanges()) { // ChangeBundle#fromNotes currently doesn't work if reading isn't enabled, // so don't attempt a diff. rebuild(rsrc); return BinaryResult.create("Rebuilt change successfully"); } // Not the same transaction as the rebuild, so may result in spurious diffs // in the case of races. This should be easy enough to detect by rerunning. ChangeBundle reviewDbBundle = bundleReader.fromReviewDb(ReviewDbUtil.unwrapDb(db.get()), rsrc.getId()); if (reviewDbBundle == null) { throw new ResourceConflictException("change is missing in ReviewDb"); } rebuild(rsrc); ChangeNotes notes = notesFactory.create(db.get(), rsrc.getChange().getProject(), rsrc.getId()); ChangeBundle noteDbBundle = ChangeBundle.fromNotes(commentsUtil, notes); List<String> diffs = reviewDbBundle.differencesFrom(noteDbBundle); if (diffs.isEmpty()) { return BinaryResult.create("No differences between ReviewDb and NoteDb"); } return BinaryResult.create( diffs.stream().collect(joining("\n", "Differences between ReviewDb and NoteDb:\n", "\n"))); } private void rebuild(ChangeResource rsrc) throws ResourceNotFoundException, OrmException, IOException { try { rebuilder.rebuild(db.get(), rsrc.getId()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(IdString.fromDecoded(rsrc.getId().toString()), e); } } }
WANdisco/gerrit
java/com/google/gerrit/server/restapi/change/Rebuild.java
Java
apache-2.0
4,432
using System; using strange.extensions.mediation.api; namespace strange.examples.strangerobots.game { public class ObjectStatus { public int x; public int y; public ObjectStatus(int xx, int yy) { x = xx; y = yy; destroyed = false; } public IView view{ get; set; } public bool destroyed { get; set; } } }
strangeioc/strangerobots
StrangeRobots/Assets/scripts/strangerobots/game/model/ObjectStatus.cs
C#
apache-2.0
335
package redis.clients.jedis.valueobject; /** * * @author leifu * @Date 2017年2月14日 * @Time 下午4:58:52 */ public class RangeRankVO { private final long min; private final long max; public RangeRankVO(long min, long max) { this.min = min; this.max = max; } public long getMin() { return min; } public long getMax() { return max; } }
sohutv/cachecloud
cachecloud-client/cachecloud-jedis/src/main/java/redis/clients/jedis/valueobject/RangeRankVO.java
Java
apache-2.0
446
# =============================================================================== # Copyright 2014 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= # ============= standard library imports ======================== # ============= local library imports ========================== from __future__ import absolute_import from pychron.hardware.core.core_device import CoreDevice class TempHumMicroServer(CoreDevice): """ http://www.omega.com/Manuals/manualpdf/M3861.pdf iServer MicroServer tested with iTHX-W """ scan_func = 'read_temperature' def read_temperature(self, **kw): v = self.ask('*SRTF', timeout=1.0, **kw) return self._parse_response(v) def read_humidity(self, **kw): v = self.ask('*SRH', timeout=1.0, **kw) return self._parse_response(v) def _parse_response(self, v): try: return float(v) except (AttributeError, ValueError, TypeError): return self.get_random_value() # ============= EOF =============================================
UManPychron/pychron
pychron/hardware/environmental_probe.py
Python
apache-2.0
1,717
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xiongyingqi.util.xml; import com.xiongyingqi.util.Assert; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import java.util.*; /** * Simple {@code javax.xml.namespace.NamespaceContext} implementation. Follows the standard * {@code NamespaceContext} contract, and is loadable via a {@code java.util.Map} or * {@code java.util.Properties} object * * @author Arjen Poutsma * @since 3.0 */ public class SimpleNamespaceContext implements NamespaceContext { private Map<String, String> prefixToNamespaceUri = new HashMap<String, String>(); private Map<String, List<String>> namespaceUriToPrefixes = new HashMap<String, List<String>>(); private String defaultNamespaceUri = ""; @Override public String getNamespaceURI(String prefix) { Assert.notNull(prefix, "prefix is null"); if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { return XMLConstants.XML_NS_URI; } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } else if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { return defaultNamespaceUri; } else if (prefixToNamespaceUri.containsKey(prefix)) { return prefixToNamespaceUri.get(prefix); } return ""; } @Override public String getPrefix(String namespaceUri) { List<?> prefixes = getPrefixesInternal(namespaceUri); return prefixes.isEmpty() ? null : (String) prefixes.get(0); } @Override public Iterator<String> getPrefixes(String namespaceUri) { return getPrefixesInternal(namespaceUri).iterator(); } /** * Sets the bindings for this namespace context. The supplied map must consist of string key value pairs. * * @param bindings the bindings */ public void setBindings(Map<String, String> bindings) { for (Map.Entry<String, String> entry : bindings.entrySet()) { bindNamespaceUri(entry.getKey(), entry.getValue()); } } /** * Binds the given namespace as default namespace. * * @param namespaceUri the namespace uri */ public void bindDefaultNamespaceUri(String namespaceUri) { bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri); } /** * Binds the given prefix to the given namespace. * * @param prefix the namespace prefix * @param namespaceUri the namespace uri */ public void bindNamespaceUri(String prefix, String namespaceUri) { Assert.notNull(prefix, "No prefix given"); Assert.notNull(namespaceUri, "No namespaceUri given"); if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { defaultNamespaceUri = namespaceUri; } else { prefixToNamespaceUri.put(prefix, namespaceUri); getPrefixesInternal(namespaceUri).add(prefix); } } /** * Removes all declared prefixes. */ public void clear() { prefixToNamespaceUri.clear(); } /** * Returns all declared prefixes. * * @return the declared prefixes */ public Iterator<String> getBoundPrefixes() { return prefixToNamespaceUri.keySet().iterator(); } private List<String> getPrefixesInternal(String namespaceUri) { if (defaultNamespaceUri.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.DEFAULT_NS_PREFIX); } else if (XMLConstants.XML_NS_URI.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.XML_NS_PREFIX); } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.XMLNS_ATTRIBUTE); } else { List<String> list = namespaceUriToPrefixes.get(namespaceUri); if (list == null) { list = new ArrayList<String>(); namespaceUriToPrefixes.put(namespaceUri, list); } return list; } } /** * Removes the given prefix from this context. * * @param prefix the prefix to be removed */ public void removeBinding(String prefix) { if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { defaultNamespaceUri = ""; } else { String namespaceUri = prefixToNamespaceUri.remove(prefix); List<String> prefixes = getPrefixesInternal(namespaceUri); prefixes.remove(prefix); } } }
blademainer/common_utils
common_helper/src/main/java/com/xiongyingqi/util/xml/SimpleNamespaceContext.java
Java
apache-2.0
5,171
/* * Copyright 2011 Jan Kronquist. * * 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.jayway.xml; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class CDataTransformer { public String transform(NodeList list) { Node node = list.item(0); if (node != null) { return node.getNodeValue(); } return null; } }
jankronquist/AirportWeather
src/main/java/com/jayway/xml/CDataTransformer.java
Java
apache-2.0
857
/* * * Copyright (c) 2020, Wasiq Bhamla. * * 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.github.wasiqb.coteafs.appium.config.device.android; import lombok.Data; /** * @author Wasiq Bhamla * @since Mar 13, 2021 */ @Data public class AdbSetting { private String host; private int port; private long timeout; }
WasiqB/coteafs-appium
src/main/java/com/github/wasiqb/coteafs/appium/config/device/android/AdbSetting.java
Java
apache-2.0
874
package com.app.apt.processor; import com.app.annotation.apt.ApiFactory; import com.app.apt.AnnotationProcessor; import com.app.apt.inter.IProcessor; import com.app.apt.util.Utils; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annotation.processing.FilerException; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.tools.Diagnostic; import static com.squareup.javapoet.TypeSpec.classBuilder; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; /** * Created by baixiaokang on 16/12/28. */ public class ApiFactoryProcessor implements IProcessor { @Override public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) { String CLASS_NAME = "ApiFactory"; String DATA_ARR_CLASS = "DataArr"; TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ API工厂 此类由apt自动生成"); try { for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ApiFactory.class))) { mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString()); for (Element e : element.getEnclosedElements()) { ExecutableElement executableElement = (ExecutableElement) e; MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(e.getSimpleName().toString()) .addJavadoc("@此方法由apt自动生成") .addModifiers(PUBLIC, STATIC); if (TypeName.get(executableElement.getReturnType()).toString().contains(DATA_ARR_CLASS)) {//返回列表数据 methodBuilder.returns(ClassName.get("io.reactivex", "Flowable")); Map<String, Object> params = new HashMap<>(); methodBuilder.addParameter(params.getClass(), "param"); ClassName apiUtil = ClassName.get("com.base.util", "ApiUtil"); ClassName C = ClassName.get("com", "C"); CodeBlock.Builder blockBuilder = CodeBlock.builder(); int len = executableElement.getParameters().size(); for (int i = 0; i < len; i++) { VariableElement ep = executableElement.getParameters().get(i); boolean isLast = i == len - 1; String split = (isLast ? "" : ","); switch (ep.getSimpleName().toString()) { case "include": blockBuilder.add("$L.getInclude(param)" + split, apiUtil); break; case "where": blockBuilder.add("$L.getWhere(param)" + split, apiUtil); break; case "skip": blockBuilder.add("$L.getSkip(param)" + split, apiUtil); break; case "limit": blockBuilder.add("$L.PAGE_COUNT" + split, C); break; case "order": blockBuilder.add("$L._CREATED_AT" + split, C); break; } } methodBuilder.addStatement( "return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())" , ClassName.get("com.api", "Api") , e.getSimpleName().toString() , blockBuilder.build().toString() , ClassName.get("com.base.util.helper", "RxSchedulers")); tb.addMethod(methodBuilder.build()); } else {//返回普通数据 methodBuilder.returns(TypeName.get(executableElement.getReturnType())); String paramsString = ""; for (VariableElement ep : executableElement.getParameters()) { methodBuilder.addParameter(TypeName.get(ep.asType()), ep.getSimpleName().toString()); paramsString += ep.getSimpleName().toString() + ","; } methodBuilder.addStatement( "return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())" , ClassName.get("com.api", "Api") , e.getSimpleName().toString() , paramsString.substring(0, paramsString.length() - 1) , ClassName.get("com.base.util.helper", "RxSchedulers")); tb.addMethod(methodBuilder.build()); } } } JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();// 生成源代码 javaFile.writeTo(mAbstractProcessor.mFiler);// 在 app module/build/generated/source/apt 生成一份源代码 } catch (FilerException e) { } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
weiwenqiang/GitHub
MVP/RxJava2ToMVP/T-MVP-master/apt/src/main/java/com/app/apt/processor/ApiFactoryProcessor.java
Java
apache-2.0
6,331
package main import ( "fmt" "github.com/gorilla/websocket" log "gopkg.in/inconshreveable/log15.v2" ) type storageMock struct { d *Daemon sType storageType log log.Logger storageShared } func (s *storageMock) Init(config map[string]interface{}) (storage, error) { s.sType = storageTypeMock s.sTypeName = storageTypeToString(storageTypeMock) if err := s.initShared(); err != nil { return s, err } return s, nil } func (s *storageMock) GetStorageType() storageType { return s.sType } func (s *storageMock) GetStorageTypeName() string { return s.sTypeName } func (s *storageMock) ContainerCreate(container container) error { return nil } func (s *storageMock) ContainerCreateFromImage( container container, imageFingerprint string) error { return nil } func (s *storageMock) ContainerCanRestore(container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerDelete(container container) error { return nil } func (s *storageMock) ContainerCopy( container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerStart(container container) error { return nil } func (s *storageMock) ContainerStop(container container) error { return nil } func (s *storageMock) ContainerRename( container container, newName string) error { return nil } func (s *storageMock) ContainerRestore( container container, sourceContainer container) error { return nil } func (s *storageMock) ContainerSetQuota( container container, size int64) error { return nil } func (s *storageMock) ContainerSnapshotCreate( snapshotContainer container, sourceContainer container) error { return nil } func (s *storageMock) ContainerSnapshotDelete( snapshotContainer container) error { return nil } func (s *storageMock) ContainerSnapshotRename( snapshotContainer container, newName string) error { return nil } func (s *storageMock) ContainerSnapshotStart(container container) error { return nil } func (s *storageMock) ContainerSnapshotStop(container container) error { return nil } func (s *storageMock) ContainerSnapshotCreateEmpty(snapshotContainer container) error { return nil } func (s *storageMock) ImageCreate(fingerprint string) error { return nil } func (s *storageMock) ImageDelete(fingerprint string) error { return nil } func (s *storageMock) MigrationType() MigrationFSType { return MigrationFSType_RSYNC } func (s *storageMock) MigrationSource(container container) ([]MigrationStorageSource, error) { return nil, fmt.Errorf("not implemented") } func (s *storageMock) MigrationSink(container container, snapshots []container, conn *websocket.Conn) error { return nil }
dustinkirkland/lxd
lxd/storage_test.go
GO
apache-2.0
2,699
package com.example.coolweather.util; import android.text.TextUtils; import com.example.coolweather.db.City; import com.example.coolweather.db.County; import com.example.coolweather.db.Province; import com.example.coolweather.gson.Weather; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by Administrator on 2017/4/12. */ public class Utility { public static boolean handProvinceResponse(String response) { if (!TextUtils.isEmpty(response)) { try { JSONArray allProvinces = new JSONArray(response); for (int i= 0; i < allProvinces.length();i ++) { JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static boolean handCityResponse(String response,int provinId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCities = new JSONArray(response); for (int i= 0; i < allCities.length();i ++) { JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static boolean handCountyResponse(String response,int cityId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCounties = new JSONArray(response); for (int i= 0; i < allCounties.length();i ++) { JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static Weather handleWeatherResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather"); String weatherContent =jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } }
wjwin/coolweather
app/src/main/java/com/example/coolweather/util/Utility.java
Java
apache-2.0
3,289
package net.kalinovcic.ld32; import static org.lwjgl.opengl.GL11.*; public class Enemy extends Sprite { public GameStage game; public char origc; public String word; public float speed; public float vely; public boolean removeMe = false; public boolean alive = true; public int health; public Behavior behavior; public double cooldown; public boolean isPickup = false; public Enemy(GameStage game, String word, float speed, Behavior behavior) { this(game, word, behavior.getSize() / 2 + LD32.random.nextFloat() * (LD32.WW - behavior.getSize()), -behavior.getSize(), speed, behavior); } public Enemy(GameStage game, String word, float x, float y, float speed, Behavior behavior) { super(behavior.getTexture(), x, y, behavior.getSize(), behavior.getSize(), 180.0f); this.game = game; this.origc = word.charAt(0); this.word = word; health = word.length(); this.behavior = behavior; this.speed = vely = speed * behavior.getSpeedMul(); behavior.init(this); } public void update(double timeDelta) { if (vely < speed) { vely += timeDelta * speed * 4; if (vely > speed) vely = speed; } if (vely > speed) { vely -= timeDelta * speed; if (vely < speed) vely = speed; } y += vely * timeDelta; behavior.update(this, timeDelta); } @Override public void render() { super.render(); if (word.length() <= 0) return; glPushMatrix(); glTranslatef(x, y - h / 2, 0.0f); float w = LD32.font.getTotalWidth(word) + 8; float h = LD32.font.getHeight(); if (x - w / 2.0f < 0) glTranslatef(-(x - w / 2.0f), 0.0f, 0.0f); if (x + w / 2.0f > LD32.WW) glTranslatef(LD32.WW - (x + w / 2.0f), 0.0f, 0.0f); if (y - this.h / 2 - h < 0) glTranslatef(0.0f, -(y - this.h / 2 - h), 0.0f); /* glBindTexture(GL_TEXTURE_2D, 0); glColor4f(0.3f, 0.3f, 0.3f, 0.7f); glBegin(GL_QUADS); glVertex2f(-w / 2.0f, 0.0f); glVertex2f(w / 2.0f, 0.0f); glVertex2f(w / 2.0f, -h); glVertex2f(-w / 2.0f, -h); glEnd(); */ behavior.labelColor(); LD32.font.drawString(-4, 0.0f, word, 1.0f, -1.0f, TrueTypeFont.ALIGN_CENTER); glPopMatrix(); } public void renderSpecial() { super.render(); if (word.length() <= 0) return; glPushMatrix(); glTranslatef(x, y - h / 2, 0.0f); float w = LD32.font.getTotalWidth(word) + 8; float h = LD32.font.getHeight(); if (x - w / 2.0f < 0) glTranslatef(-(x - w / 2.0f), 0.0f, 0.0f); if (x + w / 2.0f > LD32.WW) glTranslatef(LD32.WW - (x + w / 2.0f), 0.0f, 0.0f); if (y - this.h / 2 - h < 0) glTranslatef(0.0f, -(y - this.h / 2 - h), 0.0f); /* glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glVertex2f(-w / 2.0f, 0.0f); glVertex2f(w / 2.0f, 0.0f); glVertex2f(w / 2.0f, -h); glVertex2f(-w / 2.0f, -h); glEnd(); */ glColor3f(0.4f, 0.4f, 1.0f); LD32.font.drawString(-4, 0.0f, word, 1, -1, TrueTypeFont.ALIGN_CENTER); glPopMatrix(); } }
Kalinovcic/LD32
src/net/kalinovcic/ld32/Enemy.java
Java
apache-2.0
3,462
package org.kasource.commons.reflection.collection; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.adapters.XmlAdapter; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import org.junit.Test; public class PackageMapTest { @Test public void get() { Map<String, String> map = new HashMap<String, String>(); map.put("javax", "javax"); map.put("javax.xml", "xml"); map.put("javax.xml.bind", "bind"); PackageMap<String> packageMap = new PackageMap<String>(map); assertThat(packageMap.get(XmlAdapter.class), equalTo("bind")); } }
wigforss/Ka-Commons-Reflection
src/test/java/org/kasource/commons/reflection/collection/PackageMapTest.java
Java
apache-2.0
676
var robotsParser = require("robots-parser"), urlMod = require("url"); /** * This is a parse that analyzes URL with path /robots.txt. * * @return {Function} Returns the handler. */ module.exports = function (opts) { if (!opts) { opts = {}; } if (!opts.urlFilter) { opts.urlFilter = function () { return true; }; } return function (context) { var robots, urlObj; urlObj = urlMod.parse(context.url); // skip if this is not actually a robots.txt file. if (urlObj.pathname !== "/robots.txt") { return []; } robots = robotsParser(context.url, context.body.toString()); return robots.getSitemaps().map(function (sitemapHref) { return urlMod.resolve(context.url, sitemapHref); }).filter(function (sitemapUrl) { return opts.urlFilter(sitemapUrl, context.url); }); }; };
brendonboshell/supercrawler
lib/handlers/robotsParser.js
JavaScript
apache-2.0
868
<?php /** * Reefknot framework * * @copyright Gordian Solutions and Gordon McVey * @license http://www.apache.org/licenses/LICENSE-2.0.txt Apache license V2.0 */ namespace gordian\reefknot\access\iface; /** * Access Control Consumer interface * * @author Gordon McVey * @category Reefknot * @package Access * @subpackage Interfaces */ interface Consumer { /** * Get the ID of the item that wishes to access a resource * * @return int */ public function getId (); }
gordiansolutions/reefknot
access/iface/Consumer.php
PHP
apache-2.0
493
/* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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 3 of the License, or (at your option) any later version. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.jira.metrics; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; public class JiraWidgetTest { @Test public void testGetTemplatePath() { String path = new JiraWidget().getTemplatePath(); assertThat(getClass().getResource(path)).isNotNull(); } @Test public void testNameAndTitle() throws Exception { JiraWidget widget = new JiraWidget(); assertThat(widget.getId()).isEqualTo("jira"); assertThat(widget.getTitle()).isEqualTo("JIRA issues"); } }
aifraenkel/caltec-tools
SonarQube/Plugins/sonar-jira-master/src/test/java/org/sonar/plugins/jira/metrics/JiraWidgetTest.java
Java
apache-2.0
1,382
package i5.las2peer.services.ocd.centrality.utils; import java.util.Map; import i5.las2peer.services.ocd.centrality.data.CentralityMeasureType; import i5.las2peer.services.ocd.utils.ConditionalParameterizableFactory; public class CentralityAlgorithmFactory implements ConditionalParameterizableFactory<CentralityAlgorithm, CentralityMeasureType> { public boolean isInstantiatable(CentralityMeasureType creationType) { if(creationType.correspondsAlgorithm()) { return true; } else { return false; } } @Override public CentralityAlgorithm getInstance(CentralityMeasureType centralityMeasureType, Map<String, String> parameters) throws InstantiationException, IllegalAccessException { if(isInstantiatable(centralityMeasureType)) { CentralityAlgorithm algorithm = (CentralityAlgorithm) centralityMeasureType.getCreationMethodClass().newInstance(); algorithm.setParameters(parameters); return algorithm; } throw new IllegalStateException("This creation type is not an instantiatable algorithm."); } }
rwth-acis/REST-OCD-Services
rest_ocd_services/src/main/java/i5/las2peer/services/ocd/centrality/utils/CentralityAlgorithmFactory.java
Java
apache-2.0
1,036
class Salesforce::GroupHints < Hobo::ViewHints # model_name "My Model" # field_names :field1 => "First Field", :field2 => "Second Field" # field_help :field1 => "Enter what you want in this field" # children :primary_collection1, :aside_collection1, :aside_collection2 end
raygao/SFRWatcher
app/viewhints/salesforce/group_hints.rb
Ruby
apache-2.0
282
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.afwsamples.testdpc.policy.systemupdatepolicy; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Fragment; import android.app.TimePickerDialog; import android.app.admin.DevicePolicyManager; import android.app.admin.FreezePeriod; import android.app.admin.SystemUpdatePolicy; import android.content.Context; import android.os.Build.VERSION_CODES; import android.os.Bundle; import androidx.annotation.RequiresApi; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.Toast; import com.afwsamples.testdpc.DeviceAdminReceiver; import com.afwsamples.testdpc.R; import com.afwsamples.testdpc.common.Util; import java.time.LocalDate; import java.time.MonthDay; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; /** * This fragment provides functionalities related to managed system update that are available in a * device owner. * These includes * 1) {@link DevicePolicyManager#setSystemUpdatePolicy} * 2) {@link DevicePolicyManager#getSystemUpdatePolicy} * 3) {@link SystemUpdatePolicy} */ @TargetApi(VERSION_CODES.M) public class SystemUpdatePolicyFragment extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener { @RequiresApi(api = VERSION_CODES.O) static class Period { MonthDay mStart; MonthDay mEnd; public Period() { } public Period(MonthDay start, MonthDay end) { mStart = start; mEnd = end; } public void set(LocalDate startDate, LocalDate endDate) { mStart = MonthDay.of(startDate.getMonth(), startDate.getDayOfMonth()); mEnd = MonthDay.of(endDate.getMonth(), endDate.getDayOfMonth()); } @Override public String toString() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd"); return mStart.format(formatter) + " - " + mEnd.format(formatter); } public LocalDate getStartDate() { return mStart.atYear(LocalDate.now().getYear()); } public LocalDate getEndDate() { return mEnd.atYear(LocalDate.now().getYear()); } @TargetApi(VERSION_CODES.P) public FreezePeriod toFreezePeriod() { return new FreezePeriod(mStart, mEnd); } } private EditText mCurrentSystemUpdatePolicy; private RadioGroup mSystemUpdatePolicySelection; private LinearLayout mMaintenanceWindowDetails; private Button mSetMaintenanceWindowStart; private Button mSetMaintenanceWindowEnd; private LinearLayout mFreezePeriodPanel; private ListView mFreezePeriodList; private DevicePolicyManager mDpm; private int mMaintenanceStart; private int mMaintenanceEnd; private ArrayList<Period> mFreezePeriods = new ArrayList<>(); private FreezePeriodAdapter mFreezePeriodAdapter; @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.system_update_policy); reloadSystemUpdatePolicy(); } class FreezePeriodAdapter extends ArrayAdapter<Period> { public ArrayList<Period> mData; public FreezePeriodAdapter(Context context, ArrayList<Period> periods) { super(context, 0, periods); this.mData = periods; } @RequiresApi(api = VERSION_CODES.O) @Override public View getView(int position, View convertView, ViewGroup parent) { Period currentPeriod = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.freeze_period_row, parent, false); } Button textView = convertView.findViewById(R.id.string_period); textView.setText(currentPeriod.toString()); textView.setTag(mData.get(position)); textView.setOnClickListener(view -> { final Period period = (Period) view.getTag(); promptToSetFreezePeriod((LocalDate startDate, LocalDate endDate) -> { period.set(startDate, endDate); mFreezePeriodAdapter.notifyDataSetChanged(); }, period.getStartDate(), period.getEndDate()); }); View deleteButton = convertView.findViewById(R.id.delete_period); deleteButton.setTag(mData.get(position)); deleteButton.setOnClickListener(view -> { Period period = (Period) view.getTag(); mData.remove(period); FreezePeriodAdapter.this.notifyDataSetChanged(); }); return convertView; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDpm = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE); } @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { View view = layoutInflater.inflate(R.layout.system_update_policy, null); mCurrentSystemUpdatePolicy = view.findViewById(R.id.system_update_policy_current); mSystemUpdatePolicySelection = view.findViewById(R.id.system_update_policy_selection); mMaintenanceWindowDetails = view.findViewById(R.id.system_update_policy_windowed_details); mSetMaintenanceWindowStart = view.findViewById(R.id.system_update_policy_window_start); mSetMaintenanceWindowEnd = view.findViewById(R.id.system_update_policy_window_end); mFreezePeriodPanel = view.findViewById(R.id.system_update_policy_blackout_periods); mFreezePeriodList = view.findViewById(R.id.system_update_policy_blackout_period_list); mFreezePeriodAdapter = new FreezePeriodAdapter(getContext(), mFreezePeriods); mFreezePeriodList.setAdapter(mFreezePeriodAdapter); mSetMaintenanceWindowStart.setOnClickListener(this); mSetMaintenanceWindowEnd.setOnClickListener(this); view.findViewById(R.id.system_update_policy_set).setOnClickListener(this); view.findViewById(R.id.system_update_policy_btn_add_period).setOnClickListener(this); mSystemUpdatePolicySelection.setOnCheckedChangeListener(this); mFreezePeriodPanel.setVisibility( Util.SDK_INT >= VERSION_CODES.P ?View.VISIBLE : View.GONE); return view; } private void selectTime(final boolean isWindowStart) { int defaultMinutes = isWindowStart ? mMaintenanceStart : mMaintenanceEnd; TimePickerDialog timePicker = new TimePickerDialog(getActivity(), (picker, hour, minutes) -> { if (isWindowStart) { mMaintenanceStart = hour * 60 + minutes; } else { mMaintenanceEnd = hour * 60 + minutes; } updateMaintenanceWindowDisplay(); }, defaultMinutes / 60, defaultMinutes % 60, true); timePicker.show(); } @RequiresApi(api = VERSION_CODES.O) @Override public void onClick(View v) { switch (v.getId()) { case R.id.system_update_policy_window_start: selectTime(true); break; case R.id.system_update_policy_window_end: selectTime(false); break; case R.id.system_update_policy_set: if (setSystemUpdatePolicy()) { reloadSystemUpdatePolicy(); } break; case R.id.system_update_policy_btn_add_period: promptToSetFreezePeriod((LocalDate startDate, LocalDate endDate) -> { Period period = new Period(); period.set(startDate, endDate); mFreezePeriods.add(period); mFreezePeriodAdapter.notifyDataSetChanged(); }, LocalDate.now(), LocalDate.now()); } } interface FreezePeriodPickResult { void onResult(LocalDate startDate, LocalDate endDate); } interface DatePickResult { void onResult(LocalDate pickedDate); } @RequiresApi(api = VERSION_CODES.O) private void showDatePicker(LocalDate hint, int titleResId, DatePickResult resultCallback) { DatePickerDialog picker = new DatePickerDialog(getActivity(), (pickerObj, year, month, day) -> { final LocalDate pickedDate = LocalDate.of(year, month + 1, day); resultCallback.onResult(pickedDate); }, hint.getYear(), hint.getMonth().getValue() - 1, hint.getDayOfMonth()); picker.setTitle(getString(titleResId)); picker.show(); } @RequiresApi(api = VERSION_CODES.O) private void promptToSetFreezePeriod(FreezePeriodPickResult callback, final LocalDate startDate, final LocalDate endDate) { showDatePicker(startDate, R.string.system_update_policy_pick_start_free_period_title, pickedStartDate -> { LocalDate proposedEndDate = endDate; if (proposedEndDate.compareTo(pickedStartDate) < 0) { proposedEndDate = pickedStartDate; } showDatePicker(proposedEndDate, R.string.system_update_policy_pick_end_free_period_title, pickedEndDate -> callback.onResult(pickedStartDate, pickedEndDate)); }); } @TargetApi(VERSION_CODES.P) private boolean setSystemUpdatePolicy() { SystemUpdatePolicy newPolicy; switch (mSystemUpdatePolicySelection.getCheckedRadioButtonId()) { case R.id.system_update_policy_automatic: newPolicy = SystemUpdatePolicy.createAutomaticInstallPolicy(); break; case R.id.system_update_policy_Windowed: newPolicy = SystemUpdatePolicy.createWindowedInstallPolicy( mMaintenanceStart, mMaintenanceEnd); break; case R.id.system_update_policy_postpone: newPolicy = SystemUpdatePolicy.createPostponeInstallPolicy(); break; case R.id.system_update_policy_none: default: newPolicy = null; } try { if (Util.SDK_INT >= VERSION_CODES.P && newPolicy != null && mFreezePeriods.size() != 0) { final List<FreezePeriod> periods = new ArrayList<>(mFreezePeriods.size()); for (Period p : mFreezePeriods) { periods.add(p.toFreezePeriod()); } newPolicy.setFreezePeriods(periods); } mDpm.setSystemUpdatePolicy(DeviceAdminReceiver.getComponentName(getActivity()), newPolicy); Toast.makeText(getContext(), "Policy set successfully", Toast.LENGTH_LONG).show(); return true; } catch (IllegalArgumentException e) { Toast.makeText(getContext(), "Failed to set system update policy: " + e.getMessage(), Toast.LENGTH_LONG).show(); } return false; } private String formatMinutes(int minutes) { return String.format("%02d:%02d", minutes / 60, minutes % 60); } private void updateMaintenanceWindowDisplay() { mSetMaintenanceWindowStart.setText(formatMinutes(mMaintenanceStart)); mSetMaintenanceWindowEnd.setText(formatMinutes(mMaintenanceEnd)); } @TargetApi(VERSION_CODES.P) private void reloadSystemUpdatePolicy() { SystemUpdatePolicy policy = mDpm.getSystemUpdatePolicy(); String policyDescription = "Unknown"; if (policy == null) { policyDescription = "None"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_none); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); mFreezePeriodPanel.setVisibility(View.GONE); } else { switch (policy.getPolicyType()) { case SystemUpdatePolicy.TYPE_INSTALL_AUTOMATIC: policyDescription = "Automatic"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_automatic); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); break; case SystemUpdatePolicy.TYPE_INSTALL_WINDOWED: { mMaintenanceStart = policy.getInstallWindowStart(); mMaintenanceEnd = policy.getInstallWindowEnd(); policyDescription = String.format("Windowed: %s-%s", formatMinutes(mMaintenanceStart), formatMinutes(mMaintenanceEnd)); updateMaintenanceWindowDisplay(); mSystemUpdatePolicySelection.check(R.id.system_update_policy_Windowed); mMaintenanceWindowDetails.setVisibility(View.VISIBLE); break; } case SystemUpdatePolicy.TYPE_POSTPONE: policyDescription = "Postpone"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_postpone); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); break; } if (Util.SDK_INT >= VERSION_CODES.P) { List<FreezePeriod> freezePeriods = policy.getFreezePeriods(); mFreezePeriods.clear(); for (FreezePeriod period : freezePeriods) { Period p = new Period(period.getStart(), period.getEnd()); mFreezePeriods.add(p); } mFreezePeriodAdapter.notifyDataSetChanged(); mFreezePeriodPanel.setVisibility(View.VISIBLE); } } mCurrentSystemUpdatePolicy.setText(policyDescription); } @Override public void onCheckedChanged(RadioGroup view, int checkedId) { if (checkedId == R.id.system_update_policy_Windowed) { updateMaintenanceWindowDisplay(); mMaintenanceWindowDetails.setVisibility(View.VISIBLE); } else { mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); } if (checkedId == R.id.system_update_policy_none || Util.SDK_INT < VERSION_CODES.P) { mFreezePeriodPanel.setVisibility(View.GONE); } else { mFreezePeriodPanel.setVisibility(View.VISIBLE); } } }
googlesamples/android-testdpc
app/src/main/java/com/afwsamples/testdpc/policy/systemupdatepolicy/SystemUpdatePolicyFragment.java
Java
apache-2.0
15,547
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mx.edu.uam.practica3.controles; import mx.edu.uam.practica3.electroDomesticos.Television; /** * * @author invited */ public class ControlTelevision { public void enciendeTv(Television tv){ if(tv.isEncendido()){ System.out.println("La televisión ya se encuentra encedida"); }else{ tv.setEncendido(true); System.out.println("Se cambia el estado a ON"); } } public void apagaTv(Television tv){ if(tv.isEncendido()){ tv.setEncendido(false); System.out.println("Se cambia el estado a OFF"); }else{ System.out.println("No se puede apagar la televisión pues se encuentra apagada"); } } public void subeVolumen(Television tv){ if(tv.isEncendido()){ if(tv.getVolMaximo() == tv.getVolActual()){ System.out.println("El volumen se encuentra al Maximo posible"); }else{ tv.setVolActual(tv.getVolActual()+1); System.out.println("El volumen Actual se aumentó y es : "+ tv.getVolActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void bajaVolumen(Television tv){ if(tv.isEncendido()){ if(tv.getVolActual() == 0){ System.out.println("El volumen no se puede bajar más... Está en el mínimo"); }else{ tv.setVolActual(tv.getVolActual()-1); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void subeCanal(Television tv){ if(tv.isEncendido()){ if(tv.getUltimoCanal() == tv.getCanalActual()){ System.out.println("No puede subir canal ... Se encuentra en el Máximo Canal"); }else{ tv.setCanalActual(tv.getCanalActual()+1); System.out.println("El canal actual es: "+ tv.getCanalActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void bajaCanal(Television tv){ if(tv.isEncendido()){ if(tv.getCanalActual() == 1){ System.out.println("No puede bajar canal ... Se encuentra en el canal mìnimo"); }else{ tv.setCanalActual(tv.getCanalActual()-1); System.out.println("El canal actual es: "+ tv.getCanalActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void cambiaCanal(Television tv, int canal){ if(tv.isEncendido()){ tv.setCanalActual(canal); System.out.println("El canal actual es: "+ tv.getCanalActual()); }else{ System.out.println("La televisión se encuentra apagada"); } } }
JavaUAM2016/PracticasOCA
Practica3/luzmx/JavaApp/src/mx/edu/uam/practica3/controles/ControlTelevision.java
Java
apache-2.0
3,150
package ru.stqa.pft.addressbook.model; import com.google.common.collect.ForwardingSet; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Саша on 13.12.2016. */ public class Persons extends ForwardingSet<PersonData> { private Set<PersonData> delegate; public Persons(Persons persons) { this.delegate = new HashSet<PersonData>(persons.delegate); } public Persons() { this.delegate = new HashSet<PersonData>(); } public Persons(Collection<PersonData> persons) { this.delegate = new HashSet<PersonData>(persons); } @Override protected Set<PersonData> delegate() { return delegate; } public Persons withAdded (PersonData person){ Persons persons = new Persons(this); persons.add(person); return persons; } public Persons without (PersonData person){ Persons persons = new Persons(this); persons.remove(person); return persons; } }
martyanova/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Persons.java
Java
apache-2.0
1,043
package org.drip.service.template; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * Copyright (C) 2016 Lakshmi Krishnamurthy * Copyright (C) 2015 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * 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. */ /** * OTCInstrumentBuilder contains static Helper API to facilitate Construction of OTC Instruments. * * @author Lakshmi Krishnamurthy */ public class OTCInstrumentBuilder { /** * Construct an OTC Funding Deposit Instrument from the Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strCurrency Currency * @param strMaturityTenor The Maturity Tenor * * @return Funding Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent FundingDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == strCurrency || strCurrency.isEmpty() || null == strMaturityTenor || strMaturityTenor.isEmpty()) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", strMaturityTenor, "MAIN"); if (null == ffsc) return null; org.drip.state.identifier.ForwardLabel forwardLabel = ffsc.floatStreamConvention().floaterIndex(); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency); try { java.lang.String strFloaterTenor = forwardLabel.tenor(); org.drip.analytics.date.JulianDate dtMaturity = strMaturityTenor.contains ("D") ? new org.drip.analytics.date.JulianDate (org.drip.analytics.daycount.Convention.AddBusinessDays (dtEffective.julian(), org.drip.analytics.support.Helper.TenorToDays (strMaturityTenor), strCurrency)) : dtEffective.addTenorAndAdjust (strMaturityTenor, strCurrency); return new org.drip.product.rates.SingleStreamComponent ("DEPOSIT_" + strMaturityTenor, new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.EdgePair (dtEffective, dtMaturity), new org.drip.param.period.CompositePeriodSetting (org.drip.analytics.support.Helper.TenorToFreq (strFloaterTenor), strFloaterTenor, strCurrency, null, 1., null, null, null, null), new org.drip.param.period.ComposableFloatingUnitSetting (strFloaterTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE, null, org.drip.state.identifier.ForwardLabel.Create (strCurrency, strFloaterTenor), org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.))), null); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an OTC Forward Deposit Instrument from Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strMaturityTenor The Maturity Tenor * @param forwardLabel The Forward Label * * @return Forward Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent ForwardRateDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strMaturityTenor, final org.drip.state.identifier.ForwardLabel forwardLabel) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strCalendar = forwardLabel.currency(); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCalendar); return org.drip.product.creator.SingleStreamComponentBuilder.Deposit (dtEffective, dtEffective.addTenor (strMaturityTenor), forwardLabel); } /** * Construct an OTC Overnight Deposit Instrument from the Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strCurrency Currency * @param strMaturityTenor The Maturity Tenor * * @return Overnight Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent OvernightDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor) { if (null == dtSpot) return null; org.drip.state.identifier.OvernightLabel overnightLabel = org.drip.state.identifier.OvernightLabel.Create (strCurrency); if (null == overnightLabel) return null; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency); return null == dtEffective ? null : org.drip.product.creator.SingleStreamComponentBuilder.Deposit (dtEffective, dtEffective.addTenorAndAdjust (strMaturityTenor, strCurrency),overnightLabel); } /** * Create a Standard FRA from the Spot Date, the Forward Label, and the Strike * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Maturity Tenor * @param dblStrike Futures Strike * * @return The Standard FRA Instance */ public static final org.drip.product.fra.FRAStandardComponent FRAStandard ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor, final double dblStrike) { return null == dtSpot || null == forwardLabel ? null : org.drip.product.creator.SingleStreamComponentBuilder.FRAStandard (dtSpot.addBusDays (0, forwardLabel.currency()).addTenor (strMaturityTenor), forwardLabel, dblStrike); } /** * Construct an OTC Standard Fix Float Swap using the specified Input Parameters * * @param dtSpot The Spot Date * @param strCurrency The OTC Currency * @param strLocation Location * @param strMaturityTenor Maturity Tenor * @param strIndex Index * @param dblCoupon Coupon * * @return The OTC Standard Fix Float Swap constructed using the specified Input Parameters */ public static final org.drip.product.rates.FixFloatComponent FixFloatStandard ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strLocation, final java.lang.String strMaturityTenor, final java.lang.String strIndex, final double dblCoupon) { if (null == dtSpot) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, strLocation, strMaturityTenor, strIndex); return null == ffsc ? null : ffsc.createFixFloatComponent (dtSpot.addBusDays (0, strCurrency), strMaturityTenor, dblCoupon, 0., 1.); } /** * Construct a Standard Fix Float Swap Instances * * @param dtSpot The Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Maturity Tenor * * @return A Standard Fix Float Swap Instances */ public static final org.drip.product.rates.FixFloatComponent FixFloatCustom ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strForwardTenor = forwardLabel.tenor(); int iTenorInMonths = new java.lang.Integer (strForwardTenor.split ("M")[0]); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency).addDays (2); org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", strMaturityTenor, "MAIN"); if (null == ffsc) return null; try { org.drip.param.period.ComposableFloatingUnitSetting cfusFloating = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); org.drip.param.period.CompositePeriodSetting cpsFloating = new org.drip.param.period.CompositePeriodSetting (12 / iTenorInMonths, strForwardTenor, strCurrency, null, -1., null, null, null, null); org.drip.product.rates.Stream floatingStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective, strForwardTenor, strMaturityTenor, null), cpsFloating, cfusFloating)); org.drip.product.rates.Stream fixedStream = ffsc.fixedStreamConvention().createStream (dtEffective, strMaturityTenor, 0., 1.); org.drip.product.rates.FixFloatComponent ffc = new org.drip.product.rates.FixFloatComponent (fixedStream, floatingStream, null); ffc.setPrimaryCode ("FixFloat:" + strMaturityTenor); return ffc; } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Instance of OTC OIS Fix Float Swap * * @param dtSpot Spot Date * @param strCurrency Currency * @param strMaturityTenor The OIS Maturity Tenor * @param dblCoupon The Fixed Coupon Rate * @param bFund TRUE - Floater Based off of Fund * * @return Instance of OIS Fix Float Swap */ public static final org.drip.product.rates.FixFloatComponent OISFixFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor, final double dblCoupon, final boolean bFund) { if (null == dtSpot) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = bFund ? org.drip.market.otc.OvernightFixedFloatContainer.FundConventionFromJurisdiction (strCurrency) : org.drip.market.otc.OvernightFixedFloatContainer.IndexConventionFromJurisdiction (strCurrency, strMaturityTenor); return null == ffsc ? null : ffsc.createFixFloatComponent (dtSpot.addBusDays (0, strCurrency), strMaturityTenor, dblCoupon, 0., 1.); } /** * Construct an OTC Float-Float Swap Instance * * @param dtSpot Spot Date * @param strCurrency Currency * @param strDerivedTenor Tenor of the Derived Leg * @param strMaturityTenor Maturity Tenor of the Float-Float Swap * @param dblBasis The Float-Float Swap Basis * * @return The OTC Float-Float Swap Instance */ public static final org.drip.product.rates.FloatFloatComponent FloatFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strDerivedTenor, final java.lang.String strMaturityTenor, final double dblBasis) { if (null == dtSpot) return null; org.drip.market.otc.FloatFloatSwapConvention ffsc = org.drip.market.otc.IBORFloatFloatContainer.ConventionFromJurisdiction (strCurrency); return null == ffsc ? null : ffsc.createFloatFloatComponent (dtSpot.addBusDays (0, strCurrency), strDerivedTenor, strMaturityTenor, dblBasis, 1.); } /** * Create an Instance of the OTC CDS. * * @param dtSpot The Spot Date * @param strMaturityTenor Maturity Tenor * @param dblCoupon Coupon * @param strCurrency Currency * @param strCredit Credit Curve * * @return The OTC CDS Instance */ public static final org.drip.product.definition.CreditDefaultSwap CDS ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strMaturityTenor, final double dblCoupon, final java.lang.String strCurrency, final java.lang.String strCredit) { if (null == dtSpot || null == strCurrency) return null; org.drip.analytics.date.JulianDate dtFirstCoupon = dtSpot.addBusDays (0, strCurrency).nextCreditIMM (3); return null == dtFirstCoupon ? null : org.drip.product.creator.CDSBuilder.CreateCDS (dtFirstCoupon.subtractTenor ("3M"), dtFirstCoupon.addTenor (strMaturityTenor), dblCoupon, strCurrency, "CAD".equalsIgnoreCase (strCurrency) || "EUR".equalsIgnoreCase (strCurrency) || "GBP".equalsIgnoreCase (strCurrency) || "HKD".equalsIgnoreCase (strCurrency) || "USD".equalsIgnoreCase (strCurrency) ? 0.40 : 0.25, strCredit, strCurrency, true); } /** * Create an OTC FX Forward Component * * @param dtSpot Spot Date * @param ccyPair Currency Pair * @param strMaturityTenor Maturity Tenor * * @return The OTC FX Forward Component Instance */ public static final org.drip.product.fx.FXForwardComponent FXForward ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.product.params.CurrencyPair ccyPair, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == ccyPair) return null; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, ccyPair.denomCcy()); try { return new org.drip.product.fx.FXForwardComponent ("FXFWD::" + ccyPair.code() + "::" + strMaturityTenor, ccyPair, dtEffective.julian(), dtEffective.addTenor (strMaturityTenor).julian(), 1., null); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Array of OTC Funding Deposit Instruments from their corresponding Maturity Tenors * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of OTC Funding Deposit Instruments from their corresponding Maturity Tenors */ public static final org.drip.product.rates.SingleStreamComponent[] FundingDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < astrMaturityTenor.length; ++i) { if (null == (aSSCDeposit[i] = FundingDeposit (dtSpot, strCurrency, astrMaturityTenor[i]))) return null; aSSCDeposit[i].setPrimaryCode (astrMaturityTenor[i]); } return aSSCDeposit; } /** * Construct an Array of OTC Forward Deposit Instruments from the corresponding Maturity Tenors * * @param dtSpot Spot Date * @param astrMaturityTenor Array of Maturity Tenors * @param forwardLabel The Forward Label * * @return Forward Deposit Instrument Instance from the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent[] ForwardRateDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String[] astrMaturityTenor, final org.drip.state.identifier.ForwardLabel forwardLabel) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < astrMaturityTenor.length; ++i) { if (null == (aSSCDeposit[i] = ForwardRateDeposit (dtSpot, astrMaturityTenor[i], forwardLabel))) return null; aSSCDeposit[i].setPrimaryCode (astrMaturityTenor[i]); } return aSSCDeposit; } /** * Construct an Array of OTC Overnight Deposit Instrument from their Maturity Tenors * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of Maturity Tenor * * @return Array of Overnight Deposit Instrument from their Maturity Tenors */ public static final org.drip.product.rates.SingleStreamComponent[] OvernightDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < iNumDeposit; ++i) { if (null == (aSSCDeposit[i] = OvernightDeposit (dtSpot, strCurrency, astrMaturityTenor[i]))) return null; } return aSSCDeposit; } /** * Create an Array of Standard FRAs from the Spot Date, the Forward Label, and the Strike * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Maturity Tenors * @param adblFRAStrike Array of FRA Strikes * * @return Array of Standard FRA Instances */ public static final org.drip.product.fra.FRAStandardComponent[] FRAStandard ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor, final double[] adblFRAStrike) { if (null == astrMaturityTenor || null == adblFRAStrike) return null; int iNumFRA = astrMaturityTenor.length; org.drip.product.fra.FRAStandardComponent[] aFRA = new org.drip.product.fra.FRAStandardComponent[iNumFRA]; if (0 == iNumFRA || iNumFRA != adblFRAStrike.length) return null; for (int i = 0; i < iNumFRA; ++i) { if (null == (aFRA[i] = FRAStandard (dtSpot, forwardLabel, astrMaturityTenor[i], adblFRAStrike[i]))) return null; } return aFRA; } /** * Construct an Array of OTC Fix Float Swaps using the specified Input Parameters * * @param dtSpot The Spot Date * @param strCurrency The OTC Currency * @param strLocation Location * @param astrMaturityTenor Array of Maturity Tenors * @param strIndex Index * @param dblCoupon Coupon * * @return The Array of OTC Fix Float Swaps */ public static final org.drip.product.rates.FixFloatComponent[] FixFloatStandard ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strLocation, final java.lang.String[] astrMaturityTenor, final java.lang.String strIndex, final double dblCoupon) { if (null == astrMaturityTenor) return null; int iNumFixFloat = astrMaturityTenor.length; org.drip.product.rates.FixFloatComponent[] aFFC = new org.drip.product.rates.FixFloatComponent[iNumFixFloat]; if (0 == iNumFixFloat) return null; for (int i = 0; i < iNumFixFloat; ++i) { if (null == (aFFC[i] = FixFloatStandard (dtSpot, strCurrency, strLocation, astrMaturityTenor[i], strIndex, 0.))) return null; } return aFFC; } /** * Construct an Array of Custom Fix Float Swap Instances * * @param dtSpot The Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of Custom Fix Float Swap Instances */ public static final org.drip.product.rates.FixFloatComponent[] FixFloatCustom ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor) { if (null == dtSpot || null == forwardLabel || null == astrMaturityTenor) return null; int iNumComp = astrMaturityTenor.length; org.drip.param.period.CompositePeriodSetting cpsFloating = null; org.drip.param.period.ComposableFloatingUnitSetting cfusFloating = null; org.drip.product.rates.FixFloatComponent[] aFFC = new org.drip.product.rates.FixFloatComponent[iNumComp]; if (0 == iNumComp) return null; java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strForwardTenor = forwardLabel.tenor(); int iTenorInMonths = new java.lang.Integer (strForwardTenor.split ("M")[0]); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency).addDays (2); try { cfusFloating = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); cpsFloating = new org.drip.param.period.CompositePeriodSetting (12 / iTenorInMonths, strForwardTenor, strCurrency, null, -1., null, null, null, null); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } for (int i = 0; i < iNumComp; ++i) { org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", astrMaturityTenor[i], "MAIN"); if (null == ffsc) return null; try { org.drip.product.rates.Stream floatingStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective, strForwardTenor, astrMaturityTenor[i], null), cpsFloating, cfusFloating)); org.drip.product.rates.Stream fixedStream = ffsc.fixedStreamConvention().createStream (dtEffective, astrMaturityTenor[i], 0., 1.); aFFC[i] = new org.drip.product.rates.FixFloatComponent (fixedStream, floatingStream, null); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } aFFC[i].setPrimaryCode ("FixFloat:" + astrMaturityTenor[i]); } return aFFC; } /** * Construct an Array of OTC Fix Float OIS Instances * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of OIS Maturity Tenors * @param adblCoupon OIS Fixed Rate Coupon * @param bFund TRUE - Floater Based off of Fund * * @return Array of Fix Float OIS Instances */ public static final org.drip.product.rates.FixFloatComponent[] OISFixFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final boolean bFund) { if (null == astrMaturityTenor) return null; int iNumOIS = astrMaturityTenor.length; org.drip.product.rates.FixFloatComponent[] aFixFloatOIS = new org.drip.product.rates.FixFloatComponent[iNumOIS]; if (0 == iNumOIS) return null; for (int i = 0; i < iNumOIS; ++i) { if (null == (aFixFloatOIS[i] = OISFixFloat (dtSpot, strCurrency, astrMaturityTenor[i], adblCoupon[i], bFund))) return null; } return aFixFloatOIS; } /** * Construct an Array of OTC OIS Fix-Float Futures * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrEffectiveTenor Array of Effective Tenors * @param astrMaturityTenor Array of Maturity Tenors * @param adblCoupon Array of Coupons * @param bFund TRUE - Floater Based off of Fund * * @return Array of OIS Fix-Float Futures */ public static final org.drip.product.rates.FixFloatComponent[] OISFixFloatFutures ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrEffectiveTenor, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final boolean bFund) { if (null == dtSpot || null == astrEffectiveTenor || null == astrMaturityTenor || null == adblCoupon) return null; int iNumOISFutures = astrEffectiveTenor.length; org.drip.product.rates.FixFloatComponent[] aOISFutures = new org.drip.product.rates.FixFloatComponent[iNumOISFutures]; if (0 == iNumOISFutures || iNumOISFutures != astrMaturityTenor.length || iNumOISFutures != adblCoupon.length) return null; for (int i = 0; i < iNumOISFutures; ++i) { if (null == (aOISFutures[i] = OISFixFloat (dtSpot.addTenor (astrEffectiveTenor[i]), strCurrency, astrMaturityTenor[i], adblCoupon[i], bFund))) return null; } return aOISFutures; } /** * Construct an Array of OTC Float-Float Swap Instances * * @param dtSpot Spot Date * @param strCurrency Currency * @param strDerivedTenor Tenor of the Derived Leg * @param astrMaturityTenor Array of the Float-Float Swap Maturity Tenors * @param dblBasis The Float-Float Swap Basis * * @return Array of OTC Float-Float Swap Instances */ public static final org.drip.product.rates.FloatFloatComponent[] FloatFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strDerivedTenor, final java.lang.String[] astrMaturityTenor, final double dblBasis) { if (null == astrMaturityTenor) return null; org.drip.market.otc.FloatFloatSwapConvention ffsc = org.drip.market.otc.IBORFloatFloatContainer.ConventionFromJurisdiction (strCurrency); int iNumFFC = astrMaturityTenor.length; org.drip.product.rates.FloatFloatComponent[] aFFC = new org.drip.product.rates.FloatFloatComponent[iNumFFC]; if (null == ffsc || 0 == iNumFFC) return null; for (int i = 0; i < iNumFFC; ++i) { if (null == (aFFC[i] = ffsc.createFloatFloatComponent (dtSpot, strDerivedTenor, astrMaturityTenor[i], dblBasis, 1.))) return null; } return aFFC; } /** * Create an Array of the OTC CDS Instance. * * @param dtSpot Spot Date * @param astrMaturityTenor Array of Maturity Tenors * @param adblCoupon Array of Coupon * @param strCurrency Currency * @param strCredit Credit Curve * * @return Array of OTC CDS Instances */ public static final org.drip.product.definition.CreditDefaultSwap[] CDS ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final java.lang.String strCurrency, final java.lang.String strCredit) { if (null == dtSpot || null == strCurrency || null == astrMaturityTenor || null == adblCoupon) return null; int iNumCDS = astrMaturityTenor.length; java.lang.String strCalendar = strCurrency; org.drip.product.definition.CreditDefaultSwap[] aCDS = new org.drip.product.definition.CreditDefaultSwap[iNumCDS]; if (0 == iNumCDS || iNumCDS != adblCoupon.length) return null; org.drip.analytics.date.JulianDate dtFirstCoupon = dtSpot.addBusDays (0, strCalendar).nextCreditIMM (3); if (null == dtFirstCoupon) return null; org.drip.analytics.date.JulianDate dtEffective = dtFirstCoupon.subtractTenor ("3M"); if (null == dtEffective) return null; double dblRecovery = "CAD".equalsIgnoreCase (strCurrency) || "EUR".equalsIgnoreCase (strCurrency) || "GBP".equalsIgnoreCase (strCurrency) || "HKD".equalsIgnoreCase (strCurrency) || "USD".equalsIgnoreCase (strCurrency) ? 0.40 : 0.25; for (int i = 0; i < iNumCDS; ++i) aCDS[i] = org.drip.product.creator.CDSBuilder.CreateCDS (dtEffective, dtFirstCoupon.addTenor (astrMaturityTenor[i]), adblCoupon[i], strCurrency, dblRecovery, strCredit, strCalendar, true); return aCDS; } /** * Create an Array of OTC FX Forward Components * * @param dtSpot Spot Date * @param ccyPair Currency Pair * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of OTC FX Forward Component Instances */ public static final org.drip.product.fx.FXForwardComponent[] FXForward ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.product.params.CurrencyPair ccyPair, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumFXComp = astrMaturityTenor.length; org.drip.product.fx.FXForwardComponent[] aFXFC = new org.drip.product.fx.FXForwardComponent[iNumFXComp]; if (0 == iNumFXComp) return null; for (int i = 0; i < iNumFXComp; ++i) aFXFC[i] = FXForward (dtSpot, ccyPair, astrMaturityTenor[i]); return aFXFC; } /** * Construct an Instance of the Standard OTC FRA Cap/Floor * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Cap/Floor Maturity Tenor * @param dblStrike Cap/Floor Strike * @param bIsCap TRUE - Contract is a Cap * * @return The Cap/Floor Instance */ public static final org.drip.product.fra.FRAStandardCapFloor CapFloor ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor, final double dblStrike, final boolean bIsCap) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strForwardTenor = forwardLabel.tenor(); java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strCalendar = strCurrency; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCalendar); try { org.drip.param.period.ComposableFloatingUnitSetting cfus = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); org.drip.param.period.CompositePeriodSetting cps = new org.drip.param.period.CompositePeriodSetting (org.drip.analytics.support.Helper.TenorToFreq (strForwardTenor), strForwardTenor, strCurrency, null, 1., null, null, null, null); org.drip.product.rates.Stream floatStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective.julian(), strForwardTenor, strMaturityTenor, null), cps, cfus)); return new org.drip.product.fra.FRAStandardCapFloor (forwardLabel.fullyQualifiedName() + (bIsCap ? "::CAP" : "::FLOOR"), floatStream, "ParForward", bIsCap, dblStrike, new org.drip.product.params.LastTradingDateSetting (org.drip.product.params.LastTradingDateSetting.MID_CURVE_OPTION_QUARTERLY, "", java.lang.Integer.MIN_VALUE), null, new org.drip.pricer.option.BlackScholesAlgorithm()); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Instance of the Standard OTC FRA Cap/Floor * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Cap/Floor Maturity Tenors * @param adblStrike Array of Cap/Floor Strikes * @param bIsCap TRUE - Contract is a Cap * * @return The Cap/Floor Instance */ public static final org.drip.product.fra.FRAStandardCapFloor[] CapFloor ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor, final double[] adblStrike, final boolean bIsCap) { if (null == astrMaturityTenor || null == adblStrike) return null; int iNumCapFloor = astrMaturityTenor.length; org.drip.product.fra.FRAStandardCapFloor[] aFRACapFloor = new org.drip.product.fra.FRAStandardCapFloor[iNumCapFloor]; if (0 == iNumCapFloor || iNumCapFloor != adblStrike.length) return null; for (int i = 0; i < iNumCapFloor; ++i) { if (null == (aFRACapFloor[i] = org.drip.service.template.OTCInstrumentBuilder.CapFloor (dtSpot, forwardLabel, astrMaturityTenor[i], adblStrike[i], bIsCap))) return null; } return aFRACapFloor; } }
lakshmiDRIP/DRIP
src/main/java/org/drip/service/template/OTCInstrumentBuilder.java
Java
apache-2.0
33,137
package org.wso2.carbon.apimgt.rest.api.publisher.v1; import org.wso2.carbon.apimgt.rest.api.publisher.v1.*; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.*; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.KeyManagerListDTO; import java.util.List; import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; public interface KeyManagersApiService { public Response keyManagersGet(MessageContext messageContext) throws APIManagementException; }
nuwand/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/KeyManagersApiService.java
Java
apache-2.0
733
import React from "react"; import { mount } from "enzyme"; import { TextArea as VanillaTextArea } from "hig-vanilla"; import TextAreaAdapter from "./TextAreaAdapter"; describe("TextAreaAdapter", () => { it("implements the hig interface", () => { expect(spiedInstance => { mount( <TextAreaAdapter higInstance={spiedInstance} value="TextArea" instructions="Type in your favorite word" placeholder="Fizz" label="Favorite word" name="favorite-word" disabled required="You really have to fill this out" onBlur={() => {}} onChange={() => {}} onFocus={() => {}} onInput={() => {}} /> ); mount( <TextAreaAdapter higInstance={spiedInstance} disabled={false} required="" /> ); }).toImplementHIGInterfaceOf(VanillaTextArea); }); });
hyoshizumi/hig
packages/react/src/adapters/FormElements/TextAreaAdapter.test.js
JavaScript
apache-2.0
941
// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.12.3 // source: proto/google/fhir/proto/r5/core/resources/event_definition.proto package event_definition_go_proto import ( any "github.com/golang/protobuf/ptypes/any" _ "github.com/google/fhir/go/proto/google/fhir/proto/annotations_go_proto" codes_go_proto "github.com/google/fhir/go/proto/google/fhir/proto/r5/core/codes_go_proto" datatypes_go_proto "github.com/google/fhir/go/proto/google/fhir/proto/r5/core/datatypes_go_proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Auto-generated from StructureDefinition for EventDefinition, last updated // 2019-12-31T21:03:40.621+11:00. A description of when an event can occur. See // http://hl7.org/fhir/StructureDefinition/EventDefinition type EventDefinition struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Logical id of this artifact Id *datatypes_go_proto.Id `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Metadata about the resource Meta *datatypes_go_proto.Meta `protobuf:"bytes,2,opt,name=meta,proto3" json:"meta,omitempty"` // A set of rules under which this content was created ImplicitRules *datatypes_go_proto.Uri `protobuf:"bytes,3,opt,name=implicit_rules,json=implicitRules,proto3" json:"implicit_rules,omitempty"` // Language of the resource content Language *datatypes_go_proto.Code `protobuf:"bytes,4,opt,name=language,proto3" json:"language,omitempty"` // Text summary of the resource, for human interpretation Text *datatypes_go_proto.Narrative `protobuf:"bytes,5,opt,name=text,proto3" json:"text,omitempty"` // Contained, inline Resources Contained []*any.Any `protobuf:"bytes,6,rep,name=contained,proto3" json:"contained,omitempty"` // Additional content defined by implementations Extension []*datatypes_go_proto.Extension `protobuf:"bytes,8,rep,name=extension,proto3" json:"extension,omitempty"` // Extensions that cannot be ignored ModifierExtension []*datatypes_go_proto.Extension `protobuf:"bytes,9,rep,name=modifier_extension,json=modifierExtension,proto3" json:"modifier_extension,omitempty"` // Canonical identifier for this event definition, represented as a URI // (globally unique) Url *datatypes_go_proto.Uri `protobuf:"bytes,10,opt,name=url,proto3" json:"url,omitempty"` // Additional identifier for the event definition Identifier []*datatypes_go_proto.Identifier `protobuf:"bytes,11,rep,name=identifier,proto3" json:"identifier,omitempty"` // Business version of the event definition Version *datatypes_go_proto.String `protobuf:"bytes,12,opt,name=version,proto3" json:"version,omitempty"` // Name for this event definition (computer friendly) Name *datatypes_go_proto.String `protobuf:"bytes,13,opt,name=name,proto3" json:"name,omitempty"` // Name for this event definition (human friendly) Title *datatypes_go_proto.String `protobuf:"bytes,14,opt,name=title,proto3" json:"title,omitempty"` // Subordinate title of the event definition Subtitle *datatypes_go_proto.String `protobuf:"bytes,15,opt,name=subtitle,proto3" json:"subtitle,omitempty"` Status *EventDefinition_StatusCode `protobuf:"bytes,16,opt,name=status,proto3" json:"status,omitempty"` // For testing purposes, not real usage Experimental *datatypes_go_proto.Boolean `protobuf:"bytes,17,opt,name=experimental,proto3" json:"experimental,omitempty"` Subject *EventDefinition_SubjectX `protobuf:"bytes,18,opt,name=subject,proto3" json:"subject,omitempty"` // Date last changed Date *datatypes_go_proto.DateTime `protobuf:"bytes,19,opt,name=date,proto3" json:"date,omitempty"` // Name of the publisher (organization or individual) Publisher *datatypes_go_proto.String `protobuf:"bytes,20,opt,name=publisher,proto3" json:"publisher,omitempty"` // Contact details for the publisher Contact []*datatypes_go_proto.ContactDetail `protobuf:"bytes,21,rep,name=contact,proto3" json:"contact,omitempty"` // Natural language description of the event definition Description *datatypes_go_proto.Markdown `protobuf:"bytes,22,opt,name=description,proto3" json:"description,omitempty"` // The context that the content is intended to support UseContext []*datatypes_go_proto.UsageContext `protobuf:"bytes,23,rep,name=use_context,json=useContext,proto3" json:"use_context,omitempty"` // Intended jurisdiction for event definition (if applicable) Jurisdiction []*datatypes_go_proto.CodeableConcept `protobuf:"bytes,24,rep,name=jurisdiction,proto3" json:"jurisdiction,omitempty"` // Why this event definition is defined Purpose *datatypes_go_proto.Markdown `protobuf:"bytes,25,opt,name=purpose,proto3" json:"purpose,omitempty"` // Describes the clinical usage of the event definition Usage *datatypes_go_proto.String `protobuf:"bytes,26,opt,name=usage,proto3" json:"usage,omitempty"` // Use and/or publishing restrictions Copyright *datatypes_go_proto.Markdown `protobuf:"bytes,27,opt,name=copyright,proto3" json:"copyright,omitempty"` // When the event definition was approved by publisher ApprovalDate *datatypes_go_proto.Date `protobuf:"bytes,28,opt,name=approval_date,json=approvalDate,proto3" json:"approval_date,omitempty"` // When the event definition was last reviewed LastReviewDate *datatypes_go_proto.Date `protobuf:"bytes,29,opt,name=last_review_date,json=lastReviewDate,proto3" json:"last_review_date,omitempty"` // When the event definition is expected to be used EffectivePeriod *datatypes_go_proto.Period `protobuf:"bytes,30,opt,name=effective_period,json=effectivePeriod,proto3" json:"effective_period,omitempty"` // E.g. Education, Treatment, Assessment, etc. Topic []*datatypes_go_proto.CodeableConcept `protobuf:"bytes,31,rep,name=topic,proto3" json:"topic,omitempty"` // Who authored the content Author []*datatypes_go_proto.ContactDetail `protobuf:"bytes,32,rep,name=author,proto3" json:"author,omitempty"` // Who edited the content Editor []*datatypes_go_proto.ContactDetail `protobuf:"bytes,33,rep,name=editor,proto3" json:"editor,omitempty"` // Who reviewed the content Reviewer []*datatypes_go_proto.ContactDetail `protobuf:"bytes,34,rep,name=reviewer,proto3" json:"reviewer,omitempty"` // Who endorsed the content Endorser []*datatypes_go_proto.ContactDetail `protobuf:"bytes,35,rep,name=endorser,proto3" json:"endorser,omitempty"` // Additional documentation, citations, etc. RelatedArtifact []*datatypes_go_proto.RelatedArtifact `protobuf:"bytes,36,rep,name=related_artifact,json=relatedArtifact,proto3" json:"related_artifact,omitempty"` // "when" the event occurs (multiple = 'or') Trigger []*datatypes_go_proto.TriggerDefinition `protobuf:"bytes,37,rep,name=trigger,proto3" json:"trigger,omitempty"` } func (x *EventDefinition) Reset() { *x = EventDefinition{} if protoimpl.UnsafeEnabled { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventDefinition) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventDefinition) ProtoMessage() {} func (x *EventDefinition) ProtoReflect() protoreflect.Message { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventDefinition.ProtoReflect.Descriptor instead. func (*EventDefinition) Descriptor() ([]byte, []int) { return file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescGZIP(), []int{0} } func (x *EventDefinition) GetId() *datatypes_go_proto.Id { if x != nil { return x.Id } return nil } func (x *EventDefinition) GetMeta() *datatypes_go_proto.Meta { if x != nil { return x.Meta } return nil } func (x *EventDefinition) GetImplicitRules() *datatypes_go_proto.Uri { if x != nil { return x.ImplicitRules } return nil } func (x *EventDefinition) GetLanguage() *datatypes_go_proto.Code { if x != nil { return x.Language } return nil } func (x *EventDefinition) GetText() *datatypes_go_proto.Narrative { if x != nil { return x.Text } return nil } func (x *EventDefinition) GetContained() []*any.Any { if x != nil { return x.Contained } return nil } func (x *EventDefinition) GetExtension() []*datatypes_go_proto.Extension { if x != nil { return x.Extension } return nil } func (x *EventDefinition) GetModifierExtension() []*datatypes_go_proto.Extension { if x != nil { return x.ModifierExtension } return nil } func (x *EventDefinition) GetUrl() *datatypes_go_proto.Uri { if x != nil { return x.Url } return nil } func (x *EventDefinition) GetIdentifier() []*datatypes_go_proto.Identifier { if x != nil { return x.Identifier } return nil } func (x *EventDefinition) GetVersion() *datatypes_go_proto.String { if x != nil { return x.Version } return nil } func (x *EventDefinition) GetName() *datatypes_go_proto.String { if x != nil { return x.Name } return nil } func (x *EventDefinition) GetTitle() *datatypes_go_proto.String { if x != nil { return x.Title } return nil } func (x *EventDefinition) GetSubtitle() *datatypes_go_proto.String { if x != nil { return x.Subtitle } return nil } func (x *EventDefinition) GetStatus() *EventDefinition_StatusCode { if x != nil { return x.Status } return nil } func (x *EventDefinition) GetExperimental() *datatypes_go_proto.Boolean { if x != nil { return x.Experimental } return nil } func (x *EventDefinition) GetSubject() *EventDefinition_SubjectX { if x != nil { return x.Subject } return nil } func (x *EventDefinition) GetDate() *datatypes_go_proto.DateTime { if x != nil { return x.Date } return nil } func (x *EventDefinition) GetPublisher() *datatypes_go_proto.String { if x != nil { return x.Publisher } return nil } func (x *EventDefinition) GetContact() []*datatypes_go_proto.ContactDetail { if x != nil { return x.Contact } return nil } func (x *EventDefinition) GetDescription() *datatypes_go_proto.Markdown { if x != nil { return x.Description } return nil } func (x *EventDefinition) GetUseContext() []*datatypes_go_proto.UsageContext { if x != nil { return x.UseContext } return nil } func (x *EventDefinition) GetJurisdiction() []*datatypes_go_proto.CodeableConcept { if x != nil { return x.Jurisdiction } return nil } func (x *EventDefinition) GetPurpose() *datatypes_go_proto.Markdown { if x != nil { return x.Purpose } return nil } func (x *EventDefinition) GetUsage() *datatypes_go_proto.String { if x != nil { return x.Usage } return nil } func (x *EventDefinition) GetCopyright() *datatypes_go_proto.Markdown { if x != nil { return x.Copyright } return nil } func (x *EventDefinition) GetApprovalDate() *datatypes_go_proto.Date { if x != nil { return x.ApprovalDate } return nil } func (x *EventDefinition) GetLastReviewDate() *datatypes_go_proto.Date { if x != nil { return x.LastReviewDate } return nil } func (x *EventDefinition) GetEffectivePeriod() *datatypes_go_proto.Period { if x != nil { return x.EffectivePeriod } return nil } func (x *EventDefinition) GetTopic() []*datatypes_go_proto.CodeableConcept { if x != nil { return x.Topic } return nil } func (x *EventDefinition) GetAuthor() []*datatypes_go_proto.ContactDetail { if x != nil { return x.Author } return nil } func (x *EventDefinition) GetEditor() []*datatypes_go_proto.ContactDetail { if x != nil { return x.Editor } return nil } func (x *EventDefinition) GetReviewer() []*datatypes_go_proto.ContactDetail { if x != nil { return x.Reviewer } return nil } func (x *EventDefinition) GetEndorser() []*datatypes_go_proto.ContactDetail { if x != nil { return x.Endorser } return nil } func (x *EventDefinition) GetRelatedArtifact() []*datatypes_go_proto.RelatedArtifact { if x != nil { return x.RelatedArtifact } return nil } func (x *EventDefinition) GetTrigger() []*datatypes_go_proto.TriggerDefinition { if x != nil { return x.Trigger } return nil } // draft | active | retired | unknown type EventDefinition_StatusCode struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value codes_go_proto.PublicationStatusCode_Value `protobuf:"varint,1,opt,name=value,proto3,enum=google.fhir.r5.core.PublicationStatusCode_Value" json:"value,omitempty"` Id *datatypes_go_proto.String `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Extension []*datatypes_go_proto.Extension `protobuf:"bytes,3,rep,name=extension,proto3" json:"extension,omitempty"` } func (x *EventDefinition_StatusCode) Reset() { *x = EventDefinition_StatusCode{} if protoimpl.UnsafeEnabled { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventDefinition_StatusCode) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventDefinition_StatusCode) ProtoMessage() {} func (x *EventDefinition_StatusCode) ProtoReflect() protoreflect.Message { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventDefinition_StatusCode.ProtoReflect.Descriptor instead. func (*EventDefinition_StatusCode) Descriptor() ([]byte, []int) { return file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescGZIP(), []int{0, 0} } func (x *EventDefinition_StatusCode) GetValue() codes_go_proto.PublicationStatusCode_Value { if x != nil { return x.Value } return codes_go_proto.PublicationStatusCode_INVALID_UNINITIALIZED } func (x *EventDefinition_StatusCode) GetId() *datatypes_go_proto.String { if x != nil { return x.Id } return nil } func (x *EventDefinition_StatusCode) GetExtension() []*datatypes_go_proto.Extension { if x != nil { return x.Extension } return nil } // Type of individual the event definition is focused on type EventDefinition_SubjectX struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Choice: // *EventDefinition_SubjectX_CodeableConcept // *EventDefinition_SubjectX_Reference Choice isEventDefinition_SubjectX_Choice `protobuf_oneof:"choice"` } func (x *EventDefinition_SubjectX) Reset() { *x = EventDefinition_SubjectX{} if protoimpl.UnsafeEnabled { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventDefinition_SubjectX) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventDefinition_SubjectX) ProtoMessage() {} func (x *EventDefinition_SubjectX) ProtoReflect() protoreflect.Message { mi := &file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventDefinition_SubjectX.ProtoReflect.Descriptor instead. func (*EventDefinition_SubjectX) Descriptor() ([]byte, []int) { return file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescGZIP(), []int{0, 1} } func (m *EventDefinition_SubjectX) GetChoice() isEventDefinition_SubjectX_Choice { if m != nil { return m.Choice } return nil } func (x *EventDefinition_SubjectX) GetCodeableConcept() *datatypes_go_proto.CodeableConcept { if x, ok := x.GetChoice().(*EventDefinition_SubjectX_CodeableConcept); ok { return x.CodeableConcept } return nil } func (x *EventDefinition_SubjectX) GetReference() *datatypes_go_proto.Reference { if x, ok := x.GetChoice().(*EventDefinition_SubjectX_Reference); ok { return x.Reference } return nil } type isEventDefinition_SubjectX_Choice interface { isEventDefinition_SubjectX_Choice() } type EventDefinition_SubjectX_CodeableConcept struct { CodeableConcept *datatypes_go_proto.CodeableConcept `protobuf:"bytes,1,opt,name=codeable_concept,json=codeableConcept,proto3,oneof"` } type EventDefinition_SubjectX_Reference struct { Reference *datatypes_go_proto.Reference `protobuf:"bytes,2,opt,name=reference,proto3,oneof"` } func (*EventDefinition_SubjectX_CodeableConcept) isEventDefinition_SubjectX_Choice() {} func (*EventDefinition_SubjectX_Reference) isEventDefinition_SubjectX_Choice() {} var File_proto_google_fhir_proto_r5_core_resources_event_definition_proto protoreflect.FileDescriptor var file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDesc = []byte{ 0x0a, 0x40, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x35, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x13, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x29, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x35, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x35, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9e, 0x16, 0x0a, 0x0f, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x49, 0x64, 0x52, 0x02, 0x69, 0x64, 0x12, 0x2d, 0x0a, 0x04, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x52, 0x04, 0x6d, 0x65, 0x74, 0x61, 0x12, 0x3f, 0x0a, 0x0e, 0x69, 0x6d, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x5f, 0x72, 0x75, 0x6c, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x55, 0x72, 0x69, 0x52, 0x0d, 0x69, 0x6d, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x52, 0x75, 0x6c, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x08, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x08, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x12, 0x32, 0x0a, 0x04, 0x74, 0x65, 0x78, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x4e, 0x61, 0x72, 0x72, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x04, 0x74, 0x65, 0x78, 0x74, 0x12, 0x32, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x12, 0x3c, 0x0a, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x12, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x72, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x11, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x72, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x03, 0x75, 0x72, 0x6c, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x55, 0x72, 0x69, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x3f, 0x0a, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x52, 0x0a, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x35, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x31, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x37, 0x0a, 0x08, 0x73, 0x75, 0x62, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x08, 0x73, 0x75, 0x62, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x4f, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x42, 0x06, 0xf0, 0xd0, 0x87, 0xeb, 0x04, 0x01, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x40, 0x0a, 0x0c, 0x65, 0x78, 0x70, 0x65, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x65, 0x61, 0x6e, 0x52, 0x0c, 0x65, 0x78, 0x70, 0x65, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x12, 0x47, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x58, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x31, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x65, 0x18, 0x13, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x52, 0x04, 0x64, 0x61, 0x74, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x65, 0x72, 0x12, 0x3c, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x18, 0x15, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x12, 0x3f, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x16, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x64, 0x6f, 0x77, 0x6e, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x42, 0x0a, 0x0b, 0x75, 0x73, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x17, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x55, 0x73, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x52, 0x0a, 0x75, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x12, 0x48, 0x0a, 0x0c, 0x6a, 0x75, 0x72, 0x69, 0x73, 0x64, 0x69, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x18, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x65, 0x70, 0x74, 0x52, 0x0c, 0x6a, 0x75, 0x72, 0x69, 0x73, 0x64, 0x69, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x37, 0x0a, 0x07, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x18, 0x19, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x64, 0x6f, 0x77, 0x6e, 0x52, 0x07, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x12, 0x31, 0x0a, 0x05, 0x75, 0x73, 0x61, 0x67, 0x65, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x05, 0x75, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3b, 0x0a, 0x09, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x18, 0x1b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x64, 0x6f, 0x77, 0x6e, 0x52, 0x09, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x12, 0x3e, 0x0a, 0x0d, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x5f, 0x64, 0x61, 0x74, 0x65, 0x18, 0x1c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x65, 0x52, 0x0c, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x61, 0x6c, 0x44, 0x61, 0x74, 0x65, 0x12, 0x43, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, 0x5f, 0x64, 0x61, 0x74, 0x65, 0x18, 0x1d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x65, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x52, 0x65, 0x76, 0x69, 0x65, 0x77, 0x44, 0x61, 0x74, 0x65, 0x12, 0x46, 0x0a, 0x10, 0x65, 0x66, 0x66, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x52, 0x0f, 0x65, 0x66, 0x66, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x12, 0x3a, 0x0a, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x18, 0x1f, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x65, 0x70, 0x74, 0x52, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x12, 0x3a, 0x0a, 0x06, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x18, 0x20, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x52, 0x06, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x12, 0x3a, 0x0a, 0x06, 0x65, 0x64, 0x69, 0x74, 0x6f, 0x72, 0x18, 0x21, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x52, 0x06, 0x65, 0x64, 0x69, 0x74, 0x6f, 0x72, 0x12, 0x3e, 0x0a, 0x08, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, 0x65, 0x72, 0x18, 0x22, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x52, 0x08, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, 0x65, 0x72, 0x12, 0x3e, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x6f, 0x72, 0x73, 0x65, 0x72, 0x18, 0x23, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x6f, 0x72, 0x73, 0x65, 0x72, 0x12, 0x4f, 0x0a, 0x10, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x18, 0x24, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x41, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x52, 0x0f, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x41, 0x72, 0x74, 0x69, 0x66, 0x61, 0x63, 0x74, 0x12, 0x48, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x25, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x06, 0xf0, 0xd0, 0x87, 0xeb, 0x04, 0x01, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x1a, 0xae, 0x02, 0x0a, 0x0a, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x46, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x2b, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x52, 0x02, 0x69, 0x64, 0x12, 0x3c, 0x0a, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x3a, 0x6d, 0xc0, 0x9f, 0xe3, 0xb6, 0x05, 0x01, 0x8a, 0xf9, 0x83, 0xb2, 0x05, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x68, 0x6c, 0x37, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x53, 0x65, 0x74, 0x2f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x9a, 0xb5, 0x8e, 0x93, 0x06, 0x2c, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x68, 0x6c, 0x37, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x75, 0x72, 0x65, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x1a, 0xbc, 0x01, 0x0a, 0x08, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x58, 0x12, 0x51, 0x0a, 0x10, 0x63, 0x6f, 0x64, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x65, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x65, 0x70, 0x74, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x64, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x63, 0x65, 0x70, 0x74, 0x12, 0x4b, 0x0a, 0x09, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x42, 0x0b, 0xf2, 0xff, 0xfc, 0xc2, 0x06, 0x05, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x48, 0x00, 0x52, 0x09, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x3a, 0x06, 0xa0, 0x83, 0x83, 0xe8, 0x06, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x63, 0x68, 0x6f, 0x69, 0x63, 0x65, 0x3a, 0x73, 0xc0, 0x9f, 0xe3, 0xb6, 0x05, 0x03, 0xb2, 0xfe, 0xe4, 0x97, 0x06, 0x37, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x68, 0x6c, 0x37, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x75, 0x72, 0x65, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x9a, 0x86, 0x93, 0xa0, 0x08, 0x2a, 0x6e, 0x61, 0x6d, 0x65, 0x2e, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x28, 0x27, 0x5b, 0x41, 0x2d, 0x5a, 0x5d, 0x28, 0x5b, 0x41, 0x2d, 0x5a, 0x61, 0x2d, 0x7a, 0x30, 0x2d, 0x39, 0x5f, 0x5d, 0x29, 0x7b, 0x30, 0x2c, 0x32, 0x35, 0x34, 0x7d, 0x27, 0x29, 0x4a, 0x04, 0x08, 0x07, 0x10, 0x08, 0x42, 0x80, 0x01, 0x0a, 0x17, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x66, 0x68, 0x69, 0x72, 0x2e, 0x72, 0x35, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x50, 0x01, 0x5a, 0x5d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x66, 0x68, 0x69, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x35, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x67, 0x6f, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x98, 0xc6, 0xb0, 0xb5, 0x07, 0x05, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescOnce sync.Once file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescData = file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDesc ) func file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescGZIP() []byte { file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescOnce.Do(func() { file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescData) }) return file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDescData } var file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_goTypes = []interface{}{ (*EventDefinition)(nil), // 0: google.fhir.r5.core.EventDefinition (*EventDefinition_StatusCode)(nil), // 1: google.fhir.r5.core.EventDefinition.StatusCode (*EventDefinition_SubjectX)(nil), // 2: google.fhir.r5.core.EventDefinition.SubjectX (*datatypes_go_proto.Id)(nil), // 3: google.fhir.r5.core.Id (*datatypes_go_proto.Meta)(nil), // 4: google.fhir.r5.core.Meta (*datatypes_go_proto.Uri)(nil), // 5: google.fhir.r5.core.Uri (*datatypes_go_proto.Code)(nil), // 6: google.fhir.r5.core.Code (*datatypes_go_proto.Narrative)(nil), // 7: google.fhir.r5.core.Narrative (*any.Any)(nil), // 8: google.protobuf.Any (*datatypes_go_proto.Extension)(nil), // 9: google.fhir.r5.core.Extension (*datatypes_go_proto.Identifier)(nil), // 10: google.fhir.r5.core.Identifier (*datatypes_go_proto.String)(nil), // 11: google.fhir.r5.core.String (*datatypes_go_proto.Boolean)(nil), // 12: google.fhir.r5.core.Boolean (*datatypes_go_proto.DateTime)(nil), // 13: google.fhir.r5.core.DateTime (*datatypes_go_proto.ContactDetail)(nil), // 14: google.fhir.r5.core.ContactDetail (*datatypes_go_proto.Markdown)(nil), // 15: google.fhir.r5.core.Markdown (*datatypes_go_proto.UsageContext)(nil), // 16: google.fhir.r5.core.UsageContext (*datatypes_go_proto.CodeableConcept)(nil), // 17: google.fhir.r5.core.CodeableConcept (*datatypes_go_proto.Date)(nil), // 18: google.fhir.r5.core.Date (*datatypes_go_proto.Period)(nil), // 19: google.fhir.r5.core.Period (*datatypes_go_proto.RelatedArtifact)(nil), // 20: google.fhir.r5.core.RelatedArtifact (*datatypes_go_proto.TriggerDefinition)(nil), // 21: google.fhir.r5.core.TriggerDefinition (codes_go_proto.PublicationStatusCode_Value)(0), // 22: google.fhir.r5.core.PublicationStatusCode.Value (*datatypes_go_proto.Reference)(nil), // 23: google.fhir.r5.core.Reference } var file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_depIdxs = []int32{ 3, // 0: google.fhir.r5.core.EventDefinition.id:type_name -> google.fhir.r5.core.Id 4, // 1: google.fhir.r5.core.EventDefinition.meta:type_name -> google.fhir.r5.core.Meta 5, // 2: google.fhir.r5.core.EventDefinition.implicit_rules:type_name -> google.fhir.r5.core.Uri 6, // 3: google.fhir.r5.core.EventDefinition.language:type_name -> google.fhir.r5.core.Code 7, // 4: google.fhir.r5.core.EventDefinition.text:type_name -> google.fhir.r5.core.Narrative 8, // 5: google.fhir.r5.core.EventDefinition.contained:type_name -> google.protobuf.Any 9, // 6: google.fhir.r5.core.EventDefinition.extension:type_name -> google.fhir.r5.core.Extension 9, // 7: google.fhir.r5.core.EventDefinition.modifier_extension:type_name -> google.fhir.r5.core.Extension 5, // 8: google.fhir.r5.core.EventDefinition.url:type_name -> google.fhir.r5.core.Uri 10, // 9: google.fhir.r5.core.EventDefinition.identifier:type_name -> google.fhir.r5.core.Identifier 11, // 10: google.fhir.r5.core.EventDefinition.version:type_name -> google.fhir.r5.core.String 11, // 11: google.fhir.r5.core.EventDefinition.name:type_name -> google.fhir.r5.core.String 11, // 12: google.fhir.r5.core.EventDefinition.title:type_name -> google.fhir.r5.core.String 11, // 13: google.fhir.r5.core.EventDefinition.subtitle:type_name -> google.fhir.r5.core.String 1, // 14: google.fhir.r5.core.EventDefinition.status:type_name -> google.fhir.r5.core.EventDefinition.StatusCode 12, // 15: google.fhir.r5.core.EventDefinition.experimental:type_name -> google.fhir.r5.core.Boolean 2, // 16: google.fhir.r5.core.EventDefinition.subject:type_name -> google.fhir.r5.core.EventDefinition.SubjectX 13, // 17: google.fhir.r5.core.EventDefinition.date:type_name -> google.fhir.r5.core.DateTime 11, // 18: google.fhir.r5.core.EventDefinition.publisher:type_name -> google.fhir.r5.core.String 14, // 19: google.fhir.r5.core.EventDefinition.contact:type_name -> google.fhir.r5.core.ContactDetail 15, // 20: google.fhir.r5.core.EventDefinition.description:type_name -> google.fhir.r5.core.Markdown 16, // 21: google.fhir.r5.core.EventDefinition.use_context:type_name -> google.fhir.r5.core.UsageContext 17, // 22: google.fhir.r5.core.EventDefinition.jurisdiction:type_name -> google.fhir.r5.core.CodeableConcept 15, // 23: google.fhir.r5.core.EventDefinition.purpose:type_name -> google.fhir.r5.core.Markdown 11, // 24: google.fhir.r5.core.EventDefinition.usage:type_name -> google.fhir.r5.core.String 15, // 25: google.fhir.r5.core.EventDefinition.copyright:type_name -> google.fhir.r5.core.Markdown 18, // 26: google.fhir.r5.core.EventDefinition.approval_date:type_name -> google.fhir.r5.core.Date 18, // 27: google.fhir.r5.core.EventDefinition.last_review_date:type_name -> google.fhir.r5.core.Date 19, // 28: google.fhir.r5.core.EventDefinition.effective_period:type_name -> google.fhir.r5.core.Period 17, // 29: google.fhir.r5.core.EventDefinition.topic:type_name -> google.fhir.r5.core.CodeableConcept 14, // 30: google.fhir.r5.core.EventDefinition.author:type_name -> google.fhir.r5.core.ContactDetail 14, // 31: google.fhir.r5.core.EventDefinition.editor:type_name -> google.fhir.r5.core.ContactDetail 14, // 32: google.fhir.r5.core.EventDefinition.reviewer:type_name -> google.fhir.r5.core.ContactDetail 14, // 33: google.fhir.r5.core.EventDefinition.endorser:type_name -> google.fhir.r5.core.ContactDetail 20, // 34: google.fhir.r5.core.EventDefinition.related_artifact:type_name -> google.fhir.r5.core.RelatedArtifact 21, // 35: google.fhir.r5.core.EventDefinition.trigger:type_name -> google.fhir.r5.core.TriggerDefinition 22, // 36: google.fhir.r5.core.EventDefinition.StatusCode.value:type_name -> google.fhir.r5.core.PublicationStatusCode.Value 11, // 37: google.fhir.r5.core.EventDefinition.StatusCode.id:type_name -> google.fhir.r5.core.String 9, // 38: google.fhir.r5.core.EventDefinition.StatusCode.extension:type_name -> google.fhir.r5.core.Extension 17, // 39: google.fhir.r5.core.EventDefinition.SubjectX.codeable_concept:type_name -> google.fhir.r5.core.CodeableConcept 23, // 40: google.fhir.r5.core.EventDefinition.SubjectX.reference:type_name -> google.fhir.r5.core.Reference 41, // [41:41] is the sub-list for method output_type 41, // [41:41] is the sub-list for method input_type 41, // [41:41] is the sub-list for extension type_name 41, // [41:41] is the sub-list for extension extendee 0, // [0:41] is the sub-list for field type_name } func init() { file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_init() } func file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_init() { if File_proto_google_fhir_proto_r5_core_resources_event_definition_proto != nil { return } if !protoimpl.UnsafeEnabled { file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventDefinition); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventDefinition_StatusCode); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventDefinition_SubjectX); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes[2].OneofWrappers = []interface{}{ (*EventDefinition_SubjectX_CodeableConcept)(nil), (*EventDefinition_SubjectX_Reference)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_goTypes, DependencyIndexes: file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_depIdxs, MessageInfos: file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_msgTypes, }.Build() File_proto_google_fhir_proto_r5_core_resources_event_definition_proto = out.File file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_rawDesc = nil file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_goTypes = nil file_proto_google_fhir_proto_r5_core_resources_event_definition_proto_depIdxs = nil }
google/fhir
go/proto/google/fhir/proto/r5/core/resources/event_definition_go_proto/event_definition.pb.go
GO
apache-2.0
47,907
"""Voluptuous schemas for the KNX integration.""" import voluptuous as vol from xknx.devices.climate import SetpointShiftMode from homeassistant.const import ( CONF_ADDRESS, CONF_DEVICE_CLASS, CONF_ENTITY_ID, CONF_HOST, CONF_NAME, CONF_PORT, CONF_TYPE, ) import homeassistant.helpers.config_validation as cv from .const import ( CONF_STATE_ADDRESS, CONF_SYNC_STATE, OPERATION_MODES, PRESET_MODES, ColorTempModes, ) class ConnectionSchema: """Voluptuous schema for KNX connection.""" CONF_KNX_LOCAL_IP = "local_ip" TUNNELING_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_KNX_LOCAL_IP): cv.string, vol.Optional(CONF_PORT): cv.port, } ) ROUTING_SCHEMA = vol.Schema({vol.Optional(CONF_KNX_LOCAL_IP): cv.string}) class CoverSchema: """Voluptuous schema for KNX covers.""" CONF_MOVE_LONG_ADDRESS = "move_long_address" CONF_MOVE_SHORT_ADDRESS = "move_short_address" CONF_STOP_ADDRESS = "stop_address" CONF_POSITION_ADDRESS = "position_address" CONF_POSITION_STATE_ADDRESS = "position_state_address" CONF_ANGLE_ADDRESS = "angle_address" CONF_ANGLE_STATE_ADDRESS = "angle_state_address" CONF_TRAVELLING_TIME_DOWN = "travelling_time_down" CONF_TRAVELLING_TIME_UP = "travelling_time_up" CONF_INVERT_POSITION = "invert_position" CONF_INVERT_ANGLE = "invert_angle" DEFAULT_TRAVEL_TIME = 25 DEFAULT_NAME = "KNX Cover" SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MOVE_LONG_ADDRESS): cv.string, vol.Optional(CONF_MOVE_SHORT_ADDRESS): cv.string, vol.Optional(CONF_STOP_ADDRESS): cv.string, vol.Optional(CONF_POSITION_ADDRESS): cv.string, vol.Optional(CONF_POSITION_STATE_ADDRESS): cv.string, vol.Optional(CONF_ANGLE_ADDRESS): cv.string, vol.Optional(CONF_ANGLE_STATE_ADDRESS): cv.string, vol.Optional( CONF_TRAVELLING_TIME_DOWN, default=DEFAULT_TRAVEL_TIME ): cv.positive_int, vol.Optional( CONF_TRAVELLING_TIME_UP, default=DEFAULT_TRAVEL_TIME ): cv.positive_int, vol.Optional(CONF_INVERT_POSITION, default=False): cv.boolean, vol.Optional(CONF_INVERT_ANGLE, default=False): cv.boolean, } ) class BinarySensorSchema: """Voluptuous schema for KNX binary sensors.""" CONF_STATE_ADDRESS = CONF_STATE_ADDRESS CONF_SYNC_STATE = CONF_SYNC_STATE CONF_IGNORE_INTERNAL_STATE = "ignore_internal_state" CONF_AUTOMATION = "automation" CONF_HOOK = "hook" CONF_DEFAULT_HOOK = "on" CONF_COUNTER = "counter" CONF_DEFAULT_COUNTER = 1 CONF_ACTION = "action" CONF_RESET_AFTER = "reset_after" DEFAULT_NAME = "KNX Binary Sensor" AUTOMATION_SCHEMA = vol.Schema( { vol.Optional(CONF_HOOK, default=CONF_DEFAULT_HOOK): cv.string, vol.Optional(CONF_COUNTER, default=CONF_DEFAULT_COUNTER): cv.port, vol.Required(CONF_ACTION): cv.SCRIPT_SCHEMA, } ) AUTOMATIONS_SCHEMA = vol.All(cv.ensure_list, [AUTOMATION_SCHEMA]) SCHEMA = vol.All( cv.deprecated("significant_bit"), vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SYNC_STATE, default=True): vol.Any( vol.All(vol.Coerce(int), vol.Range(min=2, max=1440)), cv.boolean, cv.string, ), vol.Optional(CONF_IGNORE_INTERNAL_STATE, default=False): cv.boolean, vol.Required(CONF_STATE_ADDRESS): cv.string, vol.Optional(CONF_DEVICE_CLASS): cv.string, vol.Optional(CONF_RESET_AFTER): cv.positive_int, vol.Optional(CONF_AUTOMATION): AUTOMATIONS_SCHEMA, } ), ) class LightSchema: """Voluptuous schema for KNX lights.""" CONF_STATE_ADDRESS = CONF_STATE_ADDRESS CONF_BRIGHTNESS_ADDRESS = "brightness_address" CONF_BRIGHTNESS_STATE_ADDRESS = "brightness_state_address" CONF_COLOR_ADDRESS = "color_address" CONF_COLOR_STATE_ADDRESS = "color_state_address" CONF_COLOR_TEMP_ADDRESS = "color_temperature_address" CONF_COLOR_TEMP_STATE_ADDRESS = "color_temperature_state_address" CONF_COLOR_TEMP_MODE = "color_temperature_mode" CONF_RGBW_ADDRESS = "rgbw_address" CONF_RGBW_STATE_ADDRESS = "rgbw_state_address" CONF_MIN_KELVIN = "min_kelvin" CONF_MAX_KELVIN = "max_kelvin" DEFAULT_NAME = "KNX Light" DEFAULT_COLOR_TEMP_MODE = "absolute" DEFAULT_MIN_KELVIN = 2700 # 370 mireds DEFAULT_MAX_KELVIN = 6000 # 166 mireds SCHEMA = vol.Schema( { vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_STATE_ADDRESS): cv.string, vol.Optional(CONF_BRIGHTNESS_ADDRESS): cv.string, vol.Optional(CONF_BRIGHTNESS_STATE_ADDRESS): cv.string, vol.Optional(CONF_COLOR_ADDRESS): cv.string, vol.Optional(CONF_COLOR_STATE_ADDRESS): cv.string, vol.Optional(CONF_COLOR_TEMP_ADDRESS): cv.string, vol.Optional(CONF_COLOR_TEMP_STATE_ADDRESS): cv.string, vol.Optional( CONF_COLOR_TEMP_MODE, default=DEFAULT_COLOR_TEMP_MODE ): cv.enum(ColorTempModes), vol.Optional(CONF_RGBW_ADDRESS): cv.string, vol.Optional(CONF_RGBW_STATE_ADDRESS): cv.string, vol.Optional(CONF_MIN_KELVIN, default=DEFAULT_MIN_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1) ), vol.Optional(CONF_MAX_KELVIN, default=DEFAULT_MAX_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1) ), } ) class ClimateSchema: """Voluptuous schema for KNX climate devices.""" CONF_SETPOINT_SHIFT_ADDRESS = "setpoint_shift_address" CONF_SETPOINT_SHIFT_STATE_ADDRESS = "setpoint_shift_state_address" CONF_SETPOINT_SHIFT_MODE = "setpoint_shift_mode" CONF_SETPOINT_SHIFT_MAX = "setpoint_shift_max" CONF_SETPOINT_SHIFT_MIN = "setpoint_shift_min" CONF_TEMPERATURE_ADDRESS = "temperature_address" CONF_TEMPERATURE_STEP = "temperature_step" CONF_TARGET_TEMPERATURE_ADDRESS = "target_temperature_address" CONF_TARGET_TEMPERATURE_STATE_ADDRESS = "target_temperature_state_address" CONF_OPERATION_MODE_ADDRESS = "operation_mode_address" CONF_OPERATION_MODE_STATE_ADDRESS = "operation_mode_state_address" CONF_CONTROLLER_STATUS_ADDRESS = "controller_status_address" CONF_CONTROLLER_STATUS_STATE_ADDRESS = "controller_status_state_address" CONF_CONTROLLER_MODE_ADDRESS = "controller_mode_address" CONF_CONTROLLER_MODE_STATE_ADDRESS = "controller_mode_state_address" CONF_HEAT_COOL_ADDRESS = "heat_cool_address" CONF_HEAT_COOL_STATE_ADDRESS = "heat_cool_state_address" CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS = ( "operation_mode_frost_protection_address" ) CONF_OPERATION_MODE_NIGHT_ADDRESS = "operation_mode_night_address" CONF_OPERATION_MODE_COMFORT_ADDRESS = "operation_mode_comfort_address" CONF_OPERATION_MODE_STANDBY_ADDRESS = "operation_mode_standby_address" CONF_OPERATION_MODES = "operation_modes" CONF_ON_OFF_ADDRESS = "on_off_address" CONF_ON_OFF_STATE_ADDRESS = "on_off_state_address" CONF_ON_OFF_INVERT = "on_off_invert" CONF_MIN_TEMP = "min_temp" CONF_MAX_TEMP = "max_temp" DEFAULT_NAME = "KNX Climate" DEFAULT_SETPOINT_SHIFT_MODE = "DPT6010" DEFAULT_SETPOINT_SHIFT_MAX = 6 DEFAULT_SETPOINT_SHIFT_MIN = -6 DEFAULT_TEMPERATURE_STEP = 0.1 DEFAULT_ON_OFF_INVERT = False SCHEMA = vol.All( cv.deprecated("setpoint_shift_step", replacement_key=CONF_TEMPERATURE_STEP), vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional( CONF_SETPOINT_SHIFT_MODE, default=DEFAULT_SETPOINT_SHIFT_MODE ): cv.enum(SetpointShiftMode), vol.Optional( CONF_SETPOINT_SHIFT_MAX, default=DEFAULT_SETPOINT_SHIFT_MAX ): vol.All(int, vol.Range(min=0, max=32)), vol.Optional( CONF_SETPOINT_SHIFT_MIN, default=DEFAULT_SETPOINT_SHIFT_MIN ): vol.All(int, vol.Range(min=-32, max=0)), vol.Optional( CONF_TEMPERATURE_STEP, default=DEFAULT_TEMPERATURE_STEP ): vol.All(float, vol.Range(min=0, max=2)), vol.Required(CONF_TEMPERATURE_ADDRESS): cv.string, vol.Required(CONF_TARGET_TEMPERATURE_STATE_ADDRESS): cv.string, vol.Optional(CONF_TARGET_TEMPERATURE_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_STATE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_STATE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_STATUS_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_STATUS_STATE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_MODE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_MODE_STATE_ADDRESS): cv.string, vol.Optional(CONF_HEAT_COOL_ADDRESS): cv.string, vol.Optional(CONF_HEAT_COOL_STATE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_NIGHT_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_COMFORT_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_STANDBY_ADDRESS): cv.string, vol.Optional(CONF_ON_OFF_ADDRESS): cv.string, vol.Optional(CONF_ON_OFF_STATE_ADDRESS): cv.string, vol.Optional( CONF_ON_OFF_INVERT, default=DEFAULT_ON_OFF_INVERT ): cv.boolean, vol.Optional(CONF_OPERATION_MODES): vol.All( cv.ensure_list, [vol.In({**OPERATION_MODES, **PRESET_MODES})] ), vol.Optional(CONF_MIN_TEMP): vol.Coerce(float), vol.Optional(CONF_MAX_TEMP): vol.Coerce(float), } ), ) class SwitchSchema: """Voluptuous schema for KNX switches.""" CONF_STATE_ADDRESS = CONF_STATE_ADDRESS DEFAULT_NAME = "KNX Switch" SCHEMA = vol.Schema( { vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_STATE_ADDRESS): cv.string, } ) class ExposeSchema: """Voluptuous schema for KNX exposures.""" CONF_KNX_EXPOSE_TYPE = CONF_TYPE CONF_KNX_EXPOSE_ATTRIBUTE = "attribute" CONF_KNX_EXPOSE_DEFAULT = "default" CONF_KNX_EXPOSE_ADDRESS = CONF_ADDRESS SCHEMA = vol.Schema( { vol.Required(CONF_KNX_EXPOSE_TYPE): vol.Any(int, float, str), vol.Optional(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_KNX_EXPOSE_ATTRIBUTE): cv.string, vol.Optional(CONF_KNX_EXPOSE_DEFAULT): cv.match_all, vol.Required(CONF_KNX_EXPOSE_ADDRESS): cv.string, } ) class NotifySchema: """Voluptuous schema for KNX notifications.""" DEFAULT_NAME = "KNX Notify" SCHEMA = vol.Schema( { vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) class SensorSchema: """Voluptuous schema for KNX sensors.""" CONF_STATE_ADDRESS = CONF_STATE_ADDRESS CONF_SYNC_STATE = CONF_SYNC_STATE DEFAULT_NAME = "KNX Sensor" SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SYNC_STATE, default=True): vol.Any( vol.All(vol.Coerce(int), vol.Range(min=2, max=1440)), cv.boolean, cv.string, ), vol.Required(CONF_STATE_ADDRESS): cv.string, vol.Required(CONF_TYPE): vol.Any(int, float, str), } ) class SceneSchema: """Voluptuous schema for KNX scenes.""" CONF_SCENE_NUMBER = "scene_number" DEFAULT_NAME = "KNX SCENE" SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_ADDRESS): cv.string, vol.Required(CONF_SCENE_NUMBER): cv.positive_int, } ) class WeatherSchema: """Voluptuous schema for KNX weather station.""" CONF_SYNC_STATE = CONF_SYNC_STATE CONF_KNX_TEMPERATURE_ADDRESS = "address_temperature" CONF_KNX_BRIGHTNESS_SOUTH_ADDRESS = "address_brightness_south" CONF_KNX_BRIGHTNESS_EAST_ADDRESS = "address_brightness_east" CONF_KNX_BRIGHTNESS_WEST_ADDRESS = "address_brightness_west" CONF_KNX_WIND_SPEED_ADDRESS = "address_wind_speed" CONF_KNX_RAIN_ALARM_ADDRESS = "address_rain_alarm" CONF_KNX_FROST_ALARM_ADDRESS = "address_frost_alarm" CONF_KNX_WIND_ALARM_ADDRESS = "address_wind_alarm" CONF_KNX_DAY_NIGHT_ADDRESS = "address_day_night" CONF_KNX_AIR_PRESSURE_ADDRESS = "address_air_pressure" CONF_KNX_HUMIDITY_ADDRESS = "address_humidity" CONF_KNX_EXPOSE_SENSORS = "expose_sensors" DEFAULT_NAME = "KNX Weather Station" SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SYNC_STATE, default=True): vol.Any( vol.All(vol.Coerce(int), vol.Range(min=2, max=1440)), cv.boolean, cv.string, ), vol.Optional(CONF_KNX_EXPOSE_SENSORS, default=False): cv.boolean, vol.Required(CONF_KNX_TEMPERATURE_ADDRESS): cv.string, vol.Optional(CONF_KNX_BRIGHTNESS_SOUTH_ADDRESS): cv.string, vol.Optional(CONF_KNX_BRIGHTNESS_EAST_ADDRESS): cv.string, vol.Optional(CONF_KNX_BRIGHTNESS_WEST_ADDRESS): cv.string, vol.Optional(CONF_KNX_WIND_SPEED_ADDRESS): cv.string, vol.Optional(CONF_KNX_RAIN_ALARM_ADDRESS): cv.string, vol.Optional(CONF_KNX_FROST_ALARM_ADDRESS): cv.string, vol.Optional(CONF_KNX_WIND_ALARM_ADDRESS): cv.string, vol.Optional(CONF_KNX_DAY_NIGHT_ADDRESS): cv.string, vol.Optional(CONF_KNX_AIR_PRESSURE_ADDRESS): cv.string, vol.Optional(CONF_KNX_HUMIDITY_ADDRESS): cv.string, } )
tchellomello/home-assistant
homeassistant/components/knx/schema.py
Python
apache-2.0
14,928
# # Copyright 2015 Fasih # # 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. # class DN(object): def __init__(self, dn): self._dn = dn.replace(',dn', '') self._cn = [] self._displayName = [] self._givenName = [] self._homePhone = [] self._homePostalAddress = [] self._mail = [] self._mobile = [] self._o = [] self._objectClass = [] self._sn = [] self._telephoneNumber = [] self._title = [] @property def dn(self): return self._dn @property def cn(self): return self._cn @cn.setter def cn(self, v): self._cn.append(v) @property def displayName(self): return self._displayName @displayName.setter def displayName(self, v): self._displayName.append(v) @property def givenName(self): return self._givenName @givenName.setter def givenName(self, v): self._givenName.append(v) @property def homePhone(self): return self._homePhone @homePhone.setter def homePhone(self, v): self._homePhone.append(v) @property def homePostalAddress(self): return self._homePostalAddress @homePostalAddress.setter def homePostalAddress(self, v): self._homePostalAddress.append(v) @property def mail(self): return self._mail @mail.setter def mail(self, v): self._mail.append(v) @property def mobile(self): return self._mobile @mobile.setter def mobile(self, v): self._mobile.append(v) @property def o(self): return self._o @o.setter def o(self, v): self._o.append(v) @property def objectClass(self): return self._objectClass @objectClass.setter def objectClass(self, v): self._objectClass.append(v) @property def sn(self): return self._sn @sn.setter def sn(self, v): self._sn.append(v) @property def telephoneNumber(self): return self._telephoneNumber @telephoneNumber.setter def telephoneNumber(self, v): self._telephoneNumber.append(v) @property def title(self): return self._title @title.setter def title(self, v): self._title.append(v) def csv(self): items = [] items.append(self.displayName) items.append(self.givenName) items.append(self.sn) items.append(self.title) items.append(['Home']) items.append(self.homePhone) items.append(['Mobile']) items.append(self.mobile) items.append(['Mobile']) items.append(self.telephoneNumber) items.append(['Home']) items.append(self.homePostalAddress) items.append(self.mail) items.append(self.o) return ','.join([' ::: '.join([x.replace(',', ' ') for x in i]) for i in items]) def __str__(self): s = 'DN<dn=%s' % self._dn if self.cn != []: s += ', cn=%s' % self.cn if self.displayName != []: s += ', displayName=%s' % self.displayName if self.givenName != []: s += ', givenName=%s' % self.givenName if self.homePhone != []: s += ', homePhone=%s' % self.homePhone if self.homePostalAddress != []: s += ', homePostalAddress=%s' % self.homePostalAddress if self.mail != []: s += ', mail=%s' % self.mail if self.mobile != []: s += ', mobile=%s' % self.mobile if self.o != []: s += ', o=%s' % self.o if self.objectClass != []: s += ', objectClass=%s' % self.objectClass if self.sn != []: s += ', sn=%s' % self.sn if self.telephoneNumber != []: s += ', telephoneNumber=%s' % self.telephoneNumber if self.title != []: s += ', title=%s' % self.title return s + '>'
faskiri/barry2gugl
dn.py
Python
apache-2.0
3,915
package jose4j.asym; import org.jose4j.jws.JsonWebSignature; import org.jose4j.lang.JoseException; import java.security.PublicKey; public class Jose4jVerifier { public static void main(String[] args) { String token = new Jose4jProvider().create(); try { new Jose4jVerifier().verify(token); } catch (JoseException e) { e.printStackTrace(); } } public void verify(String token) throws JoseException { JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(token); PublicKey publicKey = ExampleRsaKeyPair.createPublicKey(); jws.setKey(publicKey); boolean signatureVerified = jws.verifySignature(); System.out.println("JWS Signature is valid: " + signatureVerified); String payload = jws.getPayload(); System.out.println("JWS payload: " + payload); } }
nitram509/decentral-authentication-playground
java/src/main/java/jose4j/asym/Jose4jVerifier.java
Java
apache-2.0
847
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2002-2015 Sebastiano Vigna * * 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 vigna.fastutil.ints; import java.util.*; /** An abstract class providing basic methods for lists implementing a type-specific list interface. * * <P>As an additional bonus, this class implements on top of the list operations a type-specific stack. */ public abstract class AbstractIntList extends AbstractIntCollection implements IntList, IntStack { protected AbstractIntList() {} /** Ensures that the given index is nonnegative and not greater than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or greater than the list size. */ protected void ensureIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index > size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than list size (" + ( size() ) + ")" ); } /** Ensures that the given index is nonnegative and smaller than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size. */ protected void ensureRestrictedIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index >= size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than or equal to list size (" + ( size() ) + ")" ); } public void add( final int index, final int k ) { throw new UnsupportedOperationException(); } public boolean add( final int k ) { add( size(), k ); return true; } public int removeInt( int i ) { throw new UnsupportedOperationException(); } public int set( final int index, final int k ) { throw new UnsupportedOperationException(); } public boolean addAll( int index, final Collection<? extends Integer> c ) { ensureIndex( index ); int n = c.size(); if ( n == 0 ) return false; Iterator<? extends Integer> i = c.iterator(); while ( n-- != 0 ) add( index++, i.next() ); return true; } /** Delegates to a more generic method. */ public boolean addAll( final Collection<? extends Integer> c ) { return addAll( size(), c ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntListIterator intListIterator() { return listIterator(); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntListIterator intListIterator( final int index ) { return listIterator( index ); } public IntListIterator iterator() { return listIterator(); } public IntListIterator listIterator() { return listIterator( 0 ); } public IntListIterator listIterator( final int index ) { return new AbstractIntListIterator() { int pos = index, last = -1; public boolean hasNext() { return pos < AbstractIntList.this.size(); } public boolean hasPrevious() { return pos > 0; } public int nextInt() { if ( !hasNext() ) throw new NoSuchElementException(); return AbstractIntList.this.getInt( last = pos++ ); } public int previousInt() { if ( !hasPrevious() ) throw new NoSuchElementException(); return AbstractIntList.this.getInt( last = --pos ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( int k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.add( pos++, k ); last = -1; } public void set( int k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.removeInt( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; } }; } public boolean contains( final int k ) { return indexOf( k ) >= 0; } public int indexOf( final int k ) { final IntListIterator i = listIterator(); int e; while ( i.hasNext() ) { e = i.nextInt(); if ( ( ( k ) == ( e ) ) ) return i.previousIndex(); } return -1; } public int lastIndexOf( final int k ) { IntListIterator i = listIterator( size() ); int e; while ( i.hasPrevious() ) { e = i.previousInt(); if ( ( ( k ) == ( e ) ) ) return i.nextIndex(); } return -1; } public void size( final int size ) { int i = size(); if ( size > i ) while ( i++ < size ) add( ( 0 ) ); else while ( i-- != size ) remove( i ); } public IntList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IndexOutOfBoundsException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new IntSubList( this, from, to ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntList intSubList( final int from, final int to ) { return subList( from, to ); } /** Removes elements of this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * * @param from the start index (inclusive). * @param to the end index (exclusive). */ public void removeElements( final int from, final int to ) { ensureIndex( to ); IntListIterator i = listIterator( from ); int n = to - from; if ( n < 0 ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); while ( n-- != 0 ) { i.nextInt(); i.remove(); } } /** Adds elements to this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * @param index the index at which to add elements. * @param a the array containing the elements. * @param offset the offset of the first element to add. * @param length the number of elements to add. */ public void addElements( int index, final int a[], int offset, int length ) { ensureIndex( index ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); while ( length-- != 0 ) add( index++, a[ offset++ ] ); } public void addElements( final int index, final int a[] ) { addElements( index, a, 0, a.length ); } /** Copies element of this type-specific list into the given array one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * @param from the start index (inclusive). * @param a the destination array. * @param offset the offset into the destination array where to store the first element copied. * @param length the number of elements to be copied. */ public void getElements( final int from, final int a[], int offset, int length ) { IntListIterator i = listIterator( from ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + ( from + length ) + ") is greater than list size (" + size() + ")" ); while ( length-- != 0 ) a[ offset++ ] = i.nextInt(); } private boolean valEquals(final Object a, final Object b ) { return a == null ? b == null : a.equals( b ); } public boolean equals( final Object o ) { if ( o == this ) return true; if ( !( o instanceof List) ) return false; final List<?> l = (List<?>)o; int s = size(); if ( s != l.size() ) return false; if ( l instanceof IntList ) { final IntListIterator i1 = listIterator(), i2 = ( (IntList)l ).listIterator(); while ( s-- != 0 ) if ( i1.nextInt() != i2.nextInt() ) return false; return true; } final ListIterator<?> i1 = listIterator(), i2 = l.listIterator(); while ( s-- != 0 ) if ( !valEquals( i1.next(), i2.next() ) ) return false; return true; } /** Compares this list to another object. If the argument is a {@link List}, this method performs a lexicographical comparison; otherwise, it throws a <code>ClassCastException</code>. * * @param l a list. * @return if the argument is a {@link List}, a negative integer, zero, or a positive integer as this list is lexicographically less than, equal to, or greater than the argument. * @throws ClassCastException if the argument is not a list. */ public int compareTo( final List<? extends Integer> l ) { if ( l == this ) return 0; if ( l instanceof IntList ) { final IntListIterator i1 = listIterator(), i2 = ( (IntList)l ).listIterator(); int r; int e1, e2; while ( i1.hasNext() && i2.hasNext() ) { e1 = i1.nextInt(); e2 = i2.nextInt(); if ( ( r = ( Integer.compare( ( e1 ), ( e2 ) ) ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } ListIterator<? extends Integer> i1 = listIterator(), i2 = l.listIterator(); int r; while ( i1.hasNext() && i2.hasNext() ) { if ( ( r = ( (Comparable<? super Integer>)i1.next() ).compareTo( i2.next() ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } /** Returns the hash code for this list, which is identical to {@link List#hashCode()}. * * @return the hash code for this list. */ public int hashCode() { IntegerIterator i = iterator(); int h = 1, s = size(); while ( s-- != 0 ) { int k = i.nextInt(); h = 31 * h + ( k ); } return h; } public void push( int o ) { add( o ); } public int popInt() { if ( isEmpty() ) throw new NoSuchElementException(); return removeInt( size() - 1 ); } public int topInt() { if ( isEmpty() ) throw new NoSuchElementException(); return getInt( size() - 1 ); } public int peekInt( int i ) { return getInt( size() - 1 - i ); } public boolean rem( int k ) { int index = indexOf( k ); if ( index == -1 ) return false; removeInt( index ); return true; } /** Delegates to <code>rem()</code>. */ public boolean remove( final Object o ) { return rem( ( ( ( (Integer)( o ) ).intValue() ) ) ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final IntCollection c ) { return addAll( index, (Collection<? extends Integer>)c ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final IntList l ) { return addAll( index, (IntCollection)l ); } public boolean addAll( final IntCollection c ) { return addAll( size(), c ); } public boolean addAll( final IntList l ) { return addAll( size(), l ); } /** Delegates to the corresponding type-specific method. */ public void add( final int index, final Integer ok ) { add( index, ok.intValue() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer set(final int index, final Integer ok ) { return ( Integer.valueOf( set( index, ok.intValue() ) ) ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer get(final int index ) { return ( Integer.valueOf( getInt( index ) ) ); } /** Delegates to the corresponding type-specific method. */ public int indexOf( final Object ok ) { return indexOf( ( ( ( (Integer)( ok ) ).intValue() ) ) ); } /** Delegates to the corresponding type-specific method. */ public int lastIndexOf( final Object ok ) { return lastIndexOf( ( ( ( (Integer)( ok ) ).intValue() ) ) ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer remove(final int index ) { return ( Integer.valueOf( removeInt( index ) ) ); } /** Delegates to the corresponding type-specific method. */ public void push( Integer o ) { push( o.intValue() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer pop() { return Integer.valueOf( popInt() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer top() { return Integer.valueOf( topInt() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer peek(int i ) { return Integer.valueOf( peekInt( i ) ); } public String toString() { final StringBuilder s = new StringBuilder(); final IntegerIterator i = iterator(); int n = size(); int k; boolean first = true; s.append( "[" ); while ( n-- != 0 ) { if ( first ) first = false; else s.append( ", " ); k = i.nextInt(); s.append( String.valueOf( k ) ); } s.append( "]" ); return s.toString(); } public static class IntSubList extends AbstractIntList implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; /** The list this sublist restricts. */ protected final IntList l; /** Initial (inclusive) index of this sublist. */ protected final int from; /** Final (exclusive) index of this sublist. */ protected int to; private static final boolean ASSERTS = false; public IntSubList( final IntList l, final int from, final int to ) { this.l = l; this.from = from; this.to = to; } private void assertRange() { if ( ASSERTS ) { assert from <= l.size(); assert to <= l.size(); assert to >= from; } } public boolean add( final int k ) { l.add( to, k ); to++; if ( ASSERTS ) assertRange(); return true; } public void add( final int index, final int k ) { ensureIndex( index ); l.add( from + index, k ); to++; if ( ASSERTS ) assertRange(); } public boolean addAll( final int index, final Collection<? extends Integer> c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public int getInt( int index ) { ensureRestrictedIndex( index ); return l.getInt( from + index ); } public int removeInt( int index ) { ensureRestrictedIndex( index ); to--; return l.removeInt( from + index ); } public int set( int index, int k ) { ensureRestrictedIndex( index ); return l.set( from + index, k ); } public void clear() { removeElements( 0, size() ); if ( ASSERTS ) assertRange(); } public int size() { return to - from; } public void getElements( final int from, final int[] a, final int offset, final int length ) { ensureIndex( from ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + from + length + ") is greater than list size (" + size() + ")" ); l.getElements( this.from + from, a, offset, length ); } public void removeElements( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); l.removeElements( this.from + from, this.from + to ); this.to -= ( to - from ); if ( ASSERTS ) assertRange(); } public void addElements( int index, final int a[], int offset, int length ) { ensureIndex( index ); l.addElements( this.from + index, a, offset, length ); this.to += length; if ( ASSERTS ) assertRange(); } public IntListIterator listIterator( final int index ) { ensureIndex( index ); return new AbstractIntListIterator() { int pos = index, last = -1; public boolean hasNext() { return pos < size(); } public boolean hasPrevious() { return pos > 0; } public int nextInt() { if ( !hasNext() ) throw new NoSuchElementException(); return l.getInt( from + ( last = pos++ ) ); } public int previousInt() { if ( !hasPrevious() ) throw new NoSuchElementException(); return l.getInt( from + ( last = --pos ) ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( int k ) { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.add( pos++, k ); last = -1; if ( ASSERTS ) assertRange(); } public void set( int k ) { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.removeInt( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; if ( ASSERTS ) assertRange(); } }; } public IntList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new IntSubList( this, from, to ); } public boolean rem( int k ) { int index = indexOf( k ); if ( index == -1 ) return false; to--; l.removeInt( from + index ); if ( ASSERTS ) assertRange(); return true; } public boolean remove( final Object o ) { return rem( ( ( ( (Integer)( o ) ).intValue() ) ) ); } public boolean addAll( final int index, final IntCollection c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public boolean addAll( final int index, final IntList l ) { ensureIndex( index ); to += l.size(); if ( ASSERTS ) { boolean retVal = this.l.addAll( from + index, l ); assertRange(); return retVal; } return this.l.addAll( from + index, l ); } } }
tommyettinger/doughyo
src/main/java/vigna/fastutil/ints/AbstractIntList.java
Java
apache-2.0
19,931
/* * Copyright 2008-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.griffon.runtime.javafx; import griffon.core.GriffonApplication; import griffon.core.GriffonController; import griffon.core.controller.GriffonControllerAction; import org.codehaus.griffon.runtime.core.controller.AbstractGriffonControllerActionManager; /** * @author Andres Almiray */ public class JavaFXGriffonControllerActionManager extends AbstractGriffonControllerActionManager { protected JavaFXGriffonControllerActionManager(GriffonApplication app) { super(app); } @Override protected GriffonControllerAction createControllerAction(GriffonController controller, String actionName) { return new JavaFXGriffonControllerAction(this, controller, actionName); } }
deanriverson/griffon-javafx-plugin
src/main/org/codehaus/griffon/runtime/javafx/JavaFXGriffonControllerActionManager.java
Java
apache-2.0
1,346
/* * This file is part of WebScarab, an Open Web Application Security * Project utility. For details, please see http://www.owasp.org/ * * Copyright (c) 2002 - 2004 Rogan Dawes * * Please note that this file was originally released under the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. * * As of October 2014 Rogan Dawes granted the OWASP ZAP Project permission to * redistribute this code under the Apache License, Version 2.0: * * * 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 ch.csnc.extension.httpclient; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.log4j.Logger; import ch.csnc.extension.util.Encoding; public class SSLContextManager { /** * The canonical class name of Sun PKCS#11 Provider. */ public static final String SUN_PKCS11_CANONICAL_CLASS_NAME = "sun.security.pkcs11.SunPKCS11"; /** * The canonical class name of IBMPKCS11Impl Provider. */ public static final String IBM_PKCS11_CONONICAL_CLASS_NAME = "com.ibm.crypto.pkcs11impl.provider.IBMPKCS11Impl"; /** * The name for providers of type PKCS#11. * * @see #isProviderAvailable(String) */ public static final String PKCS11_PROVIDER_TYPE = "PKCS11"; /** * The name of the {@code KeyStore} type of Sun PKCS#11 Provider. * * @see KeyStore#getInstance(String, Provider) */ private static final String SUN_PKCS11_KEYSTORE_TYPE = "PKCS11"; /** * The name of the {@code KeyStore} type of IBMPKCS11Impl Provider. * * @see KeyStore#getInstance(String, Provider) */ private static final String IBM_PKCS11_KEYSTORE_TYPE = "PKCS11IMPLKS"; private Map<String, SSLContext> _contextMaps = new TreeMap<String, SSLContext>(); private SSLContext _noClientCertContext; private String _defaultKey = null; private Map<String, Map<?, ?>> _aliasPasswords = new HashMap<String, Map<?, ?>>(); private List<KeyStore> _keyStores = new ArrayList<KeyStore>(); private Map<KeyStore, String> _keyStoreDescriptions = new HashMap<KeyStore, String>(); private Map<KeyStore, String> _keyStorePasswords = new HashMap<KeyStore, String>(); private static Logger log = Logger.getLogger(SSLContextManager.class); private static TrustManager[] _trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; private int _defaultKeystoreIndex = -1; private int _defaultAliasIndex = -1; /** Creates a new instance of SSLContextManager */ public SSLContextManager() { try { _noClientCertContext = SSLContext.getInstance("SSL"); _noClientCertContext.init(null, _trustAllCerts, new SecureRandom()); } catch (NoSuchAlgorithmException nsao) { log.error("Could not get an instance of the SSL algorithm: " + nsao.getMessage(), nsao); } catch (KeyManagementException kme) { log.error("Error initialising the SSL Context: " + kme.getMessage(), kme); } try { initMSCAPI(); } catch (Exception e) { } } public boolean isProviderAvailable(String type) { try { if (type.equals(PKCS11_PROVIDER_TYPE)) { try { Class.forName(SUN_PKCS11_CANONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { Class.forName(IBM_PKCS11_CONONICAL_CLASS_NAME); return true; } } else if (type.equals("msks")) { Class.forName("se.assembla.jce.provider.ms.MSProvider"); return true; } } catch (Throwable ignore) { } return false; } private int addKeyStore(KeyStore ks, String description, String password) { int index = _keyStores.indexOf(ks); if (index == -1) { _keyStores.add(ks); index = _keyStores.size() - 1; } _keyStoreDescriptions.put(ks, description); _keyStorePasswords.put(ks, password); return index; } public boolean removeKeyStore(int keystoreIndex) { boolean isDefaultKeyStore = (keystoreIndex == _defaultKeystoreIndex); KeyStore ks = _keyStores.get(keystoreIndex); _keyStores.remove(ks); _keyStoreDescriptions.remove(ks); _keyStorePasswords.remove(ks); if (isDefaultKeyStore) { _defaultKeystoreIndex = -1; _defaultAliasIndex = -1; } return isDefaultKeyStore; } public int getKeyStoreCount() { return _keyStores.size(); } public String getKeyStoreDescription(int keystoreIndex) { return _keyStoreDescriptions.get(_keyStores.get(keystoreIndex)); } public String getKeyStorePassword(int keystoreIndex) { return _keyStorePasswords.get(_keyStores.get(keystoreIndex)); } public int getAliasCount(int keystoreIndex) { return getAliases(_keyStores.get(keystoreIndex)).size(); } public String getAliasAt(int keystoreIndex, int aliasIndex) { return getAliases(_keyStores.get(keystoreIndex)).get(aliasIndex).getAlias(); } private List<AliasCertificate> getAliases(KeyStore ks) { List<AliasCertificate> aliases = new ArrayList<AliasCertificate>(); try { Enumeration<String> en = ks.aliases(); boolean isIbm = isIbmPKCS11Provider(); while (en.hasMoreElements()) { String alias = en.nextElement(); // Sun's and IBM's KeyStore implementations behave differently... // With IBM's KeyStore impl #getCertificate(String) returns null when #isKeyEntry(String) returns true. // If IBM add all certificates and let the user choose the correct one. if (ks.isKeyEntry(alias) || (isIbm && ks.isCertificateEntry(alias))) { Certificate cert = ks.getCertificate(alias); // IBM: Maybe we should check the KeyUsage? // ((X509Certificate) cert).getKeyUsage()[0] AliasCertificate aliasCert = new AliasCertificate(cert, alias); aliases.add(aliasCert); } } } catch (KeyStoreException kse) { kse.printStackTrace(); } return aliases; } public List<AliasCertificate> getAliases(int ks) { return getAliases(_keyStores.get(ks)); } public Certificate getCertificate(int keystoreIndex, int aliasIndex) { try { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); return ks.getCertificate(alias); } catch (Exception e) { return null; } } public String getFingerPrint(Certificate cert) throws KeyStoreException { if (!(cert instanceof X509Certificate)) { return null; } StringBuffer buff = new StringBuffer(); X509Certificate x509 = (X509Certificate) cert; try { String fingerprint = Encoding.hashMD5(cert.getEncoded()); for (int i = 0; i < fingerprint.length(); i += 2) { buff.append(fingerprint.substring(i, i + 1)).append(":"); } buff.deleteCharAt(buff.length() - 1); } catch (CertificateEncodingException e) { throw new KeyStoreException(e.getMessage()); } String dn = x509.getSubjectDN().getName(); log.info("Fingerprint is " + buff.toString().toUpperCase()); return buff.toString().toUpperCase() + " " + dn; } public boolean isKeyUnlocked(int keystoreIndex, int aliasIndex) { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); Map<?, ?> pwmap = _aliasPasswords.get(ks); if (pwmap == null) { return false; } return pwmap.containsKey(alias); } public void setDefaultKey(int keystoreIndex, int aliasIndex) throws KeyStoreException { _defaultKeystoreIndex = keystoreIndex; _defaultAliasIndex = aliasIndex; if ((_defaultKeystoreIndex == -1) || (_defaultAliasIndex == -1)) { _defaultKey = ""; } else { _defaultKey = getFingerPrint(getCertificate(keystoreIndex, aliasIndex)); } } public String getDefaultKey() { return _defaultKey; } public Certificate getDefaultCertificate() { return getCertificate(_defaultKeystoreIndex, _defaultAliasIndex); } public int initMSCAPI() throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException { try { if (!isProviderAvailable("msks")) { return -1; } Provider mscapi = (Provider) Class.forName("se.assembla.jce.provider.ms.MSProvider").newInstance(); Security.addProvider(mscapi); // init the key store KeyStore ks = KeyStore.getInstance("msks", "assembla"); ks.load(null, null); return addKeyStore(ks, "Microsoft CAPI Store", null); } catch (Exception e) { log.error("Error instantiating the MSCAPI provider: " + e.getMessage(), e); return -1; } } /* * public int initCryptoApi() throws KeyStoreException, * NoSuchAlgorithmException, CertificateException, IOException{ * * Provider mscapi = new sun.security.mscapi.SunMSCAPI(); * Security.addProvider(mscapi); * * KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); * * return addKeyStore(ks, "CryptoAPI", null); } */ public int initPKCS11(PKCS11Configuration configuration, String kspassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) { return -1; } Provider pkcs11 = createPKCS11Provider(configuration); Security.addProvider(pkcs11); // init the key store KeyStore ks = getPKCS11KeyStore(pkcs11.getName()); ks.load(null, kspassword == null ? null : kspassword.toCharArray()); return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code } private static Provider createPKCS11Provider(PKCS11Configuration configuration) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Provider pkcs11 = null; if (isSunPKCS11Provider()) { pkcs11 = createInstance(SUN_PKCS11_CANONICAL_CLASS_NAME, InputStream.class, configuration.toInpuStream()); } else if (isIbmPKCS11Provider()) { pkcs11 = createInstance(IBM_PKCS11_CONONICAL_CLASS_NAME, BufferedReader.class, new BufferedReader( new InputStreamReader(configuration.toInpuStream()))); } return pkcs11; } private static Provider createInstance(String name, Class<?> paramClass, Object param) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> instanceClass = Class.forName(name); Constructor<?> c = instanceClass.getConstructor(new Class<?>[] { paramClass }); return (Provider) c.newInstance(new Object[] { param }); } private static boolean isSunPKCS11Provider() { try { Class.forName(SUN_PKCS11_CANONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { } return false; } private static boolean isIbmPKCS11Provider() { try { Class.forName(IBM_PKCS11_CONONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { } return false; } private static KeyStore getPKCS11KeyStore(String providerName) throws KeyStoreException { String keyStoreType = SUN_PKCS11_KEYSTORE_TYPE; if (isIbmPKCS11Provider()) { keyStoreType = IBM_PKCS11_KEYSTORE_TYPE; } return KeyStore.getInstance(keyStoreType, Security.getProvider(providerName)); } public int loadPKCS12Certificate(String filename, String ksPassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Get Filename File file = new File(filename); if (!file.exists()) { throw new FileNotFoundException(filename + " could not be found"); } String name = file.getName(); // Open the file try (InputStream is = new FileInputStream(file)) { // create the keystore KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(is, ksPassword == null ? null : ksPassword.toCharArray()); return addKeyStore(ks, "PKCS#12: " + name, ksPassword); } } public boolean unlockKeyWithDefaultPassword(int keystoreIndex, int aliasIndex) throws KeyManagementException, KeyStoreException { return unlockKey(keystoreIndex, aliasIndex, getKeyStorePassword(keystoreIndex)); } public boolean unlockKey(int keystoreIndex, int aliasIndex, String keyPassword) throws KeyStoreException, KeyManagementException { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); AliasKeyManager akm = new AliasKeyManager(ks, alias, keyPassword); try { akm.getPrivateKey(alias).toString(); } catch (NullPointerException ex) { log.error("Could not get private key: " + ex.getMessage(), ex); return false; } String fingerprint = getFingerPrint(getCertificate(keystoreIndex, aliasIndex)); if (fingerprint == null) { log.info("No fingerprint found"); return false; } SSLContext sc; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException nsao) { log.error("Could not get an instance of the SSL algorithm: " + nsao.getMessage(), nsao); return false; } sc.init(new KeyManager[] { akm }, _trustAllCerts, new SecureRandom()); String key = fingerprint; if (key.indexOf(" ") > 0) { key = key.substring(0, key.indexOf(" ")); } _contextMaps.put(key, sc); log.info("Key has been unlocked."); return true; } public void invalidateSessions() { invalidateSession(_noClientCertContext); Iterator<String> it = _contextMaps.keySet().iterator(); while (it.hasNext()) { invalidateSession(_contextMaps.get(it.next())); } } private void invalidateSession(SSLContext sc) { SSLSessionContext sslsc = sc.getClientSessionContext(); if (sslsc != null) { int timeout = sslsc.getSessionTimeout(); // force sessions to be timed out sslsc.setSessionTimeout(1); sslsc.setSessionTimeout(timeout); } sslsc = sc.getServerSessionContext(); if (sslsc != null) { int timeout = sslsc.getSessionTimeout(); // force sessions to be timed out sslsc.setSessionTimeout(1); sslsc.setSessionTimeout(timeout); } } public SSLContext getSSLContext(String fingerprint) { log.info("Requested SSLContext for " + fingerprint); if (fingerprint == null || fingerprint.equals("none")) { return _noClientCertContext; } if (fingerprint.indexOf(" ") > 0) { fingerprint = fingerprint.substring(0, fingerprint.indexOf(" ")); } return _contextMaps.get(fingerprint); } }
NVolcz/zaproxy
src/ch/csnc/extension/httpclient/SSLContextManager.java
Java
apache-2.0
16,043
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kodemat.touch.visu.editor.nifty.panels; import com.jme3.app.Application; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.builder.EffectBuilder; import de.lessvoid.nifty.builder.ElementBuilder; import de.lessvoid.nifty.builder.HoverEffectBuilder; import de.lessvoid.nifty.builder.ImageBuilder; import de.lessvoid.nifty.builder.PanelBuilder; import de.lessvoid.nifty.controls.AbstractController; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import kodemat.visu.appstates.NiftyGuiAppState; import kodemat.visu.editor.IEditor; import kodemat.touch.visu.editor.TouchVisuEditor; import static kodemat.touch.visu.editor.nifty.panels.TouchImportModelPanel.guiAppState; import kodemat.visu.editor.VisuEditor; import kodemat.visu.editor.nifty.panels.IEditorPanel; import org.openide.util.Exceptions; /** * * @author OzgeA */ public class ViewCube implements IEditorPanel { static NiftyGuiAppState guiAppState; private Element editorPanel; private ViewPanelController viewPanelController; final Nifty nifty; public ViewCube(Application visuClient) { this.guiAppState = visuClient.getStateManager().getState(NiftyGuiAppState.class); nifty = guiAppState.getNifty(); } @Override public void layout(IEditor basicEditor) { final Screen screen = nifty.getScreen("hidden"); Element toolbar = screen.findElementByName("view-cube-panel"); toolbar.setConstraintX(SizeValue.percent(85)); toolbar.setConstraintY(SizeValue.percent(0)); PanelBuilder pb = new PanelBuilder("model-panel") { { height("30%"); childLayoutHorizontal(); valignTop(); controller(ViewPanelController.class.getName()); } }; editorPanel = pb.build(nifty, screen, toolbar); viewPanelController = editorPanel.getControl(ViewPanelController.class); viewPanelController.setBasicEditor((TouchVisuEditor) basicEditor); PanelBuilder pb2 = new PanelBuilder("small-icons-panel") { { height("30%"); childLayoutHorizontal(); valignCenter(); controller(ViewPanelController.class.getName()); } }; Element middlePanel = pb2.build(nifty, screen, toolbar); ViewPanelController middlePanelController = middlePanel.getControl(ViewPanelController.class); middlePanelController.setBasicEditor((TouchVisuEditor) basicEditor); PanelBuilder pb3 = new PanelBuilder("small-icons-panel") { { height("30%"); childLayoutHorizontal(); valignBottom(); controller(ViewPanelController.class.getName()); } }; Element bottomPanel = pb3.build(nifty, screen, toolbar); ViewPanelController bottomPanelController = bottomPanel.getControl(ViewPanelController.class); bottomPanelController.setBasicEditor((TouchVisuEditor) basicEditor); new ImageBuilder("Back") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/back.png"); visibleToMouse(true); interactOnClick("viewBack()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/back.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/back.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/back.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/back.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Back"); } }); } }.build(nifty, screen, editorPanel); new ImageBuilder("Left") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/left.png"); visibleToMouse(true); interactOnClick("viewLeft()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/left.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/left.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/left.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/left.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Left"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Top") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/top.png"); visibleToMouse(true); interactOnClick("viewTop()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/top.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/top.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/top.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/top.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Top"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Left") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/right.png"); visibleToMouse(true); interactOnClick("viewRight()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/right.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/right.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/right.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/right.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Right"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Back") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/front.png"); visibleToMouse(true); interactOnClick("viewOriginal()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/front.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/front.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/front.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/front.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", ""); } }); } }.build(nifty, screen, bottomPanel); toolbar.layoutElements(); } public static class ViewPanelController extends AbstractController { private TouchVisuEditor basicEditor; @Override public void bind(Nifty nifty, Screen screen, Element element, Properties parameter, Attributes controlDefinitionAttributes) { } @Override public void onStartScreen() { } @Override public boolean inputEvent(NiftyInputEvent inputEvent) { return false; } /** * @return the basicEditor */ public TouchVisuEditor getBasicEditor() { return basicEditor; } /** * @param basicEditor the basicEditor to set */ public void setBasicEditor(TouchVisuEditor basicEditor) { this.basicEditor = basicEditor; } public void viewBack() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewBack(); } }); } public void viewOriginal() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewOriginal(); } }); } public void viewLeft() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewLeft(); } }); } public void viewRight() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewRight(); } }); } public void viewTop() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewTop(); } }); } } }
akiskip/KoDeMat-Collaboration-Platform-Application
KoDeMat_TouchScreen/src/kodemat/touch/visu/editor/nifty/panels/ViewCube.java
Java
apache-2.0
12,097
package com.ai.tris.server.dao.interfaces; import com.ai.tris.server.orm.impl.ClientAppInfoBean; import java.util.List; /** * Common Database Access Object. * <p/> * Created by Sam on 2015/6/9. */ public interface ICommonDao { void querySomething(); /** * get all client app information from tris.client_app_info */ List<ClientAppInfoBean> getTrisClientAppInfo(); void insertSomething(long id); }
zhoufan2013/TRIS_Platform
server/src/main/java/com/ai/tris/server/dao/interfaces/ICommonDao.java
Java
apache-2.0
433
maintainer "Ryan J. Geyer" maintainer_email "me@ryangeyer.com" license "All rights reserved" description "Overrides the primary and secondary backup recipes to properly provide mongo data consitency" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.0.1" recipe "block_device::do_primary_backup", :description => "Creates a primary backup in the local cloud where the server is currently running.", :thread => 'block_backup' recipe "block_device::do_secondary_backup", :description => "Creates a secondary backup to the remote cloud specified by block_device/secondary provider", :thread => 'block_backup' all_recipes = [ "block_device::do_primary_backup", "block_device::do_secondary_backup" ] attribute "block_device/devices_to_use", :display_name => "Block Device(s) to Operate On", :description => "The block device(s) to operate on. Can be a comma-separated list of device names or '*' to indicate all devices. Example: device1", :required => "recommended", :default => "device1", :recipes => all_recipes attribute "block_device/devices/default/backup/rackspace_snet", :display_name => "Rackspace SNET Enabled for Backup", :description => "When 'true', Rackspace internal private networking (preferred) is used for communications between servers and Rackspace Cloud Files. Ignored for all other clouds.", :type => "string", :required => "optional", :choice => ["true", "false"], :default => "true", :recipes => all_recipes # Multiple Block Devices device_count = 2 devices = 1.upto(device_count).map {|number| "device#{number}"} # Set up the block device attributes for each device devices.sort.each_with_index.map do |device, index| [device, index + 1] end.each do |device, number| grouping "block_device/devices/#{device}", :title => "Block Device #{number}", :description => "Attributes for the block device: #{device}." attribute "block_device/devices/#{device}/backup/lineage", :display_name => "Backup Lineage (#{number})", :description => "The name associated with your primary and secondary database backups. It's used to associate them with your database environment for maintenance, restore, and replication purposes. Backup snapshots will automatically be tagged with this value (e.g. rs_backup:lineage=mysqlbackup). Backups are identified by their lineage name. Note: For servers running on Rackspace, this value also indicates the Cloud Files container to use for storing primary backups. If a Cloud Files container with this name does not already exist, one will automatically be created.", :required => device != 'device2' ? 'required' : 'optional', :recipes => all_recipes attribute "block_device/devices/#{device}/backup/primary/keep/daily", :display_name => "Keep Daily Backups (#{number})", :description => "The number of daily primary backups to keep (i.e., rotation size).", :required => "optional", :default => "14", :recipes => all_recipes attribute "block_device/devices/#{device}/backup/primary/keep/weekly", :display_name => "Keep Weekly Backups (#{number})", :description => "The number of weekly primary backups to keep (i.e., rotation size).", :required => "optional", :default => "6", :recipes => all_recipes attribute "block_device/devices/#{device}/backup/primary/keep/monthly", :display_name => "Keep Monthly Backups (#{number})", :description => "The number of monthly primary backups to keep (i.e., rotation size).", :required => "optional", :default => "12", :recipes => all_recipes attribute "block_device/devices/#{device}/backup/primary/keep/yearly", :display_name => "Keep Yearly Backups (#{number})", :description => "The number of yearly primary backups to keep (i.e., rotation size).", :required => "optional", :default => "2", :recipes => all_recipes end
cityindex-attic/cookbooks
cookbooks/block_device/metadata.rb
Ruby
apache-2.0
3,924
package org.b3mn.poem.handler; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.b3mn.poem.Identity; import org.b3mn.poem.Persistance; import org.b3mn.poem.business.Model; import org.b3mn.poem.util.AccessRight; import org.b3mn.poem.util.FilterMethod; import org.b3mn.poem.util.HandlerWithModelContext; import org.b3mn.poem.util.RestrictAccess; import org.b3mn.poem.util.SortMethod; import org.json.JSONObject; @HandlerWithModelContext(uri="/rating") public class RatingHandler extends HandlerBase { public void writeRating(Model model, HttpServletResponse response, Identity subject, Identity object) throws Exception { JSONObject rating = new JSONObject(); rating.put("userScore", model.getUserScore(subject)); rating.put("totalScore", model.getTotalScore()); rating.put("totalVotes", model.getTotalVotes()); response.getWriter().println(rating.toString()); } @Override @RestrictAccess(AccessRight.READ) public void doGet(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws Exception { Model model = new Model(object); writeRating(model, response, subject, object); } @Override @RestrictAccess(AccessRight.READ) public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws Exception { Model model = new Model(object); String userScore = request.getParameter("userScore"); if (userScore != null) model.setUserScore(subject, Integer.parseInt(userScore)); writeRating(model, response, subject, object); } @SuppressWarnings("unchecked") @SortMethod(SortName="rating") public static List<String> sortByRating(Identity subject) { List<String> results = Persistance.getSession() .createSQLQuery("SELECT access.object_name FROM " + "access LEFT JOIN model_rating ON access.object_id=model_rating.object_id " + "WHERE (access.subject_name='public' OR access.subject_id=:subject_id) " + "GROUP BY access.object_name " + "ORDER BY avg(model_rating.score) DESC NULLS LAST") .setInteger("subject_id", subject.getId()) .list(); Persistance.commit(); return results; } @SuppressWarnings({ "unchecked" }) @FilterMethod(FilterName="rating") public static Collection<String> filterByRating(Identity subject, String params) { float score = Float.parseFloat(params); List<String> results = Persistance.getSession() .createSQLQuery("SELECT access.object_name FROM access, model_rating " + "WHERE (access.subject_name='public' OR access.subject_id=:subject_id) AND access.object_id=model_rating.object_id " + "GROUP BY access.object_name " + "HAVING avg(model_rating.score) >= :score") .setFloat("score", score) .setInteger("subject_id", subject.getId()) .list(); Persistance.commit(); return results; } }
grasscrm/gdesigner
poem-jvm/src/java/org/b3mn/poem/handler/RatingHandler.java
Java
apache-2.0
2,930
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.am.repository.management.api; import io.gravitee.am.model.Group; import io.gravitee.am.model.ReferenceType; import io.gravitee.am.model.common.Page; import io.gravitee.am.repository.management.AbstractManagementTest; import io.reactivex.observers.TestObserver; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; import java.util.stream.Collectors; import static org.junit.Assert.*; /** * @author Eric LELEU (eric.leleu at graviteesource.com) * @author GraviteeSource Team */ public class GroupRepositoryTest extends AbstractManagementTest { public static final String DOMAIN_ID = "DOMAIN_ID1"; @Autowired protected GroupRepository repository; @Test public void shouldCreateGroup() { Group group = buildGroup(); TestObserver<Group> testObserver = repository.create(group).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId() != null); assertEqualsTo(group, testObserver); } private Group buildGroup() { Group group = new Group(); String random = UUID.randomUUID().toString(); group.setDescription("Description"+random); group.setName("name"+random); group.setReferenceId("ref"+random); group.setReferenceType(ReferenceType.DOMAIN); group.setCreatedAt(new Date()); group.setUpdatedAt(new Date()); group.setRoles(Arrays.asList("r1"+random, "r2"+random)); List<String> members = new ArrayList<>(); members.add("m1"+random); members.add("m2"+random); group.setMembers(members); return group; } private void assertEqualsTo(Group group, TestObserver<Group> testObserver) { testObserver.assertValue(g -> g.getName().equals(group.getName())); testObserver.assertValue(g -> g.getDescription().equals(group.getDescription())); testObserver.assertValue(g -> g.getReferenceId().equals(group.getReferenceId())); testObserver.assertValue(g -> g.getReferenceType().equals(group.getReferenceType())); testObserver.assertValue(g -> g.getMembers().size() == group.getMembers().size()); testObserver.assertValue(g -> g.getMembers().containsAll(group.getMembers())); testObserver.assertValue(g -> g.getRoles().size() == group.getRoles().size()); testObserver.assertValue(g -> g.getRoles().containsAll(group.getRoles())); } @Test public void shouldFindById() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findById(createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldFindById_WithRef() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findById(createdGroup.getReferenceType(), createdGroup.getReferenceId(), createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldUpdate() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); Group toUpdate = buildGroup(); toUpdate.setId(createdGroup.getId()); // update and check response final TestObserver<Group> testUpdate = repository.update(toUpdate).test(); testUpdate.awaitTerminalEvent(); testUpdate.assertComplete(); testUpdate.assertNoErrors(); testUpdate.assertValue(g -> g.getId().equals(toUpdate.getId())); assertEqualsTo(toUpdate, testUpdate); // validate the update using findById TestObserver<Group> testObserver = repository.findById(toUpdate.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(toUpdate.getId())); assertEqualsTo(toUpdate, testObserver); } @Test public void shouldDelete() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); // validate the creation using findById TestObserver<Group> testObserver = repository.findById(createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); final TestObserver<Void> testDelete = repository.delete(createdGroup.getId()).test(); testDelete.awaitTerminalEvent(); testDelete.assertComplete(); testDelete.assertNoErrors(); final Group existAfterDelete = repository.findById(createdGroup.getId()).blockingGet(); assertNull(existAfterDelete); } @Test public void shouldFindByMember() { Group group1 = buildGroup(); Group createdGroup1 = repository.create(group1).blockingGet(); final String member1 = group1.getMembers().get(0); final String member2 = group1.getMembers().get(1); Group group2 = buildGroup(); // create a second group to add the same member as group 1 group2.getMembers().add(member1); Group createdGroup2 = repository.create(group2).blockingGet(); TestObserver<List<Group>> testObserver = repository.findByMember(member1).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.size() == 2); testObserver.assertValue(g -> g.stream().map(Group::getId).collect(Collectors.toSet()).containsAll(Arrays.asList(createdGroup1.getId(), createdGroup2.getId()))); testObserver = repository.findByMember(member2).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.size() == 1); testObserver.assertValue(g -> g.get(0).getId().equals(createdGroup1.getId())); } @Test public void shouldFindAll() { List<Group> emptyList = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(emptyList); assertTrue(emptyList.isEmpty()); final int loop = 10; for (int i = 0; i < loop; ++i) { // build 10 group with random domain repository.create(buildGroup()).blockingGet(); } for (int i = 0; i < loop; ++i) { // build 10 group with DOMAIN_ID final Group item = buildGroup(); item.setReferenceId(DOMAIN_ID); repository.create(item).blockingGet(); } List<Group> groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.size()); assertEquals(loop, groupOfDomain.stream().filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.size()); assertEquals(loop, groupOfDomain.stream().filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); } @Test public void shouldFindAll_WithPage() { List<Group> emptyList = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(emptyList); assertTrue(emptyList.isEmpty()); final int loop = 10; for (int i = 0; i < loop; ++i) { // build 10 group with random domain repository.create(buildGroup()).blockingGet(); } for (int i = 0; i < loop; ++i) { // build 10 group with DOMAIN_ID final Group item = buildGroup(); item.setReferenceId(DOMAIN_ID); repository.create(item).blockingGet(); } Page<Group> groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 0, 20).blockingGet(); assertNotNull(groupOfDomain); assertEquals(0, groupOfDomain.getCurrentPage()); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(loop, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data = groupOfDomain.getData(); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 0, 5).blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(0, groupOfDomain.getCurrentPage()); assertEquals(5, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data1 = groupOfDomain.getData(); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 1, 5).blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(1, groupOfDomain.getCurrentPage()); assertEquals(5, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data2 = groupOfDomain.getData(); Set<String> pagedData = new HashSet<>(); pagedData.addAll(data1.stream().map(Group::getId).collect(Collectors.toSet())); pagedData.addAll(data2.stream().map(Group::getId).collect(Collectors.toSet())); // check that all group are different assertTrue(data.stream().map(Group::getId).collect(Collectors.toSet()).containsAll(pagedData)); } @Test public void shouldFindIdsIn() { final int loop = 10; List<String> ids = new ArrayList<>(); for (int i = 0; i < loop; ++i) { // build 10 group with random domain Group createdGroup = repository.create(buildGroup()).blockingGet(); if (i %2 == 0) { ids.add(createdGroup.getId()); } } final TestObserver<List<Group>> testObserver = repository.findByIdIn(ids).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertNoErrors(); testObserver.assertValue(lg -> lg.size() == ids.size()); testObserver.assertValue(lg -> lg.stream().map(Group::getId).collect(Collectors.toList()).containsAll(ids)); } @Test public void shouldFindByName() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findByName(group.getReferenceType(), group.getReferenceId(), group.getName()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldFindByName_unknown() { Group group = buildGroup(); repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findByName(group.getReferenceType(), group.getReferenceId(), "unknown").test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertNoValues(); } }
gravitee-io/graviteeio-access-management
gravitee-am-repository/gravitee-am-repository-tests/src/test/java/io/gravitee/am/repository/management/api/GroupRepositoryTest.java
Java
apache-2.0
13,131
package com.github.arteam.jdbi3.strategies; import com.codahale.metrics.MetricRegistry; import org.jdbi.v3.core.statement.StatementContext; import org.junit.Before; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AbstractStrategyTest { protected MetricRegistry registry = new MetricRegistry(); protected StatementContext ctx = mock(StatementContext.class); @Before public void setUp() throws Exception { when(ctx.getRawSql()).thenReturn("SELECT 1"); } protected long getTimerMaxValue(String name) { return registry.timer(name).getSnapshot().getMax(); } }
arteam/metrics-jdbi3
src/test/java/com/github/arteam/jdbi3/strategies/AbstractStrategyTest.java
Java
apache-2.0
650
#!/usr/bin/python import re userInput = raw_input("input equation\n") numCount = 0 operandCount = 0 entryBracketCount = 0 exitBracketCount = 0 charCount = 0 endOfLine = len(userInput) - 1 for i in range(len(userInput)): if (re.search('[\s*a-z\s*A-Z]+', userInput[i])): charCount = charCount + 1 print operandCount, " 1" elif (re.search('[\s*0-9]+', userInput[i])): numCount = numCount + 1 print operandCount, " 2" elif (re.search('[\*]', userInput[i])): print 'TRUE' # operandCount = operandCount + 1 # print operandCount, " 3.5" # elif (re.search('[\s*\+|\s*\-|\s*\/]+', userInput[i])): elif (re.search('[+-/*]+', userInput[i])): operandCount = operandCount + 1 print operandCount, " 3" # if(re.search('[\s*\+|\s*\-|\s*\/]+', userInput[endOfLine])): if(re.search('[+-/*]+', userInput[endOfLine])): print "invalid expression" print "1" exit(0) else: if((re.search('[\s*a-zA-Z]+', userInput[i - 1])) or (re.search('[\s*\d]+', userInput[i - 1]))): continue else: print 'invalid expression' print '2' exit(0) if(re.search('[\s*\d]+', userInput[i - 1])): continue else: print 'invalid expression' print '3' exit(0) if(re.search('[\s*a-zA-Z]+', userInput[i + 1])): continue elif(re.search('[\s*\d]+', userInput[i + 1])): continue elif (re.search('[\(]+', userInput[i + 1])): continue elif (re.search('[\)]+', userInput[i + 1])): continue else: print 'invalid expression' print '4' exit(0) elif (re.search('[\(]+', userInput[i])): entryBracketCount = entryBracketCount + 1 print operandCount, " 4" elif (re.search('[\)]+', userInput[i])): exitBracketCount = exitBracketCount + 1 print operandCount, " 5" if(re.search('[\)]+', userInput[endOfLine])): continue else: if(re.search('[\(]+', userInput[i + 1])): print 'invalid expression' print '5' exit(0) print operandCount, " 6" if (entryBracketCount != exitBracketCount): print "invalid expression" print '6' exit(0) elif operandCount == 0: print operandCount print "invalid expression" print '7' exit(0) elif ((numCount == 0) and (charCount == 0)): print "invalid expression" print '8' exit(0) else: print "valid expression"
dominickhera/PosaRepo
cis3250labs/parseTest.py
Python
apache-2.0
2,244
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ForumTriage_Web.Constants { public class Constants { public const int StackOverflowApiPageSize = 100; public const string StackOverflowApiRootUrl = "https://api.stackexchange.com/2.2/"; public DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); } }
martinkearn/Forum-Triage
src/ForumTriage-Web/Constants/Constants.cs
C#
apache-2.0
414
/* * Copyright 2019 Google 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. */ package com.google.jenkins.plugins.containersecurity.client; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.http.HttpTransport; import com.google.cloud.graphite.platforms.plugin.client.ClientFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2Credentials; import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials; import hudson.AbortException; import hudson.model.ItemGroup; import hudson.security.ACL; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import java.util.Optional; import lombok.NonNull; /** * Common utility methods for generating a {@link ClientFactory} that can be used to generate * clients. */ public class ClientUtil { private static final String APPLICATION_NAME = "jenkins-google-container-security"; /** * Creates a {@link ClientFactory} for generating the GCP API clients. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param domainRequirements A list of domain requirements. * @param credentialsId The ID of the credentials to use for generating clients. * @param transport An {@link Optional} parameter that specifies the {@link HttpTransport} to use. * A default will be used if unspecified. * @return A {@link ClientFactory} to get clients. * @throws AbortException If there was an error initializing the ClientFactory. */ public static ClientFactory getClientFactory( @NonNull ItemGroup itemGroup, @NonNull ImmutableList<DomainRequirement> domainRequirements, @NonNull String credentialsId, @NonNull Optional<HttpTransport> transport) throws AbortException { Preconditions.checkArgument( !credentialsId.isEmpty(), Messages.ClientFactory_CredentialsIdRequired()); ClientFactory clientFactory; try { GoogleRobotCredentials robotCreds = getRobotCredentials(itemGroup, domainRequirements, credentialsId); Credential googleCredential = getGoogleCredential(robotCreds); clientFactory = new ClientFactory(transport, googleCredential, APPLICATION_NAME); } catch (IOException | GeneralSecurityException ex) { throw new AbortException(Messages.ClientFactory_FailedToInitializeHTTPTransport(ex)); } return clientFactory; } /** * Creates a {@link ClientFactory} for generating the GCP API clients. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param credentialsId The ID of the credentials to use for generating clients. * @return A {@link ClientFactory} to get clients. * @throws AbortException If there was an error initializing the ClientFactory. */ public static ClientFactory getClientFactory(ItemGroup itemGroup, String credentialsId) throws AbortException { return getClientFactory(itemGroup, ImmutableList.of(), credentialsId, Optional.empty()); } /** * Retrieves the {@link GoogleRobotCredentials} specified by the provided credentialsId. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param domainRequirements A list of domain requirements. * @param credentialsId The ID of the credentials to retrieve. * @return The {@link GoogleRobotCredentials} with the provided ID. * @throws AbortException If there was an error retrieving the credentials. */ public static GoogleRobotCredentials getRobotCredentials( @NonNull ItemGroup itemGroup, @NonNull List<DomainRequirement> domainRequirements, @NonNull String credentialsId) throws AbortException { Preconditions.checkArgument(!credentialsId.isEmpty()); GoogleOAuth2Credentials credentials = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( GoogleOAuth2Credentials.class, itemGroup, ACL.SYSTEM, domainRequirements), CredentialsMatchers.withId(credentialsId)); if (!(credentials instanceof GoogleRobotCredentials)) { throw new AbortException(Messages.ClientFactory_FailedToRetrieveCredentials(credentialsId)); } return (GoogleRobotCredentials) credentials; } private static Credential getGoogleCredential(GoogleRobotCredentials credentials) throws GeneralSecurityException { return credentials.getGoogleCredential(new ContainerSecurityScopeRequirement()); } }
GoogleCloudPlatform/jenkins-gcr-plugin
src/main/java/com/google/jenkins/plugins/containersecurity/client/ClientUtil.java
Java
apache-2.0
5,295
var a02762 = [ [ "AmbigSpec", "a02762.html#aaa3a04113f5db03951771afa6423e7f4", null ], [ "~AmbigSpec", "a02762.html#a5283933a9e7267b3505f5f18cf289f3e", null ], [ "correct_fragments", "a02762.html#ad3a4b121b26cf829422700494aed91e4", null ], [ "correct_ngram_id", "a02762.html#a879c6167dbfc54980bfeb5a15b32bf73", null ], [ "type", "a02762.html#ae29644f82c6feac4df14b22368fa0873", null ], [ "wrong_ngram", "a02762.html#a9d7f07e5b038c6d61acc9bb75ba7ef1b", null ], [ "wrong_ngram_size", "a02762.html#a4cfb10d18b7c636f3afa5f223afa445e", null ] ];
stweil/tesseract-ocr.github.io
4.0.0-beta.1/a02762.js
JavaScript
apache-2.0
568
import React, {useContext} from 'react'; import {StyleSheet, ScrollView, Text, View, Platform, TouchableHighlight} from 'react-native'; import {NavigationContext} from 'navigation-react'; import {NavigationBar, RightBar, BarButton, SharedElement, useNavigated} from 'navigation-react-native'; export default ({colors, color}) => { const {stateNavigator} = useContext(NavigationContext); useNavigated(() => { if (Platform.OS === 'web') document.title = 'Color'; }); return ( <> <NavigationBar title="Color" barTintColor="#fff"> <RightBar> <BarButton systemItem="cancel" title="Cancel" show="always" accessibilityRole="link" href={stateNavigator.historyManager.getHref( stateNavigator.getNavigationBackLink(1) )} onPress={() => stateNavigator.navigateBack(1)} /> </RightBar> </NavigationBar> <ScrollView contentInsetAdjustmentBehavior="automatic"> <SharedElement name={color} data={{color}} style={styles.color}> <View style={{backgroundColor: color, flex: 1}} /> </SharedElement> <Text style={styles.text}>{color}</Text> <View style={styles.colors}> {[1,2,3].map(i => colors[(colors.indexOf(color) + i) % 15]) .map(subcolor => ( <TouchableHighlight key={subcolor} style={[styles.subcolor, {backgroundColor: subcolor}]} underlayColor={subcolor} accessibilityRole="link" href={stateNavigator.historyManager.getHref( stateNavigator.getRefreshLink({color: subcolor}) )} onPress={(e) => { if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return e.preventDefault() stateNavigator.refresh({color: subcolor}, 'replace'); }}> <View /> </TouchableHighlight> ) )} </View> </ScrollView> </> ); } const styles = StyleSheet.create({ back: { fontSize: 20, color: '#000', fontWeight: 'bold', paddingLeft: 20, paddingTop: 10, }, color: { height: 300, marginTop: 10, marginLeft: 15, marginRight: 15, }, text:{ fontSize: 80, color: '#000', textAlign:'center', fontWeight: 'bold', }, colors: { flexDirection: 'row', justifyContent: 'center', marginTop: 20, }, subcolor: { width: 100, height: 50, marginLeft: 4, marginRight: 4, marginBottom: 10, }, });
grahammendick/navigation
NavigationReactNativeWeb/sample/zoom/Detail.js
JavaScript
apache-2.0
2,749
package org.ovirt.mobile.movirt.util; import java.util.ArrayList; import java.util.List; import io.reactivex.disposables.Disposable; public class Disposables { private final List<Disposable> disposables = new ArrayList<>(5); public Disposables add(Disposable disposable) { disposables.add(disposable); return this; } public void destroy() { for (Disposable disposable : disposables) { if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } disposables.clear(); } public void destroyLastDisposable() { Disposable disposable = disposables.remove(disposables.size() - 1); if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } }
matobet/moVirt
moVirt/src/main/java/org/ovirt/mobile/movirt/util/Disposables.java
Java
apache-2.0
828
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution.buffer; import com.facebook.presto.execution.Lifespan; import com.facebook.presto.execution.StateMachine; import com.facebook.presto.execution.StateMachine.StateChangeListener; import com.facebook.presto.execution.buffer.ClientBuffer.PagesSupplier; import com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId; import com.facebook.presto.memory.context.LocalMemoryContext; import com.facebook.presto.spi.page.SerializedPage; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.common.util.concurrent.ListenableFuture; import io.airlift.units.DataSize; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Supplier; import static com.facebook.presto.execution.buffer.BufferState.FAILED; import static com.facebook.presto.execution.buffer.BufferState.FINISHED; import static com.facebook.presto.execution.buffer.BufferState.FLUSHING; import static com.facebook.presto.execution.buffer.BufferState.NO_MORE_BUFFERS; import static com.facebook.presto.execution.buffer.BufferState.NO_MORE_PAGES; import static com.facebook.presto.execution.buffer.BufferState.OPEN; import static com.facebook.presto.execution.buffer.OutputBuffers.BufferType.ARBITRARY; import static com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; /** * A buffer that assigns pages to queues based on a first come, first served basis. */ public class ArbitraryOutputBuffer implements OutputBuffer { private final OutputBufferMemoryManager memoryManager; @GuardedBy("this") private OutputBuffers outputBuffers = createInitialEmptyOutputBuffers(ARBITRARY); private final MasterBuffer masterBuffer; @GuardedBy("this") private final ConcurrentMap<OutputBufferId, ClientBuffer> buffers = new ConcurrentHashMap<>(); // The index of the first client buffer that should be polled private final AtomicInteger nextClientBufferIndex = new AtomicInteger(0); private final StateMachine<BufferState> state; private final String taskInstanceId; private final AtomicLong totalPagesAdded = new AtomicLong(); private final AtomicLong totalRowsAdded = new AtomicLong(); private final ConcurrentMap<Lifespan, AtomicLong> outstandingPageCountPerLifespan = new ConcurrentHashMap<>(); private final Set<Lifespan> noMorePagesForLifespan = ConcurrentHashMap.newKeySet(); private volatile Consumer<Lifespan> lifespanCompletionCallback; public ArbitraryOutputBuffer( String taskInstanceId, StateMachine<BufferState> state, DataSize maxBufferSize, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor) { this.taskInstanceId = requireNonNull(taskInstanceId, "taskInstanceId is null"); this.state = requireNonNull(state, "state is null"); requireNonNull(maxBufferSize, "maxBufferSize is null"); checkArgument(maxBufferSize.toBytes() > 0, "maxBufferSize must be at least 1"); this.memoryManager = new OutputBufferMemoryManager( maxBufferSize.toBytes(), requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"), requireNonNull(notificationExecutor, "notificationExecutor is null")); this.masterBuffer = new MasterBuffer(); } @Override public void addStateChangeListener(StateChangeListener<BufferState> stateChangeListener) { state.addStateChangeListener(stateChangeListener); } @Override public boolean isFinished() { return state.get() == FINISHED; } @Override public double getUtilization() { return memoryManager.getUtilization(); } @Override public boolean isOverutilized() { return (memoryManager.getUtilization() >= 0.5) || !state.get().canAddPages(); } @Override public OutputBufferInfo getInfo() { // // NOTE: this code must be lock free so we do not hang for state machine updates // // always get the state first before any other stats BufferState state = this.state.get(); // buffers it a concurrent collection so it is safe to access out side of guard // in this case we only want a snapshot of the current buffers @SuppressWarnings("FieldAccessNotGuarded") Collection<ClientBuffer> buffers = this.buffers.values(); int totalBufferedPages = masterBuffer.getBufferedPages(); ImmutableList.Builder<BufferInfo> infos = ImmutableList.builder(); for (ClientBuffer buffer : buffers) { BufferInfo bufferInfo = buffer.getInfo(); infos.add(bufferInfo); PageBufferInfo pageBufferInfo = bufferInfo.getPageBufferInfo(); totalBufferedPages += pageBufferInfo.getBufferedPages(); } return new OutputBufferInfo( "ARBITRARY", state, state.canAddBuffers(), state.canAddPages(), memoryManager.getBufferedBytes(), totalBufferedPages, totalRowsAdded.get(), totalPagesAdded.get(), infos.build()); } @Override public void setOutputBuffers(OutputBuffers newOutputBuffers) { checkState(!Thread.holdsLock(this), "Can not set output buffers while holding a lock on this"); requireNonNull(newOutputBuffers, "newOutputBuffers is null"); synchronized (this) { // ignore buffers added after query finishes, which can happen when a query is canceled // also ignore old versions, which is normal BufferState state = this.state.get(); if (state.isTerminal() || outputBuffers.getVersion() >= newOutputBuffers.getVersion()) { return; } // verify this is valid state change outputBuffers.checkValidTransition(newOutputBuffers); outputBuffers = newOutputBuffers; // add the new buffers for (OutputBufferId outputBufferId : outputBuffers.getBuffers().keySet()) { getBuffer(outputBufferId); } // Reset resume from position nextClientBufferIndex.set(0); // update state if no more buffers is set if (outputBuffers.isNoMoreBufferIds()) { this.state.compareAndSet(OPEN, NO_MORE_BUFFERS); this.state.compareAndSet(NO_MORE_PAGES, FLUSHING); } } if (!state.get().canAddBuffers()) { noMoreBuffers(); } checkFlushComplete(); } @Override public ListenableFuture<?> isFull() { return memoryManager.getBufferBlockedFuture(); } @Override public void registerLifespanCompletionCallback(Consumer<Lifespan> callback) { checkState(lifespanCompletionCallback == null, "lifespanCompletionCallback is already set"); this.lifespanCompletionCallback = requireNonNull(callback, "callback is null"); } @Override public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(!Thread.holdsLock(this), "Can not enqueue pages while holding a lock on this"); requireNonNull(lifespan, "lifespan is null"); requireNonNull(pages, "page is null"); checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback must be set before enqueueing data"); // ignore pages after "no more pages" is set // this can happen with a limit query if (!state.get().canAddPages() || noMorePagesForLifespan.contains(lifespan)) { return; } ImmutableList.Builder<SerializedPageReference> references = ImmutableList.builderWithExpectedSize(pages.size()); long bytesAdded = 0; long rowCount = 0; for (SerializedPage page : pages) { long retainedSize = page.getRetainedSizeInBytes(); bytesAdded += retainedSize; rowCount += page.getPositionCount(); // create page reference counts with an initial single reference references.add(new SerializedPageReference(page, 1, () -> dereferencePage(page, lifespan))); } List<SerializedPageReference> serializedPageReferences = references.build(); // reserve memory memoryManager.updateMemoryUsage(bytesAdded); // update stats totalRowsAdded.addAndGet(rowCount); totalPagesAdded.addAndGet(serializedPageReferences.size()); outstandingPageCountPerLifespan.computeIfAbsent(lifespan, ignored -> new AtomicLong()).addAndGet(serializedPageReferences.size()); // add pages to the buffer (this will increase the reference count by one) masterBuffer.addPages(serializedPageReferences); // process any pending reads from the client buffers List<ClientBuffer> buffers = safeGetBuffersSnapshot(); if (buffers.isEmpty()) { return; } // handle potential for racy update of next index and client buffers present int index = nextClientBufferIndex.get() % buffers.size(); for (int i = 0; i < buffers.size(); i++) { if (masterBuffer.isEmpty()) { // Resume from the current client buffer on the next iteration nextClientBufferIndex.set(index); break; } buffers.get(index).loadPagesIfNecessary(masterBuffer); index = (index + 1) % buffers.size(); } } @Override public void enqueue(Lifespan lifespan, int partition, List<SerializedPage> pages) { checkState(partition == 0, "Expected partition number to be zero"); enqueue(lifespan, pages); } @Override public ListenableFuture<BufferResult> get(OutputBufferId bufferId, long startingSequenceId, DataSize maxSize) { checkState(!Thread.holdsLock(this), "Can not get pages while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte"); return getBuffer(bufferId).getPages(startingSequenceId, maxSize, Optional.of(masterBuffer)); } @Override public void acknowledge(OutputBufferId bufferId, long sequenceId) { checkState(!Thread.holdsLock(this), "Can not acknowledge pages while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); getBuffer(bufferId).acknowledgePages(sequenceId); } @Override public void abort(OutputBufferId bufferId) { checkState(!Thread.holdsLock(this), "Can not abort while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); getBuffer(bufferId).destroy(); checkFlushComplete(); } @Override public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); // process any pending reads from the client buffers for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { clientBuffer.loadPagesIfNecessary(masterBuffer); } checkFlushComplete(); } @Override public void destroy() { checkState(!Thread.holdsLock(this), "Can not destroy while holding a lock on this"); // ignore destroy if the buffer already in a terminal state. if (state.setIf(FINISHED, oldState -> !oldState.isTerminal())) { noMoreBuffers(); masterBuffer.destroy(); safeGetBuffersSnapshot().forEach(ClientBuffer::destroy); memoryManager.setNoBlockOnFull(); forceFreeMemory(); } } @Override public void fail() { // ignore fail if the buffer already in a terminal state. if (state.setIf(FAILED, oldState -> !oldState.isTerminal())) { memoryManager.setNoBlockOnFull(); forceFreeMemory(); // DO NOT destroy buffers or set no more pages. The coordinator manages the teardown of failed queries. } } @Override public void setNoMorePagesForLifespan(Lifespan lifespan) { requireNonNull(lifespan, "lifespan is null"); noMorePagesForLifespan.add(lifespan); } @Override public boolean isFinishedForLifespan(Lifespan lifespan) { if (!noMorePagesForLifespan.contains(lifespan)) { return false; } AtomicLong outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan); return outstandingPageCount == null || outstandingPageCount.get() == 0; } @Override public long getPeakMemoryUsage() { return memoryManager.getPeakMemoryUsage(); } @VisibleForTesting void forceFreeMemory() { memoryManager.close(); } private synchronized ClientBuffer getBuffer(OutputBufferId id) { ClientBuffer buffer = buffers.get(id); if (buffer != null) { return buffer; } // NOTE: buffers are allowed to be created in the FINISHED state because destroy() can move to the finished state // without a clean "no-more-buffers" message from the scheduler. This happens with limit queries and is ok because // the buffer will be immediately destroyed. checkState(state.get().canAddBuffers() || !outputBuffers.isNoMoreBufferIds(), "No more buffers already set"); // NOTE: buffers are allowed to be created before they are explicitly declared by setOutputBuffers // When no-more-buffers is set, we verify that all created buffers have been declared buffer = new ClientBuffer(taskInstanceId, id); // buffer may have finished immediately before calling this method if (state.get() == FINISHED) { buffer.destroy(); } buffers.put(id, buffer); return buffer; } private synchronized List<ClientBuffer> safeGetBuffersSnapshot() { return ImmutableList.copyOf(this.buffers.values()); } private synchronized void noMoreBuffers() { if (outputBuffers.isNoMoreBufferIds()) { // verify all created buffers have been declared SetView<OutputBufferId> undeclaredCreatedBuffers = Sets.difference(buffers.keySet(), outputBuffers.getBuffers().keySet()); checkState(undeclaredCreatedBuffers.isEmpty(), "Final output buffers does not contain all created buffer ids: %s", undeclaredCreatedBuffers); } } @GuardedBy("this") private void checkFlushComplete() { // This buffer type assigns each page to a single, arbitrary reader, // so we don't need to wait for no-more-buffers to finish the buffer. // Any readers added after finish will simply receive no data. BufferState state = this.state.get(); if ((state == FLUSHING) || ((state == NO_MORE_PAGES) && masterBuffer.isEmpty())) { if (safeGetBuffersSnapshot().stream().allMatch(ClientBuffer::isDestroyed)) { destroy(); } } } @ThreadSafe private static class MasterBuffer implements PagesSupplier { @GuardedBy("this") private final LinkedList<SerializedPageReference> masterBuffer = new LinkedList<>(); @GuardedBy("this") private boolean noMorePages; private final AtomicInteger bufferedPages = new AtomicInteger(); public synchronized void addPages(List<SerializedPageReference> pages) { masterBuffer.addAll(pages); bufferedPages.set(masterBuffer.size()); } public synchronized boolean isEmpty() { return masterBuffer.isEmpty(); } @Override public synchronized boolean mayHaveMorePages() { return !noMorePages || !masterBuffer.isEmpty(); } public synchronized void setNoMorePages() { this.noMorePages = true; } @Override public synchronized List<SerializedPageReference> getPages(DataSize maxSize) { long maxBytes = maxSize.toBytes(); List<SerializedPageReference> pages = new ArrayList<>(); long bytesRemoved = 0; while (true) { SerializedPageReference page = masterBuffer.peek(); if (page == null) { break; } bytesRemoved += page.getRetainedSizeInBytes(); // break (and don't add) if this page would exceed the limit if (!pages.isEmpty() && bytesRemoved > maxBytes) { break; } // this should not happen since we have a lock checkState(masterBuffer.poll() == page, "Master buffer corrupted"); pages.add(page); } bufferedPages.set(masterBuffer.size()); return ImmutableList.copyOf(pages); } public void destroy() { checkState(!Thread.holdsLock(this), "Can not destroy master buffer while holding a lock on this"); List<SerializedPageReference> pages; synchronized (this) { pages = ImmutableList.copyOf(masterBuffer); masterBuffer.clear(); bufferedPages.set(0); } // dereference outside of synchronized to avoid making a callback while holding a lock pages.forEach(SerializedPageReference::dereferencePage); } public int getBufferedPages() { return bufferedPages.get(); } @Override public String toString() { return toStringHelper(this) .add("bufferedPages", bufferedPages.get()) .toString(); } } @VisibleForTesting OutputBufferMemoryManager getMemoryManager() { return memoryManager; } private void dereferencePage(SerializedPage pageSplit, Lifespan lifespan) { long outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan).decrementAndGet(); if (outstandingPageCount == 0 && noMorePagesForLifespan.contains(lifespan)) { checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback is not null"); lifespanCompletionCallback.accept(lifespan); } memoryManager.updateMemoryUsage(-pageSplit.getRetainedSizeInBytes()); } }
EvilMcJerkface/presto
presto-main/src/main/java/com/facebook/presto/execution/buffer/ArbitraryOutputBuffer.java
Java
apache-2.0
20,308
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: trust@f4-i.fh-hannover.de * Website: http://trust.f4.hs-hannover.de/ * * This file is part of visitmeta-dataservice, version 0.5.0, * implemented by the Trust@HsH research group at the Hochschule Hannover. * %% * Copyright (C) 2012 - 2015 Trust@HsH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.hshannover.f4.trust.visitmeta.ifmap; import java.util.ArrayList; import java.util.List; /** * Encapsulates the result of one if-MAP update */ public class PollResult { private final List<ResultItem> mResults; public PollResult(List<ResultItem> results) { mResults = results; } public List<ResultItem> getResults() { return mResults; } @Deprecated public List<ResultItem> getUpdates() { List<ResultItem> tmp = new ArrayList<ResultItem>(); for(ResultItem item : mResults) { if (item.getType() == ResultItemTypeEnum.UPDATE) { tmp.add(item); } } return tmp; } @Deprecated public List<ResultItem> getDeletes() { List<ResultItem> tmp = new ArrayList<ResultItem>(); for(ResultItem item : mResults) { if (item.getType() == ResultItemTypeEnum.DELETE) { tmp.add(item); } } return tmp; } }
MReichenbach/visitmeta
dataservice/src/main/java/de/hshannover/f4/trust/visitmeta/ifmap/PollResult.java
Java
apache-2.0
2,331
using IntelliTect.Coalesce.TypeDefinition; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Claims; using IntelliTect.Coalesce.Utilities; using System.Reflection; using System.Globalization; namespace IntelliTect.Coalesce.Helpers.Search { public class SearchableValueProperty : SearchableProperty { public SearchableValueProperty(PropertyViewModel prop) : base(prop) { } [Flags] public enum ParseFlags { None = 0, HaveYear = 1 << 0, HaveMonth = 1 << 1, HaveDay = 1 << 2, HaveHour = 1 << 3, HaveMinute = 1 << 4, HaveSecond = 1 << 5, HaveDate = HaveYear | HaveMonth | HaveDay, HaveTime = HaveHour | HaveMinute | HaveSecond, HaveDateTime = HaveDate | HaveTime, } public static Dictionary<string, ParseFlags> DateFormats = new Dictionary<string, ParseFlags> { { "MMM yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMMM yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMM, yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMMM, yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMM-yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMMM-yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMM/yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MMMM/yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy MM", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy M", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy-MM", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy-M", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy/MM", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy/M", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MM/yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "M/yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "MM-yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "M-yyyy", ParseFlags.HaveYear | ParseFlags.HaveMonth }, { "yyyy", ParseFlags.HaveYear }, { "yy", ParseFlags.HaveYear }, //{ DateTimeFormatInfo.CurrentInfo.MonthDayPattern, ParseFlags.HaveDate }, //{ DateTimeFormatInfo.CurrentInfo.FullDateTimePattern, ParseFlags.HaveDateTime }, //{ DateTimeFormatInfo.CurrentInfo.LongDatePattern, ParseFlags.HaveDate }, //{ DateTimeFormatInfo.CurrentInfo.LongTimePattern, ParseFlags.HaveTime }, //{ DateTimeFormatInfo.CurrentInfo.RFC1123Pattern, ParseFlags.HaveDateTime }, //{ DateTimeFormatInfo.CurrentInfo.ShortDatePattern, ParseFlags.HaveDate }, //{ DateTimeFormatInfo.CurrentInfo.ShortTimePattern, ParseFlags.HaveTime }, //{ DateTimeFormatInfo.CurrentInfo.SortableDateTimePattern, ParseFlags.HaveDateTime }, //{ DateTimeFormatInfo.CurrentInfo.UniversalSortableDateTimePattern, ParseFlags.HaveDateTime }, }; public override IEnumerable<(PropertyViewModel property, string statement)> GetLinqDynamicSearchStatements( ClaimsPrincipal? user, TimeZoneInfo timeZone, string? propertyParent, string rawSearchTerm) { if (!Property.SecurityInfo.IsReadable(user)) { yield break; } var propType = Property.Type; var propertyAccessor = propertyParent == null ? Property.Name : $"{propertyParent}.{Property.Name}"; if (propType.IsDate) { string DateLiteral(DateTime date) { if (propType.IsDateTimeOffset && date.Kind != DateTimeKind.Utc) throw new ArgumentException("datetimeoffset comparand must be a UTC date."); return $"{Property.PureType.Name}" + $"({date.Year}, {date.Month}, {date.Day}, {date.Hour}, {date.Minute}, {date.Second}" + $"{(propType.IsDateTimeOffset ? " , TimeSpan(0)" : "")})"; } #pragma warning disable IDE0018 // Inline variable declaration. Invalid suggestion - this variable is used more than once. DateTime dt; #pragma warning restore IDE0018 // Inline variable declaration foreach (var formatInfo in DateFormats) { if (DateTime.TryParseExact( rawSearchTerm, formatInfo.Key, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt )) { if (propType.IsDateTimeOffset) dt = TimeZoneInfo.ConvertTimeToUtc(dt, timeZone); if (formatInfo.Value == (ParseFlags.HaveYear | ParseFlags.HaveMonth)) { yield return ( Property, $"({propertyAccessor} >= {DateLiteral(dt)} && {propertyAccessor} < {DateLiteral(dt.AddMonths(1))})" ); } else if (formatInfo.Value == (ParseFlags.HaveYear)) { yield return ( Property, $"({propertyAccessor} >= {DateLiteral(dt)} && {propertyAccessor} < {DateLiteral(dt.AddYears(1))})" ); } yield break; } } // We didn't find any specific format above. // Try general date parsing for either searching by day or by minute. if (DateTime.TryParse(rawSearchTerm, CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt)) { TimeSpan range; if (dt.TimeOfDay == TimeSpan.Zero) { // No time component (or time was midnight - this is a limitation we're willing to take for simplicity). // Search by day. dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, DateTimeKind.Unspecified); range = TimeSpan.FromDays(1); } else if (dt.Minute == 0 && dt.Second == 0) { // Time Component present, but without minutes or seconds. // Search for the entire hour. dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0, DateTimeKind.Unspecified); range = TimeSpan.FromHours(1); } else { // Time Component present. Search to the minute. dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0, DateTimeKind.Unspecified); range = TimeSpan.FromMinutes(1); } if (propType.IsDateTimeOffset) dt = TimeZoneInfo.ConvertTimeToUtc(dt, timeZone); yield return ( Property, $"({propertyAccessor} >= {DateLiteral(dt)} && {propertyAccessor} < {DateLiteral(dt.Add(range))})" ); yield break; } } else if (propType.IsEnum) { var enumValuePair = propType.EnumValues .FirstOrDefault(kvp => string.Equals(kvp.Name, rawSearchTerm, StringComparison.OrdinalIgnoreCase)); // If the input string mapped to a valid enum value, search by the int value of that enum value. if (enumValuePair != null) { yield return (Property, $"({propertyAccessor} == \"{enumValuePair.Value}\")"); } } else if (propType.IsNumber || propType.IsGuid) { var propertyClrType = propType.TypeInfo; var typeConverter = System.ComponentModel.TypeDescriptor.GetConverter(propertyClrType); // This allows us to check if the conversion is valid without exceptions // (in our code, anyway - the default implementation of this is just a try catch anyway) if (typeConverter.IsValid(rawSearchTerm)) { var comparand = typeConverter.ConvertFromString(rawSearchTerm); if (propType.IsGuid) { comparand = $"\"{comparand}\""; } yield return (Property, $"({propertyAccessor} == {comparand})"); } } else if (propType.IsString) { // Theoretical support for EF.Functions.Like. Not yet supported in DynamicLinq. // https://github.com/StefH/System.Linq.Dynamic.Core/issues/105 /* switch (Property.SearchMethod) { case DataAnnotations.SearchAttribute.SearchMethods.BeginsWith: yield return (Property, $"({propertyAccessor} != null && EF.Functions.Like({propertyAccessor}, \"{term}%\")"); break; case DataAnnotations.SearchAttribute.SearchMethods.Contains: yield return (Property, $"({propertyAccessor} != null && EF.Functions.Like({propertyAccessor}, \"%{term}%\")"); break; default: throw new NotImplementedException(); } * */ var term = rawSearchTerm.EscapeStringLiteralForLinqDynamic(); yield return (Property, $"({propertyAccessor} != null && {propertyAccessor}.{string.Format(Property.SearchMethodCall, term)})"); } else { } } } }
IntelliTect/Coalesce
src/IntelliTect.Coalesce/Helpers/Search/SearchableValueProperty.cs
C#
apache-2.0
10,495
/* * Copyright (C) 2014 Stratio (http://stratio.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 com.stratio.qa.utils; import java.util.ArrayList; import java.util.Map; public class CassandraQueryUtils { public String insertData(String table, Map<String, Object> fields) { String query = "INSERT INTO " + table + " ("; for (int i = 0; i < fields.size() - 1; i++) { query += fields.keySet().toArray()[i] + ", "; } query += fields.keySet().toArray()[fields.size() - 1] + ") VALUES ("; for (int i = 0; i < fields.size() - 1; i++) { query += "" + fields.values().toArray()[i] + ", "; } query += "" + fields.values().toArray()[fields.size() - 1] + ");"; return query; } public String createTable(String table, Map<String, String> colums, ArrayList<String> primaryKey) { String query = "CREATE TABLE " + table + " ("; for (int i = 0; i < colums.size(); i++) { query += colums.keySet().toArray()[i] + " " + colums.values().toArray()[i] + ", "; } query = query + "PRIMARY KEY("; if (primaryKey.size() == 1) { query += primaryKey.get(0) + "));"; } else { for (int e = 0; e < primaryKey.size() - 1; e++) { query += primaryKey.get(e) + ", "; } query += primaryKey.get(primaryKey.size() - 1) + "));"; } return query; } public String useQuery(String keyspace) { return "USE " + keyspace + ";"; } public String createKeyspaceReplication(Map<String, String> replication) { StringBuilder result = new StringBuilder(); if (!replication.isEmpty()) { for (Map.Entry<String, String> entry : replication.entrySet()) { result.append(entry.getKey()).append(": ") .append(entry.getValue()).append(", "); } } return result.toString().substring(0, result.length() - 2); } public String createKeyspaceQuery(Boolean ifNotExists, String keyspaceName, String replication, String durableWrites) { String result = "CREATE KEYSPACE "; if (ifNotExists) { result = result + "IF NOT EXISTS "; } result = result + keyspaceName; if (!"".equals(replication) || !"".equals(durableWrites)) { result += " WITH "; if (!"".equals(replication)) { result += "REPLICATION = {" + replication + "}"; } if (!"".equals(durableWrites)) { if (!"".equals(replication)) { result += " AND "; } result += "durable_writes = " + durableWrites; } } result = result + ";"; return result; } public String dropKeyspaceQuery(Boolean ifExists, String keyspace) { String query = "DROP KEYSPACE "; if (ifExists) { query += "IF EXISTS "; } query = query + keyspace + ";"; return query; } public String dropTableQuery(Boolean ifExists, String table) { String query = "DROP TABLE "; if (ifExists) { query += "IF EXISTS "; } query = query + table + ";"; return query; } public String truncateTableQuery(Boolean ifExists, String table) { String query = "TRUNCATE TABLE "; if (ifExists) { query += "IF EXISTS "; } query = query + table + ";"; return query; } }
gbecares/bdt
src/main/java/com/stratio/qa/utils/CassandraQueryUtils.java
Java
apache-2.0
4,153
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.web.boot; import com.evolveum.midpoint.model.api.authentication.MidPointLdapAuthenticationProvider; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.ldap.DefaultSpringSecurityContextSource; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.security.ldap.userdetails.UserDetailsContextMapper; /** * Created by Viliam Repan (lazyman). */ @Profile("ldap") @Configuration public class LdapSecurityConfig { @Value("${auth.ldap.host}") private String ldapHost; @Value("${auth.ldap.manager:}") private String ldapUserDn; @Value("${auth.ldap.password:#{null}}") private String ldapUserPassword; @Value("${auth.ldap.dn.pattern:#{null}}") private String ldapDnPattern; @Value("${auth.ldap.search.pattern:#{null}}") private String ldapSearchPattern; @Value("${auth.ldap.search.subtree:true}") private boolean searchSubtree; @Bean public LdapContextSource contextSource() { DefaultSpringSecurityContextSource ctx = new DefaultSpringSecurityContextSource(ldapHost); ctx.setUserDn(ldapUserDn); ctx.setPassword(ldapUserPassword); return ctx; } @Bean public MidPointLdapAuthenticationProvider midPointAuthenticationProvider( @Qualifier("userDetailsService") UserDetailsContextMapper userDetailsContextMapper) { MidPointLdapAuthenticationProvider provider = new MidPointLdapAuthenticationProvider(bindAuthenticator()); provider.setUserDetailsContextMapper(userDetailsContextMapper); return provider; } @Bean public BindAuthenticator bindAuthenticator() { BindAuthenticator auth = new BindAuthenticator(contextSource()); if (StringUtils.isNotEmpty(ldapDnPattern)) { auth.setUserDnPatterns(new String[]{ldapDnPattern}); } if (StringUtils.isNotEmpty(ldapSearchPattern)) { auth.setUserSearch(userSearch()); } return auth; } @ConditionalOnProperty("auth.ldap.search.pattern") @Bean public FilterBasedLdapUserSearch userSearch() { FilterBasedLdapUserSearch search = new FilterBasedLdapUserSearch("", ldapSearchPattern, contextSource()); search.setSearchSubtree(searchSubtree); return search; } }
bshp/midPoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/boot/LdapSecurityConfig.java
Java
apache-2.0
3,067
package org.apereo.cas.support.events.redis; import org.apereo.cas.redis.core.CasRedisTemplate; import org.apereo.cas.support.events.CasEventRepositoryFilter; import org.apereo.cas.support.events.dao.AbstractCasEventRepository; import org.apereo.cas.support.events.dao.CasEvent; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import lombok.val; import java.time.ZonedDateTime; import java.util.Objects; import java.util.stream.Stream; /** * This is {@link RedisCasEventRepository} that stores event data into a redis database. * * @author Misagh Moayyed * @since 6.4.0 */ @ToString @Getter @Slf4j public class RedisCasEventRepository extends AbstractCasEventRepository { private static final String KEY_SEPARATOR = ":"; private static final String CAS_PREFIX = RedisCasEventRepository.class.getSimpleName(); private final CasRedisTemplate<String, CasEvent> template; private final long scanCount; public RedisCasEventRepository(final CasEventRepositoryFilter eventRepositoryFilter, final CasRedisTemplate<String, CasEvent> redisTemplate, final long scanCount) { super(eventRepositoryFilter); this.template = redisTemplate; this.scanCount = scanCount; } private static String getKey(final String type, final String principal, final String timestamp) { return CAS_PREFIX + KEY_SEPARATOR + type + KEY_SEPARATOR + principal + KEY_SEPARATOR + timestamp; } @Override public Stream<? extends CasEvent> load() { val keys = getKeys("*", "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> load(final ZonedDateTime dateTime) { val keys = getKeys("*", "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsOfTypeForPrincipal(final String type, final String principal) { val keys = getKeys(type, principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsOfTypeForPrincipal(final String type, final String principal, final ZonedDateTime dateTime) { val keys = getKeys(type, principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsOfType(final String type) { val keys = getKeys(type, "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsOfType(final String type, final ZonedDateTime dateTime) { val keys = getKeys(type, "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsForPrincipal(final String id) { val keys = getKeys("*", id, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsForPrincipal(final String principal, final ZonedDateTime dateTime) { val keys = getKeys("*", principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public CasEvent saveInternal(final CasEvent event) { val key = getKey(event.getType(), event.getPrincipalId(), String.valueOf(event.getTimestamp())); LOGGER.trace("Saving event record based on key [{}]", key); val ops = this.template.boundValueOps(key); ops.set(event); return event; } private Stream<String> getKeys(final String type, final String principal, final String timestamp) { val key = getKey(type, principal, timestamp); LOGGER.trace("Fetching records based on key [{}]", key); return template.keys(key, this.scanCount); } }
apereo/cas
support/cas-server-support-events-redis/src/main/java/org/apereo/cas/support/events/redis/RedisCasEventRepository.java
Java
apache-2.0
4,922
package org.javarosa.core.model.instance.utils; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Collection of static form loading methods * * @author Phillip Mates */ public class FormLoadingUtils { public static FormInstance loadFormInstance(String formFilepath) throws InvalidStructureException, IOException { TreeElement root = xmlToTreeElement(formFilepath); return new FormInstance(root, null); } public static TreeElement xmlToTreeElement(String xmlFilepath) throws InvalidStructureException, IOException { InputStream is = FormLoadingUtils.class.getResourceAsStream(xmlFilepath); TreeElementParser parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); try { return parser.parse(); } catch (XmlPullParserException e) { throw new IOException(e.getMessage()); } catch (UnfullfilledRequirementsException e) { throw new IOException(e.getMessage()); } } }
dimagi/javarosa
javarosa/core/src/main/java/org/javarosa/core/model/instance/utils/FormLoadingUtils.java
Java
apache-2.0
1,407
/* * Copyright 2011 Matthias Fuchs * * 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 <stromx/runtime/Data.h> #include <stromx/runtime/Image.h> #include <stromx/cvsupport/Image.h> #include <memory> #include <boost/python.hpp> using namespace boost::python; using namespace stromx::runtime; namespace { std::auto_ptr<stromx::cvsupport::Image> allocateFromDimension(const unsigned int width, const unsigned int height, const Image::PixelType pixelType) { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(width, height, pixelType)); } std::auto_ptr<stromx::cvsupport::Image> allocateFromFile(const std::string & filename) { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(filename)); } std::auto_ptr<stromx::cvsupport::Image> allocateFromFileWithAccess(const std::string & filename, const stromx::cvsupport::Image::Conversion access) { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(filename, access)); } } void exportImage() { scope in_Operator = class_<stromx::cvsupport::Image, bases<stromx::runtime::Image>, std::auto_ptr<stromx::cvsupport::Image> >("Image", no_init) .def("__init__", make_constructor(&allocateFromFile)) .def("__init__", make_constructor(&allocateFromDimension)) .def("__init__", make_constructor(&allocateFromFileWithAccess)) .def<void (stromx::cvsupport::Image::*)(const std::string &) const>("save", &stromx::cvsupport::Image::save) .def<void (stromx::cvsupport::Image::*)(const std::string &)>("open", &stromx::cvsupport::Image::open) .def<void (stromx::cvsupport::Image::*)(const std::string &, const stromx::cvsupport::Image::Conversion)>("open", &stromx::cvsupport::Image::open) .def<void (stromx::cvsupport::Image::*)(const unsigned int, const unsigned int, const Image::PixelType)>("resize", &stromx::cvsupport::Image::resize) ; enum_<stromx::cvsupport::Image::Conversion>("Conversion") .value("UNCHANGED", stromx::cvsupport::Image::UNCHANGED) .value("GRAYSCALE", stromx::cvsupport::Image::GRAYSCALE) .value("COLOR", stromx::cvsupport::Image::COLOR) ; implicitly_convertible< std::auto_ptr<stromx::cvsupport::Image>, std::auto_ptr<Data> >(); }
sparsebase/stromx
python/stromx/cvsupport/Image.cpp
C++
apache-2.0
2,869
/* * sshIt: simple, powerful, open-source SSH client for Android * Copyright 2014 Alpha 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. */ package org.alphallc.sshit.util; /** * This class is from: * * Encryptor.java * Copyright 2008 Zach Scrivena * zachscrivena@gmail.com * http://zs.freeshell.org/ */ import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * Perform AES-128 encryption. */ public final class Encryptor { /** name of the character set to use for converting between characters and bytes */ private static final String CHARSET_NAME = "UTF-8"; /** random number generator algorithm */ private static final String RNG_ALGORITHM = "SHA1PRNG"; /** message digest algorithm (must be sufficiently long to provide the key and initialization vector) */ private static final String DIGEST_ALGORITHM = "SHA-256"; /** key algorithm (must be compatible with CIPHER_ALGORITHM) */ private static final String KEY_ALGORITHM = "AES"; /** cipher algorithm (must be compatible with KEY_ALGORITHM) */ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * Private constructor that should never be called. */ private Encryptor() {} /** * Encrypt the specified cleartext using the given password. * With the correct salt, number of iterations, and password, the decrypt() method reverses * the effect of this method. * This method generates and uses a random salt, and the user-specified number of iterations * and password to create a 16-byte secret key and 16-byte initialization vector. * The secret key and initialization vector are then used in the AES-128 cipher to encrypt * the given cleartext. * * @param salt * salt that was used in the encryption (to be populated) * @param iterations * number of iterations to use in salting * @param password * password to be used for encryption * @param cleartext * cleartext to be encrypted * @return * ciphertext * @throws Exception * on any error encountered in encryption */ public static byte[] encrypt( final byte[] salt, final int iterations, final String password, final byte[] cleartext) throws Exception { /* generate salt randomly */ SecureRandom.getInstance(RNG_ALGORITHM).nextBytes(salt); /* compute key and initialization vector */ final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); byte[] pw = password.getBytes(CHARSET_NAME); for (int i = 0; i < iterations; i++) { /* add salt */ final byte[] salted = new byte[pw.length + salt.length]; System.arraycopy(pw, 0, salted, 0, pw.length); System.arraycopy(salt, 0, salted, pw.length, salt.length); Arrays.fill(pw, (byte) 0x00); /* compute SHA-256 digest */ shaDigest.reset(); pw = shaDigest.digest(salted); Arrays.fill(salted, (byte) 0x00); } /* extract the 16-byte key and initialization vector from the SHA-256 digest */ final byte[] key = new byte[16]; final byte[] iv = new byte[16]; System.arraycopy(pw, 0, key, 0, 16); System.arraycopy(pw, 16, iv, 0, 16); Arrays.fill(pw, (byte) 0x00); /* perform AES-128 encryption */ final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(iv)); Arrays.fill(key, (byte) 0x00); Arrays.fill(iv, (byte) 0x00); return cipher.doFinal(cleartext); } /** * Decrypt the specified ciphertext using the given password. * With the correct salt, number of iterations, and password, this method reverses the effect * of the encrypt() method. * This method uses the user-specified salt, number of iterations, and password * to recreate the 16-byte secret key and 16-byte initialization vector. * The secret key and initialization vector are then used in the AES-128 cipher to decrypt * the given ciphertext. * * @param salt * salt to be used in decryption * @param iterations * number of iterations to use in salting * @param password * password to be used for decryption * @param ciphertext * ciphertext to be decrypted * @return * cleartext * @throws Exception * on any error encountered in decryption */ public static byte[] decrypt( final byte[] salt, final int iterations, final String password, final byte[] ciphertext) throws Exception { /* compute key and initialization vector */ final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); byte[] pw = password.getBytes(CHARSET_NAME); for (int i = 0; i < iterations; i++) { /* add salt */ final byte[] salted = new byte[pw.length + salt.length]; System.arraycopy(pw, 0, salted, 0, pw.length); System.arraycopy(salt, 0, salted, pw.length, salt.length); Arrays.fill(pw, (byte) 0x00); /* compute SHA-256 digest */ shaDigest.reset(); pw = shaDigest.digest(salted); Arrays.fill(salted, (byte) 0x00); } /* extract the 16-byte key and initialization vector from the SHA-256 digest */ final byte[] key = new byte[16]; final byte[] iv = new byte[16]; System.arraycopy(pw, 0, key, 0, 16); System.arraycopy(pw, 16, iv, 0, 16); Arrays.fill(pw, (byte) 0x00); /* perform AES-128 decryption */ final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(iv)); Arrays.fill(key, (byte) 0x00); Arrays.fill(iv, (byte) 0x00); return cipher.doFinal(ciphertext); } }
alphallc/connectbot
src/org/alphallc/sshit/util/Encryptor.java
Java
apache-2.0
6,172
package com.github.zhongl.benchmarker; import org.junit.Test; import java.util.concurrent.CountDownLatch; /** @author <a href="mailto:zhong.lunfu@gmail.com">zhongl<a> */ public class RandomOptionalFactoryTest { private final StatisticsCollector collector = new StatisticsCollector(); private final CountDownLatch latch = new CountDownLatch(1); @Test public void optionsWereCreated() throws Exception { AssertCreatedFactory f1 = new AssertCreatedFactory(); AssertCreatedFactory f2 = new AssertCreatedFactory(); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } f1.assertCreated(); f2.assertCreated(); } @Test public void optionsWereCreatedByRatio() throws Exception { AssertCreatedFactory f1 = new AssertCreatedFactory(); AssertCreatedFactory f2 = new AssertCreatedFactory(); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2, f1); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } f1.assertCreatedGreaterThan(5); f2.assertCreatedGreaterThan(2); } @Test public void optionsWereCreatedByFix() throws Exception { AssertCreatedFactory af1 = new AssertCreatedFactory(); AssertCreatedFactory af2 = new AssertCreatedFactory(); CallableFactory f1 = new FixInstanceSizeFactory(5, af1); CallableFactory f2 = new FixInstanceSizeFactory(5, af2); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2, f1); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } af1.assertCreated(5); af2.assertCreated(5); } }
zhongl/lab
benchmarker/src/test/java/com/github/zhongl/benchmarker/RandomOptionalFactoryTest.java
Java
apache-2.0
1,903
""" WSGI config for comic project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys SITE_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) sys.path.append(SITE_ROOT) sys.path.append(os.path.join(SITE_ROOT,"comic")) os.environ.setdefault("PYTHON_EGG_CACHE", "/tmp/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "comic.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
cpatrick/comic-django
django/comic/wsgi.py
Python
apache-2.0
1,360
package QueueHandlers; import org.junit.Test; import javax.jms.JMSException; import java.io.IOException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by Andras on 27/07/2016. */ public class JMSPublisherTest { public static class TestObject implements Serializable { private static final long serialVersionUID = 42L; private String mString = "Hello"; private int mId = 10; private static int mCounter = 0; public TestObject() { mId = mCounter++; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeObject( mString ); out.writeInt( mId ); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { mString = (String)in.readObject(); mId = in.readInt(); } // private void readObjectNoData() // throws ObjectStreamException // { // // } @Override public String toString() { return mString + " " + mId; } } @Test public void OnePublisherMoreListenerQueue() throws JMSException, InterruptedException { final int LISTENER_COUNT = 10; JMSPublisher lPublisher = new JMSPublisher( "JMSTEST" ); lPublisher.Connect(); JMSListener[] listeners = new JMSListener[LISTENER_COUNT]; for( int i = 0; i < LISTENER_COUNT; i++ ) { listeners[ i ] = new JMSListener( "JMSTEST" ); listeners[ i ].Connect(); } for( int i = 0; i < LISTENER_COUNT; i++ ) lPublisher.Publish( new TestObject() ); Thread.sleep( 2000 ); lPublisher.Disconnect(); for( int i = 0; i < LISTENER_COUNT; i++ ) { TestObject lTestObject = (TestObject)listeners[ i ].Listen(); System.out.println( "Listener " + i + ": " + lTestObject ); } Thread.sleep( 2000 ); for( int i = 0; i < LISTENER_COUNT; i++ ) listeners[ i ].Disconnect(); } }
andrasigneczi/TravelOptimizer
DataCollector/src/test/QueueHandlers/JMSPublisherTest.java
Java
apache-2.0
1,980
package lt.inventi.apollo.wicket.theme.settings; import lt.inventi.apollo.wicket.theme.ActiveSessionThemeProvider; import lt.inventi.apollo.wicket.theme.ActiveThemeProvider; import lt.inventi.apollo.wicket.theme.DefaultThemeRepository; import lt.inventi.apollo.wicket.theme.ITheme; import lt.inventi.apollo.wicket.theme.none.EmptyTheme; public final class ThemeSettings { private final ActiveThemeProvider provider; public ThemeSettings() { this(new EmptyTheme()); } public ThemeSettings(ITheme theme) { this.provider = new ActiveSessionThemeProvider(new DefaultThemeRepository(theme)); } public ThemeSettings(ITheme... themes) { DefaultThemeRepository repo = new DefaultThemeRepository(themes[0]); for (int i = 1; i < themes.length; i++) { repo.add(themes[i]); } this.provider = new ActiveSessionThemeProvider(repo); } public ActiveThemeProvider getActiveThemeProvider() { return provider; } }
inventiLT/inventi-wicket
inventi-wicket-resources/src/main/java/lt/inventi/apollo/wicket/theme/settings/ThemeSettings.java
Java
apache-2.0
1,007
namespace HanRuEdu.LDAL { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; [MetadataType(typeof(EDU_ZXJX_11_A01_LWSJ_metadata))] public partial class EDU_ZXJX_11_A01_LWSJ { public EDU_ZXJX_11_A01_LWSJ() { LWMC = ""; LWZY = ""; LWNR = ""; SCSJ = DateTime.Now; } public class EDU_ZXJX_11_A01_LWSJ_metadata { [Required(ErrorMessage = "±ØÌî")] [Display(Name = "±àºÅ")] public Int32 ID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧУ")] public Int32 SCHOOLID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧÄê")] public Int32 XNID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧÆÚ")] public Int32 XQID { get; set; } [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)] [Display(Name = "ÂÛÎÄÃû³Æ")] [StringLength(100)] [DisplayFormat(ConvertEmptyStringToNull = false)] public String LWMC { get; set; } [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)] [Display(Name = "ÂÛÎÄÕªÒª")] [StringLength(100)] [DisplayFormat(ConvertEmptyStringToNull = false)] public String LWZY { get; set; } [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)] [Display(Name = "ÂÛÎÄÄÚÈÝ")] [DisplayFormat(ConvertEmptyStringToNull = false)] public String LWNR { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ÉÏ´«½Ìʦ")] public Int32 SCJSID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ÉÏ´«Ê±¼ä")] public DateTime SCSJ { get; set; } } } }
shinkxw/DataAnalysisSystem
export/model/HANRU/ZXJX/EDU_ZXJX_11_A01_LWSJ_MODEL.cs
C#
apache-2.0
1,997
/* * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.contactcenterinsights; // [START contactcenterinsights_create_issue_model] import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient; import com.google.cloud.contactcenterinsights.v1.IssueModel; import com.google.cloud.contactcenterinsights.v1.LocationName; import java.io.IOException; public class CreateIssueModel { public static void main(String[] args) throws Exception, IOException { // TODO(developer): Replace this variable before running the sample. String projectId = "my_project_id"; createIssueModel(projectId); } public static IssueModel createIssueModel(String projectId) throws Exception, IOException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ContactCenterInsightsClient client = ContactCenterInsightsClient.create()) { // Construct a parent resource. LocationName parent = LocationName.of(projectId, "us-central1"); // Construct an issue model. IssueModel issueModel = IssueModel.newBuilder() .setDisplayName("my-model") .setInputDataConfig( IssueModel.InputDataConfig.newBuilder().setFilter("medium=\"CHAT\"").build()) .build(); // Call the Insights client to create an issue model. IssueModel response = client.createIssueModelAsync(parent, issueModel).get(); System.out.printf("Created %s%n", response.getName()); return response; } } } // [END contactcenterinsights_create_issue_model]
googleapis/java-contact-center-insights
samples/snippets/src/main/java/com/example/contactcenterinsights/CreateIssueModel.java
Java
apache-2.0
2,347
package com.tvd12.ezyfox.database.service; public interface EzyCrudService<I,E> extends EzyCountSerivce, EzySaveService<E>, EzyFindService<I, E>, EzyDeleteService<I> { }
youngmonkeys/ezyfox
ezyfox-database/src/main/java/com/tvd12/ezyfox/database/service/EzyCrudService.java
Java
apache-2.0
181
/** * * Copyright (c) 2012 - 2014 Carnegie Mellon University * 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. * * @author Chaitra Radhakrishna, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: wei.zhang@cs.cmu.edu * * */ package Wordnet; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Queue; //import java.util.Map; import java.util.Set; public class SetUtil { public static boolean calculauteIntersection(Set<String> wordList1, Set<String> wordList2) { Set<String> allWords = populateWordset(wordList1, wordList2); // int M11 = 0; Iterator<String> wordList = allWords.iterator(); while (wordList.hasNext()) { String word = wordList.next(); boolean freq1 = wordList1.contains(word); boolean freq2 = wordList2.contains(word); if (freq1 && freq2) { return true; } } return false; } public static Set<String> checkSet(Set<String> set) { if (set == null) set = new HashSet<String>(); return set; } static Set<String> populateWordset(Set<String> wordList1, Set<String> wordList2) { Set<String> allWords = new HashSet<String>(); Set<String> wordIterator = null; Iterator<String> iterator = null; // wordIterator = wordList1.keySet(); iterator = wordList1.iterator(); while (iterator.hasNext()) { allWords.add(iterator.next()); } // wordIterator = wordList2.keySet(); iterator = wordList2.iterator(); while (iterator.hasNext()) { allWords.add(iterator.next()); } return allWords; } public static Set<String> addStringArray(Set<String> set, String[] array) { set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static Queue<String> addStringArraytoQueue(Queue<String> set , String[] array) { //set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static Set<String> addStringList(Set<String> set, List<String> array) { set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static List<String> setToList(Set<String> set)// List<String> array) { ArrayList<String> list = new ArrayList<String>(); set = checkSet(set); for (String string : set) { list.add(string); } return list; } }
weizh/geolocator-3.0
geolocator-3.0/src/Wordnet/SetUtil.java
Java
apache-2.0
3,264
package com.tylerlubeck.maraudersmapmultiuser.Models; /** * Created by Tyler on 4/16/2015. */ public class MyLocation { String building_name; int floor_number; int x_coordinate; int y_coordinate; String image_url; public MyLocation() {} public MyLocation(String buildingName, int floorNumber, int x, int y, String imageUrl) { this.building_name = buildingName; this.floor_number = floorNumber; this.x_coordinate = x; this.y_coordinate = y; this.image_url = imageUrl; } public String getImageUrl() { return image_url; } public int getXCoordinate() { return x_coordinate; } public int getYCoordinate() { return y_coordinate; } public String getFloorName() { return String.format("%s Floor %d", building_name, floor_number); } public int getFloorNumber() { return this.floor_number; } public String toString() { return String.format("%s Floor %s: (%d, %d)", building_name, floor_number, x_coordinate, y_coordinate); } }
TeamSirius/MaraudersMapMultiUser
app/src/main/java/com/tylerlubeck/maraudersmapmultiuser/Models/MyLocation.java
Java
apache-2.0
1,160
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Storages.Binary.Algo File: TickBinarySerializer.cs Created: 2015, 12, 14, 1:43 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Storages.Binary { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ecng.Common; using Ecng.Collections; using Ecng.Serialization; using StockSharp.Messages; using StockSharp.Localization; class TickMetaInfo : BinaryMetaInfo<TickMetaInfo> { public TickMetaInfo(DateTime date) : base(date) { FirstId = -1; } public override object LastId => PrevId; public long FirstId { get; set; } public long PrevId { get; set; } public override void Write(Stream stream) { base.Write(stream); stream.Write(FirstId); stream.Write(PrevId); stream.Write(FirstPrice); stream.Write(LastPrice); WriteNonSystemPrice(stream); WriteFractionalVolume(stream); WriteLocalTime(stream, MarketDataVersions.Version47); if (Version < MarketDataVersions.Version50) return; stream.Write(ServerOffset); if (Version < MarketDataVersions.Version54) return; WriteOffsets(stream); } public override void Read(Stream stream) { base.Read(stream); FirstId = stream.Read<long>(); PrevId = stream.Read<long>(); FirstPrice = stream.Read<decimal>(); LastPrice = stream.Read<decimal>(); ReadNonSystemPrice(stream); ReadFractionalVolume(stream); ReadLocalTime(stream, MarketDataVersions.Version47); if (Version < MarketDataVersions.Version50) return; ServerOffset = stream.Read<TimeSpan>(); if (Version < MarketDataVersions.Version54) return; ReadOffsets(stream); } public override void CopyFrom(TickMetaInfo src) { base.CopyFrom(src); FirstId = src.FirstId; PrevId = src.PrevId; FirstPrice = src.FirstPrice; LastPrice = src.LastPrice; } } class TickBinarySerializer : BinaryMarketDataSerializer<ExecutionMessage, TickMetaInfo> { public TickBinarySerializer(SecurityId securityId) : base(securityId, 50, MarketDataVersions.Version54) { } protected override void OnSave(BitArrayWriter writer, IEnumerable<ExecutionMessage> messages, TickMetaInfo metaInfo) { if (metaInfo.IsEmpty()) { var first = messages.First(); metaInfo.FirstId = metaInfo.PrevId = first.TradeId ?? 0; metaInfo.ServerOffset = first.ServerTime.Offset; } writer.WriteInt(messages.Count()); var allowNonOrdered = metaInfo.Version >= MarketDataVersions.Version48; var isUtc = metaInfo.Version >= MarketDataVersions.Version50; var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version54; foreach (var msg in messages) { if (msg.ExecutionType != ExecutionTypes.Tick) throw new ArgumentOutOfRangeException(nameof(messages), msg.ExecutionType, LocalizedStrings.Str1695Params.Put(msg.TradeId)); var tradeId = msg.TradeId ?? 0; // сделки для индексов имеют нулевой номер if (tradeId < 0) throw new ArgumentOutOfRangeException(nameof(messages), tradeId, LocalizedStrings.Str1020); // execution ticks (like option execution) may be a zero cost // ticks for spreads may be a zero cost or less than zero //if (msg.TradePrice < 0) // throw new ArgumentOutOfRangeException(nameof(messages), msg.TradePrice, LocalizedStrings.Str1021Params.Put(msg.TradeId)); metaInfo.PrevId = writer.SerializeId(tradeId, metaInfo.PrevId); // pyhta4og. // http://stocksharp.com/forum/yaf_postsm6450_Oshibka-pri-importie-instrumientov-s-Finama.aspx#post6450 var volume = msg.TradeVolume; if (metaInfo.Version < MarketDataVersions.Version53) { if (volume == null) throw new ArgumentException(LocalizedStrings.Str1022Params.Put((object)msg.TradeId ?? msg.TradeStringId), nameof(messages)); if (volume < 0) throw new ArgumentOutOfRangeException(nameof(messages), volume, LocalizedStrings.Str1022Params.Put(msg.TradeId)); writer.WriteVolume(volume.Value, metaInfo, SecurityId); } else { writer.Write(volume != null); if (volume != null) { if (volume < 0) throw new ArgumentOutOfRangeException(nameof(messages), volume, LocalizedStrings.Str1022Params.Put(msg.TradeId)); writer.WriteVolume(volume.Value, metaInfo, SecurityId); } } writer.WritePriceEx(msg.GetTradePrice(), metaInfo, SecurityId); writer.WriteSide(msg.OriginSide); var lastOffset = metaInfo.LastServerOffset; metaInfo.LastTime = writer.WriteTime(msg.ServerTime, metaInfo.LastTime, LocalizedStrings.Str985, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); metaInfo.LastServerOffset = lastOffset; if (metaInfo.Version < MarketDataVersions.Version40) continue; if (metaInfo.Version < MarketDataVersions.Version47) writer.WriteLong((msg.LocalTime - msg.ServerTime).Ticks); else { var hasLocalTime = true; if (metaInfo.Version >= MarketDataVersions.Version49) { hasLocalTime = !msg.LocalTime.IsDefault() && msg.LocalTime != msg.ServerTime; writer.Write(hasLocalTime); } if (hasLocalTime) { lastOffset = metaInfo.LastLocalOffset; metaInfo.LastLocalTime = writer.WriteTime(msg.LocalTime, metaInfo.LastLocalTime, LocalizedStrings.Str1024, allowNonOrdered, isUtc, metaInfo.LocalOffset, allowDiffOffsets, ref lastOffset); metaInfo.LastLocalOffset = lastOffset; } } if (metaInfo.Version < MarketDataVersions.Version42) continue; if (metaInfo.Version >= MarketDataVersions.Version51) { writer.Write(msg.IsSystem != null); if (msg.IsSystem != null) writer.Write(msg.IsSystem.Value); } else writer.Write(msg.IsSystem ?? true); if (msg.IsSystem == false) { if (metaInfo.Version >= MarketDataVersions.Version51) writer.WriteNullableInt(msg.TradeStatus); else writer.WriteInt(msg.TradeStatus ?? 0); } var oi = msg.OpenInterest; if (metaInfo.Version < MarketDataVersions.Version46) writer.WriteVolume(oi ?? 0m, metaInfo, SecurityId); else { writer.Write(oi != null); if (oi != null) writer.WriteVolume(oi.Value, metaInfo, SecurityId); } if (metaInfo.Version < MarketDataVersions.Version45) continue; writer.Write(msg.IsUpTick != null); if (msg.IsUpTick != null) writer.Write(msg.IsUpTick.Value); if (metaInfo.Version < MarketDataVersions.Version52) continue; writer.Write(msg.Currency != null); if (msg.Currency != null) writer.WriteInt((int)msg.Currency.Value); } } public override ExecutionMessage MoveNext(MarketDataEnumerator enumerator) { var reader = enumerator.Reader; var metaInfo = enumerator.MetaInfo; metaInfo.FirstId += reader.ReadLong(); var volume = metaInfo.Version < MarketDataVersions.Version53 ? reader.ReadVolume(metaInfo) : reader.Read() ? reader.ReadVolume(metaInfo) : (decimal?)null; var price = reader.ReadPriceEx(metaInfo); var orderDirection = reader.Read() ? (reader.Read() ? Sides.Buy : Sides.Sell) : (Sides?)null; var allowNonOrdered = metaInfo.Version >= MarketDataVersions.Version48; var isUtc = metaInfo.Version >= MarketDataVersions.Version50; var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version54; var prevTime = metaInfo.FirstTime; var lastOffset = metaInfo.FirstServerOffset; var serverTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, metaInfo.GetTimeZone(isUtc, SecurityId), allowDiffOffsets, ref lastOffset); metaInfo.FirstTime = prevTime; metaInfo.FirstServerOffset = lastOffset; var msg = new ExecutionMessage { //LocalTime = metaInfo.FirstTime, ExecutionType = ExecutionTypes.Tick, SecurityId = SecurityId, TradeId = metaInfo.FirstId, TradeVolume = volume, OriginSide = orderDirection, TradePrice = price, ServerTime = serverTime, }; if (metaInfo.Version < MarketDataVersions.Version40) return msg; if (metaInfo.Version < MarketDataVersions.Version47) { msg.LocalTime = msg.ServerTime - reader.ReadLong().To<TimeSpan>() + metaInfo.LocalOffset; } else { var hasLocalTime = true; if (metaInfo.Version >= MarketDataVersions.Version49) hasLocalTime = reader.Read(); if (hasLocalTime) { var prevLocalTime = metaInfo.FirstLocalTime; lastOffset = metaInfo.FirstLocalOffset; var localTime = reader.ReadTime(ref prevLocalTime, allowNonOrdered, isUtc, metaInfo.LocalOffset, allowDiffOffsets, ref lastOffset); metaInfo.FirstLocalTime = prevLocalTime; metaInfo.FirstLocalOffset = lastOffset; msg.LocalTime = localTime; } //else // msg.LocalTime = msg.ServerTime; } if (metaInfo.Version < MarketDataVersions.Version42) return msg; msg.IsSystem = metaInfo.Version < MarketDataVersions.Version51 ? reader.Read() : (reader.Read() ? reader.Read() : (bool?)null); if (msg.IsSystem == false) { msg.TradeStatus = metaInfo.Version < MarketDataVersions.Version51 ? reader.ReadInt() : reader.ReadNullableInt<int>(); } if (metaInfo.Version < MarketDataVersions.Version46 || reader.Read()) msg.OpenInterest = reader.ReadVolume(metaInfo); if (metaInfo.Version < MarketDataVersions.Version45) return msg; if (reader.Read()) msg.IsUpTick = reader.Read(); if (metaInfo.Version >= MarketDataVersions.Version52) { if (reader.Read()) msg.Currency = (CurrencyTypes)reader.ReadInt(); } return msg; } } }
risty/StockSharp
Algo/Storages/Binary/TickBinarySerializer.cs
C#
apache-2.0
10,190
(function(root, undef) { /////////////////////////////////////////////////////////////////////////////////////////////// // pg.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// $rdf.PG = { createNewStore: function(fetcherTimeout) { var store = new $rdf.IndexedFormula(); // this makes "store.fetcher" variable available $rdf.fetcher(store, fetcherTimeout, true); return store; } } /** * Some common and useful namespaces already declared for you */ $rdf.PG.Namespaces = { LINK: $rdf.Namespace("http://www.w3.org/2007/ont/link#"), HTTP: $rdf.Namespace("http://www.w3.org/2007/ont/http#"), HTTPH: $rdf.Namespace("http://www.w3.org/2007/ont/httph#"), RDF: $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), RDFS: $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"), OWL: $rdf.Namespace("http://www.w3.org/2002/07/owl#"), RSS: $rdf.Namespace("http://purl.org/rss/1.0/"), XSD: $rdf.Namespace("http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#dt-"), IANA: $rdf.Namespace("http://www.iana.org/assignments/link-relations/#"), CERT: $rdf.Namespace("http://www.w3.org/ns/auth/cert"), WAC: $rdf.Namespace("http://www.w3.org/ns/auth/acl#"), LDP: $rdf.Namespace("http://www.w3.org/ns/ldp#"), SIOC: $rdf.Namespace("http://rdfs.org/sioc/ns#"), DC: $rdf.Namespace("http://purl.org/dc/elements/1.1/"), FOAF: $rdf.Namespace("http://xmlns.com/foaf/0.1/"), CONTACT: $rdf.Namespace("http://www.w3.org/2000/10/swap/pim/contact#"), STAT: $rdf.Namespace("http://www.w3.org/ns/posix/stat#"), GEOLOC: $rdf.Namespace("http://www.w3.org/2003/01/geo/wgs84_pos#") } /** * Permits to get metadata about a pointed graph. * Like request headers and response headers. * RDFLib put these in the store as triples and it's not always easy to know where it puts the info. * This makes it easier to find back these metadatas */ $rdf.PG.MetadataHelper = { assertSingleStatement: function(stmts,msg) { if ( !stmts || stmts.length != 1 ) { throw new Error(msg + " - Expected exactly one statement. Found: "+stmts); } }, getRequestNode: function(pg) { var fetchUriAsLit = $rdf.lit(pg.why().uri); var stmts = store.statementsMatching(undefined, $rdf.PG.Namespaces.LINK("requestedURI"), fetchUriAsLit, store.fetcher.appNode); this.assertSingleStatement(stmts,"There should be exactly one request node"); var stmt = stmts[0]; return stmt.subject; }, getResponseNode: function(requestNode) { var stmts = store.statementsMatching(requestNode, $rdf.PG.Namespaces.LINK("response"), undefined); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, getResponseHeaderValue: function(responseNode,headerName) { var headerSym = $rdf.PG.Namespaces.HTTPH(headerName.toLowerCase()); var stmts = store.statementsMatching(responseNode, headerSym, undefined, responseNode); if ( !stmts || stmts.length == 0 ) return undefined; var stmt = stmts[0]; return stmt.object; }, getResponseStatus: function(responseNode) { var statusSym = $rdf.PG.Namespaces.HTTP("status"); var stmts = store.statementsMatching(responseNode, statusSym, undefined, responseNode); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, getResponseStatusText: function(responseNode) { var statusSym = $rdf.PG.Namespaces.HTTP("statusText"); var stmts = store.statementsMatching(responseNode, statusSym, undefined, responseNode); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, /** * Returns an helper method that is bound to the given pointed graph and permits to get metadatas related * to the underlying document / resource / named graph * * Note that you can only use this if the underlying document of the pg was retrieved through the fetcher. * If the data was added to the store manually then the requests/responses metadatas are not present in the store * unless you have added them by yourself */ forPointedGraph: function(pg) { var self = this; var requestNode = this.getRequestNode(pg); var responseNode = this.getResponseNode(requestNode); return { getRequestNode: function() { return requestNode; }, getResponseNode: function() { return responseNode; }, getResponseStatus: function() { return self.getResponseStatus(responseNode); }, getResponseStatusText: function() { return self.getResponseStatusText(responseNode); }, getResponseHeaderValue: function(headerName) { return self.getResponseHeaderValue(responseNode,headerName); } } } } $rdf.PG.Utils = { /** * Just a little helper method to verify preconditions and fail fast. * See http://en.wikipedia.org/wiki/Precondition * See http://en.wikipedia.org/wiki/Fail-fast * @param condition * @param message */ checkArgument: function(condition, message) { if (!condition) { throw Error('IllegalArgumentException: ' + (message || 'No description')); } }, /** * remove hash from URL - this gets the document location * @param url * @returns {*} */ fragmentless: function(url) { return url.split('#')[0]; }, isFragmentless: function(url) { return url.indexOf('#') == -1; }, isFragmentlessSymbol: function(node) { return this.isSymbolNode(node) && this.isFragmentless(this.symbolNodeToUrl(node)); }, getTermType: function(node) { if ( node && node.termType ) { return node.termType } else { throw new Error("Can't get termtype on this object. Probably not an RDFlib node: "+node); } }, isLiteralNode: function(node) { return this.getTermType(node) == 'literal'; }, isSymbolNode: function(node) { return this.getTermType(node) == 'symbol'; }, isBlankNode: function(node) { return this.getTermType(node) == 'bnode'; }, literalNodeToValue: function(node) { this.checkArgument(this.isLiteralNode(node), "Node is not a literal node:"+node); return node.value; }, symbolNodeToUrl: function(node) { this.checkArgument(this.isSymbolNode(node), "Node is not a symbol node:"+node); return node.uri; }, /** * Get the nodes for a given relation symbol * @param pg * @param relSym * @returns => List[Nodes] */ getNodes: function(pg, relSym) { return _.chain( pg.rels(relSym) ) .map(function(pg) { return pg.pointer; }).value(); }, getLiteralNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isLiteralNode) .value(); }, getSymbolNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isSymbolNode) .value(); }, getBlankNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isBlankNode) .value(); }, /** * * @param pgList * @returns {*} */ getLiteralValues: function(pgList) { var rels = (slice.call(arguments, 1)); var res = _.chain(pgList) .map(function (pg) { return pg.getLiteral(rels); }) .flatten() .value(); return res; } } $rdf.PG.Utils.Rx = { /** * Permits to create an RxJs observable based on a list of promises * @param promiseList the list of promise you want to convert as an RxJs Observable * @param subject the type of Rx Subject you want to use (default to ReplaySubject) * @param onError, an optional callback for handling errors * @return {*} */ promiseListToObservable: function(promiseList, subject, onError) { if ( promiseList.length == 0 ) { return Rx.Observable.empty(); } // Default to ReplaySubject var subject = subject || new Rx.ReplaySubject(); // Default to non-blocking error logging var onError = onError || function(error) { console.debug("Promise error catched in promiseListToObservable: ",error); // true means the stream won't continue. return false; }; var i = 0; promiseList.map(function(promise) { promise.then( function (promiseValue) { subject.onNext(promiseValue); i++; if ( i == promiseList.length ) { subject.onCompleted(); } }, function (error) { var doStop = onError(error); if ( doStop ) { subject.onError(error); } else { i++; if ( i == promiseList.length ) { subject.onCompleted(); } } } ) }); return subject.asObservable(); } } $rdf.PG.Filters = { isLiteralPointer: function(pg) { return pg.isLiteralPointer(); }, isBlankNodePointer: function(pg) { return pg.isBlankNodePointer(); }, isSymbolPointer: function(pg) { return pg.isSymbolPointer(); } } $rdf.PG.Transformers = { literalPointerToValue: function(pg) { return $rdf.PG.Utils.literalNodeToValue(pg.pointer); }, symbolPointerToValue: function(pg) { return $rdf.PG.Utils.symbolNodeToUrl(pg.pointer); }, tripleToSubject: function(triple) { return triple.subject; }, tripleToPredicate: function(triple) { return triple.predicate; }, tripleToObject: function(triple) { return triple.object; } } /////////////////////////////////////////////////////////////////////////////////////////////// // pointedGraph.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// /** * A pointed graph is a pointer in a named graph. * A named graph is an http resource/document which contains an RDF graph. * A pointer is a particular node in this graph. * * This PointedGraph implementation provides methods to navigate from one node to another in the current namedGraph, * but it also permits to jump from one namedGraph to another (firing http requests) if a pointer points to a remote node. * * @param {$rdf.store} store - Quad Store * @param {$rdf.node} pointer: point in the current graph. Type: Literal, Bnode, or URI * @param {$rdf.sym} namedGraphUrl: the URL of the current RDF graph. * @return {$rdf.PointedGraph} */ $rdf.pointedGraph = function(store, pointer, namedGraphUrl) { return new $rdf.PointedGraph(store, pointer, namedGraphUrl); }; $rdf.PointedGraph = function() { $rdf.PointedGraph = function(store, pointer, namedGraphUrl) { // TODO assert the pointer is a node $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isFragmentlessSymbol(namedGraphUrl),"The namedGraphUrl should be a fragmentless symbol! -> "+namedGraphUrl); this.store = store; this.pointer = pointer; this.namedGraphUrl = namedGraphUrl; // The namedGraphFetchUrl is the namedGraphUrl that may or not be proxified. // We need this because we kind of hacked RDFLib and unfortunatly if there's a cors proxy enabled, // rdflib will only remember the proxified version of the url in the store this.namedGraphFetchUrl = store.fetcher.proxifySymbolIfNeeded(namedGraphUrl); }; $rdf.PointedGraph.prototype.constructor = $rdf.PointedGraph; // TODO this logging stuff must be moved somewhere else :( // Logs. var logLevels = $rdf.PointedGraph.logLevels = { nologs: 0, debug: 1, info: 2, warning: 3, error: 4 }; // Default is no logs. $rdf.PointedGraph.logLevel = logLevels.nologs; // To change the level of logs $rdf.PointedGraph.setLogLevel = function(level) { $rdf.PointedGraph.logLevel = (logLevels[level] == null ? logLevels.info : logLevels[level]); } var doLog = function(level, consoleLogFunction ,messageArray) { var loggingEnabled = ($rdf.PointedGraph.logLevel !== logLevels.nologs); if ( loggingEnabled ) { var shouldLog = ( (logLevels[level] || logLevels.debug) >= $rdf.PointedGraph.logLevel ); if ( shouldLog ) { // TODO maybe it may be cool to prefix the log with the current pg infos consoleLogFunction.apply(console,messageArray); } } } // Specific functions for each level of logs. var debug = function() { doLog('debug', console.debug, _.toArray(arguments)) }; var info = function() { doLog('info', console.info, _.toArray(arguments)) }; var warning = function() { doLog('warning', console.warn, _.toArray(arguments)) }; var error = function() { doLog('error', console.error, _.toArray(arguments)) }; // Utils. function sparqlPatch(uri, query) { var promise = $.ajax({ type: "PATCH", url: uri, contentType: 'application/sparql-update', dataType: 'text', processData:false, data: query }).promise(); return promise; } function sparqlPut(uri, query) { var promise = $.ajax({ type: "PUT", url: uri, contentType: 'application/sparql-update', dataType: 'text', processData:false, data: query }).promise(); return promise; } /** * From the pointer, this follows a predicate/symbol/rel and gives a list of pointer in the same graph/document. * @param {$rdf.sym} rel the relation from this node * @returns {[PointedGraph]} of PointedGraphs with the same graph name in the same store */ $rdf.PointedGraph.prototype.rel = function (rel) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(rel) , "The argument should be a symbol:"+rel); var self = this; var resList = this.getCurrentDocumentTriplesMatching(this.pointer, rel, undefined, false); return _.map(resList, function (triple) { return new $rdf.PointedGraph(self.store, triple.object, self.namedGraphUrl, self.namedGraphFetchUrl); }); } $rdf.PointedGraph.prototype.relFirst = function(relUri) { var l = this.rel(relUri); if (l.length > 0) return l[0]; } /** * This is the reverse of "rel": this permits to know which PG in the current graph/document points to the given pointer * @param {$rdf.sym} rel the relation to this node * @returns {[PointedGraph]} of PointedGraphs with the same graph name in the same store */ $rdf.PointedGraph.prototype.rev = function (rel) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(rel) , "The argument should be a symbol:"+rel); var self = this; var resList = this.getCurrentDocumentTriplesMatching(undefined, rel, this.pointer, false); return _.map(resList, function (triple) { return new $rdf.PointedGraph(self.store, triple.subject, self.namedGraphUrl, self.namedGraphFetchUrl); }); } $rdf.PointedGraph.prototype.revFirst = function(relUri) { var l = this.rev(relUri); if (l.length > 0) return l[0]; } /** * Same as "rel" but follow mmultiple predicates/rels * @returns {*} */ // Array[relUri] => Array[Pgs] TODO to rework $rdf.PointedGraph.prototype.rels = function() { var self = this; var pgList = _.chain(arguments) .map(function(arg) { return self.rel(arg) }) .flatten() .value() return pgList; } /** * This permits to follow a relation in the local graph and then jump asynchronously. * This produces a stream of pointed graphs in the form of an RxJs Observable * @param Observable[PointedGraph] * @param onJumpError */ $rdf.PointedGraph.prototype.jumpRelObservable = function(relUri) { var pgList = this.rel(relUri); var pgPromiseList = pgList.map(function(pg) { return pg.jumpAsync(); }); return $rdf.PG.Utils.Rx.promiseListToObservable(pgPromiseList); } /** * Just an alias for jumpRelPathObservable * @param relPath * @param onJumpErrorCallback * @return {*} */ $rdf.PointedGraph.prototype.followPath = function(relPath) { return this.jumpRelPathObservable(relPath); } /** * Permits to follow a relation/predicate path, jumping from one document to another when it's needed * @param relPath * @param onJumpErrorCallback optional callback to handle jump errors, because they are not emitted in the stream * @return {*} */ $rdf.PointedGraph.prototype.jumpRelPathObservable = function(relPath) { $rdf.PG.Utils.checkArgument(relPath && relPath.length > 0,"No relation to follow! "+relPath); var head = relPath[0]; var tail = relPath.slice(1); var headStream = this.jumpRelObservable(head); if ( _.isEmpty(tail) ) { return headStream; } else { return headStream.flatMap(function(pg) { var tailStream = pg.jumpRelPathObservable(tail); return tailStream; }) } } /** * Nearly the same as jumpAsync except it will not fetch remote document but will only use documents * that are already in the store. This means that you can't jump to a remote document that has not been previously * loaded in the store or an error will be thrown. * @returns {$rdf.PointedGraph} */ $rdf.PointedGraph.prototype.jump = function() { if ( this.isLocalPointer() ) { return this; } else { var pointerDocumentUrl = this.getSymbolPointerDocumentUrl(); var pointerDocumentFetchUrl = this.store.fetcher.proxifyIfNeeded(pointerDocumentUrl); var uriFetchState = this.store.fetcher.getState(pointerDocumentFetchUrl); if (uriFetchState == 'fetched') { return $rdf.pointedGraph(this.store, this.pointer, $rdf.sym(pointerDocumentUrl), $rdf.sym(pointerDocumentFetchUrl) ); } else { // If this error bothers you, you may need to use jumpAsync throw new Error("Can't jump because the jump requires ["+pointerDocumentUrl+"] to be already fetched." + " This resource is not in the store. State="+uriFetchState); } } } /** * This permits to jump to the pointer document if the document * This will return the current PG if the pointer is local (bnode/literal/local symbols...) * This will return a new PG if the pointer refers to another document. * * So, basically * - (documentUrl - documentUrl#hash ) will return (documentUrl - documentUrl#hash ) * - (documentUrl - documentUrl2#hash ) will return (documentUrl2 - documentUrl2#hash ) * * @returns {Promise[PointedGraph]} */ $rdf.PointedGraph.prototype.jumpAsync = function() { var originalPG = this; if ( originalPG.isLocalPointer() ) { return Q.fcall(function () { return originalPG; }) } else { return this.jumpFetchRemote(); } } /** * This permits to follow a remote symbol pointer and fetch the remote document. * This will give you a PG with the same pointer but the underlying document will be * the remote document instead of the current document. * * For exemple, let's suppose: * - current PG (documentUrl,pointer) is (url1, url1#profile) * - current document contains triple (url1#profile - foaf:knows - url2#profile) * - you follow the foaf:knows rel and get PG2 (url1, url2#profile) * - then you can jumpFetch on PG2 because url2 != url1 * - this will give you PG3 (url2, url2#profile) * - you'll have the same pointer, but the document is different * * @returns {Promise[PointedGraph]} */ $rdf.PointedGraph.prototype.jumpFetchRemote = function() { $rdf.PG.Utils.checkArgument( this.isRemotePointer(),"You are not supposed to jumpFetch if you already have all the data locally. Pointer="+this.pointer); var pointerUrl = this.getSymbolPointerUrl(); var referrerUrl = $rdf.PG.Utils.symbolNodeToUrl(this.namedGraphUrl); var force = false; return this.store.fetcher.fetch(pointerUrl, referrerUrl, force); } // relUri => List[Symbol] $rdf.PointedGraph.prototype.getSymbol = function() { var rels = _.flatten(arguments); // TODO: WTF WHY DO WE NEED TO FLATTEN!!! var pgList = this.rels.apply(this, rels); var symbolValueList = _.chain(pgList) .filter($rdf.PG.Filters.isSymbolPointer) .map($rdf.PG.Transformers.symbolPointerToValue) .value(); return symbolValueList } // relUri => List[Literal] // TODO change the name $rdf.PointedGraph.prototype.getLiteral = function () { var rels = _.flatten(arguments); // TODO: WTF WHY DO WE NEED TO FLATTEN!!! var pgList = this.rels.apply(this, rels); var literalValueList = _.chain(pgList) .filter($rdf.PG.Filters.isLiteralPointer) .map($rdf.PG.Transformers.literalPointerToValue) .value(); return literalValueList; } // Interaction with the PGs. $rdf.PointedGraph.prototype.delete = function(relUri, value) { // TODO to rework? remove hardcoded namespace value var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n' + 'DELETE DATA \n' + '{' + "<" + this.pointer.value + ">" + relUri + ' "' + value + '"' + '. \n' + '}'; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.insert = function(relUri, value) { // TODO to rework? remove hardcoded namespace value? var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n' + 'INSERT DATA \n' + '{' + "<" + this.pointer.value + ">" + relUri + ' "' + value + '"' + '. \n' + '}'; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.update = function (relUri, newValue, oldvalue) { var query = 'DELETE DATA \n' + '{' + "<" + this.pointer.value + "> " + relUri + ' "' + oldvalue + '"' + '} ;\n' + 'INSERT DATA \n' + '{' + "<" + this.pointer.value + "> " + relUri + ' "' + newValue + '"' + '. } '; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.updateStore = function(relUri, newValue) { this.store.removeMany(this.pointer, relUri, undefined, this.namedGraphFetchUrl); this.store.add(this.pointer, relUri, newValue, this.namedGraphFetchUrl); } $rdf.PointedGraph.prototype.replaceStatements = function(pg) { var self = this; this.store.removeMany(undefined, undefined, undefined, pg.namedGraphFetchUrl); _.each(pg.store.statements, function(stat) { self.store.add(stat.subject, stat.predicate, stat.object, pg.namedGraphFetchUrl) }); } $rdf.PointedGraph.prototype.addRel = function(rel, object) { this.store.add( this.pointer, rel, object, this.why() ); } $rdf.PointedGraph.prototype.removeRel = function(rel, object) { this.store.removeMany( this.pointer, rel, object, this.why() ); } $rdf.PointedGraph.prototype.ajaxPut = function (baseUri, data, success, error, done) { $.ajax({ type: "PUT", url: baseUri, dataType: "text", contentType: "text/turtle", processData: false, data: data, success: function (data, status, xhr) { if (success) success(xhr) }, error: function (xhr, status, err) { if (error) error(xhr) } }) .done(function () { if (done) done() }); } $rdf.PointedGraph.prototype.print = function() { return this.printSummary() + " = { "+this.printContent() + "}" } $rdf.PointedGraph.prototype.printSummary = function() { return "PG[pointer="+this.pointer+" - NamedGraph="+this.namedGraphUrl+"]"; } $rdf.PointedGraph.prototype.printContent = function() { return $rdf.Serializer(this.store).statementsToN3(this.store.statementsMatching(undefined, undefined, undefined, this.namedGraphFetchUrl)); } $rdf.PointedGraph.prototype.toString = function() { return this.printSummary(); } /** * Return a clone of the current pointed graph in another store. * This is useful to edit a pointed graph. * Once the edit is validated it may be nice to merge the small temporary edited store * to the original big store. */ // TODO need better name $rdf.PointedGraph.prototype.deepCopyOfGraph = function() { var self = this; var triples = this.store.statementsMatching(undefined, undefined, undefined, this.namedGraphFetchUrl); var store = new $rdf.IndexedFormula(); $rdf.fetcher(store, 100000, true); // TODO; deals with timeOut _.each(triples, function(stat) { store.add(stat.subject, stat.predicate, stat.object, self.namedGraphFetchUrl) }); return new $rdf.PointedGraph(store, this.pointer, this.namedGraphUrl, this.namedGraphFetchUrl); } $rdf.PointedGraph.prototype.isSymbolPointer = function() { return $rdf.PG.Utils.isSymbolNode(this.pointer); } $rdf.PointedGraph.prototype.isLiteralPointer = function() { return $rdf.PG.Utils.isLiteralNode(this.pointer); } $rdf.PointedGraph.prototype.isBlankNodePointer = function() { return $rdf.PG.Utils.isBlankNode(this.pointer); } /** * Returns the Url of the pointer. * The url may contain a fragment. * Will fail if the pointer is not a symbol because you can't get an url for a blank node or a literal. */ $rdf.PointedGraph.prototype.getSymbolPointerUrl = function() { return $rdf.PG.Utils.symbolNodeToUrl(this.pointer); } /** * Returns the Url of the document in which points the symbol pointer. * The url is a document URL so it won't contain a fragment. * Will fail if the pointer is not a symbol because you can't get an url for a blank node or a literal. */ $rdf.PointedGraph.prototype.getSymbolPointerDocumentUrl = function() { var pointerUrl = this.getSymbolPointerUrl(); return $rdf.PG.Utils.fragmentless(pointerUrl); } /** * Returns the current document/namedGraph Url (so it has no fragment) */ $rdf.PointedGraph.prototype.getCurrentDocumentUrl = function() { return $rdf.PG.Utils.symbolNodeToUrl(this.namedGraphUrl); } /** * This permits to find triples in the current document. * This will not look in the whole store but will only check in the current document/namedGraph * @param pointer (node) * @param rel (node) * @param object (node) * @param onlyOne: set true if you only want one triple result (for perf reasons for exemple) * @returns {*} */ $rdf.PointedGraph.prototype.getCurrentDocumentTriplesMatching = function (pointer,rel,object,onlyOne) { var why = this.why(); return this.store.statementsMatching(pointer, rel, object, this.why(), onlyOne); } /** * Builds a metadata helper to get metadatas related to the underlying documment * @return {*} */ $rdf.PointedGraph.prototype.currentDocumentMetadataHelper = function() { return $rdf.PG.MetadataHelper.forPointedGraph(this); } /** * In the actual version it seems that RDFLib use the fetched url as the "why" * Maybe it's because we have modified it a little bit to work better with our cors proxy. * This is why we need to pass the namedGraphFetchUrl and not the namedGraphUrl */ $rdf.PointedGraph.prototype.why = function() { return this.namedGraphFetchUrl; } /** * This permits to find the triples that matches a given rel/predicate and object * for the current pointer in the current document. * @param rel * @param object * @param onlyOne */ $rdf.PointedGraph.prototype.getPointerTriplesMatching = function(rel,object,onlyOne) { return this.getCurrentDocumentTriplesMatching(this.pointer, rel, object, onlyOne); } /** * Permits to know if there is at least one triple in this graph that matches the pointer, predicate and object * @param rel * @param object * @param onlyOne * @return {boolean} */ $rdf.PointedGraph.prototype.hasPointerTripleMatching = function(rel,object) { return this.getPointerTriplesMatching(rel,object,true).length > 0; } /** * Returns the Url of the currently pointed document. * Most of the time it will return the current document url. * It will return a different url only for non-local symbol nodes. * * If you follow a foaf:knows, you will probably get a list of PGs where the pointer document * URL is not local because your friends will likely describe themselves in different resources. */ $rdf.PointedGraph.prototype.getPointerDocumentUrl = function() { if ( this.isSymbolPointer() ) { return this.getSymbolPointerDocumentUrl(); } else { return this.getCurrentDocumentUrl(); } } /** * Permits to know if the pointer is local to the current document. * This will be the case for blank nodes, literals and local symbol pointers. * @returns {boolean} */ $rdf.PointedGraph.prototype.isLocalPointer = function() { return this.getPointerDocumentUrl() == this.getCurrentDocumentUrl(); } $rdf.PointedGraph.prototype.isRemotePointer = function() { return !this.isLocalPointer(); } /** * Permits to "move" to another subject in the given graph * @param newPointer * @returns {$rdf.PointedGraph} */ $rdf.PointedGraph.prototype.withPointer = function(newPointer) { return new $rdf.PointedGraph(this.store, newPointer, this.namedGraphUrl, this.namedGraphFetchUrl); } /** * Permits to know if the given pointer have at least one rel that can be followed. * This means that the current pointer exists in the local graph as a subject in at least one triple. */ $rdf.PointedGraph.prototype.hasRels = function() { return this.getCurrentDocumentTriplesMatching(this.pointer, undefined, undefined, true).length > 0; } /** * Permits to know if the given pointer have at least one rev that can be followed. * This means that the current pointer exists in the local graph as an object in at least one triple. */ $rdf.PointedGraph.prototype.hasRevs = function() { return this.getCurrentDocumentTriplesMatching(undefined, undefined, this.pointer, true).length > 0; } return $rdf.PointedGraph; }(); /////////////////////////////////////////////////////////////////////////////////////////////// // fetcherWithPromise.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// /* TODO: this proxification code is kind of duplicate of RDFLib's "crossSiteProxyTemplate" code. How can we make this code be integrated in rdflib nicely? */ /** * Permits to know in which conditions we are using a CORS proxy (if one is configured) * @param uri */ $rdf.Fetcher.prototype.requiresProxy = function(url) { var isCorsProxyConfigured = $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate; if ( !isCorsProxyConfigured ) { return false; } else { // /!\ this may not work with the original version of RDFLib var isUriAlreadyProxified = (url.indexOf($rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate) == 0); var isHomeServerUri = (url.indexOf($rdf.Fetcher.homeServer) == 0) if ( isUriAlreadyProxified || isHomeServerUri ) { return false; } else { return true; } } } /** * permits to proxify the URI * @param uri * @returns {string} */ $rdf.Fetcher.prototype.proxify = function(uri) { if ( uri && uri.indexOf('#') != -1 ) { throw new Error("Tit is forbiden to proxify an uri with a fragment:"+uri); } if ( uri && uri.indexOf($rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate) == 0 ) { throw new Error("You are trying to proxify an URL that seems to already been proxified!"+uri); } return $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate + encodeURIComponent(uri); }; /** * Permits to proxify an url if RDFLib is configured to be used with a CORS Proxy * @param url * @returns {String} the original url or the proxied url */ $rdf.Fetcher.prototype.proxifyIfNeeded = function(url) { if ( this.requiresProxy(url) ) { return this.proxify(url); } else { return url; } } $rdf.Fetcher.prototype.proxifySymbolIfNeeded = function(symbol) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(symbol),"This is not a symbol!"+symbol); var url = $rdf.PG.Utils.symbolNodeToUrl(symbol); var proxifiedUrl = this.proxifyIfNeeded(url); return $rdf.sym(proxifiedUrl); } /** * Return the Promise of a pointed graph for a given url * @param {String} uri to fetch as string. The URI may contain a fragment because it results in a pointedGraph * @param {String} referringTerm the uri as string. Referring to the requested url * @param {boolean} force, force fetching of resource even if already in store * @return {Promise} of a pointedGraph */ $rdf.Fetcher.prototype.fetch = function(uri, referringTerm, force) { var self = this; var uriSym = $rdf.sym(uri); var docUri = $rdf.PG.Utils.fragmentless(uri); var docUriSym = $rdf.sym(docUri); // The doc uri to fetch is the doc uri that may have been proxyfied var docUriToFetch = self.proxifyIfNeeded(docUri); var docUriToFetchSym = $rdf.sym(docUriToFetch); // if force mode enabled -> we previously unload so that uriFetchState will be "unrequested" if ( force ) { self.unload(docUriToFetchSym); } var uriFetchState = self.getState(docUriToFetch); // if it was already fetched we return directly the pointed graph pointing if (uriFetchState == 'fetched') { return Q.fcall(function() { return $rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym) }); } // if it was already fetched and there was an error we do not try again // notice you can call "unload(symbol)" if you want a failed request to be fetched again if needed else if ( uriFetchState == 'failed') { return Q.fcall(function() { throw new Error("Previous fetch has failed for"+docUriToFetch+" -> Will try to fetch it again"); }); } // else maybe a request for this uri is already pending, or maybe we will have to fire a request // in both case we are interested in the answer else if ( uriFetchState == 'requested' || uriFetchState == 'unrequested' ) { if ( uriFetchState == 'requested') { console.debug("A request is already being done for",docUriToFetch," -> will wait for that response"); } var deferred = Q.defer(); self.addCallback('done', function fetchDoneCallback(uriFetched) { if ( docUriToFetch == uriFetched ) { deferred.resolve($rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym)); return false; // stop } return true; // continue }); self.addCallback('fail', function fetchFailureCallback(uriFetched, statusString, xhr) { if ( docUriToFetch == uriFetched ) { deferred.reject(new Error("Async fetch failure [uri="+uri+"][statusCode="+xhr.status+"][reason="+statusString+"]")); return false; // stop } return true; // continue }); if (uriFetchState == 'unrequested') { var result = self.requestURI(docUriToFetch, referringTerm, force); if (result == null) { // TODO not sure of the effect of this line. This may cause the promise to be resolved twice no? deferred.resolve($rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym)); } } return deferred.promise; } else { throw new Error("Unknown and unhandled uriFetchState="+uriFetchState+" - for URI="+uri) } }})(this);
read-write-web/react-foaf
js/lib/rdflib/rdflib-stample-pg-extension-0.1.1.js
JavaScript
apache-2.0
38,343
package com.hubspot.singularity.resources; import static com.hubspot.singularity.WebExceptions.checkBadRequest; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.google.common.base.Optional; import com.google.inject.Inject; import com.hubspot.singularity.SingularityDeployHistory; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityRequestHistory; import com.hubspot.singularity.SingularityService; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskIdHistory; import com.hubspot.singularity.SingularityUser; import com.hubspot.singularity.auth.SingularityAuthorizationHelper; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.history.DeployHistoryHelper; import com.hubspot.singularity.data.history.DeployTaskHistoryHelper; import com.hubspot.singularity.data.history.HistoryManager; import com.hubspot.singularity.data.history.RequestHistoryHelper; import com.hubspot.singularity.data.history.TaskHistoryHelper; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; @Path(HistoryResource.PATH) @Produces({ MediaType.APPLICATION_JSON }) @Api(description = "Manages historical data for tasks, requests, and deploys.", value = HistoryResource.PATH) public class HistoryResource extends AbstractHistoryResource { public static final String PATH = SingularityService.API_BASE_PATH + "/history"; private final DeployHistoryHelper deployHistoryHelper; private final TaskHistoryHelper taskHistoryHelper; private final RequestHistoryHelper requestHistoryHelper; private final DeployTaskHistoryHelper deployTaskHistoryHelper; @Inject public HistoryResource(HistoryManager historyManager, TaskManager taskManager, DeployManager deployManager, DeployHistoryHelper deployHistoryHelper, TaskHistoryHelper taskHistoryHelper, RequestHistoryHelper requestHistoryHelper, SingularityAuthorizationHelper authorizationHelper, Optional<SingularityUser> user, DeployTaskHistoryHelper deployTaskHistoryHelper) { super(historyManager, taskManager, deployManager, authorizationHelper, user); this.requestHistoryHelper = requestHistoryHelper; this.deployHistoryHelper = deployHistoryHelper; this.taskHistoryHelper = taskHistoryHelper; this.deployTaskHistoryHelper = deployTaskHistoryHelper; } @GET @Path("/task/{taskId}") @ApiOperation("Retrieve the history for a specific task.") public SingularityTaskHistory getHistoryForTask(@ApiParam("Task ID to look up") @PathParam("taskId") String taskId) { SingularityTaskId taskIdObj = getTaskIdObject(taskId); return getTaskHistory(taskIdObj); } private Integer getLimitCount(Integer countParam) { if (countParam == null) { return 100; } checkBadRequest(countParam >= 0, "count param must be non-zero"); if (countParam > 1000) { return 1000; } return countParam; } private Integer getLimitStart(Integer limitCount, Integer pageParam) { if (pageParam == null) { return 0; } checkBadRequest(pageParam >= 1, "page param must be 1 or greater"); return limitCount * (pageParam - 1); } @GET @Path("/request/{requestId}/tasks/active") @ApiOperation("Retrieve the history for all active tasks of a specific request.") public List<SingularityTaskIdHistory> getTaskHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId) { authorizationHelper.checkForAuthorizationByRequestId(requestId, user); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForRequest(requestId); return taskHistoryHelper.getTaskHistoriesFor(taskManager, activeTaskIds); } @GET @Path("/request/{requestId}/deploy/{deployId}") @ApiOperation("Retrieve the history for a specific deploy.") public SingularityDeployHistory getDeploy(@ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId) { return getDeployHistory(requestId, deployId); } @GET @Path("/request/{requestId}/deploy/{deployId}/tasks/active") @ApiOperation("Retrieve the task history for a specific deploy.") public List<SingularityTaskIdHistory> getActiveDeployTasks( @ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId) { authorizationHelper.checkForAuthorizationByRequestId(requestId, user); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForDeploy(requestId, deployId); return taskHistoryHelper.getTaskHistoriesFor(taskManager, activeTaskIds); } @GET @Path("/request/{requestId}/deploy/{deployId}/tasks/inactive") @ApiOperation("Retrieve the task history for a specific deploy.") public List<SingularityTaskIdHistory> getInactiveDeployTasks( @ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); SingularityDeployKey key = new SingularityDeployKey(requestId, deployId); return deployTaskHistoryHelper.getBlendedHistory(key, limitStart, limitCount); } @GET @Path("/request/{requestId}/tasks") @ApiOperation("Retrieve the history for all tasks of a specific request.") public List<SingularityTaskIdHistory> getTaskHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return taskHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/request/{requestId}/deploys") @ApiOperation("") public List<SingularityDeployHistory> getDeploys( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return deployHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/request/{requestId}/requests") @ApiOperation("") public List<SingularityRequestHistory> getRequestHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Naximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return requestHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/requests/search") @ApiOperation("Search for requests.") public Iterable<String> getRequestHistoryForRequestLike( @ApiParam("Request ID prefix to search for") @QueryParam("requestIdLike") String requestIdLike, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); List<String> requestIds = historyManager.getRequestHistoryLike(requestIdLike, limitStart, limitCount); return authorizationHelper.filterAuthorizedRequestIds(user, requestIds); // TODO: will this screw up pagination? } }
acbellini/Singularity
SingularityService/src/main/java/com/hubspot/singularity/resources/HistoryResource.java
Java
apache-2.0
8,756
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.am.gateway.handler.common.vertx.web.handler; import io.gravitee.am.gateway.handler.common.utils.ConstantKeys; import io.gravitee.am.gateway.handler.common.vertx.web.handler.impl.CookieSession; import io.gravitee.am.service.AuthenticationFlowContextService; import io.vertx.core.Handler; import io.vertx.reactivex.ext.web.RoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import static io.gravitee.am.gateway.handler.common.utils.ConstantKeys.AUTH_FLOW_CONTEXT_VERSION_KEY; import static java.util.Optional.ofNullable; /** * @author Eric LELEU (eric.leleu at graviteesource.com) * @author GraviteeSource Team */ public class AuthenticationFlowContextHandler implements Handler<RoutingContext> { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFlowContextHandler.class); private AuthenticationFlowContextService authenticationFlowContextService; private final boolean exitOnError; public AuthenticationFlowContextHandler(AuthenticationFlowContextService authenticationFlowContextService, Environment env) { this.authenticationFlowContextService = authenticationFlowContextService; this.exitOnError = env.getProperty("authenticationFlow.exitOnError", Boolean.class, Boolean.FALSE); } @Override public void handle(RoutingContext context) { CookieSession session = (CookieSession) context.session().getDelegate(); if (session != null && !session.isDestroyed()) { final String transactionId = session.get(ConstantKeys.TRANSACTION_ID_KEY); final int version = ofNullable((Number) session.get(AUTH_FLOW_CONTEXT_VERSION_KEY)).map(Number::intValue).orElse(1); authenticationFlowContextService.loadContext(transactionId, version) .subscribe( ctx -> { // store the AuthenticationFlowContext in order to provide all related information about this context context.put(ConstantKeys.AUTH_FLOW_CONTEXT_KEY, ctx); // store only the AuthenticationFlowContext.data attributes in order to simplify EL templating // and provide an up to date set of data if the enrichAuthFlow Policy ius used multiple time in a step // {#context.attributes['authFlow']['entry']} context.put(ConstantKeys.AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, ctx.getData()); context.next(); }, error -> { LOGGER.warn("AuthenticationFlowContext can't be loaded", error); if (exitOnError) { context.fail(error); } else { context.next(); } }); } } }
gravitee-io/graviteeio-access-management
gravitee-am-gateway/gravitee-am-gateway-handler/gravitee-am-gateway-handler-common/src/main/java/io/gravitee/am/gateway/handler/common/vertx/web/handler/AuthenticationFlowContextHandler.java
Java
apache-2.0
3,713
/* * 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.ignite.ml.tree.randomforest; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ignite.ml.composition.ModelsComposition; import org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator; import org.apache.ignite.ml.dataset.Dataset; import org.apache.ignite.ml.dataset.feature.FeatureMeta; import org.apache.ignite.ml.dataset.feature.ObjectHistogram; import org.apache.ignite.ml.dataset.impl.bootstrapping.BootstrappedDatasetPartition; import org.apache.ignite.ml.dataset.impl.bootstrapping.BootstrappedVector; import org.apache.ignite.ml.dataset.primitive.context.EmptyContext; import org.apache.ignite.ml.tree.randomforest.data.TreeRoot; import org.apache.ignite.ml.tree.randomforest.data.impurity.GiniHistogram; import org.apache.ignite.ml.tree.randomforest.data.impurity.GiniHistogramsComputer; import org.apache.ignite.ml.tree.randomforest.data.impurity.ImpurityHistogramsComputer; import org.apache.ignite.ml.tree.randomforest.data.statistics.ClassifierLeafValuesComputer; import org.apache.ignite.ml.tree.randomforest.data.statistics.LeafValuesComputer; /** * Classifier trainer based on RandomForest algorithm. */ public class RandomForestClassifierTrainer extends RandomForestTrainer<ObjectHistogram<BootstrappedVector>, GiniHistogram, RandomForestClassifierTrainer> { /** Label mapping. */ private Map<Double, Integer> lblMapping = new HashMap<>(); /** * Constructs an instance of RandomForestClassifierTrainer. * * @param meta Features meta. */ public RandomForestClassifierTrainer(List<FeatureMeta> meta) { super(meta); } /** {@inheritDoc} */ @Override protected RandomForestClassifierTrainer instance() { return this; } /** * Aggregates all unique labels from dataset and assigns integer id value for each label. * This id can be used as index in arrays or lists. * * @param dataset Dataset. * @return true if initialization was done. */ @Override protected boolean init(Dataset<EmptyContext, BootstrappedDatasetPartition> dataset) { Set<Double> uniqLabels = dataset.compute( x -> { Set<Double> labels = new HashSet<>(); for (int i = 0; i < x.getRowsCount(); i++) labels.add(x.getRow(i).label()); return labels; }, (l, r) -> { if (l == null) return r; if (r == null) return l; Set<Double> lbls = new HashSet<>(); lbls.addAll(l); lbls.addAll(r); return lbls; } ); if(uniqLabels == null) return false; int i = 0; for (Double label : uniqLabels) lblMapping.put(label, i++); return super.init(dataset); } /** {@inheritDoc} */ @Override protected ModelsComposition buildComposition(List<TreeRoot> models) { return new ModelsComposition(models, new OnMajorityPredictionsAggregator()); } /** {@inheritDoc} */ @Override protected ImpurityHistogramsComputer<GiniHistogram> createImpurityHistogramsComputer() { return new GiniHistogramsComputer(lblMapping); } /** {@inheritDoc} */ @Override protected LeafValuesComputer<ObjectHistogram<BootstrappedVector>> createLeafStatisticsAggregator() { return new ClassifierLeafValuesComputer(lblMapping); } }
amirakhmedov/ignite
modules/ml/src/main/java/org/apache/ignite/ml/tree/randomforest/RandomForestClassifierTrainer.java
Java
apache-2.0
4,400
package com.sicdlib.dao.pyhtonDAO.imple; import com.sicdlib.dao.IBaseDAO; import com.sicdlib.dao.pyhtonDAO.IMOEDataDAO; import com.sicdlib.dto.entity.MoeDataEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * Created by init on 2017/6/4. */ @Repository("moeDataDAO") public class MOEDataDAO implements IMOEDataDAO{ @Autowired private IBaseDAO baseDAO; @Override public Boolean saveMOEData(MoeDataEntity moeData) { try{ baseDAO.save(moeData); return true; }catch (Exception e){ e.printStackTrace(); return false; } } }
V119/spidersManager
src/com/sicdlib/dao/pyhtonDAO/imple/MOEDataDAO.java
Java
apache-2.0
690
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_4430 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4430.java
Java
apache-2.0
151
<?php use Shackle\Rule; $set = Rule\Import::getInstance(); $set3 = $set->add(new Rule\Iterator(new Rule\Set('.', array('min' => 1)))); $set3->add(new Rule\Equal('email', array('equal' => 'test2@test.dk', 'message' => 'ekstra6 failed (email is invalid)'))); $set3->add(new Rule\Equal('firstname', array('equal' => 'bla2', 'message' => 'ekstra6 failed (firstname is invalid)'))); $set3->add(new Rule\Equal('/ekstra1', array('equal' => 153, 'message' => 'ekstra6 failed (absolute test)')));
martinvium/shackle
examples/validators2.php
PHP
apache-2.0
489
/** * Copyright (c) 2016 Source Auditor Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.spdx.compare; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.spdx.rdfparser.InvalidSPDXAnalysisException; import org.spdx.rdfparser.model.SpdxDocument; import org.spdx.rdfparser.model.SpdxFile; import org.spdx.rdfparser.model.SpdxItem; import org.spdx.rdfparser.model.SpdxSnippet; import com.google.common.base.Objects; import com.google.common.collect.Maps; /** * Compares two SPDX snippets. The <code>compare(snippetA, snippetB)</code> method will perform the comparison and * store the results. <code>isDifferenceFound()</code> will return true of any * differences were found. * @author Gary O'Neall * */ public class SpdxSnippetComparer extends SpdxItemComparer { private boolean inProgress = false; private boolean differenceFound = false; private boolean byteRangeEquals = true; private boolean lineRangeEquals = true; private boolean snippetFromFilesEquals = true; private boolean nameEquals = true; /** * Map of any difference between snippet from files where the file names are equal */ Map<SpdxDocument, Map<SpdxDocument, SpdxFileDifference>> snippetFromFileDifferences = Maps.newHashMap(); /** * Map of snippetFromFiles where the file names are different (and therefore considered a unique file) */ Map<SpdxDocument, Map<SpdxDocument, SpdxFile>> uniqueSnippetFromFile = Maps.newHashMap(); /** * @param extractedLicenseIdMap map of all extracted license IDs for any SPDX documents to be added to the comparer */ public SpdxSnippetComparer(Map<SpdxDocument, Map<SpdxDocument, Map<String, String>>> extractedLicenseIdMap) { super(extractedLicenseIdMap); } /** * Add a snippet to the comparer and performs the comparison to any existing documents * @param spdxDocument document containing the package * @param snippet snippet to be added * @param licenseXlationMap A mapping between the license IDs from licenses in fileA to fileB * @throws SpdxCompareException * @param spdxDocument * @param snippet */ public void addDocumentSnippet(SpdxDocument spdxDocument, SpdxSnippet snippet) throws SpdxCompareException { checkInProgress(); if (this.name == null) { this.name = snippet.toString(); } inProgress = true; Iterator<Entry<SpdxDocument, SpdxItem>> iter = this.documentItem.entrySet().iterator(); SpdxSnippet snippet2 = null; SpdxDocument document2 = null; while (iter.hasNext() && snippet2 == null) { Entry<SpdxDocument, SpdxItem> entry = iter.next(); if (entry.getValue() instanceof SpdxSnippet) { snippet2 = (SpdxSnippet)entry.getValue(); document2 = entry.getKey(); } } if (snippet2 != null) { try { if (!snippet2.equivalentConsideringNull(snippet2.getByteRange(), snippet.getByteRange())) { this.byteRangeEquals = false; this.differenceFound = true; } } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting byte range: "+e.getMessage())); } try { if (!snippet2.equivalentConsideringNull(snippet2.getLineRange(), snippet.getLineRange())) { this.lineRangeEquals = false; this.differenceFound = true; } } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting line range: "+e.getMessage())); } try { SpdxFile fromFile = snippet.getSnippetFromFile(); SpdxFile fromFile2 = snippet2.getSnippetFromFile(); compareSnippetFromFiles(spdxDocument, fromFile, document2, fromFile2); } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting snippet from file: "+e.getMessage())); } if (!SpdxComparer.stringsEqual(snippet2.getName(), snippet.getName())) { this.nameEquals = false; this.differenceFound = true; } } inProgress = false; super.addDocumentItem(spdxDocument, snippet); } /** * Compares the snippetFromFiles and updates the properties isSnippetFromFilesEquals, * uniqueSnippetFromFiles, and snippetFromFilesDifferences * @param fromFile * @param fromFile2 * @throws SpdxCompareException */ private void compareSnippetFromFiles(SpdxDocument spdxDocument, SpdxFile fromFile, SpdxDocument document2, SpdxFile fromFile2) throws SpdxCompareException { if (fromFile == null) { if (fromFile2 != null) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(document2); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(document2, unique); } unique.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } } else if (fromFile2 == null) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(spdxDocument); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(spdxDocument, unique); } unique.put(document2, fromFile); this.snippetFromFilesEquals = false; } else if (!Objects.equal(fromFile2.getName(), fromFile.getName())) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(spdxDocument); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(spdxDocument, unique); } unique.put(document2, fromFile); Map<SpdxDocument, SpdxFile> unique2 = this.uniqueSnippetFromFile.get(document2); if (unique2 == null) { unique2 = Maps.newHashMap(); this.uniqueSnippetFromFile.put(document2, unique2); } unique2.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } else { SpdxFileComparer fileCompare = new SpdxFileComparer(this.extractedLicenseIdMap); fileCompare.addDocumentFile(spdxDocument, fromFile); fileCompare.addDocumentFile(document2, fromFile2); if (fileCompare.isDifferenceFound()) { this.snippetFromFilesEquals = false; Map<SpdxDocument, SpdxFileDifference> comparerMap = Maps.newHashMap(); this.snippetFromFileDifferences.put(spdxDocument, comparerMap); Map<SpdxDocument, SpdxFileDifference> comparerMap2 = this.snippetFromFileDifferences.get(document2); if (comparerMap2 == null) { comparerMap2 = Maps.newHashMap(); this.snippetFromFileDifferences.put(document2, comparerMap2); } comparerMap.put(document2, fileCompare.getFileDifference(spdxDocument, document2)); comparerMap2.put(spdxDocument, fileCompare.getFileDifference(document2, spdxDocument)); } } if (!this.snippetFromFilesEquals) { this.differenceFound = true; } } /** * @return the differenceFound * @throws SpdxCompareException */ @Override public boolean isDifferenceFound() throws SpdxCompareException { checkInProgress(); return differenceFound || super.isDifferenceFound(); } /** * checks to make sure there is not a compare in progress * @throws SpdxCompareException * */ @Override protected void checkInProgress() throws SpdxCompareException { if (inProgress) { throw(new SpdxCompareException("File compare in progress - can not obtain compare results until compare has completed")); } super.checkInProgress(); } /** * Get any file difference for the Spdx Snippet From File between the two SPDX documents * If the fileName is different, the they are considered unique files and the getUniqueSnippetFromFile should be called * to obtain the unique file * @param docA * @param docB * @return the file difference or null if there is no file difference */ public SpdxFileDifference getSnippetFromFileDifference(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); Map<SpdxDocument, SpdxFileDifference> differenceMap = this.snippetFromFileDifferences.get(docA); if (differenceMap == null) { return null; } return differenceMap.get(docB); } /** * @return the byteRangeEquals */ public boolean isByteRangeEquals() throws SpdxCompareException { checkInProgress(); return byteRangeEquals; } /** * @return the lineRangeEquals */ public boolean isLineRangeEquals() throws SpdxCompareException { checkInProgress(); return lineRangeEquals; } /** * The snippetFromFiles can be true if there are some unique snippetFromFiles or differences between the snippetFromFiles (or both) * @return the snippetFromFilesEquals */ public boolean isSnippetFromFilesEquals() throws SpdxCompareException { checkInProgress(); return snippetFromFilesEquals; } /** * @return the nameEquals */ public boolean isNameEquals() throws SpdxCompareException { checkInProgress(); return nameEquals; } /** * Get an SpdxFile that only exists in docA but not docB * @param docA * @param docB * @return */ public SpdxFile getUniqueSnippetFromFile(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); Map<SpdxDocument, SpdxFile> docMap = this.uniqueSnippetFromFile.get(docA); if (docMap == null) { return null; } return docMap.get(docB); } /** * @return Total number of snippets */ public int getNumSnippets() { return this.documentItem.size(); } /** * @param spdxDocument * @return */ public SpdxSnippet getDocSnippet(SpdxDocument spdxDocument) { SpdxItem retItem = this.documentItem.get(spdxDocument); if (retItem != null && retItem instanceof SpdxSnippet) { return (SpdxSnippet)retItem; } else { return null; } } }
spdx/tools
src/org/spdx/compare/SpdxSnippetComparer.java
Java
apache-2.0
9,956
<?php use Sy\Http\Dispatcher; ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Error</title> <style> body { margin: 0; } .base { background: #edecea; padding: 100px 80px; margin-bottom: 20px; } .base .message { font-weight: 300; font-size: 35px; line-height: 43px; margin-bottom: 15px; } .base .description { font-weight: 300; font-size: 18px; } .request { padding: 50px 80px; } .request .title { text-transform: uppercase; font-size: 18px; letter-spacing: 1px; padding: 0 5px 5px 5px; margin-bottom: 15px; } .request table { width: 100%; border-collapse: collapse; margin-bottom: 80px; } .request table td { padding: 8px 6px; font-size: 13px; color: #455275; border-bottom: 1px solid #e8e8e8; word-break: break-word; } .request table td.name { font-weight: 600; color: #999; width: 30%; text-transform: uppercase; } </style> </head> <body> <div class="base"> <div class="message">404 Not Found</div> <div class="description"> <?php switch ($code) { case Dispatcher::ROUTE_ERR_ACTION: echo 'ROUTE_ERR_ACTION'; break; case Dispatcher::ROUTE_ERR_CONTROLLER: echo 'ROUTE_ERR_CONTROLLER'; break; case Dispatcher::ROUTE_ERR_MODULE: echo 'ROUTE_ERR_MODULE'; break; } ?> </div> </div> <div class="request"> <div class="title">Request</div> <table> <tr><td class="name">module</td><td><?=htmlspecialchars($request->module)?></td></tr> <tr><td class="name">controller</td><td><?=htmlspecialchars($request->controller)?></td></tr> <tr><td class="name">action</td><td><?=htmlspecialchars($request->action)?></td></tr> <tr><td class="name">request_uri</td><td><?=htmlspecialchars($request->server['REQUEST_URI'])?></td></tr> <tr><td class="name">uri</td><td><?=htmlspecialchars($request->uri)?></td></tr> <tr><td class="name">extension</td><td><?=htmlspecialchars($request->extension)?></td></tr> <tr><td class="name">param</td><td><?=htmlspecialchars(var_export($request->param, true))?></td></tr> </table> <div class="title">Server</div> <table> <?php foreach ($request->server as $k => $v) { ?> <tr><td class="name"><?=htmlspecialchars($k)?></td><td><?=htmlspecialchars($v)?></td></tr> <?php } ?> </table> <?php if (is_array($request->get)) { ?> <div class="title">Get</div> <table> <?php foreach ($request->get as $k => $v) { ?> <tr><td class="name"><?=htmlspecialchars($k)?></td><td><?=htmlspecialchars($v)?></td></tr> <?php } ?> </table> <?php } ?> <?php if (is_array($request->post)) { ?> <div class="title">Post</div> <table> <?php foreach ($request->post as $k => $v) { ?> <tr><td class="name"><?=htmlspecialchars($k)?></td><td><?=htmlspecialchars($v)?></td></tr> <?php } ?> </table> <?php } ?> <?php if (is_array($request->cookie)) { ?> <div class="title">Cookie</div> <table> <?php foreach ($request->cookie as $k => $v) { ?> <tr><td class="name"><?=htmlspecialchars($k)?></td><td><?=htmlspecialchars($v)?></td></tr> <?php } ?> </table> <?php } ?> </div> </body> </html>
sylingd/SYFramework
src/Data/error_404_debug.php
PHP
apache-2.0
3,238
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.execution; import com.google.common.util.concurrent.ListenableFuture; import io.trino.Session; import io.trino.connector.CatalogName; import io.trino.execution.warnings.WarningCollector; import io.trino.metadata.Metadata; import io.trino.metadata.QualifiedObjectName; import io.trino.metadata.TableHandle; import io.trino.security.AccessControl; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ColumnMetadata; import io.trino.spi.type.Type; import io.trino.spi.type.TypeNotFoundException; import io.trino.sql.tree.AddColumn; import io.trino.sql.tree.ColumnDefinition; import io.trino.sql.tree.Expression; import io.trino.transaction.TransactionManager; import java.util.List; import java.util.Map; import java.util.Optional; import static com.google.common.util.concurrent.Futures.immediateVoidFuture; import static io.trino.metadata.MetadataUtil.createQualifiedObjectName; import static io.trino.metadata.MetadataUtil.getRequiredCatalogHandle; import static io.trino.spi.StandardErrorCode.COLUMN_ALREADY_EXISTS; import static io.trino.spi.StandardErrorCode.COLUMN_TYPE_UNKNOWN; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND; import static io.trino.spi.StandardErrorCode.TYPE_NOT_FOUND; import static io.trino.spi.connector.ConnectorCapabilities.NOT_NULL_COLUMN_CONSTRAINT; import static io.trino.sql.NodeUtils.mapFromProperties; import static io.trino.sql.ParameterUtils.parameterExtractor; import static io.trino.sql.analyzer.SemanticExceptions.semanticException; import static io.trino.sql.analyzer.TypeSignatureTranslator.toTypeSignature; import static io.trino.type.UnknownType.UNKNOWN; import static java.util.Locale.ENGLISH; public class AddColumnTask implements DataDefinitionTask<AddColumn> { @Override public String getName() { return "ADD COLUMN"; } @Override public ListenableFuture<Void> execute( AddColumn statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (tableHandle.isEmpty()) { if (!statement.isTableExists()) { throw semanticException(TABLE_NOT_FOUND, statement, "Table '%s' does not exist", tableName); } return immediateVoidFuture(); } CatalogName catalogName = getRequiredCatalogHandle(metadata, session, statement, tableName.getCatalogName()); accessControl.checkCanAddColumns(session.toSecurityContext(), tableName); Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle.get()); ColumnDefinition element = statement.getColumn(); Type type; try { type = metadata.getType(toTypeSignature(element.getType())); } catch (TypeNotFoundException e) { throw semanticException(TYPE_NOT_FOUND, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName()); } if (type.equals(UNKNOWN)) { throw semanticException(COLUMN_TYPE_UNKNOWN, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName()); } if (columnHandles.containsKey(element.getName().getValue().toLowerCase(ENGLISH))) { if (!statement.isColumnNotExists()) { throw semanticException(COLUMN_ALREADY_EXISTS, statement, "Column '%s' already exists", element.getName()); } return immediateVoidFuture(); } if (!element.isNullable() && !metadata.getConnectorCapabilities(session, catalogName).contains(NOT_NULL_COLUMN_CONSTRAINT)) { throw semanticException(NOT_SUPPORTED, element, "Catalog '%s' does not support NOT NULL for column '%s'", catalogName.getCatalogName(), element.getName()); } Map<String, Expression> sqlProperties = mapFromProperties(element.getProperties()); Map<String, Object> columnProperties = metadata.getColumnPropertyManager().getProperties( catalogName, tableName.getCatalogName(), sqlProperties, session, metadata, accessControl, parameterExtractor(statement, parameters), true); ColumnMetadata column = ColumnMetadata.builder() .setName(element.getName().getValue()) .setType(type) .setNullable(element.isNullable()) .setComment(element.getComment()) .setProperties(columnProperties) .build(); metadata.addColumn(session, tableHandle.get(), column); return immediateVoidFuture(); } }
Praveen2112/presto
core/trino-main/src/main/java/io/trino/execution/AddColumnTask.java
Java
apache-2.0
5,732
import httplib from pyamf import AMF0, AMF3 from pyamf import remoting from pyamf.remoting.client import RemotingService height = 1080 def build_amf_request(const, playerID, videoPlayer, publisherID): env = remoting.Envelope(amfVersion=3) env.bodies.append( ( "/1", remoting.Request( target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", body=[const, playerID, videoPlayer, publisherID], envelope=env ) ) ) return env def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey): conn = httplib.HTTPConnection("c.brightcove.com") envelope = build_amf_request(const, playerID, videoPlayer, publisherID) conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'}) response = conn.getresponse().read() response = remoting.decode(response).bodies[0][1].body return response def play(const, playerID, videoPlayer, publisherID, playerKey): rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey) streamName = "" streamUrl = rtmpdata['FLVFullLengthURL']; for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False): streamHeight = item['frameHeight'] if streamHeight <= height: streamUrl = item['defaultURL'] streamName = streamName + rtmpdata['displayName'] return [streamName, streamUrl];
aplicatii-romanesti/allinclusive-kodi-pi
.kodi/addons/plugin.video.kidsplace/brightcovePlayer.py
Python
apache-2.0
1,587
package org.pac4j.cas.authorization; import org.pac4j.cas.client.CasClient; import org.pac4j.core.authorization.generator.AuthorizationGenerator; import org.pac4j.core.context.WebContext; import org.pac4j.core.context.session.SessionStore; import org.pac4j.core.profile.UserProfile; import java.util.Optional; /** * Default {@link AuthorizationGenerator} implementation for a {@link CasClient} which is able * to retrieve the isRemembered status from the CAS response and put it in the profile. * * @author Michael Remond * @since 1.5.1 */ public class DefaultCasAuthorizationGenerator implements AuthorizationGenerator { public static final String DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME = "longTermAuthenticationRequestTokenUsed"; // default name of the CAS attribute for remember me authentication (CAS 3.4.10+) protected String rememberMeAttributeName = DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME; public DefaultCasAuthorizationGenerator() { } public DefaultCasAuthorizationGenerator(final String rememberMeAttributeName) { this.rememberMeAttributeName = rememberMeAttributeName; } @Override public Optional<UserProfile> generate(final WebContext context, final SessionStore sessionStore, final UserProfile profile) { final var rememberMeValue = (String) profile.getAttribute(rememberMeAttributeName); final var isRemembered = rememberMeValue != null && Boolean.parseBoolean(rememberMeValue); profile.setRemembered(isRemembered); return Optional.of(profile); } }
pac4j/pac4j
pac4j-cas/src/main/java/org/pac4j/cas/authorization/DefaultCasAuthorizationGenerator.java
Java
apache-2.0
1,548
// Copyright 2017-2021 The Usacloud 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. // Code generated by 'github.com/sacloud/usacloud/tools/gen-commands'; DO NOT EDIT package subnet import ( "github.com/sacloud/usacloud/pkg/cmd/core" "github.com/spf13/cobra" "github.com/spf13/pflag" ) func (p *readParameter) CleanupEmptyValue(fs *pflag.FlagSet) { } func (p *readParameter) buildFlags(fs *pflag.FlagSet) { fs.StringVarP(&p.Zone, "zone", "", p.Zone, "(*required) ") fs.StringVarP(&p.Parameters, "parameters", "", p.Parameters, "Input parameters in JSON format") fs.BoolVarP(&p.GenerateSkeleton, "generate-skeleton", "", p.GenerateSkeleton, "Output skeleton of parameters with JSON format (aliases: --skeleton)") fs.BoolVarP(&p.Example, "example", "", p.Example, "Output example parameters with JSON format") fs.StringVarP(&p.OutputType, "output-type", "o", p.OutputType, "Output format options: [table/json/yaml] (aliases: --out)") fs.BoolVarP(&p.Quiet, "quiet", "q", p.Quiet, "Output IDs only") fs.StringVarP(&p.Format, "format", "", p.Format, "Output format in Go templates (aliases: --fmt)") fs.StringVarP(&p.Query, "query", "", p.Query, "Query for JSON output") fs.StringVarP(&p.QueryDriver, "query-driver", "", p.QueryDriver, "Name of the driver that handles queries to JSON output options: [jmespath/jq]") fs.SetNormalizeFunc(p.normalizeFlagName) } func (p *readParameter) normalizeFlagName(_ *pflag.FlagSet, name string) pflag.NormalizedName { switch name { case "skeleton": name = "generate-skeleton" case "out": name = "output-type" case "fmt": name = "format" } return pflag.NormalizedName(name) } func (p *readParameter) buildFlagsUsage(cmd *cobra.Command) { var sets []*core.FlagSet { var fs *pflag.FlagSet fs = pflag.NewFlagSet("zone", pflag.ContinueOnError) fs.SortFlags = false fs.AddFlag(cmd.LocalFlags().Lookup("zone")) sets = append(sets, &core.FlagSet{ Title: "Zone options", Flags: fs, }) } { var fs *pflag.FlagSet fs = pflag.NewFlagSet("input", pflag.ContinueOnError) fs.SortFlags = false fs.AddFlag(cmd.LocalFlags().Lookup("generate-skeleton")) fs.AddFlag(cmd.LocalFlags().Lookup("parameters")) sets = append(sets, &core.FlagSet{ Title: "Input options", Flags: fs, }) } { var fs *pflag.FlagSet fs = pflag.NewFlagSet("output", pflag.ContinueOnError) fs.SortFlags = false fs.AddFlag(cmd.LocalFlags().Lookup("format")) fs.AddFlag(cmd.LocalFlags().Lookup("output-type")) fs.AddFlag(cmd.LocalFlags().Lookup("query")) fs.AddFlag(cmd.LocalFlags().Lookup("query-driver")) fs.AddFlag(cmd.LocalFlags().Lookup("quiet")) sets = append(sets, &core.FlagSet{ Title: "Output options", Flags: fs, }) } { var fs *pflag.FlagSet fs = pflag.NewFlagSet("example", pflag.ContinueOnError) fs.SortFlags = false fs.AddFlag(cmd.LocalFlags().Lookup("example")) sets = append(sets, &core.FlagSet{ Title: "Parameter example", Flags: fs, }) } core.BuildFlagsUsage(cmd, sets) } func (p *readParameter) setCompletionFunc(cmd *cobra.Command) { } func (p *readParameter) SetupCobraCommandFlags(cmd *cobra.Command) { p.buildFlags(cmd.Flags()) p.buildFlagsUsage(cmd) p.setCompletionFunc(cmd) }
yamamoto-febc/usacloud
pkg/cmd/commands/subnet/zz_read_gen.go
GO
apache-2.0
3,731
@extends('layouts.admin_template') @section('content') <!-- Sidebar --> @include('sidebar') <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> {{ $page_title or "CADASTRAR CLIENTE" }} <small>{{ $page_description or null }} </small> </h1> <!-- You can dynamically generate breadcrumbs here --> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"> </i> Menu </a> </li> <li class="active">Configurações </li> </ol> </section> <!-- Main content --> <section class="content"> @if ( Session::has('mensagem')) <div class="alert alert-info"> {{ Session::get('mensagem') }} </div> @endif <div class="row"> @include('setting.menu_setting') <!-- /.col --> <div class="col-md-9"> <div class="box box-default"> <div class="row"> <div class="col-md-12" > <h3 class="page-header"> <i class="fa fa-info-circle" aria-hidden="true"> </i> Informações gerais </h3> </div> <div class="col-md-12"> <div class="col-md-4"> <div class="info-box bg-yellow"> <span class="info-box-icon"> <i class="fa fa-bar-chart" aria-hidden="true"> </i> </span> <div class="info-box-content"> <span class="info-box-text">Logado pela empresa </span> <span class="info-box-number"> </span> <div class="progress"> <div class="progress-bar" style="width: 50%"> </div> </div> <span class="progress-description"> @if(Session::get('business_name')) {{ Session::get('business_name') }} @endif </span> </div> <!-- /.info-box-content --> </div> </div> <div class="col-md-4"> <div class="info-box bg-green"> <span class="info-box-icon"> <i class="fa fa-exchange" aria-hidden="true"> </i> </span> <div class="info-box-content"> <span class="info-box-text">Vistoria Finalizada </span> <span class="info-box-number"> </span> <div class="progress"> <div class="progress-bar" style="width: 50%"> </div> </div> </div> <!-- /.info-box-content --> </div> </div> <div class="col-md-4"> <div class="info-box bg-red"> <span class="info-box-icon"> <i class="fa fa-list-alt" aria-hidden="true"> </i> </span> <div class="info-box-content"> <span class="info-box-text">Vistoria rascunho </span> <span class="info-box-number"> </span> <div class="progress"> <div class="progress-bar" style="width: 50%"> </div> </div> </div> <!-- /.info-box-content --> </div> </div> </div> </div> {{-- FIM ROW --}} </div> <div class="box box-default"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Cadastro</h3> </div> <!-- /.box-header --> <!-- form start --> <form role="form"> <div class="box-body"> <div class="form-group"> <label for="exampleInputEmail1">Razão Social</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> </div> <!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> <!-- /.box --> </div> </div> </div> <!--/.col (left) --> </div> <!--/.col (9) --> </div> </section> </div> <!-- /.content-wrapper --> @endsection
Junior-Shyko/admin
resources/views/setting/business.blade.php
PHP
apache-2.0
7,351