text
stringlengths
184
4.48M
/** * Copyright 2005-2020 Talend * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or or EPL 1.0 (the "Licenses"). You can * select the license that you prefer but you may not use this file except in * compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * https://restlet.talend.com/ * * Restlet is a registered trademark of Talend S.A. */ package org.restlet.test.resource; import java.io.Serializable; import org.restlet.engine.util.SystemUtils; /** * Test bean to be serialized. * * @author Jerome Louvel */ public class MyBean implements Serializable { private static final long serialVersionUID = 1L; private String description; private String name; public MyBean() { } public MyBean(String name, String description) { super(); this.name = name; this.description = description; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyBean other = (MyBean) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String getDescription() { return description; } public String getName() { return name; } @Override public int hashCode() { return SystemUtils.hashCode(name, description); } public void setDescription(String description) { this.description = description; } public void setName(String name) { this.name = name; } }
require 'pry' class Api::V0::MarketsController < ApplicationController def index render json: { data: MarketSerializer.format_markets(Market.all) } end def show begin render json: { data: MarketSerializer.format_market(Market.find(params[:id])) } rescue StandardError => e render json: { errors: [{ detail: e.message }] }, status: :not_found end end def create market = Market.new(market_params) if market.save render json: { data: MarketSerializer.format_market(market) }, status: :created else render json: { errors: [{ detail: market.errors.full_messages }] }, status: :bad_request end end def search if invalid_parameters? render json: { errors: [{ detail: "Invalid set of parameters. Please provide a valid set of parameters to perform a search with this endpoint." }] }, status: :unprocessable_entity else markets = Market.build_search_query(search_hash) if markets.empty? render json: { data: [] }, status: :ok else render json: { data: MarketSerializer.format_markets(markets) }, status: :ok end end end def nearest_atms begin market = Market.find(params[:id]) atms = NearestAtmFacade.nearest_atms(market.lat, market.lon).compact render json: { data: AtmSerializer.format_atms(atms) }, status: :ok rescue StandardError => e render json: { errors: [{ detail: e.message }] }, status: :not_found end end private def market_params params.require(:market).permit(:name, :street, :city, :county, :state, :zip, :lat, :lon) end def search_hash permitted_params = params.permit(:state, :city, :name) permitted_params.to_h.transform_values(&:titleize).symbolize_keys end def invalid_parameters? invalid_combinations = [ [:city], [:city, :name] ] valid_combinations = [ [:state], [:state, :city], [:state, :city, :name], [:state, :name], [:name] ] invalid_combinations.any? { |combination| search_hash.keys.sort == combination.sort } || valid_combinations.none? { |combination| search_hash.keys.sort == combination.sort } end end
import { useDispatch, useSelector } from 'react-redux'; import { useEffect, useState } from 'react'; import { addPanda } from '../store/PandaRedux'; import { useNavigate } from 'react-router-dom'; import { clearPandaState } from '../store/PandaRedux'; import { CustomForm } from '../components/CustomForm'; import { address, gender } from '../util/address'; export const AddPandaPage = () => { const dispatch = useDispatch(); const message = useSelector(state => state.panda.message); const addedPanda = useSelector(state=> state.panda.panda); const navigate = useNavigate(); const [formData, setFormData] = useState({ name: '', birthday: '', gender: gender[0], imageUrl: '', address: address[0], personality: '', }); useEffect(() => { if (message) { alert(message); } if (addedPanda) { dispatch(clearPandaState()); navigate('/profile'); } }, [message, addedPanda, navigate]); const handleChange = (event) => { const { name, value } = event.target; setFormData(prevState => ({ ...prevState, [name]: value })); }; const handleSubmit = async (event) => { event.preventDefault(); // console.log("form", formData); dispatch(addPanda(formData)); }; return ( <div> <h1> Add Panda Profile</h1> <CustomForm onSubmit={handleSubmit}> <label> Name: <input type="text" name="name" value={formData.name} onChange={handleChange} required /> </label> <label> Birthday: <input type="date" name="birthday" value={formData.birthday} onChange={handleChange} required /> </label> <label> gender: <select name="gender" value={formData.gender} onChange={handleChange} required> {gender.map((gender, index) => ( <option key={index} value={gender}> {gender} </option> ))} </select> </label> <label> Image URL: <input type="text" name="imageUrl" value={formData.imageUrl} onChange={handleChange} required /> </label> <label> Address: <select name="address" value={formData.address} onChange={handleChange} required> {address.map((address, index) => ( <option key={index} value={address}> {address} </option> ))} </select> </label> <label> Personality: <input type="text" name="personality" value={formData.personality} onChange={handleChange} required /> </label> <button type="submit">Create Profile</button> </CustomForm> </div> ); }
// // Copyright 2020 gRPC 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. // #include <memory> #include <gtest/gtest.h> #include <grpc/grpc.h> #include <grpc/grpc_crl_provider.h> #include <grpc/grpc_security.h> #include <grpcpp/security/server_credentials.h> #include <grpcpp/security/tls_credentials_options.h> #include <grpcpp/security/tls_crl_provider.h> #include "test/core/util/test_config.h" #include "test/cpp/util/tls_test_utils.h" #define CA_CERT_PATH "src/core/tsi/test_creds/ca.pem" #define SERVER_CERT_PATH "src/core/tsi/test_creds/server1.pem" #define SERVER_KEY_PATH "src/core/tsi/test_creds/server1.key" #define CRL_DIR_PATH "test/core/tsi/test_creds/crl_data/crls" namespace { constexpr const char* kRootCertName = "root_cert_name"; constexpr const char* kRootCertContents = "root_cert_contents"; constexpr const char* kIdentityCertName = "identity_cert_name"; constexpr const char* kIdentityCertPrivateKey = "identity_private_key"; constexpr const char* kIdentityCertContents = "identity_cert_contents"; using ::grpc::experimental::CreateStaticCrlProvider; using ::grpc::experimental::ExternalCertificateVerifier; using ::grpc::experimental::FileWatcherCertificateProvider; using ::grpc::experimental::NoOpCertificateVerifier; using ::grpc::experimental::StaticDataCertificateProvider; using ::grpc::experimental::TlsServerCredentials; using ::grpc::experimental::TlsServerCredentialsOptions; } // namespace namespace grpc { namespace testing { namespace { TEST( CredentialsTest, TlsServerCredentialsWithStaticDataCertificateProviderLoadingRootAndIdentity) { experimental::IdentityKeyCertPair key_cert_pair; key_cert_pair.private_key = kIdentityCertPrivateKey; key_cert_pair.certificate_chain = kIdentityCertContents; std::vector<experimental::IdentityKeyCertPair> identity_key_cert_pairs; identity_key_cert_pairs.emplace_back(key_cert_pair); auto certificate_provider = std::make_shared<StaticDataCertificateProvider>( kRootCertContents, identity_key_cert_pairs); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_root_certs(); options.set_root_cert_name(kRootCertName); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } // ServerCredentials should always have identity credential presented. // Otherwise gRPC stack will fail. TEST(CredentialsTest, TlsServerCredentialsWithStaticDataCertificateProviderLoadingIdentityOnly) { experimental::IdentityKeyCertPair key_cert_pair; key_cert_pair.private_key = kIdentityCertPrivateKey; key_cert_pair.certificate_chain = kIdentityCertContents; std::vector<experimental::IdentityKeyCertPair> identity_key_cert_pairs; // Adding two key_cert_pair(s) should still work. identity_key_cert_pairs.emplace_back(key_cert_pair); identity_key_cert_pairs.emplace_back(key_cert_pair); auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(identity_key_cert_pairs); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } TEST( CredentialsTest, TlsServerCredentialsWithFileWatcherCertificateProviderLoadingRootAndIdentity) { auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_root_certs(); options.set_root_cert_name(kRootCertName); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithCrlChecking) { auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_root_certs(); options.set_root_cert_name(kRootCertName); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); options.set_crl_directory(CRL_DIR_PATH); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } // ServerCredentials should always have identity credential presented. // Otherwise gRPC stack will fail. TEST( CredentialsTest, TlsServerCredentialsWithFileWatcherCertificateProviderLoadingIdentityOnly) { auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithSyncExternalVerifier) { auto verifier = ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true); auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_root_certs(); options.set_root_cert_name(kRootCertName); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); options.set_certificate_verifier(verifier); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithAsyncExternalVerifier) { auto verifier = ExternalCertificateVerifier::Create<AsyncCertificateVerifier>(true); auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.watch_root_certs(); options.set_root_cert_name(kRootCertName); options.watch_identity_key_cert_pairs(); options.set_identity_cert_name(kIdentityCertName); options.set_cert_request_type( GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY); options.set_certificate_verifier(verifier); auto server_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(server_credentials.get() != nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithCrlProvider) { auto provider = experimental::CreateStaticCrlProvider({}); ASSERT_TRUE(provider.ok()); auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.set_crl_provider(*provider); auto channel_credentials = grpc::experimental::TlsServerCredentials(options); GPR_ASSERT(channel_credentials.get() != nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithCrlProviderAndDirectory) { auto provider = experimental::CreateStaticCrlProvider({}); ASSERT_TRUE(provider.ok()); auto certificate_provider = std::make_shared<FileWatcherCertificateProvider>( SERVER_KEY_PATH, SERVER_CERT_PATH, CA_CERT_PATH, 1); grpc::experimental::TlsServerCredentialsOptions options(certificate_provider); options.set_crl_directory(CRL_DIR_PATH); options.set_crl_provider(*provider); auto server_credentials = grpc::experimental::TlsServerCredentials(options); // TODO(gtcooke94) - behavior might change to make this return nullptr in // the future GPR_ASSERT(server_credentials != nullptr); } TEST(CredentialsTest, TlsCredentialsOptionsDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options(provider); (void)options; } TEST(CredentialsTest, MultipleOptionsOneCertificateProviderDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options_1(provider); (void)options_1; TlsServerCredentialsOptions options_2(provider); (void)options_2; } TEST(CredentialsTest, MultipleOptionsOneCertificateVerifierDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); auto verifier = std::make_shared<NoOpCertificateVerifier>(); TlsServerCredentialsOptions options_1(provider); options_1.set_certificate_verifier(verifier); TlsServerCredentialsOptions options_2(provider); options_2.set_certificate_verifier(verifier); } TEST(CredentialsTest, MultipleOptionsOneCrlProviderDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); auto crl_provider = CreateStaticCrlProvider(/*crls=*/{}); EXPECT_TRUE(crl_provider.ok()); TlsServerCredentialsOptions options_1(provider); options_1.set_crl_provider(*crl_provider); TlsServerCredentialsOptions options_2(provider); options_2.set_crl_provider(*crl_provider); } TEST(CredentialsTest, TlsServerCredentialsDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options(provider); auto server_creds = TlsServerCredentials(options); EXPECT_NE(server_creds, nullptr); } TEST(CredentialsTest, MultipleServerCredentialsOneOptionsDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options(provider); auto server_creds_1 = TlsServerCredentials(options); EXPECT_NE(server_creds_1, nullptr); auto server_creds_2 = TlsServerCredentials(options); EXPECT_NE(server_creds_2, nullptr); } TEST(CredentialsTest, MultipleServerCredentialsOneCertificateVerifierDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options(provider); auto verifier = std::make_shared<NoOpCertificateVerifier>(); options.set_certificate_verifier(verifier); auto server_creds_1 = TlsServerCredentials(options); EXPECT_NE(server_creds_1, nullptr); auto server_creds_2 = TlsServerCredentials(options); EXPECT_NE(server_creds_2, nullptr); } TEST(CredentialsTest, MultipleServerCredentialsOneCrlProviderDoesNotLeak) { auto provider = std::make_shared<StaticDataCertificateProvider>("root-pem"); TlsServerCredentialsOptions options(provider); auto crl_provider = CreateStaticCrlProvider(/*crls=*/{}); EXPECT_TRUE(crl_provider.ok()); options.set_crl_provider(*crl_provider); auto server_creds_1 = TlsServerCredentials(options); EXPECT_NE(server_creds_1, nullptr); auto server_creds_2 = TlsServerCredentials(options); EXPECT_NE(server_creds_2, nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithGoodMinMaxTlsVersions) { grpc::experimental::TlsServerCredentialsOptions options( /*certificate_provider=*/nullptr); options.set_min_tls_version(grpc_tls_version::TLS1_2); options.set_max_tls_version(grpc_tls_version::TLS1_3); auto server_credentials = grpc::experimental::TlsServerCredentials(options); EXPECT_NE(server_credentials, nullptr); } TEST(CredentialsTest, TlsServerCredentialsWithBadMinMaxTlsVersions) { grpc::experimental::TlsServerCredentialsOptions options( /*certificate_provider=*/nullptr); options.set_min_tls_version(grpc_tls_version::TLS1_3); options.set_max_tls_version(grpc_tls_version::TLS1_2); auto server_credentials = grpc::experimental::TlsServerCredentials(options); EXPECT_EQ(server_credentials, nullptr); } } // namespace } // namespace testing } // namespace grpc int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); grpc::testing::TestEnvironment env(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
// // SummaryItemTests.swift // Neds // // Created by Wael Saad on 20/3/2024. // Copyright © 2024 NetTrinity. All rights reserved. // @testable import Neds import XCTest import SwiftUI final class SummaryItemTests: XCTestCase { func testGivenRaceSummary_WhenViewInitialized_ThenExpectedRaceNameDisplayed() { // Given let sampleRaceSummary = RaceSummary( raceID: "0e585683-ec46-4caa-b45c-0682a5f4bba9", raceName: "Tasbreeders Night 5Th April Plate (C1)", raceNumber: 1, meetingID: "ee3656cc-8c7e-4e01-a4eb-8344de47eddb", meetingName: "Launceston", category: .greyhound, advertisedStart: AdvertisedStart(seconds: Date().timeIntervalSince1970), venueID: "377c03a4-6154-4b32-b8f0-ecfc8a6869ef", venueName: "Launceston", venueState: "TAS", venueCountry: .aus ) let summaryItem = SummaryItem(raceSummary: sampleRaceSummary) // When let raceName = summaryItem.raceSummary.raceName // Then XCTAssertEqual(raceName, "Tasbreeders Night 5Th April Plate (C1)") } func testGivenRaceSummary_WhenViewInitialized_ThenExpectedTextColorSet() { // Given let sampleRaceSummary = RaceSummary( raceID: "0e585683-ec46-4caa-b45c-0682a5f4bba9", raceName: "Tasbreeders Night 5Th April Plate (C1)", raceNumber: 1, meetingID: "ee3656cc-8c7e-4e01-a4eb-8344de47eddb", meetingName: "Launceston", category: .greyhound, advertisedStart: AdvertisedStart(seconds: Date().timeIntervalSince1970), venueID: "377c03a4-6154-4b32-b8f0-ecfc8a6869ef", venueName: "Launceston", venueState: "TAS", venueCountry: .aus ) let summaryItem = SummaryItem(raceSummary: sampleRaceSummary) // When let textColor = summaryItem.textColor // Then XCTAssertEqual(textColor, .red) } }
/** * @file modbus.h * @author simakeng (simakeng@outlook.com) * @brief modbus slave protocol * @version 0.1 * @date 2023-04-17 * * @copyright Copyright (c) 2023 * */ #include <stdint.h> #include <libe15-errors.h> typedef struct { uint16_t reg_start_addr; uint32_t reg_map_len; error_t (*read_handler)(uint32_t offset, uint32_t size, uint8_t *data, uint8_t *error_code_out); error_t (*write_handler)(uint32_t offset, uint32_t data, uint8_t *error_code_out); void *usr_ptr; } modbus_reg_desc_t; enum { /// @brief no error MODBUS_ERR_NONE = 0, /** * @brief The function code received in the query is not an * allowable action for the server (or slave). This * may be because the function code is only * applicable to newer devices, and was not * implemented in the unit selected. It could also * indicate that the server (or slave) is in the wrong * state to process a request of this type, for * example because it is unconfigured and is being * asked to return register values. */ MODBUS_ERR_ILLEGAL_FUNCTION = 0x01, /** * @brief The data address received in the query is not an * allowable address for the server (or slave). More * specifically, the combination of reference number * and transfer length is invalid. For a controller with * 100 registers, the PDU addresses the first * register as 0, and the last one as 99. If a request * is submitted with a starting register address of 96 * and a quantity of registers of 4, then this request * will successfully operate (address-wise at least) * on registers 96, 97, 98, 99. If a request is * submitted with a starting register address of 96 * and a quantity of registers of 5, then this request * will fail with Exception Code 0x02 “Illegal Data * Address” since it attempts to operate on registers * 96, 97, 98, 99 and 100, and there is no register * with address 100. */ MODBUS_ERR_ILLEGAL_DATA_ADDRESS = 0x02, /** * @brief A value contained in the query data field is not an * allowable value for server (or slave). This * indicates a fault in the structure of the remainder * of a complex request, such as that the implied * length is incorrect. It specifically does NOT mean * that a data item submitted for storage in a register * has a value outside the expectation of the * application program, since the MODBUS protocol * is unaware of the significance of any particular * value of any particular register. */ MODBUS_ERR_ILLEGAL_DATA_VALUE = 0x03, /** * @brief An unrecoverable error occurred while the server * (or slave) was attempting to perform the * requested action. */ MODBUS_ERR_SLAVE_DEVICE_FAILURE = 0x04, /** * @brief Specialized use in conjunction with programming commands. * The server (or slave) has accepted the request * and is processing it, but a long duration of time * will be required to do so. This response is * returned to prevent a timeout error from occurring * in the client (or master). The client (or master) * can next issue a Poll Program Complete message * to determine if processing is completed. */ MODBUS_ERR_ACKNOWLEDGE = 0x05, /** * @brief Specialized use in conjunction with programming commands. * The server (or slave) is engaged in processing a * long–duration program command. The client (or * master) should retransmit the message later when * the server (or slave) is free. */ MODBUS_ERR_SLAVE_DEVICE_BUSY = 0x06, /** * @brief Specialized use in conjunction with function codes * 20 and 21 and reference type 6, to indicate that * the extended file area failed to pass a consistency * check. The server (or slave) attempted to read record * file, but detected a parity error in the memory. * The client (or master) can retry the request, but * service may be required on the server (or slave) * device. */ MODBUS_ERR_MEMORY_PARITY_ERROR = 0x08, /** * @brief Specialized use in conjunction with gateways, * indicates that the gateway was unable to allocate * an internal communication path from the input * port to the output port for processing the request. * Usually means that the gateway is misconfigured * or overloaded. */ MODBUS_ERR_GATEWAY_PATH_UNAVAILABLE = 0x0A, /** * @brief Specialized use in conjunction with gateways, * indicates that no response was obtained from the * target device. Usually means that the device is * not present on the network. */ MODBUS_ERR_GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND = 0x0B, }; enum { MODBUS_FN_READ_DISCRETE_INPUTS = 0x02, MODBUS_FN_READ_COILS = 0x01, MODBUS_FN_WRITE_SINGLE_COIL = 0x05, MODBUS_FN_WRITE_MULTIPLE_COILS = 0x0F, MODBUS_FN_READ_INPUT_REGISTERS = 0x04, MODBUS_FN_READ_HOLDING_REGISTERS = 0x03, MODBUS_FN_WRITE_SINGLE_REGISTER = 0x06, MODBUS_FN_WRITE_MULTIPLE_REGISTERS = 0x10, MODBUS_FN_READ_WRITE_MULTIPLE_REGISTERS = 0x17, MODBUS_FN_MASK_WRITE_REGISTER = 0x16, MODBUS_FN_READ_FIFO_QUEUE = 0x18, MODBUS_FN_READ_FILE_RECORD = 0x14, MODBUS_FN_WRITE_FILE_RECORD = 0x15, MODBUS_FN_READ_EXCEPTION_STATUS = 0x07, MODBUS_FN_DIAGNOSTICS = 0x08, MODBUS_FN_GET_COMM_EVENT_COUNTER = 0x0B, MODBUS_FN_GET_COMM_EVENT_LOG = 0x0C, MODBUS_FN_REPORT_SLAVE_ID = 0x11, MODBUS_FN_ENCAPSULATED_INTERFACE_TRANSPORT = 0x2B, }; typedef struct { modbus_reg_desc_t *input_regs; uint8_t input_reg_cnt; modbus_reg_desc_t *holding_regs; uint8_t holding_reg_cnt; /** * @brief This is a callback function to setup a Protocal Data Unit (PDU) transmit * @param size the size of the PDU * @param pdata the pointer to the PDU * @return error code 0 for success, < 0 failed, > 0 no more action need. * @note User should implement this function to setup the system for transmitting the PDU. * If the user intends to use IRQ to transmit the PDU, the user should call * `modbus_slave_send_get_data` function in the IRQ handler to get the data. in this function * user should only prepare the hardware. In this case, the return value of this function should * be 0 (ALL_OK), ** and this is the intended behavior **. * * If the user intends to use DMA to transmit the PDU, after setting up the DMA in this callback, * the user should call `modbus_slave_send_get_data` with flag `MODBUS_SEND_CPLT` to notify * the modbus driver. * * If the user sent the PDU within this callback, the return value of this function * should be greater than 0. */ error_t (*request_pdu_transmit)(uint32_t size, const void *pdata); } modbus_slave_init_t; typedef struct { const modbus_slave_init_t *desc; uint8_t recv_buf[32]; uint8_t send_buf[32]; uint8_t tx_cnt; uint8_t tx_total; uint8_t rx_cnt; uint8_t slave_addr; uint32_t rx_state; uint16_t crc; } modbus_slave_t; enum { /// new byte coming MODBUS_RECV_DATA, /// the last byte is received, this byte is invalid MODBUS_RECV_END, /// there is an error occured in the reciveing MODBUS_RECV_ERROR, /// this function call returns a valid byte MODBUS_SEND_NORMAL, /// this function call returns a invalid byte, and there will be no more bytes. MODBUS_SEND_CPLT, }; /** * @brief Update all internal states of a modbus slave according to the received byte. * @param slave the modbus slave instance * @param byte the received byte, 8bit * @param state the state of the modbus slave, one of MODBUS_RECV_ *?@note this function should be called at every byte received in the pripheral interrupt handler. */ void modbus_slave_recv_handler(modbus_slave_t *slave, uint32_t byte, uint32_t state); error_t modbus_slave_init(modbus_slave_t *slave, const modbus_slave_init_t *desc, uint8_t slave_addr); error_t modbus_slave_set_addr(modbus_slave_t *slave, uint8_t slave_addr); uint32_t modbus_slave_send_get_data(modbus_slave_t *slave, uint8_t *data_out);
import { useEffect, useState } from "react"; import Header from "./Header"; import { Container, CssBaseline, ThemeProvider, createTheme, } from "@mui/material"; import { Outlet } from "react-router-dom"; import { ToastContainer } from "react-toastify"; import "react-toastify/ReactToastify.css"; import agent from "../api/agent"; import Loading from "./Loading"; import { getCookie } from "../utils/util"; import { useAppDispatch } from "../store/configureStore"; import { setBasket } from "../../features/basket/basketSlice"; function App() { // const {setBasket} = useStoreContext(); const dispatch = useAppDispatch(); const [loading, setLoading] = useState(true); useEffect(() => { const buyerId=getCookie("buyerId") if(buyerId){ agent.Basket.get() .then(basket => dispatch(setBasket(basket))) .catch(error => console.log(error)) .finally(() => setLoading(false));} else setLoading(false) }, [dispatch]); const [darkMode, setDarkMode] = useState(false); const paletteType = darkMode ? "dark" : "light"; const theme = createTheme({ palette: { mode: paletteType, background: { default: paletteType === "dark" ? "#121212" : "#cddc39", }, }, }); function setMode() { setDarkMode(!darkMode); } if(loading) return <Loading message='Ładowanie Sklepu ...'></Loading> return ( <ThemeProvider theme={theme}> <ToastContainer position="bottom-right" hideProgressBar theme="colored" /> <CssBaseline /> <Header darkMode={darkMode} setDarkMode={setMode} /> <Container> <Outlet></Outlet> </Container> </ThemeProvider> ); } export default App;
import { faker } from '@faker-js/faker'; import { expect } from '@playwright/test'; import { createCustomer, serverRequest, stripeRequest, test, VALID_CARD } from '../helpers'; test.describe('Paying for lessons', () => { let scheduleLessonResponse; let completePaymentResponse; let refundId; test.beforeAll(async ({ browser, request }) => { test.setTimeout(30 * 1000) const testPage = await browser.newPage(); const customerId = await createCustomer(testPage, faker.name.findName(), faker.internet.email(), VALID_CARD); const data = { customer_id: customerId, amount: 123, description: 'Schedule Lesson Route API Test', } scheduleLessonResponse = await serverRequest(request, 'POST', 'schedule-lesson', data); scheduleLessonResponse = scheduleLessonResponse.payment; }) test('Should Accept Customer, Amount, and Description as its Input Parameters:4.1.1', async ({ page, request }) => { expect(scheduleLessonResponse.id).toBeTruthy(); }); test('Should Create a Payment Intent:4.1.2', async () => { expect(scheduleLessonResponse.id).toBeTruthy(); expect(scheduleLessonResponse.id).toContain('pi_'); expect(scheduleLessonResponse.amount_received).toBe(0); expect(scheduleLessonResponse.amount_capturable).toBe(123); expect(scheduleLessonResponse.status).toBe('requires_capture'); }); test('Should Return a Payment Intent Object upon Succesful Scheduling of a Lesson:4.1.3', async () => { expect(scheduleLessonResponse.object).toBeTruthy(); expect(scheduleLessonResponse.object).toBe('payment_intent'); }); test('Should Return an Error when using an Invalid Customer ID:4.1.4', async ({ request }) => { const invalidCustomerId = 'ci_invalid'; const data = { customer_id: invalidCustomerId, amount: 123, description: 'Schedule Lesson Route API Test', } const response = await serverRequest(request, 'POST', 'schedule-lesson', data); expect(response.error.code).toBeTruthy(); expect(response.error.code).toBe('resource_missing'); expect(response.error.message).toBeTruthy(); expect(response.error.message).toBe(`No such customer: '${invalidCustomerId}'`); }); test('Should Create Payment Intents in USD:4.1.5', () => { expect(scheduleLessonResponse.currency).toBeTruthy(); expect(scheduleLessonResponse.currency).toBe('usd'); }); test('Should Accept Payment Intent ID and an Optional Amount as Input Parameters.:4.2.1', async ({ request }) => { const data = { payment_intent_id: scheduleLessonResponse.id, amount: 123, } completePaymentResponse = await serverRequest(request, 'POST', 'complete-lesson-payment', data); completePaymentResponse = completePaymentResponse.payment; }); test('Should Capture and Confirm the Payment Intent:4.2.2', () => { expect(completePaymentResponse.id).toBeTruthy(); expect(completePaymentResponse.id).toContain('pi_'); expect(completePaymentResponse.amount_capturable).toBe(0); expect(completePaymentResponse.amount_received).toBe(123); expect(completePaymentResponse.status).toBe('succeeded'); }); test('Should Return a Payment Intent Object upon Succesful Payment Capture:4.2.3', () => { expect(completePaymentResponse.object).toBeTruthy(); expect(completePaymentResponse.object).toBe('payment_intent'); }); test('Should Return an Error when using Invalid Paramaters:4.2.4', async ({ request }) => { const invalidPaymentIntent = 'pi_invalid'; const data = { payment_intent_id: invalidPaymentIntent, amount: 123, } const response = await serverRequest(request, 'POST', 'complete-lesson-payment', data); expect(response.error.code).toBeTruthy(); expect(response.error.code).toBe('resource_missing'); expect(response.error.message).toBeTruthy(); expect(response.error.message).toBe(`No such payment_intent: '${invalidPaymentIntent}'`); }); test('Should Accept Payment Intent ID and an Amount as Input Parameters.:4.3.1', async ({ request }) => { const data = { payment_intent_id: scheduleLessonResponse.id, amount: 123, } refundId = await serverRequest(request, 'POST', 'refund-lesson', data); refundId = refundId.refund; }); test('Should Refund the Customer for the Lesson Amount.:4.3.2', async ({ request }) => { const response = await stripeRequest(request, 'GET', `refunds/${refundId}`); expect(response.amount).toBeTruthy(); expect(response.amount).toBe(123); }); test('Should Return a Refund Object ID if the Refund was Successful:4.3.3', () => { expect(refundId).toBeTruthy(); expect(refundId).toContain('re_'); }); test('Should Return an Error when using Invalid Paramaters:4.3.4', async ({ request }) => { const invalidPaymentIntent = 'pi_invalid'; const data = { payment_intent_id: invalidPaymentIntent, amount: 123, } const response = await serverRequest(request, 'POST', 'refund-lesson', data); expect(response.error.code).toBeTruthy(); expect(response.error.code).toBe('resource_missing'); expect(response.error.message).toBeTruthy(); expect(response.error.message).toBe(`No such payment_intent: '${invalidPaymentIntent}'`); }); });
import { useCallback, useEffect, useState } from "react" import useToastContext from "../../hooks/useToastContext"; import { searchCollections } from "../../services/search"; import CollectionList from "../profile-collection/CollectionList"; const LIMIT = 8; const CollectionSearchResultDisplay = (props) => { const { searchText } = props; const setToast = useToastContext(); const [hasMore, setHasMore] = useState(true); const [pages, setPages] = useState(-1); const [collections, setCollections] = useState([]); const [loading, setLoading] = useState(false); const loadNextPage = useCallback(async () => { if (!hasMore || !searchText) { return; } try { const nextPage = pages + 1; const fetchedCollections = await searchCollections(searchText, nextPage * LIMIT, LIMIT); const updatedCollections = [...collections, ...fetchedCollections] const updatedHasMore = fetchedCollections && fetchedCollections.length >= LIMIT; setPages(nextPage); setHasMore(updatedHasMore); setCollections(updatedCollections); } catch (e) { setToast({ message: "Unable to load search results. Please try again later.", color: "danger" }); } }, [hasMore, searchText, pages, collections, setToast]); const loadInitialPage = useCallback(async () => { if (!searchText) { return; } try { setLoading(true); const nextPage = 0; const fetchedCollections = await searchCollections(searchText, nextPage * LIMIT, LIMIT); const updatedHasMore = fetchedCollections && fetchedCollections.length >= LIMIT; setPages(nextPage); setHasMore(updatedHasMore); setCollections(fetchedCollections); } catch (e) { setToast({ message: "Unable to load search results. Please try again later.", color: "danger" }); } finally { setLoading(false); } }, [searchText, setToast]) useEffect(() => { if (props.searchText) { loadInitialPage(); } }, [loadInitialPage, props.searchText]); return ( <> <CollectionList listEnded={!hasMore} onScrollEnd={loadNextPage} collections={collections} emptyMessage="😵‍💫 No matching collections found. Try other keywords!" /> </> ) } export default CollectionSearchResultDisplay;
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "IDisableActor.h" #include "BasicPawn.generated.h" UCLASS() class TOONTANKS_API ABasicPawn : public APawn, public IDisableActor { GENERATED_BODY() public: // Sets default values for this pawn's properties ABasicPawn(); void HandleDestruction(); class UProjectilePoolComponent* GetProjectilePool() const { return ProjectilePoolComp; }; protected: virtual void BeginPlay() override; void TurnTurretToPoint(FVector Point); void TurnTurretByAngle(FRotator Angle); void FireProjectileAtLocation(FVector Location); UPROPERTY(EditAnywhere) float FireCooldown = 3.f; private: UPROPERTY(VisibleAnywhere) class UCapsuleComponent* CapsuleComp; UPROPERTY(VisibleAnywhere) UStaticMeshComponent* BodyMesh; UPROPERTY(VisibleAnywhere) UStaticMeshComponent* TurretMesh; UPROPERTY(VisibleAnywhere) USceneComponent* ProjectileSpawnPoint; UPROPERTY(VisibleAnywhere) class UHealthComponent* HealthComp; UPROPERTY(EditAnywhere) class UProjectilePoolComponent* ProjectilePoolComp = nullptr; UPROPERTY(EditAnywhere) TSubclassOf<class UCameraShakeBase> DeathCameraShake; UPROPERTY(EditAnywhere) class UParticleSystem* DestroyParticles; UPROPERTY(EditAnywhere) class USoundBase* FireProjectileSound; UPROPERTY(EditAnywhere) USoundBase* DestructionSound; UPROPERTY(EditAnywhere) TSubclassOf<class AProjectile> ProjectileClass; };
====== HTML & CSS Tutorial ====== Mit dieser Anleitung lernen Sie die Grundlagen von HTML & CSS, damit Sie eigene Webprojekte realisieren können. Wir beginnen **sofort mit einem Projekt**, anstatt zuerst langweilige Theorie abzuhandeln. Die Theorie wird erklärt, sobald sie für das Projekt benötigt wird. Sie werden damit sehr schnell eine solide Grundlage für die Webentwicklung erhalten. Ich werde Sie auf verschiedene Unterlagen hinweisen, so dass Sie später beliebige Bereiche vertiefen können. ===== Das Projekt ===== Das Projekt, welches wir Schritt-für-Schritt erarbeiten, ist Ihr persönliches **Web Portfolio**. Dieses Portfolio beinhaltet eine Startseite, einen Blog, eine Seite für Ihre zukünftigen Webprojekte und eine Kontaktseite. {{portfolio.de.png?nolink|Portfolio}} ===== Grundidee ===== Die Grundidee dieses Tutorials ist, dass Sie einen Einstieg in die Webprogrammierung erhalten und dabei lernen, wie Sie sich selbständig die Informationen beschaffen können, die Sie brauchen. Dann werden Sie in der Lage sein, immer komplexere Webprojekte zu realisieren! ===== Was sind HTML & CSS? ===== **HTML** (Hypertext Markup Language) ist für die **Struktur** der Webseite verantwortlich. In HTML werden zum Beispiel Überschriften, Abschnitte, Texte und Bilder definiert. **CSS** (Cascading Style Sheets) ist für die **Formatierung** und für das **Layout** der Webseite verantwortlich. In CSS werden zum Beispiel Farben, Schriften, Abstände und sogar Animationen definiert. Die beiden Sprachen, HTML und CSS, sind unabhängig voneinander und sollten auch in unterschiedlichen Dateien gespeichert werden. <HTML> <div class="alert alert-info"> <strong>Merke:</strong> HTML gibt den Inhalt einer Webseite an während CSS das Aussehen dieses Inhalts definiert. </div> </HTML> ===== Webseite oder Webapplikation ===== Mit HTML und CSS lassen sich sehr komplexe Webseiten entwickeln. Diese Webseiten werden jedoch **statisch** sein, was bedeutet, dass Besucher die Seiten zwar anschauen können aber sie können nicht damit interagieren können (ausser durch das Klicken auf Links). Um **dynamische** Webseiten zu programmieren, welche interaktiv sind, braucht man eine weitere Programmiersprache, wie zum Beispiel JavaScript oder Dart. Damit lassen sich ganze //Webapplikationen// entwickeln, wo ein Besucher zum Beispiel Berechnungen durchführen, ein Spiel spielen oder Chatfunktionen benutzen kann. Das HTML & CSS Tutorial ist so aufgebaut, dass Sie direkt danach mit dem Lernen von Dart (oder JavaScript) beginnen können. Wenn Sie also möchten, können Sie bald eigene //Webapplikationen// entwickeln. ===== Mobile ===== Viele oder manchmal sogar die Mehrheit der Zugriffe auf Webseiten erfolgen heute über mobile Geräte wie Smartphones oder Tablets. Deshalb ist es zentral, dass unsere Webseite auf den kleinen Bildschirmen von mobilen Geräten gut angezeigt wird. Wir werden uns in diesem Tutorial darum kümmern. Auch wenn wir später interaktive Webapplikationen entwickeln, werden wir dafür sorgen, dass diese auf mobilen Geräten laufen! ===== Auf geht's ===== → Beginnen Sie Ihre Reise mit [[##|Teil 1: Unsere erste Webseite]]. Viel Spass! ---- //Quellen//<html><br></html> <html><em class="small"></html> [[http://www.lostgarden.com/2007/05/dancs-miraculously-flexible-game.html|Planet Cute]] Bild stammt von Daniel Cook (Lostgarden.com), veröffentlicht unter [[http://creativecommons.org/licenses/by/3.0/us/|CC BY 3.0]]. <html></em></html> ---- Diese Seite ist abgeleitet von [[https://code.makery.ch/|code.makery]] von [[https://code.makery.ch/about/|Marco Jakob]], verwendet unter [[https://creativecommons.org/licenses/by/4.0/|CC BY]].\\ Sie ist lizenziert unter [[https://creativecommons.org/licenses/by-nc-sa/4.0/|CC BY-NC-SA]] von Daniel Fahrni <daniel.fahrni@bzz.ch>.
const express = require('express'); const User = require("../models/User"); const Post = require('../models/Post'); const router = express(); //CREATE POST router.post("/", async (req, res) => { const newPost = new Post(req.body); try { const savedPost = await newPost.save(); res.status(201).json(savedPost); } catch (error) { res.status(500).json(error.message); } }); //UPDATE POST router.put("/:id", async (req, res) => { try { const post = await Post.findById(req.params.id); if (post.username === req.body.username) { try { const updatedPost = await Post.findByIdAndUpdate(req.params.id, { $set: req.body }, { new: true }); res.status(200).json(updatedPost); } catch (error) { res.status(500).json(error.message); } } else { res.status(401).json('You can update your post!'); } } catch (error) { res.status(500).json(error.message); } }); //DELETE POST router.delete("/:id", async (req, res) => { try { const post = await Post.findById(req.params.id); if (post.username === req.body.username) { try { await post.deleteOne(); res.status(200).json("Post deleted..!"); } catch (error) { res.status(500).json(error.message); } } else { res.status(401).json('You can delete only your post!'); } } catch (error) { res.status(500).json(error.message); } }); //GET POST router.get("/:id", async (req, res) => { try { const post = await Post.findById(req.params.id); res.status(200).json(post); } catch (error) { res.status(500).json(error.message); } }); //GET ALL POST router.get("/", async (req, res) => { const username=req.query.user; const catName=req.query.cat; try { let posts; if(username){ posts=await Post.find({username}); }else if(catName){ posts=await Post.find({categories:{ $in:[catName] }}); }else{ posts=await Post.find({}); } res.status(200).json(posts); } catch (error) { res.status(500).json(error.message); } }); module.exports = router;
#ifndef _SPINLOCK_H_ #define _SPINLOCK_H_ #include "boost/atomic.hpp" /*! @brief SpinLock implementation @author kwchen @reference http://stackoverflow.com/questions/10966528/how-to-use-boost-atomic-to-remove-race-condition */ class SpinLock { private: boost::atomic<bool> m_bIsLock; public: SpinLock () : m_bIsLock(false) { } SpinLock ( const SpinLock& lock ) : m_bIsLock(false) { } SpinLock operator= ( const SpinLock& lock ) { m_bIsLock = false; return *this; } /*! @brief acquire spin-lock @author kwchen */ void lock () { while ( m_bIsLock.exchange(true, boost::memory_order_acquire) == true ) { // busy waiting } } /*! @brief release spin-lock @author kwchen */ void unlock () { m_bIsLock.store(false, boost::memory_order_release); } }; #endif
import { Box, Button, ButtonGroup, Center, Heading, Text, useColorModeValue, VStack } from '@chakra-ui/react' import React, { createContext, PropsWithChildren, useContext } from 'react' import { Helmet } from 'react-helmet-async' import { Loading } from '../../../common-components/Loading' import { INITIAL_BG_IMAGE } from '../../../util/configs/environment.config' import { l } from '../../../util/language' import { useConfigQuery } from '../../hooks/config/useConfigQuery' import { ConfigDto } from './types' import { KirDevLogo } from '../../../assets/kir-dev-logo' export const ConfigContext = createContext<ConfigDto | undefined>(undefined) export const ConfigProvider = ({ children }: PropsWithChildren) => { const { data, isLoading, error, refetch } = useConfigQuery((err) => console.error('[ERROR] at ConfigProvider', JSON.stringify(err, null, 2)) ) const bg = useColorModeValue('white', 'gray.900') if (isLoading) return ( <Center flexDirection="column" h="100vh" backgroundImage={INITIAL_BG_IMAGE} backgroundPosition="center" backgroundSize="cover"> <VStack p={5} borderRadius={5} bg={bg}> <Loading /> <Box w={40} maxH={40} my={3}> <KirDevLogo /> </Box> </VStack> </Center> ) if (error) return ( <Center flexDirection="column" h="100vh" backgroundImage={INITIAL_BG_IMAGE} backgroundPosition="center" backgroundSize="cover"> <Helmet title={l('error-page-helmet')} /> <VStack spacing={5} p={5} borderRadius={5} bg={bg}> <Heading textAlign="center">{l('error-page-title')}</Heading> <Text textAlign="center" color="gray.500" marginTop={10}> {l('error-connection-unsuccessful')} </Text> <ButtonGroup justifyContent="center" marginTop={10}> <Button colorScheme="brand" onClick={() => { refetch() }} > Újra </Button> </ButtonGroup> </VStack> </Center> ) return <ConfigContext.Provider value={data}>{children}</ConfigContext.Provider> } export const useConfigContext = () => { const ctx = useContext(ConfigContext) if (typeof ctx === 'undefined') { throw new Error('useConfigContext must be used within a ConfigProvider') } return ctx }
package ru.bodikov.otus.domain; import lombok.AccessLevel; import lombok.Getter; import lombok.experimental.FieldDefaults; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; @FieldDefaults(makeFinal = true,level = AccessLevel.PRIVATE) @Getter public class Cassette { CurrencyAndBanknoteNominalKey key; ArrayDeque<Banknote> banknotes = new ArrayDeque<>(); public Cassette(CurrencyAndBanknoteNominalKey key) { this.key = key; } public Banknote extractBanknote(){ return banknotes.pop(); } public List<Banknote> extractBanknotes(int count){ if (count > banknotes.size()){ throw new RuntimeException("Cassette dont have enough banknotes: " + count); } List<Banknote> out = new ArrayList<>(); for (int i = 0; i < count; i++){ out.add(extractBanknote()); } return out; } public boolean addBanknote(Banknote banknote){ return banknotes.add(banknote); } public int getCountOfBanknotes(){ return banknotes.size(); } public static Cassette createCasseteWithInitState(CurrencyAndBanknoteNominalKey key , int countOfBanknotes){ Cassette cassette = new Cassette(key); for (int i = 0; i < countOfBanknotes; i++) { cassette.addBanknote(new Banknote(key)); } return cassette; } }
<template> <ContentWrap> <!-- 搜索工作栏 --> <el-form ref="queryFormRef" :inline="true" :model="queryParams"> <el-form-item label="岗位名称" prop="name"> <el-input v-model="queryParams.name" clearable placeholder="请输入岗位名称" @keyup.enter="handleQuery" /> </el-form-item> <el-form-item label="岗位编码" prop="code"> <el-input v-model="queryParams.code" clearable placeholder="请输入岗位编码" @keyup.enter="handleQuery" /> </el-form-item> <el-form-item> <el-button type="primary" @click="handleQuery"> <Icon class="mr-5px" icon="ep:search" /> 搜索 </el-button> <el-button @click="resetQuery"> <Icon class="mr-5px" icon="ep:refresh" /> 重置 </el-button> </el-form-item> </el-form> <!-- 操作工具栏 --> <el-row :gutter="10"> <el-col :span="1.5"> <el-button v-hasPermi="['system:post:add']" plain type="primary" @click="openForm('create')" > <Icon class="mr-5px" icon="ep:plus" /> 新增 </el-button> </el-col> </el-row> </ContentWrap> <!-- 列表 --> <ContentWrap> <el-table v-loading="loading" :data="list"> <el-table-column align="center" label="岗位编号" prop="id" /> <el-table-column align="center" label="岗位名称" prop="name" /> <el-table-column align="center" label="岗位编码" prop="code" /> <el-table-column align="center" label="岗位顺序" prop="sort" /> <el-table-column align="center" label="岗位备注" prop="remark" /> <el-table-column align="center" label="状态" prop="status"> <template #default="scope"> <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" /> </template> </el-table-column> <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime" width="180" /> <el-table-column align="center" label="操作"> <template #default="scope"> <el-button v-hasPermi="['system:post:update']" link type="primary" @click="openForm('update', scope.row.id)" > 编辑 </el-button> <el-button v-hasPermi="['system:post:remove']" link type="danger" @click="handleDelete(scope.row.id)" > 删除 </el-button> </template> </el-table-column> </el-table> <!-- 分页 --> <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total" @pagination="getList" /> </ContentWrap> <!-- 表单弹窗:添加/修改 --> <PostForm ref="formRef" @success="handleQuery" /> </template> <script lang="ts" setup> import { dateFormatter } from '@/utils/formatTime' import * as HTTP from '@/api/system/post' import PostForm from './PostForm.vue' import { COMMON_STATUS_ENUM } from '@/utils/enums' defineOptions({ name: 'SystemPost' }) const message = useMessage() // 消息弹窗 const { t } = useI18n() // 国际化 const loading = ref(true) // 列表的加载中 const total = ref(0) // 列表的总页数 const list = ref([]) // 列表的数据 const queryParams = reactive({ pageNo: 1, pageSize: 10, code: '', name: '', status: undefined }) const queryFormRef = ref() // 搜索的表单 /** 查询岗位列表 */ const getList = async () => { loading.value = true try { const data = await HTTP.listData(queryParams.value) list.value = data.list total.value = data.total } finally { loading.value = false } } /** 搜索按钮操作 */ const handleQuery = () => { queryParams.value.pageNo = 1 getList() } /** 重置按钮操作 */ const resetQuery = () => { queryFormRef.value.resetFields() handleQuery() } /** 添加/修改操作 */ const formRef = ref() const openForm = (type: string, id?: number) => { formRef.value.open(type, id) } /** 修改岗位状态 */ const handleStatusChange = async (row: any) => { try { // 修改状态的二次确认 const text = row.status === COMMON_STATUS_ENUM.ENABLE ? '启用' : '停用' await message.confirm('确认要"' + text + '""' + row.name + '"吗?') // 发起修改状态 await HTTP.updateData({ id: row.id, status: row.status }) // 刷新列表 await getList() } catch { // 取消后,进行恢复按钮 row.status = row.status === COMMON_STATUS_ENUM.ENABLE ? COMMON_STATUS_ENUM.DISABLE : COMMON_STATUS_ENUM.ENABLE } } /** 删除按钮操作 */ const handleDelete = async (id: number) => { try { // 删除的二次确认 await message.delConfirm() // 发起删除 await HTTP.delData(id) message.success(t('common.delSuccess')) // 刷新列表 await getList() } catch {} } /** 初始化 **/ onMounted(() => { getList() }) </script>
"use client" import {useEffect, useState} from "react"; import {getSingleOffer} from "@/sanity/lib/sanity-utils"; import {Faq, Gallery, OfferHero, Separator, Services} from "@/components"; import Advantages from "@/components/&offer/Advantages"; import HowWeWork from "@/components/&offer/HowWeWork"; import Loader from "@/components/common/Loader"; export default function OfferLayout({slug}) { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { if (isLoading) { const fetchData = async () => { try { const data = await getSingleOffer(slug); setData(data) } catch (e) { console.log("error", e) } setIsLoading(false) } fetchData(); } setIsLoading(false) }, [slug, isLoading]); if(data === null) { return <Loader /> }else{ return ( <div className={"relative"}> { data && ( <> <OfferHero data={data}/> <Advantages data={data}/> <HowWeWork data={data}/> { data.services && data.service_header && ( <Services data={data.services} header={data.service_header}/> ) } <Gallery images={data.gallery}/> <Faq data={data.faq}/> <Separator/> </> ) } </div> ) } }
"use client"; import { ArrowLongLeftIcon, ArrowLongRightIcon, MagnifyingGlassIcon, } from "@heroicons/react/20/solid"; import { useRouter } from "next/navigation"; import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; interface UserInfo { nom: string; prenom: string; email: string; } interface User { userInfo: UserInfo; etapesInscription: { status: { etapesInscription: string }; }; date: string; numeroDossier: string; } export default function Table() { const userData = useSelector((state: RootState) => state.admin.allData); const userId = useSelector((state: RootState) => state.admin.userSelected); const [data, setData] = useState<User[]>([]); const [searchTerm, setSearchTerm] = useState(""); const [currentPage, setCurrentPage] = useState(1); const [itemsPerPage, setItemsPerPage] = useState(10); const dispatch = useDispatch(); const route = useRouter(); useEffect(() => { if (userData && typeof userData === "object") { const usersArray: User[] = Object.values(userData); setData(usersArray); } }, [userData]); const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => { setSearchTerm(event.target.value); setCurrentPage(1); // Reset to first page on search change }; function getStatusColor(status: string | undefined) { if (!status) return "text-gray-500"; // Pas de status switch (status) { case "en cours de traitement": return "text-yellow-500 font-semibold"; case "dossier complété et validé": return "text-green-500"; case "Refusé": return "text-red-500"; default: return "text-gray-500"; // Couleur par défaut pour les autres cas } } function capitalizeFirstLetter(input: string | null | undefined): string { const string = input || ""; // Convertit null ou undefined en chaîne vide if (string === "") return ""; return string.charAt(0).toUpperCase() + string.slice(1); } const filteredData = searchTerm === "" ? data : data.filter( (person) => person.userInfo.nom .toLowerCase() .includes(searchTerm.toLowerCase()) || person.userInfo.prenom .toLowerCase() .includes(searchTerm.toLowerCase()) || person.userInfo.email .toLowerCase() .includes(searchTerm.toLowerCase()) || (person.etapesInscription?.status?.etapesInscription && person?.etapesInscription?.status?.etapesInscription .toLowerCase() .includes(searchTerm.toLowerCase())) || false || person.date.toLowerCase().includes(searchTerm.toLowerCase()) ); const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = filteredData.slice(indexOfFirstItem, indexOfLastItem); const handleNextPage = () => { if (currentPage < Math.ceil(filteredData.length / itemsPerPage)) { setCurrentPage(currentPage + 1); } }; const handlePreviousPage = () => { if (currentPage > 1) { setCurrentPage(currentPage - 1); } }; const pageNumbers = []; for (let i = 1; i <= Math.ceil(filteredData.length / itemsPerPage); i++) { pageNumbers.push(i); } const openUserPage = (userId: string) => { route.push("/admin/espace/user?id=" + userId); }; return ( <div className="px-4 sm:px-6 lg:px-8"> <div className="sm:flex sm:items-center"> <div className="sm:flex-auto"> <h1 className="text-base font-semibold leading-6 text-gray-900"> Utilisateurs </h1> <p className="mt-2 text-sm text-gray-700"> Voici la liste des utilisateurs enregistrés dans la base de données. </p> </div> <div className="relative mt-2 flex items-center"> <input type="text" name="search" id="search" className="block w-full rounded-md border-0 py-1.5 px-1 pr-14 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 sm:text-sm sm:leading-6" placeholder="Recherche..." onChange={handleSearchChange} /> <div className="absolute inset-y-0 right-0 flex items-center justify-center py-1.5 pr-1.5"> <MagnifyingGlassIcon className="h-5 w-5 text-slate-400" /> </div> </div> </div> <div className="mt-8 flow-root"> <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <table className="min-w-full divide-y divide-gray-300"> <thead> <tr> <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-0" > Nom, prénom </th> <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900" > Étape </th> <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900" > Email </th> <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900" > Téléphone </th> <th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-0"> <span className="sr-only">Edit</span> </th> </tr> </thead> <tbody className="divide-y divide-gray-200"> {currentItems.map((person, index) => ( <tr key={index} className="hover:bg-slate-50 transition duration-150 ease-in-out cursor-pointer" onClick={() => openUserPage(person.numeroDossier)} > <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0"> {person.userInfo.nom} {person.userInfo.prenom} </td> <td className={`whitespace-nowrap px-3 py-4 text-sm ${getStatusColor( person.etapesInscription?.status?.etapesInscription !== null ? person.etapesInscription?.status?.etapesInscription : "" )}`} > {person.etapesInscription ? capitalizeFirstLetter( person.etapesInscription?.status ?.etapesInscription !== null || undefined || "" ? person.etapesInscription?.status ?.etapesInscription : "en cours de remplissage" ) : "En cours de remplissage"} </td> <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> {person.userInfo.email} </td> <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> {person.date} </td> <td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-0"> <a href="#" className="text-green-600 hover:text-green-900" > Edit <span className="sr-only">, {person.userInfo.nom}</span> </a> </td> </tr> ))} </tbody> </table> </div> </div> </div> <nav className="flex justify-between items-center pt-4"> <button onClick={handlePreviousPage} disabled={currentPage === 1}> <ArrowLongLeftIcon className="h-5 w-5 text-gray-400" /> </button> <div> {pageNumbers.map((number) => ( <button key={number} onClick={() => setCurrentPage(number)} className={`inline-flex items-center rounded-md font-medium text-sm mx-1 ${ number === currentPage ? "text-green-500" : "text-gray-700" }`} > {number} </button> ))} </div> <button onClick={handleNextPage} disabled={ currentPage === Math.ceil(filteredData.length / itemsPerPage) } > <ArrowLongRightIcon className="h-5 w-5 text-gray-400" /> </button> </nav> </div> ); }
using AutoMapper; using Conduit.Application.Interfaces; using Conduit.Domain.DTOs; using Conduit.Domain.Entities; using Conduit.Domain.Exceptions; using Conduit.Domain.Interfaces; namespace Conduit.Application.Services { public class ProfileService : IProfileService { private readonly IUserRepository userRepository; private readonly IMapper mapper; private class UsersRelationship { public User Follower { get; set; } public User Followee { get; set; } public bool IsFollowing { get; set; } } public ProfileService(IUserRepository userRepository, IMapper mapper) { this.userRepository = userRepository; this.mapper = mapper; } public async Task<UserProfileDto> GetUserProfile(string Username) { var User = await userRepository.GetUserByUsername(Username); return mapper.Map<UserProfileDto>(User); } public async Task<UserProfileDto> GetUserProfile(string Username, string CurrentUserName) { var Users = await GetUsers(Username, CurrentUserName); var User = Users.Followee; bool isFollowing = Users.IsFollowing; var UserProfile = mapper.Map<UserProfileDto>(User); UserProfile.Following = isFollowing; return UserProfile; } public async Task<UserProfileDto> FollowUser(string Username, string CurrentUserName) { var Users = await GetUsers(Username, CurrentUserName); if (Users.IsFollowing) { throw new ConflictException("You already follow this user"); } var FollowedUser = await userRepository.FollowUser(Users.Followee, Users.Follower); var FollowedUserProfile = mapper.Map<UserProfileDto>(FollowedUser); FollowedUserProfile.Following = true; return FollowedUserProfile; } public async Task<UserProfileDto> UnFollowUser(string Username, string CurrentUserName) { var Users = await GetUsers(Username, CurrentUserName); if (!Users.IsFollowing) { throw new ConflictException("You don't follow this user"); } var UnFollowedUser = await userRepository.UnFollowUser(Users.Followee, Users.Follower); var UnFollowedUserProfile = mapper.Map<UserProfileDto>(UnFollowedUser); UnFollowedUserProfile.Following = false; return UnFollowedUserProfile; } private async Task<UsersRelationship> GetUsers(string FolloweeName, string FollowerName) { try { var User = await userRepository.GetUserByUsername(FolloweeName); var CurrentUser = await userRepository.GetUserWithFollowings(FollowerName); bool isFollowing = CheckFollowStatus(User.UserId, CurrentUser); return new UsersRelationship { Followee = User, Follower = CurrentUser, IsFollowing = isFollowing }; } catch (Exception) { throw new NotFoundException("The user you rquested doesn't exist"); } } public bool CheckFollowStatus(int userId, User currentUser) { return currentUser.Followings.Any(user => user.FolloweeId == userId); } } }
import pandas import time import json from qiskit import IBMQ from qiskit_aer import Aer, AerSimulator from azure.quantum.qiskit import AzureQuantumProvider from rsa import * from order_generic import * from order_classic import * from order_quantum import * from qiskit.providers.fake_provider import FakePrague from qiskit_aer.noise import NoiseModel from qiskit.result import Result def run_exp_0(): # Experiment 0: Brute-force factorization digits = 8 primes = get_primes(10 ** digits) N = {} for d in range(1, digits): primes_with_digits = filter_primes_digits(d, primes) p, q = random.sample(primes_with_digits, 2) n = p * q print(f"p: {p}, q: {q}, n:{n}") N[n] = d for n, d in N.items(): start = time.time() p, q = find_factors(n) end = time.time() print(f'n: {n}, digits: {d}, p: {p}, q: {q}, time: {end - start}') # Experiment 0.5: Produce table # data = {} # data['x'] = [2, 3, 6, 8, 10, 12, 14] # data['y'] = [9.059906005859375e-06, 2.86102294921875e-06, # 1.3113021850585938e-05, 0.00025725364685058594, # 0.007128238677978516, 0.043366193771362305, # 0.3220024108886719] # df = pandas.DataFrame.from_dict(data) # df.plot(x='x', y='y', marker='.', legend=None) # plt.title('Factorization of n (brute-force)') # plt.xlabel('Digits of n') # plt.ylabel('Time taken (s)') # plt.show() def run_exp_1(): # Experiment 1: Communication based on RSA alice, bob = RSA(max_prime=1000), RSA(max_prime=1000) encrypted = bob.encrypt(msg=150, public_key=alice.public_key, n=alice.n) decrypted = alice.decrypt(encrypted) print(f'Encrypted: {encrypted}, Decrypted: {decrypted}') encrypted = bob.encrypt(msg='secret', public_key=alice.public_key, n=alice.n) decrypted = alice.decrypt(encrypted) print(f'Encrypted: {encrypted}, Decrypted: {decrypted}') def run_exp_2(): # Experiment 2: Breaking RSA alice, bob = RSA(p=3, q=5), RSA(max_prime=1000) public_key, n = alice.public_key, alice.n attacker = BreakRSA(n=n, public_key=public_key, period_finder=ClassicalPeriodFinder()) encrypted = bob.encrypt(msg=6, public_key=alice.public_key, n=alice.n) decrypted = alice.decrypt(encrypted) decrypted_attacker = attacker.decrypt(encrypted) print(f'Encrypted: {encrypted}, Decrypted: {decrypted}, Decrypted by Attacker: {decrypted_attacker}') plot_periodic_function(a=13, N=15) plt.show() def get_ibm_provider(backend): # Provider - IBMQ # IBMQ.save_account('') IBMQ.load_account() provider = IBMQ.get_provider() # for p in provider.backends(): # print(p) return provider.get_backend(backend) def get_azure_provider(backend): # Provider - Azure provider = AzureQuantumProvider( resource_id="", location="West Europe" ) # print("This workspace's targets:") # for backend in provider.backends(): # print("- " + backend.name()) # ionq.qpu.aria-1, ionq.simulator, quantinuum.sim.h1-1sc, quantinuum.qpu.h1-1, rigetti.sim.qvm, rigetti.qpu.ankaa-2 return provider.get_backend(backend) if __name__ == '__main__': # Experiment 3 - Quantum Order Finding backend = get_ibm_provider('ibm_brisbane') # backend = get_azure_provider('ionq.simulator') # backend = Aer.get_backend('aer_simulator') # backend = AerSimulator().from_backend(get_ibm_provider('ibm_brisbane')) # start = time.time() # period_finder = SemiPeriodFinder(backend=backend, postprocess=True) # r = period_finder.simulate(2, 21) # running_time = time.time() - start # print(f'{running_time}') # execute_one_by_one = True # shots = 1024 # circuits = [] # for N in [21]: # for a in [4]: # period_finder = SemiPeriodFinder(backend=backend, postprocess=True, N=N) # period_finder.create_circuit(a, draw=False) # period_finder.circuit.name = f"shor_{a}_mod_{N}_semi" # if execute_one_by_one: # result = backend.run(transpile(period_finder.circuit, backend), shots=shots).result() # result = result.to_dict() # f = open(f"shor_{a}_mod_{N}_semi", "w") # # f.write(json.dumps(result)) # f.close() # else: # circuits.append(transpile(period_finder.circuit, backend)) # if not execute_one_by_one: # backend.run(circuits, shots=shots) # execute_one_by_one = True # shots = 1024 # circuits = [] # for a in [4]: # period_finder = PeriodFinder4_21(backend=backend, postprocess=True) # period_finder.create_circuit(a, draw=False) # period_finder.circuit.name = f"shor_{a}_mod21_optimized" # if execute_one_by_one: # result = backend.run(transpile(period_finder.circuit, backend), shots=shots) # else: # circuits.append(transpile(period_finder.circuit, backend)) # if not execute_one_by_one: # backend.run(circuits, shots=shots) # # execute_one_by_one = True # shots = 1024 # circuits = [] # for a in [11]: # period_finder = PeriodFinder11_15(backend=backend, postprocess=True) # period_finder.create_circuit(a, draw=True) # period_finder.circuit.name = f"shor_{a}_mod15_optimized" # if execute_one_by_one: # result = backend.run(transpile(period_finder.circuit, backend), shots=shots) # else: # circuits.append(transpile(period_finder.circuit, backend)) # if not execute_one_by_one: # backend.run(circuits, shots=shots) # Submit jobs into queue (15) # execute_one_by_one = False # shots = 1024 # circuits = [] # for a in [2, 7, 8, 11, 13]: # period_finder = PeriodFinder15(backend=backend, postprocess=True) # period_finder.create_circuit(a, draw=False) # period_finder.circuit.name = f"shor_{a}_mod15" # if execute_one_by_one: # result = backend.run(transpile(period_finder.circuit, backend), shots=shots) # else: # circuits.append(transpile(period_finder.circuit, backend)) # if not execute_one_by_one: # backend.run(circuits, shots=shots) # # execute_one_by_one = False # shots = 1024 # circuits = [] # for a in [2, 7, 8, 11, 13]: # period_finder = PeriodFinder15Kitaev(backend=backend, postprocess=True) # period_finder.create_circuit(a, draw=False) # period_finder.circuit.name = f"shor_{a}_mod15_kitaev" # if execute_one_by_one: # result = backend.run(transpile(period_finder.circuit, backend), shots=shots) # else: # circuits.append(transpile(period_finder.circuit, backend)) # if not execute_one_by_one: # backend.run(circuits, shots=shots) # # Submit jobs into queue (21) execute_one_by_one = True shots = 1024 circuits = [] for a in [4, 5, 8, 13, 16]: period_finder = PeriodFinder21(backend=backend, postprocess=True) period_finder.create_circuit(a, draw=False) period_finder.circuit.name = f"shor_{a}_mod21" if execute_one_by_one: result = backend.run(transpile(period_finder.circuit, backend), shots=shots) else: circuits.append(transpile(period_finder.circuit, backend)) if not execute_one_by_one: backend.run(circuits, shots=shots) # Retrieve job # job = backend.retrieve_job("crdxq9dnzrx00081w0x0") # result = job.result() # for i in range(len(job.result().results)): # counts = result.get_counts(i) # classical_postprocessing(counts, 2**8, 10, True) # Retrieve job # f = open('/home/user3574/PycharmProjects/master_shor/experiments/simulator/noise/21/shor_4_21_optimized.json') # data = json.load(f) # result = Result.from_dict(data) # for i in range(len(result.results)): # counts = result.get_counts(i) # classical_postprocessing(counts, 2**8, 1024, True) # f.close() # a = 4 # period_finder = PeriodFinder21(provider, backend_name=backend, postprocess=True) # r = period_finder.simulate(a) # print(f'Period finding: N: {21}, a: {a}, r: {r}') # plot_periodic_function(a=a, N=21) # a = 2 # period_finder = PeriodFinder15Kitaev(provider, backend_name=backend, postprocess=True) # r = period_finder.simulate(a) # print(f'Period finding: N: {15}, a: {a}, r: {r}') # plot_periodic_function(a=a, N=15) # period_finder = SemiPeriodFinder(provider=Aer, backend_name='aer_simulator', postprocess=True) # period_finder.simulate(4, 21)
Describe Data.Base32.Crockford Before all let B = vital#vital#new().import('Data.Base32.Crockford') End Describe .encode() It encode string to base32 encoded string. Assert Equals(B.encode("hello, world!"), 'D1JPRV3F5GG7EVVJDHJ22') End It encode string RFC Test Vector 1. Assert Equals(B.encode("" ), '' ) End It encode string RFC Test Vector 2. Assert Equals(B.encode("f" ), 'CR' ) End It encode string RFC Test Vector 3. Assert Equals(B.encode("fo" ), 'CSQG' ) End It encode string RFC Test Vector 4. Assert Equals(B.encode("foo" ), 'CSQPY' ) End It encode string RFC Test Vector 5. Assert Equals(B.encode("foob" ), 'CSQPYRG' ) End It encode string RFC Test Vector 6. Assert Equals(B.encode("fooba" ), 'CSQPYRK1' ) End It encode string RFC Test Vector 7. Assert Equals(B.encode("foobar"), 'CSQPYRK1E8') End End Describe .encodebin() It encode string encoded as hex to base32 encoded string. Assert Equals(B.encodebin('68656c6c6f2c20776f726c6421'), 'D1JPRV3F5GG7EVVJDHJ22') End End Describe .encodebytes() It encode bytes-list encoded as hex to base32 encoded string. Assert Equals(B.encodebytes([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]), 'D1JPRV3F5GG7EVVJDHJ22') End End Describe .decode() It decode base32 encoded string to string. Assert Equals(B.decode("D1JPRV3F5GG7EVVJDHJ22"), 'hello, world!') End It decode string RFC Test Vector 1. Assert Equals(B.decode("" ), '' ) End It decode string RFC Test Vector 2. Assert Equals(B.decode("CR" ), 'f' ) End It decode string RFC Test Vector 3. Assert Equals(B.decode("CSQG" ), 'fo' ) End It decode string RFC Test Vector 4. Assert Equals(B.decode("CSQPY" ), 'foo' ) End It decode string RFC Test Vector 5. Assert Equals(B.decode("CSQPYRG" ), 'foob' ) End It decode string RFC Test Vector 6. Assert Equals(B.decode("CSQPYRK1" ), 'fooba' ) End It decode string RFC Test Vector 7. Assert Equals(B.decode("CSQPYRK1E8"), 'foobar') End End Describe .decoderaw() It decode base32 encoded string to bytes-list. Assert Equals(B.decoderaw("D1JPRV3F5GG7EVVJDHJ22"), [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]) End End End
import { ObjectType, Field } from '@nestjs/graphql'; import { Model } from 'objection'; import BaseModel from '../../common/base.model'; import { CommentEntityTypeEnum } from '../comment.enum'; import { User } from '../../user/entities/user.entity'; import { File } from '../../file/entities/file.entity'; @ObjectType() export class Comment extends BaseModel { static get tableName() { return 'comment'; } @Field() id: string; @Field({ nullable: true }) parentId?: string; @Field() authorId: string; @Field(() => CommentEntityTypeEnum) entityType: CommentEntityTypeEnum; @Field() entityId: string; @Field() body: string; @Field() created: string; @Field() updated: string; @Field(() => [File], { nullable: true }) attachments?: File[]; static get jsonSchema() { return { type: 'object', properties: { id: { type: 'string' }, parentId: { type: ['string', null] }, authorId: { type: 'string' }, entityType: { type: 'string' }, entityId: { type: 'string' }, body: { type: 'string' }, created: { type: 'string' }, updated: { type: 'string' }, }, }; } static get relationMappings() { return { author: { relation: Model.BelongsToOneRelation, modelClass: User, join: { from: 'comment.author_id', to: 'user.id', }, }, parent: { relation: Model.BelongsToOneRelation, modelClass: Comment, join: { from: 'comment.parent_id', to: 'comment.id', }, }, attachments: { relation: Model.ManyToManyRelation, modelClass: File, join: { from: 'comment.id', through: { from: 'comment_attachment.comment_id', to: 'comment_attachment.file_id', }, to: 'file.id', }, }, }; } }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:guard/Employer/Screen/Invite/MyJobList.dart'; import 'package:guard/admin/utils/GlobalVariables.dart'; import 'package:guard/chat/chatpage.dart'; import 'package:guard/users/Screens/EmployeDetail.dart'; class SingleJEmployeCard extends StatelessWidget { final snap; const SingleJEmployeCard({super.key, this.snap}); void showEmployeeDetails(BuildContext context) { showModalBottomSheet<void>( context: context, isScrollControlled: true, // Set to true for a full-height bottom sheet builder: (BuildContext context) { return FractionallySizedBox( heightFactor: 0.8, // Set to 70% of the screen height child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: EmployeDetailScreen( FullName: snap["FullName"], email: snap["email"], phone: snap["phone"], BadgeType: snap["BadgeType"], DrivingLicence: snap["DrivingLicence"], City: snap["City"], Shift: snap["Shift"], gender: snap['gender'] ?? '', dateOfBirth: snap['dateOfBirth'], photoUrl: snap['photoUrl'], police: snap['police'] ?? false, )), ], ), ); }, ); } @override Widget build(BuildContext context) { double H = MediaQuery.of(context).size.height; return Card( margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 20), elevation: 3, child: Padding( padding: const EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Name: ${snap['FullName']}', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), const SizedBox(height: 10), const Text( 'Badges:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), Text(snap['BadgeType'].toString()), const SizedBox(height: 10), const Text( 'Licence Type:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), Text(snap['DrivingLicence']), const SizedBox(height: 10), SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.black, textStyle: const TextStyle(fontSize: 18), ), onPressed: () async { userIdForInvitation = snap['uid']; // Replace with the actual document ID showDialog( context: context, builder: (context) => SizedBox( height: H / 50, child: AlertDialog( content: SizedBox( height: H / 3, child: MyJobsList(), ), ), ), ); }, child: const Text('Invite'), ), ), SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.black, textStyle: const TextStyle(fontSize: 18), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ChatPage(id: snap['uid'], name: 'username'), )); }, child: const Text('Chat'), ), ), ], ), ), ); } } class SingleJEmployeCard2 extends StatelessWidget { final snap; const SingleJEmployeCard2({super.key, this.snap}); void showEmployeeDetails(BuildContext context) { showModalBottomSheet<void>( context: context, isScrollControlled: true, // Set to true for a full-height bottom sheet builder: (BuildContext context) { return FractionallySizedBox( heightFactor: 0.8, // Set to 70% of the screen height child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: EmployeDetailScreen( FullName: snap["FullName"], email: snap["email"], phone: snap["phone"], BadgeType: snap["BadgeType"], DrivingLicence: snap["DrivingLicence"], City: snap["City"], Shift: snap["Shift"], gender: snap['gender'] ?? '', dateOfBirth: snap['dateOfBirth'], photoUrl: snap['photoUrl'], police: snap['police'] ?? false, )), ], ), ); }, ); } @override Widget build(BuildContext context) { double H = MediaQuery.of(context).size.height; return Card( margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 20), elevation: 3, child: Padding( padding: const EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Name: ${snap['FullName']}', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), const SizedBox(height: 10), const Text( 'Badges:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), Text(snap['BadgeType'].toString()), const SizedBox(height: 10), const Text( 'Licence Type:', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox(height: 10), Text(snap['DrivingLicence']), const SizedBox(height: 10), SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.black, textStyle: const TextStyle(fontSize: 18), ), onPressed: () async { userIdForInvitation = snap['uid']; // Replace with the actual document ID showDialog( context: context, builder: (context) => SizedBox( height: H / 50, child: AlertDialog( content: SizedBox( height: H / 3, child: MyJobsList(), ), ), ), ); }, child: const Text('Invite'), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( width: MediaQuery.of(context).size.width * 0.35, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.black, textStyle: const TextStyle(fontSize: 18), ), onPressed: () { showEmployeeDetails(context); }, child: const Text('View Details'), ), ), SizedBox( width: MediaQuery.of(context).size.width * 0.35, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.black, textStyle: const TextStyle(fontSize: 18), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ChatPage(id: snap['uid'], name: 'username'), )); }, child: const Text('Chat'), ), ), ], ), ], ), ), ); } } Future<void> inviteToJob(String docId, String candidateId) async { try { // Reference the Firestore collection and document final CollectionReference usersCollection = FirebaseFirestore.instance.collection('users'); final DocumentReference docRef = usersCollection.doc(docId); // Update the candidates list using FieldValue.arrayUnion await docRef.update({ 'invitations': FieldValue.arrayUnion([candidateId]), }); print('Candidate invited successfully to job $docId'); } catch (e) { print('Error adding candidate to job: $e'); rethrow; } } Future<void> accepteInvitation(String docId, String idTOAdd) async { try { // Reference the Firestore collection and document final CollectionReference usersCollection = FirebaseFirestore.instance.collection('users'); final DocumentReference docRef = usersCollection.doc(docId); // Update the candidates list using FieldValue.arrayUnion await docRef.update({ 'accepted': FieldValue.arrayUnion([idTOAdd]), }); print('Candidate invited successfully to job $docId'); } catch (e) { print('Error adding candidate to job: $e'); rethrow; } }
# WDM: Wavelength Division Multiplexing E' possibile fare **multiplexing**, ovvero mandare **più segnali all'interno della stessa fibra**: ogni segnale avrà una diversa lunghezza d'onda. Esistono due soluzioni: la prima è detta **dense** (DWDM) dove ci sono molte lunghezze d'onda (più costoso), mentre la seconda è **coarse** (CWDM) dove ci sono poche lunghezze d'onda (più economico). ![[Pasted image 20231207152749.png]] L'idea generale è quella di trasmettere più bit in parallelo, andando ad **aumentare la capacità della fibra** stessa. Dal punto di visto degli operatori si aumenta il ROI. E' successivamente possibile realizzare sistemi per cambiare la lunghezza d'onda (**wavelength switching**) dei segnali, per poi combinare insieme di segnali differenti: ![[Pasted image 20231207153325.png]] La rete dell'operatore avrà un **backbone** composto da collegamenti che possono gestire la fibra, mentre i collegamenti ai vari router sono tradizionali. All'interno del backbone ci sono gli **switch ottici** che sono in grado di gestire canali in fibra ottica. I router si velocizzano in quanto la rete interna è più veloce. ```ad-note title: Optical Switch In questo scenario gli switch ottici trasportano **segnali**, non pacchetti. In altre parole non c'è nulla di legato ad IP, ma i pacchetti vengono instradati in questo backbone una volta convertiti in segnali ottici. ``` ![[Pasted image 20231207153548.png]] # Optical switching #recuperare ultimi 10 minuti
import { Card, Title } from "@mantine/core" import { determineColorPercentUp } from "~/utils/utilities" import { CardGroupLayout, LayoutData, links as cardGroupLinks, } from "../CardGroupLayout" import styles from "./styles.css" export const links = () => { return [...cardGroupLinks(), { rel: "stylesheet", href: styles }] } export type PresearchListType = { meta: { description: string url: string server_description: string | null server_url: string | null gateway_pool: string remote_addr: string version: string } status: { connected: boolean blocked: boolean in_current_state_since: string minutes_in_current_state: number } period: { avg_latency_ms: number avg_latency_score: number avg_reliability_score: number avg_staked_capacity_percent: number avg_success_rate: number avg_success_rate_score: number avg_uptime_score: number avg_utilization_percent: number connections: { num_connections: number most_recent_connection: string } disconnections: { num_disconnections: number most_recent_disconnection: string } period_end_date: string period_seconds: number period_start_date: string rewardable_requests: number successful_requests: number total_pre_earned: number total_requests: number total_uptime_seconds: number uptime_percentage: number } }[] export type PresearchItemType = { meta: { description: string url: string server_description: string | null server_url: string | null gateway_pool: string remote_addr: string version: string } status: { connected: boolean blocked: boolean in_current_state_since: string minutes_in_current_state: number } period: { avg_latency_ms: number avg_latency_score: number avg_reliability_score: number avg_staked_capacity_percent: number avg_success_rate: number avg_success_rate_score: number avg_uptime_score: number avg_utilization_percent: number connections: { num_connections: number most_recent_connection: string } disconnections: { num_disconnections: number most_recent_disconnection: string } period_end_date: string period_seconds: number period_start_date: string rewardable_requests: number successful_requests: number total_pre_earned: number total_requests: number total_uptime_seconds: number uptime_percentage: number } } export const PresearchNodeCard = (data: PresearchItemType) => { const layout = [ { text: "Status :", value: data.status.connected ? "Connected" : "Disconnected", color: data.status.connected ? "green" : "red", }, { text: "Server Pool :", value: data.meta.gateway_pool }, { text: "Uptime :", value: +data.period.uptime_percentage.toPrecision(1), color: determineColorPercentUp(data.period.uptime_percentage), }, { text: "Successful Requests:", value: data.period.successful_requests }, { text: "Pre Earned:", value: data.period.total_pre_earned.toFixed(2), }, ] return ( <Card className="presearchNodeCard"> <Title order={3} align="center"> {data.meta.description} </Title> {layout.map((item: LayoutData) => { return ( <CardGroupLayout key={item.text} text={item.text} url={item.url} value={item.value} color={item.color} /> ) })} </Card> ) }
import fs from 'fs-extra'; import { minify } from 'csso'; import sass from 'sass'; import less from 'less'; async function compileLess(weight: string): Promise<string> { return ( await less.render(fs.readFileSync('less/' + weight + '.less').toString(), { paths: ['less'], filename: weight + '.less', }) ).css; } describe('compare less and sass output', () => { it('thin', async () => { const cLess = await compileLess('thin'); const cSass = sass.compile('sass/thin.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('light', async () => { const cLess = await compileLess('light'); const cSass = sass.compile('sass/light.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('regular', async () => { const cLess = await compileLess('regular'); const cSass = sass.compile('sass/regular.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('bold', async () => { const cLess = await compileLess('bold'); const cSass = sass.compile('sass/bold.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('fill', async () => { const cLess = await compileLess('fill'); const cSass = sass.compile('sass/fill.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('duotone', async () => { const cLess = await compileLess('duotone'); const cSass = sass.compile('sass/duotone.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); it('index', async () => { const cLess = await compileLess('index'); const cSass = sass.compile('sass/index.scss').css; expect(minify(cLess).css).toEqual(minify(cSass).css); }); });
<template> <div> <v-btn icon depressed color="primary" @click="getRoles"><v-icon>mdi-pencil</v-icon></v-btn> <v-dialog v-model="addPermModel" width="500"> <v-form v-model="valid" ref="form" lazy-validation> <v-card> <v-card-title> Edit User <v-spacer/> <v-btn icon @click="addPermModel=false"><v-icon>mdi-close</v-icon></v-btn> </v-card-title> <v-card-text> <v-row> <v-col> <v-text-field label="Name" outlined v-model="form.name" :rules="nameRule" /> </v-col> <v-col> <v-text-field label="Surname" outlined v-model="form.surname" :rules="surnameRule" /> </v-col> </v-row> <v-row> <v-col> <v-text-field label="Job Title" outlined v-model="form.jobtitle" :rules="jobtitleRule" /> </v-col> <v-col> <v-select label="Title" outlined v-model="form.title" :rules="titleRule" :items="titlelist" /> </v-col> </v-row> <v-row> <v-col> <v-text-field label="Email" outlined type="email" v-model="form.email" :rules="emailRule" /> </v-col> <v-col> <v-text-field label="Phonenumber" outlined v-model="form.phonenumber" :rules="phonenumberRule" /> </v-col> </v-row> <v-row> <v-col> <v-select label="Role" outlined v-model="form.roleId" :rules="roleRule" :items="roles" item-value="id" item-text="name" /> </v-col> </v-row> </v-card-text> <v-card-actions> <v-btn rounded class="error" @click="addPermModel=false">Cancel</v-btn> <v-spacer/> <v-btn rounded class="success" @click="submit" :loading="loading" :disabled="loading">Submit</v-btn> </v-card-actions> </v-card> </v-form> </v-dialog> <v-snackbar :color="color" right top v-model="snackbar" >{{text}}</v-snackbar> </div> </template> <script> export default { props:['user'], data(){ return{ addPermModel:false, valid:false, form:{ name:this.user.name, surname:this.user.surname, email:this.user.email, phonenumber:this.user.phonenumber, jobtitle:this.user.jobtitle, title:this.user.title, roleId:this.user.roleId, procuremententityId:this.user.procuremententityId }, nameRule:[v=>!!v || 'Name is required'], surnameRule:[v=>!!v || 'Surname is required'], emailRule:[ v => !!v || 'E-mail is required', v => /.+@.+\..+/.test(v) || 'E-mail must be valid', ], phonenumberRule:[v=>!!v || 'Phone number is required'], jobtitleRule:[v=>!!v || 'Jobtitle is required'], titleRule:[v=>!!v || 'title is required'], roleRule:[v=>!!v || 'Role is required'], titlelist:['Mr','Mrs','Miss','Ms','Dr','Prof'], snackbar:false, color:'', text:'', loading:false } },methods:{ async getRoles(){ await this.$store.dispatch('roles/getRoles') this.addPermModel=true }, async submit(){ if(this.$refs.form.validate()) { this.valid = true this.loading=true const payload ={id:this.user.id,data:this.form} await this.$store.dispatch('procuremententity/editUser',payload) this.loading=false } } },computed:{ roles(){ let data = this.$store.state.roles.roles return data.filter(dt=>{return dt.level =='ENTITY'}) } } } </script> <style> </style>
<?php namespace Drupal\single_content_sync\Plugin\SingleContentSyncBaseFieldsProcessor; use Drupal\Core\Entity\FieldableEntityInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\single_content_sync\ContentExporterInterface; use Drupal\single_content_sync\SingleContentSyncBaseFieldsProcessorPluginBase; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Plugin implementation for taxonomy_term base fields processor plugin. * * @SingleContentSyncBaseFieldsProcessor( * id = "taxonomy_term", * label = @Translation("Taxonomy Term base fields processor"), * entity_type = "taxonomy_term", * ) */ class TaxonomyTerm extends SingleContentSyncBaseFieldsProcessorPluginBase implements ContainerFactoryPluginInterface { /** * The content exporter service. * * @var \Drupal\single_content_sync\ContentExporterInterface */ protected ContentExporterInterface $exporter; /** * Constructs new TaxonomyTerm plugin instance. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\single_content_sync\ContentExporterInterface $exporter * The content exporter service. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, ContentExporterInterface $exporter) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->exporter = $exporter; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('single_content_sync.exporter'), ); } /** * {@inheritdoc} */ public function exportBaseValues(FieldableEntityInterface $entity): array { return [ 'name' => $entity->getName(), 'weight' => $entity->getWeight(), 'langcode' => $entity->language()->getId(), 'description' => $entity->getDescription(), 'parent' => $entity->get('parent')->target_id ? $this->exporter->doExportToArray($entity->get('parent')->entity) : 0, ]; } /** * {@inheritdoc} */ public function mapBaseFieldsValues(array $values): array { return [ 'name' => $values['name'], 'weight' => $values['weight'], 'langcode' => $values['langcode'], 'description' => $values['description'], ]; } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>PayNow QR Info</title> <meta name="description" content="PayNow QR Code Reader"> <meta name="author" content="SitePoint"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.5/build/pure-min.css" integrity="sha384-LTIDeidl25h2dPxrB2Ekgc9c7sEC3CWGM6HeFmuDNUjX76Ert4Z4IY714dhZHPLd" crossorigin="anonymous"> <script type="text/javascript" src="https://webrtc.github.io/adapter/adapter-latest.js"></script> <style> .l-box { padding: 1em; } #pn-table td:empty::before { content: "-" } </style> <script type="text/javascript" src="instascan.min.js"></script> <script> function extractPayNowQR(qr) { var rx = /\d{8}SG.PAYNOW(.*)(\d{8}SG\..*){0,1}/g; var arr = rx.exec(qr); if (arr !=null && arr.length >1) { return arr[1]; } return ""; } function extractValue(str) { rxId = RegExp("(\\d{2})(\\d{2})(.*)", "g") idLengthArr = rxId.exec(str); length = parseInt(idLengthArr[2]); rxValue = RegExp("(\\d{2})(\\d{2})(.{" + length + "})(.*)", "g") result = rxValue.exec(str); id = result[1]; value = result[3]; remainder = result[4]; return { id, length, value, remainder }; } function extractPNQRContent(pnQR) { pnContent = new Map(); remainderString = pnQR; do { extractObj = extractValue(remainderString); remainderString = extractObj.remainder; if (extractObj.value.substr(0, 2) == "01" || extractObj.value.substr(0, 2) == "00") { remainderString2 = extractObj.value; do { extractObj2 = extractValue(remainderString2); remainderString2 = extractObj2.remainder; pnContent.set(extractObj.id + "-" + extractObj2.id, extractObj2.value); } while (remainderString2.length > 0) } else { pnContent.set(extractObj.id, extractObj.value); } } while (remainderString.length > 0) return pnContent; } function parseyyyymmdd(str) { if (!/^(\d){8}$/.test(str)) return "invalid date"; var y = str.substr(0, 4), m = str.substr(4, 2), d = str.substr(6, 2); return new Date(y, m - 1, d); } </script> </head> <body> <div class="pure-g"> <div class="pure-u-1"> <div class="l-box"> <h2>PayNow QR Reader</h2> <p>This is a showcase app to display PayNow info encoded in a QR code. Please allow camera permission to scan.</p> <button id="btn-scan-qr" onclick="startScan()">Start/Stop Scan QR</button> </div> </div> <div class="pure-u-1"> <video id="preview" playsinline></video> <script type="text/javascript"> var isScan = false; let scanner = new Instascan.Scanner({ video: document.getElementById('preview'), mirror: false }); scanner.addListener('scan', function (content) { var pnQR = extractPayNowQR(content); if (pnQR =="") { alert("Not a PayNow QR.\n\nContent:\n"+content); } else { var pnContent = extractPNQRContent(pnQR); displayPNContent(pnContent); } scanner.stop(); isScan = false; }); function startScan() { if (!isScan) { isScan = true; Instascan.Camera.getCameras().then(function (cameras) { if (cameras.length > 1) { // Check iPhone and iPad including iPadOS 13+ regardless of desktop mode settings var iOSiPadOS = /^iP/.test(navigator.platform) || /^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4; if (iOSiPadOS) { scanner.start(cameras[0]); } else { scanner.start(cameras[1]); } } else if (cameras.length > 0) { scanner.start(cameras[0]); } else { alert('No cameras found.'); } }).catch(function (e) { console.error(e); }); } else { scanner.stop(); isScan = false; } } </script> </div> <div class="pure-u-1"> <div class="l-box"> <h3>Result:</h3> <table class="pure-table" id="pn-table"> <thead> <td>Field</td> <td>Value</td> </thead> <tr> <td>Payee Type</td> <td id="01"></td> </tr> <tr> <td>Payee</td> <td id="02"></td> </tr> <tr> <td>Editable?</td> <td id="03"></td> </tr> <tr> <td>Amount ($)</td> <td id="54"></td> </tr> <tr> <td>Display</td> <td id="59"></td> </tr> <tr> <td>Reference (Uneditable)</td> <td id="05"></td> </tr> <tr> <td>Bill Reference</td> <td id="62-01"></td> </tr> <tr> <td>Expiry Date</td> <td id="04"></td> </tr> </table> </div> <div class="l-box"> <button onclick="resetTable()">Reset</button> </div> </div> </div> <script> /* // Example usage var qr = ""; var pnQR = extractPayNowQR(qr); var pnContent = extractPNQRContent(pnQR); */ // display function displayPNContent(pnContent) { resetTable(); for (const [key, value] of pnContent.entries()) { console.log(key, value); elem = document.getElementById(key); switch (key) { case "01": if (value == 2) { elem.textContent = "UEN" } else { elem.textContent = "Mobile" } break; case "03": if (value == 1) { elem.textContent = "Yes" } else { elem.textContent = "No" } break; case "04": var dateformatted = value.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3'); elem.textContent = dateformatted; break; case "02": case "05": case "54": case "59": case "62-01": elem.textContent = value; break; default: } } } var backupTable = document.getElementById("pn-table").innerHTML; function resetTable() { document.getElementById("pn-table").innerHTML = backupTable; } </script> </body> </html>
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace Utility { public static class Texture2DExtensions { public static void InsertTexture(this Texture2D origin, Texture2D other, int x, int y) { origin.SetPixels(x, y, other.width, other.height, other.GetPixels()); origin.Apply(); } public static void InsertTextureInRect(this Texture2D origin, Texture2D other, int x, int y, int width, int height) { var pixels = Resizer.Resize2DArray(other.GetPixels(), other.width, other.height, width, height); try { /*if (x + width > origin.width || x + width > other.width || y + height > origin.height || y + height > other.height) { return; }*/ origin.SetPixels(x, y, width, height, pixels); origin.Apply(); } catch { Debug.LogError("Process not completed, image out of bounds" + " OriginW: " + origin.width + " - OriginH: " + origin.height + " - OtherW: " + other.width + " - OtherH: " + other.height + " - TW: " + width + " - TH: " + height + " - pixels: " + pixels.Length + " - X: " + x + " - Y: " + y); } } public static void MirrorY(this Texture2D origin) { int height = origin.height; Color[] pixels = new Color[origin.width*origin.height]; Array.Copy(origin.GetPixels(),pixels, pixels.Length); for(int i = 0; i < height; i++) { origin.SetPixels(0, i, origin.width, 1, pixels.Skip((height - 1 - i) * origin.width).Take(origin.width).ToArray()); } origin.Apply(); } public static void MirrorY(this Texture2D origin, int stride) { int height = origin.height/stride; Color[] pixels = new Color[origin.width * origin.height]; Array.Copy(origin.GetPixels(), pixels, pixels.Length); for (int i = 0; i < height; i++) { origin.SetPixels(0, i, origin.width, stride, pixels.Skip((height - 1 - i) * origin.width).Take(origin.width*stride).ToArray()); } origin.Apply(); } public static Texture2D MergeTextures(this Texture2D origin, Texture2D other) { if (origin.width != other.width || origin.height != other.height) { throw new Exception("Textures do not have the same size"); } var t = new Texture2D(origin.width, origin.height); for (int j = 0; j < origin.height; j++) { for (int i = 0; i < origin.width; i++) { if (other.GetPixel(i, j).a == 0) { t.SetPixel(i, j, origin.GetPixel(i, j)); } else { t.SetPixel(i, j, other.GetPixel(i, j)); } } } t.Apply(); return t; } public static Texture2D FitSquare(this Texture2D origin) { int size = (origin.width > origin.height ? origin.width : origin.height); var ofsset = ((Vector2.one * size - new Vector2(origin.width, origin.height))/2).ToInt(); var texture = new Texture2D(size, size); for (int j = 0; j < origin.height; j++) { for (int i = 0; i < origin.width; i++) { texture.SetPixel(ofsset.x + i, ofsset.y + j, origin.GetPixel(i,j)); } } texture.Apply(); return texture; } public static Texture2D SubTexture(this Texture2D origin, int x, int y, int width, int height) { var texture = new Texture2D(width, height); for (int j = 0; j < width; j++) { for (int i = 0; i < width; i++) { texture.SetPixel(i, j, origin.GetPixel(x + i, y + j)); } } texture.Apply(); return texture; } public static void Set(this Texture2D texture, Color32 color) { for(int j = 0; j < texture.height; j++) { for (int i = 0; i < texture.width; i++) { texture.SetPixel(i,j, color); } } texture.Apply(); } } }
<script setup> const props = defineProps({ modelValue: { type: String, required: true, }, name: { type: String, required: true, default: '', }, label: { type: String, required: true, default: '', }, rows: { type: String, required: true, default: '', }, errors: { type: Array, default: () => [], }, }); const emit = defineEmits(['update:modelValue']); function onInput($event) { const { value } = $event.target; emit('update:modelValue', value); }; </script> <template> <div class="form-wrapper"> <label class="label" :for="props.name">{{ props.label }}</label> <textarea :id="props.name" class="input" :name="props.name" :rows="props.rows" :value="props.modelValue" @input="onInput" /> <ClientError v-for="error of props.errors" :key="error.$uid" :error="error.$message" /> </div> </template>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1 style="color: red;">HTML Basic</h1> <h2>HTML Documents</h2> <p>All HTML documents must start with a document type declaration: (!DOCTYPE) html. The HTML document itself begins with (html) and ends with (/html). The visible part of the HTML document is between (body) and (/body).</p> <p>E.g HTML Documents</p> <!DOCTYPE html> <h>Nguyễn Lê Nhật Anh</h> <p>Đây là đoạn văn bản giới thiệu bản thân</p> <h2>The (!DOCTYPE) Declaration</h2> <p>The (!DOCTYPE) declaration represents the document type, and helps browsers to display web pages correctly. It must only appear once, at the top of the page (before any HTML tags). The (!DOCTYPE) declaration is not case sensitive. The (!DOCTYPE) declaration for HTML5 is:</p> <p>E.g The !DOCTYPE Declaration : <!DOCTYPE html> </p> <h1>HTML Elements</h1> <p>The HTML element is everything from the start tag to the end tag: (tagname)Content goes here...(/tagname)</p> <h2>E.g</h2> <p> <h>Nguyễn Lê Nhật Anh</h> <p>Đây là đoạn văn bản giới thiệu bản thân</p> </br> </p> <h1>HTML Attributes</h1> <p> <ul> <li>All HTML elements can have attributes</li> <li>Attributes provide additional information about elements</li> <li>Attributes are always specified in the start tag</li> <li>Attributes usually come in name/value pairs like: name="value"</li> </ul> </p> <h2>E.g</h2> <img src="https://scontent.fhan14-3.fna.fbcdn.net/v/t39.30808-6/339103090_1223437781616656_5022959676252426249_n.jpg?_nc_cat=110&ccb=1-7&_nc_sid=efb6e6&_nc_eui2=AeGA_MkzAg_xG_u0-bofvsBOvzF9jhKVLG6_MX2OEpUsbsCb6_Aefa3j2q6U7kqeEYy6dRK5zsipRnsNhSFERxqh&_nc_ohc=VQVnCCQUpLkAX-5Ed-g&_nc_ht=scontent.fhan14-3.fna&oh=00_AfDp91-vHePC55c3Ho8YPrFpQONhzoVQygwoXhr6nq2ZzQ&oe=65B4CCE0" width="500" height="600"> </br> <a href="https://web.facebook.com/nhatanh.ltv/">Facebook</a> </br> <h1>HTML Headings</h1> <p> HTML headings are defined with the (h1) to (h6) tags. (h1) defines the most important heading. (h6) defines the least important heading. </p> <h2>E.g</h2> <h2>E.g</h2> <h1>heading 1</h1> <h2>heading 2</h2> <h3>heading 3</h3> <h4>heading 4</h4> <h5>heading 5</h5> <h1>HTML Paragraphs</h1> <p> The HTML (p) element defines a paragraph. A paragraph always starts on a new line, and browsers automatically add some white space (a margin) before and after a paragraph. </p> <h2>E.g</h2> <p>Đây là đoạn văn bản giới thiệu bản thân tôi.</p> <p>This paragraph contains a lot of spaces in the source code, but the browser ignores it..</p> <h1>HTML Styles</h1> <p> The HTML style attribute is used to add styles to an element, such as color, font, size, and more. </p> <h2>E.g</h2> <body> <h1 style="color: blueviolet;">Tiêu đề</h1> <p style="background-color:tomato;">Tôi là Đạt.</p> </body> <h1>HTML Text Formatting</h1> HTML contains several elements for defining text with a special meaning. <p>E.g</p> <p><b>This text is bold</b></p> <p><i>This text is italic.</i></p> <p><small>Đây là ai.</small></p> <h1>HTML Quotation and Citation Elements</h1> <p>In this chapter we will go through the (blockquote),(q), (abbr), (address), (cite), and (bdo) HTML elements.</p> <p>E.g</p> <p>WWF's goal is to: <q>Build a future where people live in harmony with nature.</q></p> <p> <address> Written by John Doe.<br> Visit us at:<br> Example.com<br> Box 564, Disneyland<br> USA </address> </p> <h1>HTML Comments</h1> <p>HTML comments are not displayed in the browser, but they can help document your HTML source code.</p> <p>E.g</p> <p> <!-- This is a comment --> <p>This is a paragraph.</p> <!-- Remember to add more information here --> <h1>HTML Colors</h1> <p>HTML colors are specified with predefined color names, or with RGB, HEX, HSL, RGBA, or HSLA values.</p> <p>E.g</p> <p> <p style="color:DodgerBlue;">Lorem ipsum...</p> <h1 style="background-color:rgba(255, 99, 71, 0.2);">rgba(255, 99, 71, 0.2)</h1> <h1 style="background-color:#a0a0a0;">#a0a0a0</h1> </p> <h1 style="color:red">Define an HTML Table</h1> <p>A table in HTML consists of table cells inside rows and columns.</p> <h3>Table Cells</h3> <p>Each table cell is defined by a "td" and a "td" tag.</p> <p>Everything between "td" and "td" are the content of the table cell.</p> <h3>Example</h3> <table> <tr> <th>Hoc sinh 1</th> <th>Hoc sinh 2</th> <th>Hoc sinh 3</th> </tr> <tr> <td>Dũng</td> <td>Tuấn Anh</td> <td>Đạt</td> </tr> <tr> <td>8.5</td> <td>7</td> <td>7,75</td> </tr> </table> <h1 style="color:red">HTML images</h1> <p>Images can improve the design and the appearance of a web page.</p> <h3>Example</h3> <img src="https://images.pexels.com/photos/19749008/pexels-photo-19749008/free-photo-of-portrait-of-brunette-woman-wearing-black-dress.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"> <h1 style="color:red">HTML Links</h1> <p>HTML links are hyperlinks. You can click on a link and jump to another document. When you move the mouse over a link, the mouse arrow will turn into a little hand.</p> <p>The most important attribute of the "a" element is the href attribute, which indicates the link's destination. The link text is the part that will be visible to the reader. Clicking on the link text, will send the reader to the specified URL address. </p> <h3>Example</h3> <a href="https://www.facebook.com/dat2208">Link facebook ny Tuấn Anh</a> <h1 style="color:red">HTML List</h1> <h3>Unordered HTML List</h3> <p>An unordered list starts with the "ul" tag. Each list item starts with the "li" tag. The list items will be marked with bullets (small black circles) by default:</p> <h3>Ordered HTML List</h3> <p>An ordered list starts with the "ol" tag. Each list item starts with the "li" tag. The list items will be marked with numbers by default:</p> <h3>HTML Description Lists</h3> <p>HTML also supports description lists. A description list is a list of terms, with a description of each term. The "dl" tag defines the description list, the "dt" tag defines the term (name), and the "dd" tag describes each term:</p> <h3>HTML List Tags</h3> <p>ul ol li dl dt dd </p> <h3>Example</h3> <ol> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> <h1 style="color:red">HTML Block and Inline Elements</h1> <h3>Block-level Elements</h3> <p>A block-level element always starts on a new line, and the browsers automatically add some space (a margin) before and after the element. A block-level element always takes up the full width available (stretches out to the left and right as far as it can). Two commonly used block elements are: "p" and "div". The "p" element defines a paragraph in an HTML document. The "div" element defines a division or a section in an HTML document.</p> <h3>Inline Elements</h3> <p>An inline element does not start on a new line. An inline element only takes up as much width as necessary. This is a "span" element inside a paragraph.</p> <h4>Example </h4> <span>Chào các bạn</span> <h3>The "div" Element</h3> <p>The "div" element is often used as a container for other HTML elements. The "div" element has no required attributes, but style, class and id are common. When used together with CSS, the "div" element can be used to style blocks of content:</p> <h4>Example </h4> <div> <h2>Nguyễn Tuấn Anh</h2> <p>Nguyễn Tuấn Anh là 1 học sinh trong những học sinh học CNTT ở trường đại học Thủ đô Hà Nội</p> </div> </body> </html>
import React from "react"; import PropTypes from "prop-types"; import { FaEdit, FaWindowClose } from "react-icons/fa"; import "./style.css"; export default function Tasks({ tasks, handleEditTask, handleDeleteTask }) { return ( <ul className="tasks"> {tasks.map((task, index) => ( <li key={index}> {task} <span> <FaEdit className="edit" onClick={(e) => handleEditTask(e, index)} /> <FaWindowClose className="delete" onClick={(e) => handleDeleteTask(e, index)} /> </span> </li> ))} </ul> ); } Tasks.propTypes = { handleDeleteTask: PropTypes.func.isRequired, handleEditTask: PropTypes.func.isRequired, tasks: PropTypes.array.isRequired, };
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; // create mapping unique is addres and return owner wallel company contract helloWorld { struct Company { string name; uint age; uint workers; } // worked privazky addreess wallet in to compani mapping(address => Company) private companies; address public ceo; // public for see get function vivoda // func why realisation and ispolnayetsa one time 4tob SC zapyshen s moego addr constructor() { ceo = msg.sender; } function addCompany(string memory name, uint age, uint workers) public { require(age < 2, "your company shold be older then 2 years "); address sender = msg.sender; // vstroenaya func - vernyt addr inicialtora etogo walleta/contracta Company memory newCompany; newCompany.name = name; newCompany.age = age; newCompany.workers = workers; companies[sender] = newCompany; } function getCompany() public view returns (string memory name, uint age, uint workers) { address sender = msg.sender; return (companies[sender].name, companies[sender].age, companies[sender].workers); } function deleteCompany (address sender) public { require(msg.sender == ceo, "Your are not ceo!"); delete companies[sender]; } }
import React from "react"; const UploadFiles = (props) => { const { uploadedFiles, setUploadedFiles } = props.formState; //Handling file event const handleFileEvent = (e) => { const chosenFiles = Array.prototype.slice.call(e.target.files); handleFileAdd(chosenFiles); }; //Add files to state const handleFileAdd = (files) => { const uploaded = [...uploadedFiles]; files.some((file) => { if (uploaded.findIndex((f) => f.name === file.name) === -1) { uploaded.push(file); } }); setUploadedFiles(uploaded); }; const removeFile = (fileNameToRemove) => { const temp = uploadedFiles.filter((item) => item.name !== fileNameToRemove); setUploadedFiles(temp); }; return ( <div className="flex flex-col items-center border-2 p-3 border-dashed rounded-md"> <label htmlFor="photos" className="p-2"> Zdjęcia </label> <label htmlFor="file-upload"> <a className="block border-2 text-sm border-black p-1 font-bold uppercase text-black bg-white hover:bg-black hover:text-white duration-200 cursor-pointer"> Dodaj </a> </label> <input id="file-upload" type="file" multiple accept=".png,.jpg,.jpeg,.bmp,.pdf" className="hidden" onChange={handleFileEvent} /> <ul> {uploadedFiles.length > 0 && uploadedFiles.map((file) => ( <li key={file.name}> <a className="px-1 cursor-pointer text-red-600" onClick={() => removeFile(file.name)} > x </a> {file.name} {(file.size / 1024 / 1024).toPrecision(3)}MB </li> ))} </ul> </div> ); }; export default UploadFiles;
<?php get_header(); ?> <div class="main"> <div class="content"> <div class="posts"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h2 class="post-title"><?php the_title(); ?></h2> <div class="post-date">Added <?php the_time('F j, Y'); ?> at <?php the_time('g:i a'); ?><?php if ( get_post_meta($post->ID, 'duration', true) ) : ?> | Duration: <?php echo get_post_meta($post->ID, 'duration', true) ?> mins<?php endif; ?></div> <div class="single-post"> <?php the_content(); ?> <?php echo get_post_meta($post->ID,'videoid',true);?> <div class="clear"></div> <div class="video-category">Category: <?php the_category(', ') ?></div> <div class="video-tags"><?php the_tags() ?></div> <div class="clear"></div> </div> <?php comments_template(); ?> <h2 class="post-title">Related videos</h2> <?php $args = array( 'numberposts' => 6, 'orderby' => 'rand' ); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?> <div class="post" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(array(240,180), array('alt' => get_the_title(), 'title' => '')); ?></a> <?php if ( get_post_meta($post->ID, 'duration', true) ) : ?><div class="duration"><?php echo get_post_meta($post->ID, 'duration', true) ?></div><?php endif; ?> <div class="link"><a href="<?php the_permalink() ?>"><?php short_title('...', '34'); ?></a></div> <span>Added: <?php the_time('F j, Y'); ?> at <?php the_time('g:i a'); ?></span> <span><?php the_tags('Tags: ', ', ', ''); ?></span> </div> <?php endforeach; ?> <div class="clear"></div> <?php endwhile; else: ?> <h2>Sorry, no posts matched your criteria</h2> <?php endif; ?> <div class="clear"></div> </div> <?php get_sidebar('left'); ?> </div> <?php get_sidebar('right'); ?> <div class="clear"></div> </div> <?php get_footer(); ?>
class Box< T > { public T t; public boolean equalTo( Box< T > other) { return this.t.equals(other.t); } public Box< T > copy() { return new Box<T>(t); } public Box(T t) { this.t = t; } public void put( T t) { this.t = t;} public T take() { return t; } public boolean contains( T t) { return this.t == t; } public String toString() { return "Box["+t.toString()+"]"; } } class Test { public static void main(String[] args) { Box<Number> numberBox = new Box<Number>(0L); Box<? extends Number> unknownBox = numberBox; boolean equal = true; equal = unknownBox.equalTo(unknownBox); // error equal = unknownBox.equalTo(numberBox); // error Box<?> box1 = unknownBox.copy(); // ok Box<? extends Number> box2 = unknownBox.copy(); // ok Box<Number> box3 = unknownBox.copy(); // error } }
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from test.cinn.utils.testing import assert_llir_equal from cinn import ir, to_cinn_llir from cinn.runtime.data_array import DataArray from cinn.schedule import IRSchedule as sch def test_compute_at_elementwise(): @to_cinn_llir def elementwise_add( X: DataArray((128, 128)), Y: DataArray((128, 128)), A: DataArray((128, 128)), ): for i in range(128): for j in range(128): with ir.ScheduleBlockContext("A") as A_block: i1, j1 = ir.AxisMap("SS", [i, j]) A[i1, j1] = X[i1, j1] * 2.0 for i in range(128): for j in range(128): with ir.ScheduleBlockContext("Y"): i1, j1 = ir.AxisMap("SS", [i, j]) sch.compute_at(A_block.block, i, False) Y[i1, j1] = A[i1, j1] + 2.0 @to_cinn_llir def elementwise_add_gt( X: DataArray((128, 128)), Y: DataArray((128, 128)), A: DataArray((128, 128)), ): for i in range(128): for j in range(128): with ir.ScheduleBlockContext("A"): i1, j1 = ir.AxisMap("SS", [i, 0 + j]) A[i1, j1] = X[i1, j1] * 2.0 for k in range(128): with ir.ScheduleBlockContext("Y"): i2, k1 = ir.AxisMap("SS", [i, k]) Y[i2, k1] = A[i2, k1] + 2.0 assert_llir_equal(elementwise_add, elementwise_add_gt) def test_reverse_compute_at(): @to_cinn_llir def reverse_compute_at_tiled( A: DataArray((128, 128)), B: DataArray((128, 128)), C: DataArray((128, 128)), ): for i0 in range(8): for j0 in range(8): for i1 in range(16): for j1 in range(16): with ir.ScheduleBlockContext("B") as B_block: vi, vj = ir.AxisMap( "SS", [i0 * 16 + i1, j0 * 16 + j1] ) B[vi, vj] = A[vi, vj] * 2.0 for i in range(128): for j in range(128): with ir.ScheduleBlockContext("C") as C_block: vi, vj = ir.AxisMap("SS", [i, j]) C[vi, vj] = B[vi, vj] + 1.0 sch.reverse_compute_at(C_block.block, B_block.i1) @to_cinn_llir def reverse_compute_at_tiled_gt( A: DataArray((128, 128)), B: DataArray((128, 128)), C: DataArray((128, 128)), ): for i0 in range(8): for j0 in range(8): for i1 in range(16): for j1 in range(16): with ir.ScheduleBlockContext("B") as B_block: vi, vj = ir.AxisMap( "SS", [i0 * 16 + i1, j0 * 16 + j1] ) B[vi, vj] = A[vi, vj] * 2.0 for j2 in range(16): with ir.ScheduleBlockContext("C") as C_block: vi, vj = ir.AxisMap( "SS", [16 * i0 + i1, 16 * j0 + j2] ) C[vi, vj] = B[vi, vj] + 1.0 assert_llir_equal(reverse_compute_at_tiled, reverse_compute_at_tiled_gt) if __name__ == '__main__': test_compute_at_elementwise() test_reverse_compute_at()
package com.compose.codearticle.presentaion.screens.settingScreen.composabels import android.annotation.SuppressLint import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.compose.codearticle.presentaion.screens.settingScreen.SettingScreenViewModel import com.compose.codearticle.presentaion.screens.settingScreen.uiStates.Constants.DarkMode import com.compose.codearticle.presentaion.screens.settingScreen.uiStates.SettingItemUiState import com.compose.codearticle.presentaion.theme.Ubuntu @SuppressLint("SuspiciousIndentation", "StateFlowValueCalledInComposition") @Composable fun SettingItemCard( settingItemUiState: SettingItemUiState, settingScreenViewModel: SettingScreenViewModel, onClick: () -> Unit ) { Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clickable { onClick() } .fillMaxWidth() .padding(10.dp) ) { Box( modifier = Modifier .size(30.dp), contentAlignment = Alignment.CenterStart ) { Icon( painter = painterResource(id = settingItemUiState.icon), contentDescription = null, modifier = Modifier .size(20.dp), tint = if (settingItemUiState.settingName == "Logout") MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onBackground ) } Box( contentAlignment = Alignment.CenterStart, modifier = Modifier.weight(1f) ) { Text( text = settingItemUiState.settingName, fontSize = 15.sp, fontFamily = Ubuntu, fontWeight = FontWeight.Medium, color = if (settingItemUiState.settingName == "Logout") MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onBackground, ) } Text( text = settingItemUiState.subTitle, fontSize = 12.sp, fontFamily = Ubuntu, fontWeight = FontWeight.Normal, modifier = Modifier.padding(horizontal = 5.dp), color = MaterialTheme.colorScheme.onBackground ) if (settingItemUiState.settingName == DarkMode) { settingItemUiState.defaultBox = DefaultDarkModeBox() } else { if (settingItemUiState.settingName == "Logout") { settingItemUiState.defaultBox = null } else { settingItemUiState.defaultBox = DefaultSettingBox() } } } }
# With clauses ## Grammar These clauses use the [unreal time](/topics/parts-of-speech/verbs/conjunctive.md). ## I wish, if only 💡 kéž by, kdyby tak We can use the verb **wish** or a phrase **if only**. We can use the conjunction **that** after the verb **wish**. > **I wish** I had more time for my friends. <br/> > **If only** I could go back in time. <br/> > **I wish that** I could fly. 🔃 **I wish** I could fly. <br/> > He **wishes** he had more time for his kids. <br/> > She **wished** she could disappear. <br/> ## Wishes for the present ### Regrets 💡 že je mi líto, že mě mrzí, že něco nějak je (či není) We use a verb in the past tense. We do not use conditionals (**would**, **could**, etc.) in these clauses. > I wish I had a girlfriend. <br/> > I wish he understood me. <br/> > I wish she didn't have a boyfriend. <br/> > 🔴 I wish I would have more money. ➡ 🟢 I wish I had more money. <br/> If the verb is **be**, we can use **were** for all persons. > I wish you were here. <br/> > I wish she was here with me. 🔃 I wish she were here with me. <br/> > I wish I wasn't sick. 🔃 I wish I weren't sick. <br/> ### Wishes for something to happen 💡 přejeme, aby se něco stalo, aby někdo něco udělal (nyní nebo v budoucnu), vyčítání We use the modal verb **would** in these clauses. > I wish you would leave! 💡*Už odejdi, chci, abys už šel, tak už jdi!* <br/> > I wish they would stop fighting! 💡*Ať už přestanou ...* <br/> > I wish you wouldn't lie to me. 💡*Nelži ...* <br/> > I wish he would stop calling me. <br/> > She wishes he would quit smoking. <br/> We cannot use these clauses for persons which has the particular wish, so for example I cannot wish that I could change anything. > 🔴 I wish **I would** stop smoking. ➡ 🟢 I wish **I could** stop smoking. <br/> ## Wishes for the past ### Regrets 💡 kéž by se to bývalo nestalo, či kéž by se bývalo stalo něco jinak (samozřejmě to ale už nyní nelze změnit) We use a verb in the past perfect tense. > I wish he had told me the truth. <br/> > Now he wishes he had tried harder. <br/> > Watching you play makes me wish I hadn't given up guitar when I was a kid. <br/> > If only I had kept my mouth shut. Now everyone's mad at me. <br/> ## Wishes for the past ### Wishes for something to happen We do not use a wish clause, but a sentence with the verb **hope**. We can use either present tense or future tense after the verb **hope**, it depends on the meaning. > 🔴 I wish it's sunny tomorrow. ➡ 🟢 I hope it's sunny tomorrow. <br/> > I bought a lottery ticket. I hope I win. <br/> > I hope everything is fine. 🆚 I hope everything will be fine. <br/> ## Wish outside wish clauses Following clauses are not wish clauses. **Wish** can be used as a ✏ formal variant of the verb **want**, or in the meaning 💡* popřát někomu*. > If you wish to continue, press "ok". <br/> > The course is good for people who wish to pursue a career in financial management. <br/> > You can sit here, if you wish. <br/> > They wished me luck. <br/> > No one wished me happy birthday. <br/> > I sent a card to wish him a speedy recovery. <br/>
import SurveyCSS from "./SurveyPage.module.scss"; export default function SurveyPage() { return ( <div className={SurveyCSS["survey-page"]}> <div className={SurveyCSS.container}> <header className={SurveyCSS.header}> <h1 className={SurveyCSS.title}>Pet Ownership!</h1> <p className={SurveyCSS.description}> Are you a pet owner? Become a member of our exclusive club! </p> </header> <form className={SurveyCSS["survey-form"]}> <label id="name-label" htmlFor="name"> Name: </label> <input id="name" placeholder="Enter your name" type="text" required className={SurveyCSS.regular} /> <label id="email-label" htmlFor="email"> Email: </label> <input id="email" placeholder="Enter your email" type="email" required className={SurveyCSS.regular} /> <label id="number-label" htmlFor="number"> Number: </label> <input id="number" placeholder="Enter your number" type="number" min="100000" max="9999999999" className={SurveyCSS.regular} /> <p> How much experience do you have with owning a pet?</p> <select className={SurveyCSS.dropdown} title="experience with pets"> <option value="none">No Experience</option> <option value="little">Some Experience</option> <option value="experienced"> Experienced </option> </select> <p> Would you like to join our newsletter?</p> <div className={SurveyCSS.radio}> <label> <input name="join" value="yes" type="radio" title="join" defaultChecked /> Yes </label> <label> <input name="join" value="no" type="radio" title="don't join" /> No </label> </div> <p> What types of pets do you have?</p> <div className={SurveyCSS.checkboxes}> <label htmlFor="dogs"> <input name="dogs" value="dogs" type="checkbox" /> Dogs </label> <label htmlFor="cats"> <input name="cats" value="cats" type="checkbox" /> Cats </label> <label htmlFor="fish"> <input name="fish" value="fish" type="checkbox" /> Fish </label> </div> <p>Any Addditional Comments? </p> <textarea title="comments" className={SurveyCSS.textarea} /> <label htmlFor="submit"> <input className={SurveyCSS.submit} name="submit" type="submit" /> </label> </form> </div> </div> ); }
Want to customize the various linters Stickler CI uses? This page contains reference documentation on how to customize each of the tools that Stickler offers. If you're still looking for answers, please tweet us @sticklerci or email us at support@stickler-ci.com. Stickler CI is configured through a file in your repository. This file controls which linters are enabled and what their options are. Put your file in the root directory of your project. An example file is In this example we've enabled , , and . We are using a custom config file for jscs, and have ignored all files in and . In addition to configuring specific linters, you can also configure how Stickler CI inspects your code: An example of the above config options would be: The above would not review any pull requests against the or branches, and also ignore any in and all files in . A number of languages have de-facto linters in use. To save you having to always enable these linters, Stickler CI provides a base configuration file for every repository. The default configuration enables , , , and . It also ignores files in , , and . If you want to disable one of the default linters, you can do so using the attribute: The above would disable the linter which is enabled by default. Check bash, zsh and sh scripts with shellcheck for lint and common mistakes. Both warnings and errors will be turned into code review comments. If you don't want code review comments for specific rules, you should ignore them via the option. Check Javascript with JSCS. If you don't supply a config file or a preset, the default JSCS rules will be used. Check Javascript code with jshint. If you don't supply a config file the jshint defaults will be used. Check Javascript, and JSX code with eslint. In addition to the core ESLint rules, we also provide popular modules for React and Ember.js To get started linting React applications, you can use the following ESLint configuration: To start linting Ember.js projects, you can use the following ESLint configuration: If there is a preset you'd like to see support for drop us a line. Use StandardJs to check Javascript. Standard offers easy to use style rules with no configuration to manage. Check PHP, Javascript and or CSS code with phpcs. Check puppet manifests with puppet-lint, against the puppetlabs style guide. files will be respected, to allow each project to disable checks. A list of checks can be found by running locally. files will be respected, as described here. Check typescript code with tslint. You need to include a configuration file in your project or use the option to provide a path to a config file. Check YAML files with yamllint. This is handy to examine confiugration files for many tools, and heira data in puppet. Please tweet at us @sticklerci or email us at support@stickler-ci.com and we will help you out.|||
# 第五章:攻击后 - 对目标的行动 在现代黑客和系统攻击的世界中,攻击者不太关心利用,而是关心可以利用该访问权限做什么。这是攻击者实现攻击的全部价值的部分。 一旦系统被攻击,攻击者通常执行以下活动: + 进行快速评估以表征本地环境(基础设施、连接性、帐户、目标文件的存在以及可以促进进一步攻击的应用程序) + 定位并复制或修改感兴趣的目标文件,如数据文件(专有数据和财务信息) + 创建额外的帐户并修改系统以支持后期利用活动 + 尝试通过捕获管理员或系统级凭据来垂直升级用于访问的特权级别 + 尝试通过受损系统将攻击转移到网络的其余部分来攻击其他数据系统(水平升级) + 安装持久后门和隐蔽通道,以保持控制并与受损系统进行安全通信(在第六章中介绍了这一点,*后期利用-持久性*) + 从受损系统中删除攻击的迹象 要成功,后期利用活动需要对目标操作系统和文件结构有全面的了解,以确保可以绕过保护控制。第一步是在本地网络环境中对受损系统进行侦察。 在本章中,您将学到以下内容: + 如何绕过 Windows 用户账户控制(UAC) + 如何对受损系统进行快速侦察 + 如何从受损系统获取敏感数据(掠夺) + 如何创建额外的账户 + 如何使用 Metasploit Framework 进行后期利用活动 + 垂直和水平升级技术,以提高您的访问权限并增加受损账户的数量 + 如何使用反取证技术掩盖踪迹,防止发现受损 # 绕过 Windows 用户账户控制 在 Windows Vista 及更高版本中,微软引入了安全控制,限制进程以三种不同的完整性级别运行:高、中和低。高完整性进程具有管理员权限,中级进程以标准用户权限运行,低完整性进程受限,强制要求程序在受损时造成最小的损害。 要执行任何特权操作,程序必须以管理员身份运行,并遵守 UAC 设置。四个 UAC 设置如下: + **始终通知**:这是最严格的设置,当任何程序想要使用更高级别的权限时,它将提示本地用户。 + **只在程序尝试对计算机进行更改时通知我**:这是默认的 UAC 设置。当本机 Windows 程序请求更高级别的权限时,它不会提示用户。但是,如果第三方程序想要提升权限,它将提示。 + **只在程序尝试对计算机进行更改时通知我(不使我的桌面变暗)**:这与默认设置相同,但在提示用户时不会使系统的监视器变暗。 + **从不通知**:此选项将系统恢复到 Vista 之前的状态。如果用户是管理员,所有程序都将以高完整性运行。 因此,在利用后立即,测试人员(和攻击者)希望了解以下两件事: + 系统识别的用户是谁? + 他们在系统上有什么权限? 可以使用以下命令确定: ``` C:\> whoami /groups ``` 受损系统正在高完整性环境中运行,如下截图中的“强制标签\高强制级别标签”所示: ![绕过 Windows 用户账户控制](img/3121OS_05_01.jpg) 如果“标签”是“强制标签\中等强制级别”,测试人员需要将标准用户权限提升为管理员权限,以便许多后期利用步骤能够成功。 提升权限的第一个选项是从 Metasploit 运行`exploit/windows/local/ask`,这将启动`RunAs`攻击。这将创建一个可执行文件,当调用时,将运行一个程序来请求提升的权限。可执行文件应使用`EXE::Custom`选项创建,或者使用`Veil-Evasion`加密,以避免本地杀毒软件的检测。 `RunAs`攻击的缺点是用户将收到警告,即来自未知发布者的程序想要对计算机进行更改。此警报可能导致特权升级被识别为攻击。 如果系统的当前用户属于管理员组,并且 UAC 设置为默认的“仅在程序尝试更改计算机时通知我”(如果设置为“始终通知”则不起作用),攻击者将能够使用 Metasploit `exploit/windows/local/bypassuac`模块来提升其权限。 `bypassuac`模块在目标系统上创建多个工件,并且大多数防病毒软件都能识别。但是,`exploit/windows/local/bypassuac_inject`模块将可执行文件直接放入运行内存中的反射 DLL 中,并且不会触及硬盘,最大程度地减少了被防病毒软件检测到的机会。 尝试绕过 UAC 控制时的一些注意事项如下: + 绕过 UAC 攻击不适用于 Windows Vista,用户需要确认每个特权访问。 + Windows 8 仍然容易受到这种攻击。但是,Metasploit Framework 攻击目前不适用于 Windows 8.1。如果尝试,用户将被提示点击“确定”按钮,然后攻击才能获得提升的特权——这几乎不是一个隐秘的攻击。攻击者可以通过选择使用`exploit/windows/local/ask`来修改攻击,这将提高成功的机会。 + 在考虑系统间移动(水平/横向升级)时,如果当前用户是域用户,并且在其他系统上具有本地管理员特权,您可以使用现有的身份验证令牌来获取访问权限并绕过 UAC。实现这一点的常见攻击是 Metasploit `exploit/windows/local/current_user_psexec`。 # 对受损系统进行快速侦察 一旦系统被攻击,攻击者需要获取有关该系统、其网络环境、用户和用户帐户的关键信息。通常,他们将从 shell 提示符输入一系列命令或调用这些命令的脚本。 如果受损系统基于 Unix 平台,则典型的本地侦察命令将包括以下内容: | 命令 | 描述 | | --- | --- | | `/etc/resolv.conf` | 使用`copy`命令访问和查看系统当前的 DNS 设置。因为它是一个具有读权限的全局文件,所以在访问时不会触发警报。 | | `/etc/passwd`和`/etc/shadow` | 这些是包含用户名和密码哈希的系统文件。具有根级访问权限的人可以复制它,并可以使用诸如 John the Ripper 之类的工具来破解密码。 | | `whoami and who -a` | 识别本地系统上的用户。 | | `ifconfig -a`,`iptables -L -n`和`netstat -r` | 提供网络信息。`ifconfig -a`提供 IP 地址详细信息,`iptables -L -n`列出本地防火墙中保存的所有规则(如果存在),`netstat -r`显示内核维护的路由信息。 | | `uname -a` | 打印内核版本。 | | `ps aux` | 打印当前运行的服务、进程 ID 和其他信息。 | | `dpkg -l yum list &#124; grep installed`和`dpkg -l rpm -qa --last &#124; head` | 识别已安装的软件包。 | 这些命令包含了可用选项的简要概述。有关如何使用它的完整信息,请参考相应命令的帮助文件。 对于 Windows 系统,将输入以下命令: | 命令 | 描述 | | --- | --- | | `whoami /all` | 列出当前用户、SID、用户特权和组。 | | `ipconfig /all`和`ipconfig /displaydns` | 显示有关网络接口、连接协议和本地 DNS 缓存的信息。 | | `netstat -bnao`和`netstat -r` | 列出端口和连接以及相应的进程(`-b`)到无查找(`-n`),所有连接(`-a`)和父进程 ID(`-o`)。`-r`选项显示路由表。它们需要管理员权限才能运行。 | | `net view` 和 `net view /domain` | 查询 NBNS/SMB 以定位当前工作组或域中的所有主机。使用 `/domain` 可以获取主机可用的所有域。 | | `net user /domain` | 列出定义域中的所有用户。 | | `net user %username% /domain` | 如果用户是查询的域的一部分,则获取有关当前用户的信息(如果您是本地用户,则不需要 `/domain`)。它包括登录时间、上次更改密码的时间、登录脚本和组成员资格。 | | `net accounts` | 打印本地系统的密码策略。要打印域的密码策略,请使用 `net accounts /domain`。 | | `net localgroup administrators` | 打印管理员本地组的成员。使用 `/domain` 开关获取当前域的管理员。 | | `net group "Domain Controllers" /domain` | 打印当前域的域控制器列表。 | | `net share` | 显示当前共享的文件夹,这些文件夹中共享的数据可能没有足够的访问控制,并显示它们指向的路径。 | ## 使用 WMIC 脚本语言 在较新的系统上,攻击者和渗透测试人员利用内置的脚本语言,例如**Windows 管理规范命令行**(**WMIC**),这是一个用于简化访问 Windows 管理的命令行和脚本接口。如果受损系统支持 WMIC,则可以使用多个命令来收集信息。参考以下表格: | 命令 | 描述 | | --- | --- | | `wmic nicconfig get ipaddress,macaddress` | 获取 IP 地址和 MAC 地址 | | `wmic computersystem get username` | 验证被 compromise 的帐户 | | `wmic netlogin get name, lastlogon` | 确定谁最后使用了这个系统以及他们上次登录的时间 | | `wmic desktop get screensaversecure, screensavertimeout` | 确定屏幕保护程序是否受密码保护以及超时时间 | | `wmic logon get authenticationpackage` | 确定支持哪些登录方法 | | `wmic process get caption, executablepath, commandline` | 识别系统进程 | | `wmic process where name="process_name" call terminate` | 终止特定进程 | | `wmic os get name, servicepackmajorversion` | 确定系统的操作系统 | | `wmic product get name, version` | 识别已安装的软件 | | `wmic product where name="name' call uninstall /nointeractive` | 卸载或移除已定义的软件包 | | `wmic share get /ALL` | 识别用户可访问的共享 | | `wmic /node:"machinename" path Win32_TerminalServiceSetting where AllowTSConnections="0" call SetAllowTSConnections "1"` | 远程启动 RDP | | `wmic nteventlog get path, filename, writeable` | 查找所有系统事件日志,并确保它们可以被修改(在覆盖痕迹时使用) | PowerShell 是建立在.NET Framework 上的脚本语言,从控制台运行,使用户可以访问 Windows 文件系统和诸如注册表之类的对象。它默认安装在 Windows 7 操作系统和更高版本上。PowerShell 通过允许在本地和远程目标上使用 shell 集成和互操作性,扩展了 WMIC 提供的脚本支持和自动化。 PowerShell 为测试人员提供了对受损系统上的 shell 和脚本语言的访问。由于它是 Windows 操作系统的本机功能,其命令的使用不会触发防病毒软件。当在远程系统上运行脚本时,PowerShell 不会写入磁盘,从而绕过防病毒软件和白名单控制(假设用户已允许使用 PowerShell)。 PowerShell 支持许多内置函数,称为 cmdlet。PowerShell 的一个优点是 cmdlet 被别名为常见的 Unix 命令,因此输入`ls`命令将返回典型的目录列表,如下面的屏幕截图所示: !使用 WMIC 脚本语言 PowerShell 是一种功能丰富的语言,能够支持非常复杂的操作;建议用户花时间熟悉其使用。以下表格描述了一些可以在受损后立即使用的较简单的命令: | 命令 | 描述 | | --- | --- | | `Get-Host &#124; Select Version` | 识别受害者系统使用的 PowerShell 版本。一些 cmdlet 在不同版本中被添加或调用。 | | `Get-Hotfix` | 识别已安装的安全补丁和系统热修复。 | | `Get-Acl` | 识别组名和用户名。 | | `Get-Process, Get-Service` | 列出当前的进程和服务。 | | `gwmi win32_useraccount` | 调用 WMI 列出用户帐户。 | | `Gwmi_win32_group` | 调用 WMI 列出 SID、名称和域组。 | 渗透测试人员可以将 Windows 本机命令、DLL、.NET 函数、WMI 调用和 PowerShell cmdlet 结合在一起,创建扩展名为`.ps1`的 PowerShell 脚本。 ### 提示 在最近的渗透测试中,我们被禁止在客户系统上安装任何可执行软件。我们在一个受损的系统上使用了一个 PowerShell 键盘记录器来获取管理员级别的凭据,然后侵入了网络上的大多数系统。最有效的利用和后利用脚本,包括键盘记录器,都是 Nikhil Mittal 的`Nishang`包的一部分([`code.google.com/p/nishang/downloads/detail?name=nishang_0.3.0.zip`](https://code.google.com/p/nishang/downloads/detail?name=nishang_0.3.0.zip))。 侦察还应扩展到本地网络。由于您是“盲目”的,您需要创建一个可以与受损主机通信的活动系统和子网的地图。首先,在 shell 提示符中输入`IFCONFIG`(基于 Unix 的系统)或`IPCONFIG /ALL`(Windows 系统)。这将允许攻击者确定以下内容: + 是否启用了 DHCP 寻址。 + 本地 IP 地址,这也将识别至少一个活动子网。 + 网关 IP 地址和 DNS 服务器地址。系统管理员通常在整个网络上遵循编号约定,如果攻击者知道一个地址,比如网关服务器`172.16.21.5`,他们将 ping 地址,比如`172.16.20.5`,`172.16.22.5`等等,以找到其他子网。 + 用于利用**Active Directory**账户的域名。 如果攻击系统和目标系统都使用 Windows,则可以使用`net view`命令枚举网络上的其他 Windows 系统。攻击者使用`netstat -rn`命令来查看路由表,其中可能包含对感兴趣的网络或系统的静态路由。 可以使用`nmap`扫描本地网络以嗅探 ARP 广播。此外,Kali 还有几个工具可用于 SNMP 端点分析,包括`nmap`、`onesixtyone`和`snmpcheck`。 部署数据包嗅探器以映射流量将帮助您识别主机名、活动子网和域名。如果未启用 DHCP 寻址,它还将允许攻击者识别任何未使用的静态 IP 地址。Kali 预配置了 Wireshark(基于 GUI 的数据包嗅探器),但您也可以在后利用脚本中或从命令行中使用`tshark`,如下面的屏幕截图所示: !使用 WMIC 脚本语言 # 查找和获取敏感数据-掠夺目标 术语**掠夺**(有时被称为**偷窃**)是黑客成功侵入系统后,将自己视为海盗,竞相赶到目标地点窃取或破坏尽可能多的数据的遗留物。这些术语作为参考,仍然存在,用于指代在实现利用的目标后,更加谨慎地窃取或修改专有或财务数据的做法。 然后,攻击者可以专注于次要目标——提供信息以支持额外攻击的系统文件。次要文件的选择将取决于目标的操作系统。例如,如果受损的系统是 Unix,则攻击者还将针对以下目标: + 系统和配置文件(通常在`/etc`目录中,但根据实现方式,它们可能在`/usr/local/etc`或其他位置) + 密码文件(`/etc/password`和`/etc/shadow`) + `.ssh`目录中的配置文件和公钥/私钥 + `.gnupg`目录中可能包含的公钥和私钥环 + 电子邮件和数据文件 在 Windows 系统中,攻击者将针对以下目标: + 系统内存,可用于提取密码、加密密钥等。 + 系统注册表文件 + 包含密码的**安全账户管理器**(**SAM**)数据库的哈希版本,或者可能在`%SYSTEMROOT%\repair\SAM`和`%SYSTEMROOT%\System32\config\RegBack\SAM`中找到的 SAM 数据库的其他版本 + 用于加密的任何其他密码或种子文件 + 电子邮件和数据文件 ### 提示 不要忘记查看包含临时项目的文件夹,例如附件。例如,`UserProfile\AppData\Local\Microsoft\Windows\Temporary Internet Files\`可能包含感兴趣的文件、图像和 Cookie。 如前所述,系统内存对于任何攻击者来说包含大量信息。因此,通常是您需要获取的优先文件。系统内存可以从以下几个来源下载为单个镜像文件: + 通过上传工具到受损系统,然后直接复制内存(工具包括**Belkasoft RAM capturer**、**MandiantMemoryze**和**MonsolsDumpIt**)。 + 通过复制 Windows 休眠文件`hiberfil.sys`,然后使用 Kali 中的`取证`菜单中的 Volatility 来解密和分析文件。Volatility 是一个框架,用于分析系统 RAM 和其他包含系统内存的文件的内存转储。它依赖于用 Python 编写的插件来分析内存并提取数据,如加密密钥、密码、注册表信息、进程和连接信息。 + 通过复制虚拟机并将 VMEM 文件转换为内存文件。 ### 提示 如果您将设计用于捕获内存的程序上传到受损系统,可能会被防病毒软件识别为恶意软件。大多数防病毒软件应用程序会识别内存获取软件的哈希签名和行为,并在内存内容面临泄露风险时发出警报以保护敏感内容。获取软件将被隔离,并且目标将收到警报,提醒他们受到攻击。 为了避免这种情况,使用 Metasploit Framework 在目标的内存中完全运行可执行文件,使用以下命令: ``` meterpreter> execute -H -m -d calc.exe -f <memoryexecutable + parameters> ``` 先前的命令将`calc.exe`作为虚拟可执行文件执行,但上传内存获取可执行文件以在其进程空间中运行。 可执行文件不会显示在诸如任务管理器之类的进程列表中,使用数据取证技术进行检测要困难得多,因为它没有写入磁盘。此外,它将避开系统的防病毒软件,因为通常不会扫描内存空间以寻找恶意软件。 一旦物理内存被下载,就可以使用 Volatility Framework 对其进行分析,这是一组用于法庭取证分析内存的 Python 脚本集。如果操作系统受支持,Volatility 将扫描内存文件并提取以下内容: + 足以将图像与其源系统*联系*起来的图像信息和系统数据。 + 运行的进程、加载的 DLL、线程、套接字、连接和模块。 + 打开的网络套接字和连接,以及最近打开的网络连接。 + 内存地址,包括物理和虚拟内存映射。 + LM/NTLM 哈希和 LSA 秘密。**LanMan**(**LM**)密码哈希是微软最初尝试保护密码的方法。多年来,它变得很容易破解,并将哈希转换回实际密码。**NT LanMan**(**NTLM**)哈希是更近期的,对攻击更有韧性。然而,它们通常与 NTLM 版本一起存储,以实现向后兼容性的目的。**本地安全机构**(**LSA**)存储本地密码的“秘密”:远程访问(有线或无线)、VPN、自动登录密码等。系统上存储的任何密码都是脆弱的,特别是如果用户重复使用密码。 + 存储在内存中的特定正则表达式或字符串。 使用感染了 Zeus 恶意软件的系统的示例图像([`code.google.com/p/volatility/wiki/SampleMemoryImages`](https://code.google.com/p/volatility/wiki/SampleMemoryImages)),我们将使用 Volatility Framework 来提取加密的 LanMan 密码哈希。 第一步是使用以下命令确定图像类型和操作系统: ``` root@kali:usr/share/volatility# python vol.py imageinfo -f /root/Desktop/zeus.vmem ``` 上一条命令的执行如下截图所示: ![查找和获取敏感数据-掠夺目标](img/3121OS_05_04.jpg) **hivelist**插件将在调用以下命令时打印出各个注册表蜂巢的初始虚拟内存位置: ``` root@kali:usr/share/volatility#python vol.py hivelist -f /root/Desktop/zeus.vmem ``` 上一条命令的执行如下截图所示: ![查找和获取敏感数据-掠夺目标](img/3121OS_05_05.jpg) 为了转储哈希,需要 SAM 和 SYSTEM 蜂巢的初始虚拟内存位置。使用以下命令,结果被导入到逗号分隔的文件中,以便由密码破解应用程序直接导入: ``` root@kali:usr/share/volatility#python vol.py hashdump -f /root/Desktop/zeus.vmem -y 0xe101b008 -s 0xe1544008 >>/root/Desktop/hashdump.csv ``` 上一条命令的执行如下截图所示: ![查找和获取敏感数据-掠夺目标](img/3121OS_05_06.jpg) 孤立的 LM 哈希可以使用 Hashcat、John the Ripper、Ophcrack 和 Rainbow Tables 进行破解。 # 创建额外的帐户 以下命令是高度侵入性的,通常会在事件响应过程中被系统所有者检测到。然而,它们经常被攻击者植入,以转移对更持久的访问机制的注意力。请参阅以下表格: | 命令 | 描述 | | --- | --- | | `net user attacker password /add` | 创建一个名为`attacker`的新本地帐户,密码为`password`。 | | `net localgroup administrators attacker /add` | 将新用户`attacker`添加到本地管理员组。在某些情况下,命令将是`net localgroup administrators /add attacker`。 | | `net user username /active:yes /domain` | 将非活动或禁用的帐户更改为活动状态。在小型组织中,这将引起注意。密码管理不善的大型企业可能有 30%的密码被标记为“非活动”,因此这可能是一种获得帐户的有效方式。 | | `net share name$=C:\ /grant:attacker,FULL /unlimited` | 将`C:`(或其他指定的驱动器)共享为 Windows 共享,并授予用户(攻击者)对该驱动器上所有内容的完全访问或修改权限。 | 如果创建一个新用户帐户,当有人登录到受损系统的欢迎屏幕时会被注意到。要使帐户不可见,您需要使用以下`REG`命令从命令行修改注册表: ``` REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion \WinLogon\SpecialAccounts\UserList /V account_name / T REG_DWORD /D 0 ``` 这将修改指定的注册表键以隐藏用户的帐户(`/V`)。同样,根据目标操作系统的具体版本可能有特殊的语法要求,因此首先确定 Windows 版本,然后在受控测试环境中验证它,然后再对目标实施。 # 使用 Metasploit 进行后渗透活动 Metasploit 被开发用于支持利用和后渗透活动。当前版本包含大约 200 个模块,简化了后渗透活动。我们将回顾一些最重要的模块。 在下面的屏幕截图中,我们成功地利用了 Windows XP 系统(这是一个经常用于验证`meterpreter`更复杂方面的“经典”攻击)。初始步骤是立即对网络和受损系统进行侦察。 初始的`meterpreter` shell 很脆弱,容易在较长时间内失败。因此,一旦系统被利用,我们将迁移 shell 并将其绑定到更稳定的进程上。这也使得检测利用更加困难。 在`meterpreter`提示符下,输入`ps`以获取正在运行的进程列表,如下面的屏幕截图所示: ![使用 Metasploit 进行后渗透活动](img/3121OS_05_07.jpg) `ps`命令还返回每个进程的完整路径名。这在之前的屏幕截图中被省略了。`ps`列表确定`c:\windows\Explorer.EXE`正在运行。在这种特殊情况下,它被标识为进程 ID`1460`,如下面的屏幕截图所示。由于这是一个通常稳定的应用程序,我们将把 shell 迁移到该进程。 ![使用 Metasploit 进行后渗透活动](img/3121OS_05_08.jpg) 现在我们已经与远程系统建立了稳定的 shell 连接,我们将使用支持后渗透活动的`meterpreter`脚本。 要识别的第一个参数之一是:我们是否在虚拟机上?在受损系统和攻击者之间打开`meterpreter`会话后,发出命令`run checkvm`,如下面的屏幕截图所示。返回的数据表明`这是一个 VMware 虚拟机`。 ![使用 Metasploit 进行后渗透活动](img/3121OS_05_09.jpg) 通过`meterpreter`可用的一些最重要的后渗透模块在下表中描述: | 命令 | 描述 | | --- | --- | | `run checkvm` | 确定虚拟机是否存在。 | | `run getcountermeasure` | 检查受损系统的安全配置(防病毒软件、防火墙等)。 | | `run killav` | 禁用运行在受损系统上的大多数防病毒服务。这个脚本经常过时,成功应该手动验证。 | | `run hostsedit` | 允许攻击者向 Windows `HOSTS`文件添加条目。这可以将流量转向不同的站点(一个假站点),该站点将下载其他工具或确保防病毒软件无法连接到互联网或本地服务器以获取签名更新。 | | `run winenum` | 执行受损系统的命令行和 WMIC 特性描述。它从注册表和 LM 哈希中转储重要的键。 | | `run scraper` | 收集其他脚本未收集的全面信息,例如整个 Windows 注册表。 | | `run upload` 和 `run download` | 允许攻击者在目标系统上上传和下载文件。 | | `run keyscan_start`、`run keyscan_stop` 和 `run keyscan_dump` | 在受损系统上启动和停止本地键盘记录器。当数据收集完成时,收集的文本数据将被转储到攻击者的系统上。 | | `run getprivs` | 尝试启用当前进程可用的所有权限。对于权限提升非常有用。 | | `run getsystem` | 尝试将权限提升到 Windows `SYSTEM`级别;授予用户最大可能的权限提升。 | | `Run hashdump` | 转储攻击者系统上 SAM 数据库的内容。 | | `run getgui` | 允许用户启用 RDP(`getgui -e`)并设置用户名和密码(`getgui -u`)。`gettelnet`脚本可以以相同的方式运行。 | | `run vnc` | 为攻击者提供对受损系统的远程 GUI(VNC)访问。 | 最有效的`meterpreter`脚本之一是**Windows 枚举器**(**winenum**)。如下图所示,它使用命令行和 WMIC 调用来完全描述目标系统: ![使用 Metasploit 进行后渗透活动](img/3121OS_05_10.jpg) 除了枚举,`winenum`脚本还会转储注册表并收集系统哈希以便解密,如下面的屏幕截图所示: ![使用 Metasploit 进行后渗透活动](img/3121OS_05_11.jpg) `meterpreter`附带了几个支持复杂功能的有用库。例如,`espia`库支持通过以下命令对受损系统进行截屏: ``` meterpreter> use espia Loading extension espia ... success. meterpreter> screenshot /Desktop/target.jpeg Screenshot saved to: /root/xsWoDDbW.jpeg ``` `stdapi`库允许远程攻击者通过收集受损系统的音频和视频来操纵网络摄像头,并将数据传送回攻击者。 # 提升受损主机上的用户权限 通常可以获得对系统的“访客”或“用户”访问权限。攻击者通常受到降低的权限级别的限制,因此,常见的后渗透活动是从“访客”提升访问权限到“用户”再到“管理员”,最终到“系统”。获得访问权限的这种上升过程通常被称为**垂直提升**。 用户可以实施多种方法来获取高级访问凭据,包括以下内容: + 使用网络嗅探器和/或键盘记录器来捕获传输的用户凭据(`dsniff`旨在从实时传输或从 Wireshark 或 tshark 会话保存的`pcap`文件中提取密码)。 + 搜索本地存储的密码。一些用户会在电子邮件文件夹中收集密码(通常称为“密码”)。由于密码重用和简单的密码构建系统很常见,因此在提升过程中找到的密码可以被使用。 NirSoft([www.nirsoft.net](http://www.nirsoft.net))制作了几个免费工具,可以使用`meterpreter`上传到受损系统,从操作系统和缓存密码的应用程序(邮件、远程访问软件、FTP 和 Web 浏览器)中提取密码。 + 使用`meterpreter`或应用程序(如**hobocopy**、**fgdump**和**pwdump**)转储`SAM`和`SYSKEY`文件(这些可以使用`meterpreter`上传到目标)。 + 使用诸如进程注入器([www.tarasco.org/security/Process_Injector/](http://www.tarasco.org/security/Process_Injector/))之类的工具,直接将恶意代码注入到在`SYSTEM`级别运行的服务中。 + 当一些应用程序加载时,它们会按特定顺序读取**动态链接库**(**DLL**)文件。可以创建一个与合法 DLL 同名的伪造 DLL,将其放置在特定目录位置,并让应用程序加载和执行它,从而使攻击者获得提升的权限。已知有几个应用程序容易受到此类 DLL 劫持的影响([www.exploit-db.com/dll-hijacking-vulnerable-applications/](http://www.exploit-db.com/dll-hijacking-vulnerable-applications/))。 + 应用使用缓冲区溢出或其他手段来提升权限的漏洞利用。 + 执行`getsystem`脚本,将自动将管理员权限提升到`SYSTEM`级别,从`meterpreter`提示符中执行。 ### 提示 Windows 7 和 2008 不允许从不受信任的系统远程访问管理共享,如`ADMIN$`、`C$`等。这些共享可能需要`meterpreter`脚本(如 incognito)或支持通过 SMB 进行攻击。为了解决这个问题,将`HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`添加到注册表,并添加一个名为`LocalAccountTokenFilterPolicy`的新 DWORD(32 位)键,并将值设置为`1`。 # 使用隐身模式重播身份验证令牌 一个特别有趣的`meterpreter`库是`incognito`,它允许你模拟和重播用户令牌。令牌是临时密钥,允许你访问网络和系统资源,而无需在每次特定访问时提供密码或其他凭据。这些令牌在系统重启之前会持续存在。 一旦你妥协了一个系统,你可以使用令牌模拟之前创建令牌的用户,而无需破解用户的密码。这种令牌模拟可能允许攻击者提升他们的权限。 在提示符中输入以下内容: ``` use incognito ``` 执行前面的命令的结果如下截屏所示: ![使用隐身模式重播身份验证令牌](img/3121OS_05_12.jpg) 第一步是识别受损系统上存在的所有有效令牌。你能看到的令牌数量将取决于最初用于妥协目标系统的访问级别。 你还会看到有两种类型的令牌,如下面的截屏所示。委派令牌支持交互式登录(例如,本地登录系统或通过远程桌面登录)。模拟令牌用于非交互式会话,例如当系统连接到网络驱动器时。 ![使用隐身模式重播身份验证令牌](img/3121OS_05_13.jpg) 如你所见,一个委派令牌被识别为`管理员`。如果我们可以模拟这个令牌,我们就可以获得它的权限。 在`incognito`中调用`impersonate_token`命令(如下面的截屏所示),请注意命令中需要两个反斜杠: ![使用隐身模式重播身份验证令牌](img/3121OS_05_14.jpg) 现在,如果我们从`meterpreter`提示符中运行 shell 命令并输入`whoami`,它会将我们标识为我们模拟的管理员令牌。 ## 使用 Windows 凭据编辑器操纵访问凭据 **Windows 凭据编辑器**(**WCE**)—[`www.ampliasecurity.com/research/wcefaq.html`](http://www.ampliasecurity.com/research/wcefaq.html)—是`incognito`脚本的改进版本。它有 32 位和 64 位版本,以及声称可在所有 Windows 平台上工作的“通用”版本。WCE 允许用户做以下事情: + 对 Windows 系统执行传递哈希攻击 + 从系统内存中收集 NTLM 凭据(带或不带代码注入) + 从 Windows 系统收集 Kerberos 票据 + 使用收集到的 Kerberos 票据在其他 Windows 或 Unix 系统上获取访问权限 + 转储 Windows 系统存储的明文密码(见下一节) 要使用 WCE,从`meterpreter`提示符上传可执行文件到受损系统。然后,启动交互式 shell 并执行 WCE。如下面的截屏所示,`-w`选项轻松提取了明文`管理员`密码: ![使用 Windows 凭据编辑器操纵访问凭据](img/3121OS_05_15.jpg) ## 从管理员升级到 SYSTEM 管理员权限允许攻击者创建和管理帐户,并访问系统上可用的大部分数据。然而,一些复杂的功能要求请求者具有`SYSTEM`级别的访问权限。有几种方法可以继续将权限升级到`SYSTEM`级别。最常见的方法是使用`at`命令,Windows 用它来安排特定时间的任务。`at`命令始终以`SYSTEM`级别的权限运行。 使用交互式 shell(在`meterpreter`提示符下输入`shell`),打开命令提示符并确定受损系统的本地时间。如果时间是下午 12:50(`at`函数使用 24 小时制),则安排一个交互式命令 shell 在稍后的时间运行,如下面的屏幕截图所示: ![从管理员升级到 SYSTEM](img/3121OS_05_16.jpg) 在安排`at`任务运行后,在`meterpreter`提示符下重新确认您的访问权限,如下面的屏幕截图所示: ![从管理员升级到 SYSTEM](img/3121OS_05_17.jpg) 如您所见,权限已被提升到`SYSTEM`级别。 # 使用水平升级访问新账户 在水平升级中,攻击者保留其现有凭据,但使用它们来操作不同用户的帐户。例如,受损系统 A 上的用户攻击系统 B 上的用户,试图对其进行攻击。 当我们审查一些攻击向量时,我们将使用水平升级攻击。 # 掩盖你的行踪 一旦系统被利用,攻击者必须掩盖自己的行踪,以避免被发现,或者至少使事件的重建对防御者更加困难。 攻击者可以完全删除 Windows 事件日志(如果它们正在被活跃地保留在受损的服务器上)。这可以通过系统的命令行和以下命令来完成: ``` C:\ del %WINDIR%\*.log /a/s/q/f ``` 该命令指示删除所有日志(`/a`),包括所有子文件夹中的文件(`/s`)。`/q`选项禁用所有查询,要求*是*或*否*的响应,`/f`选项强制删除文件,使恢复更加困难。 这也可以通过在`meterpreter`提示符下发出`clearev`命令来完成。这将清除目标系统的应用程序、系统和安全日志(此命令没有选项或参数)。 通常情况下,删除系统日志不会触发用户的任何警报。事实上,大多数组织配置日志记录是如此随意,以至于缺少系统日志被视为可能发生的情况,它们的丢失并不会受到深入调查。 Metasploit 还有一个额外的技巧——`timestomp`选项允许攻击者更改文件的 MACE 参数(文件的最后修改时间、访问时间、创建时间和 MFT 条目修改时间)。一旦系统被攻破并建立了`meterpreter` shell,就可以调用`timestomp`,如下面的屏幕截图所示: ![掩盖你的行踪](img/3121OS_05_18.jpg) 例如,受损系统的`C:`包含一个名为`README.txt`的文件。该文件的 MACE 值表明它是最近创建的,如下面的屏幕截图所示: ![掩盖你的行踪](img/3121OS_05_19.jpg) 如果我们想隐藏这个文件,可以将它移动到一个杂乱的目录,比如`windows\system32`。然而,任何按照创建日期或其他基于 MAC 的变量对该目录的内容进行排序的人都会发现这个文件。因此,要将`cmd.exe`文件的 MAC 信息复制到`README.txt`文件中,请使用以下命令: ``` meterpreter>timestomp README.txt -f C:\\WINDOWS\system32\cmd.exe ``` 我们还可以选择使用`-b`开关来清除 MAC 数据。如下面的屏幕截图所示,我们选择将 MAC 数据更改为未来的时间(2106 年)。 ![掩盖你的行踪](img/3121OS_05_20.jpg) 这样的更改会引起调查人员的注意,但他们将无法使用数据进行法证分析。原始 Windows 平台的属性是什么样子的?如果系统管理员调用文件的系统属性,创建和修改日期已经改回到 1601 年(微软用作初始系统启动时间的日期)。相比之下,文件的最后访问时间保持准确。您可以在以下截图中看到: ![掩盖你的踪迹](img/3121OS_05_21.jpg) 尽管这是预期行为,但它仍然为调查人员提供线索。为了完全破坏调查,攻击者可以使用以下命令递归更改目录或特定驱动器上的所有设置时间: ``` meterpreter>timestompC:\\ -r ``` 解决方案并不完美。很明显发生了攻击。此外,时间戳可能会保留在硬盘的其他位置,并可供调查人员访问。如果目标系统正在使用入侵检测系统(如 Tripwire)积极监控系统完整性的变化,将生成`timestomp`活动的警报。因此,在真正需要隐蔽方法时,销毁时间戳的价值有限。 # 摘要 在这一章中,我们关注的是目标系统被利用后紧随其后的行动。我们回顾了对服务器和本地环境进行的初步快速评估。我们还学会了如何识别和定位感兴趣的目标文件,创建用户账户,执行垂直升级以提高访问权限,并消除入侵迹象。 在下一章中,我们将学习如何实施持久后门以保留访问权限,并学习支持与被攻击系统进行隐蔽通信的技术。
// Copyright (c) 2018-2023 Made to Order Software Corp. All Rights Reserved // // https://snapwebsites.org/project/snapdev // contact@m2osw.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /** \file * \brief Verify that the chownnm() function works. * * This file implements tests for the chownnm() function. */ // self // #include <snapdev/chownnm.h> #include <snapdev/file_contents.h> #include <snapdev/user_groups.h> #include "catch_main.h" // C++ lib // #include <set> // last include // #include <snapdev/poison.h> CATCH_TEST_CASE("chownnm", "[os]") { CATCH_START_SECTION("chownnm: change group") { struct group const * grp(getgrnam("snapwebsites")); if(grp == nullptr) { std::cerr << "warning: skipping change group test because \"snapwebsites\" group doesn't exist.\n"; } else { char const * user(getenv("USER")); bool permitted(true); CATCH_REQUIRE(user != nullptr); if(strcmp(user, "root") != 0) { std::set<std::string> our_groups(snapdev::user_group_names<std::set<std::string>>(user)); if(our_groups.find("snapwebsites") == our_groups.end()) { permitted = false; std::cerr << "error: we expect the tester to be the \"root\" user or part of the \"snapwebsites\" group to run this test section.\n"; } } if(permitted) { std::string const filename(SNAP_CATCH2_NAMESPACE::g_tmp_dir() + "/group-test.txt"); snapdev::file_contents system_groups(filename); system_groups.contents("test file--testing changing group\n"); system_groups.write_all(); struct stat st; CATCH_REQUIRE(stat(filename.c_str(), &st) == 0); if(st.st_gid == grp->gr_gid) { std::cerr << "warning: your default group is \"snapwebsites\" so the test is not going to change anything\n"; } CATCH_REQUIRE(snapdev::chownnm(filename, std::string(), "snapwebsites") == 0); struct stat verify; CATCH_REQUIRE(stat(filename.c_str(), &verify) == 0); CATCH_REQUIRE(verify.st_gid == grp->gr_gid); // restore former group // struct group * org_group(getgrgid(st.st_gid)); CATCH_REQUIRE(org_group != nullptr); CATCH_REQUIRE(snapdev::chownnm(filename, std::string(), org_group->gr_name) == 0); CATCH_REQUIRE(stat(filename.c_str(), &verify) == 0); CATCH_REQUIRE(verify.st_gid == org_group->gr_gid); } } } CATCH_END_SECTION() CATCH_START_SECTION("chownnm: change owner") { // TODO: this is contradictory since we can't run this test as root... // char const * user(getenv("USER")); CATCH_REQUIRE(user != nullptr); struct passwd const * pwd(getpwnam("snapwebsites")); if(pwd == nullptr || strcmp(user, "root") != 0) { std::cerr << "warning: skipping change owner test because your are not root and/or the \"snapwebsites\" user doesn't exist.\n"; } else { std::string const filename(SNAP_CATCH2_NAMESPACE::g_tmp_dir() + "/owner-test.txt"); snapdev::file_contents system_groups(filename); system_groups.contents("test file--testing changing owner\n"); system_groups.write_all(); struct stat st; CATCH_REQUIRE(stat(filename.c_str(), &st) == 0); if(st.st_uid == pwd->pw_uid) { // this should not happen since we tested above that we are // root to properly run this test (otherwise we bail out) // std::cerr << "warning: your default owner is \"snapwebsites\" so the test is not going to change anything\n"; } CATCH_REQUIRE(snapdev::chownnm(filename, "snapwebsites", std::string()) == 0); struct stat verify; CATCH_REQUIRE(stat(filename.c_str(), &verify) == 0); CATCH_REQUIRE(verify.st_uid == pwd->pw_uid); // restore former group // struct passwd * org_owner(getpwuid(st.st_uid)); CATCH_REQUIRE(org_owner != nullptr); CATCH_REQUIRE(snapdev::chownnm(filename, std::string(), org_owner->pw_name) == 0); CATCH_REQUIRE(stat(filename.c_str(), &verify) == 0); CATCH_REQUIRE(verify.st_uid == org_owner->pw_uid); } } CATCH_END_SECTION() } // vim: ts=4 sw=4 et
import '@testing-library/jest-dom/extend-expect'; import { render, screen } from '@testing-library/react'; import addDays from 'date-fns/addDays'; import format from 'date-fns/format'; import { colors } from '../../styles/colors'; import Calendar from './Calendar'; describe('Calendar Component', () => { const startDate = new Date(); const endDate = addDays(new Date(), 5); it('Verificar se está sendo renderizado', () => { // Given const onChangeMock = jest.fn(); // When render( <Calendar onChange={onChangeMock} startDate={startDate} endDate={endDate} selected={startDate} />, ); // Then expect(screen.getByRole('textbox')).toBeInTheDocument(); }); it('Verificar se estilo brand está funcionando', () => { // Given const onChangeMock = jest.fn(); // When render( <Calendar onChange={onChangeMock} startDate={startDate} endDate={endDate} selected={startDate} brand />, ); // Then const calendar = screen.getByRole('textbox'); expect(calendar).toHaveStyle(`color: ${colors.brand10}`); expect(calendar).toHaveStyle(`border: 1px solid ${colors.brandLight}`); expect(calendar).toHaveStyle(`background-color: ${colors.brandLight}`); expect(calendar).toHaveStyle(`color: ${colors.brand10}`); }); it('Verificar se label está funcionando', () => { // Given const onChangeMock = jest.fn(); // When render( <Calendar onChange={onChangeMock} startDate={startDate} endDate={endDate} selected={startDate} label="Calendário" />, ); // Then expect(screen.getByText('Calendário')).toBeInTheDocument(); }); it('Verificar se otherFormatDate está funcionando', () => { // Given const onChangeMock = jest.fn(); // When render( <Calendar onChange={onChangeMock} startDate={startDate} endDate={endDate} selected={startDate} otherFormatDate="MM-dd-yyyy" />, ); // Then const calendar = screen.getByRole('textbox'); expect(calendar.closest('input')?.value).toEqual( format(startDate, 'MM-dd-yyyy'), ); }); });
// Copyright (C) 2023-2024 Free Software Foundation, Inc. // // This file is part of the GNU Proc Macro Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. use bridge; use std::fmt; /// A region of source code along with macro expansion information. #[derive(Copy, Clone)] pub struct Span(pub(crate) bridge::span::Span); impl Span { // TODO: Add experimental API functions for this type /// Creates a new span that resolves at the macro call location. pub fn call_site() -> Self { Span(bridge::span::Span::call_site()) } /// Creates a new span that resolved sometimes at macro call site, and /// sometimes at macro definition site. pub fn mixed_site() -> Self { Span(bridge::span::Span::mixed_site()) } /// Creates a new span with the same line/column informations but that /// resolve symbols as though it were at `other`. /// /// # Arguments /// /// * `other` - Other span to resolve at. pub fn resolved_at(&self, other: Span) -> Self { Span(self.0.resolved_at(other.0)) } /// Creates a new span with the same name resolution behavior as self, but /// with the line/column information of `other`. /// /// # Arguments /// /// * `other` - Other span containing the line/column informations to use. pub fn located_at(&self, other: Span) -> Self { Span(self.0.located_at(other.0)) } /// Return the source text behind a span. pub fn source_text(&self) -> Option<String> { self.0.source_text() } } impl fmt::Debug for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } }
import { RouterModule, Routes } from '@angular/router'; import { AuthenticationGuard } from 'src/app/core/guards/authentication.guard'; import { LayoutComponent } from './layout.component'; import { NgModule } from '@angular/core'; const routes: Routes = [ { path: 'dashboard', component: LayoutComponent, loadChildren: () => import('../dashboard/dashboard.module').then((m) => m.DashboardModule), canActivate: [AuthenticationGuard], }, { path: 'category', component: LayoutComponent, loadChildren: () => import('../category/category.module').then((m) => m.CategoryModule), }, { path: 'activity', component: LayoutComponent, loadChildren: () => import('../activity/activity.module').then((m) => m.ActivityModule), canActivate: [AuthenticationGuard], }, { path: 'profile', component: LayoutComponent, loadChildren: () => import('../profile/profile.module').then((m) => m.ProfileModule), // canActivate: [AuthenticationGuard], }, { path: '', redirectTo: 'dashboard', pathMatch: 'full' }, { path: '**', redirectTo: 'error/404' }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class LayoutRoutingModule {}
const express = require('express') const bodyParser = require('body-parser') const dotenv = require('dotenv') const cardsController = require('./controllers/cardsController') const authRoutes = require('./routes/auth') const { verifyToken } = require('./middleware/authMiddleware') dotenv.config() const app = express() const PORT = process.env.PORT || 3000 app.use(bodyParser.json()) // CORS middleware app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*') next() }) // Routes app.use('/auth', authRoutes) app.get('/cards', verifyToken, cardsController.getAllCards) app.post('/cards/create', verifyToken, cardsController.createCard) app.put('/cards/:id', verifyToken, cardsController.updateCard) app.delete('/cards/:id', verifyToken, cardsController.deleteCard) app.get('/cards/types', verifyToken, cardsController.getAllTypes) app.get('/cards/sets', verifyToken, cardsController.getAllSets) app.get('/cards/rarities', verifyToken, cardsController.getAllRarities) app.get('/cards/count', verifyToken, cardsController.getCardCount) app.get('/cards/random', verifyToken, cardsController.getRandomCard) app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`) })
console.log("Hello geys"); // public private protected / readonly static abstract class Cars { static manufactureCountry = "Ukraine"; protected details: string[] = []; // private key gives access only from currrent class but protected gives access from any extended class constructor(public readonly name: string, private model: string) {} static makeSimpleCar(name: string, model: string) { // static method which we can use without making instance of class, it"s like utils function inside Cars namespacing return { name, model, country: Cars.manufactureCountry }; } getModel(this: Cars) { // this always ref to instance of current Class return this.model; } addDetail(detail: string) { this.details.push(detail); } printDetailsInformation() { console.log(this.details.length); console.log(this.details); } abstract printCarPresentation(this: Cars): void; } // const lada = new Cars("lastochka", "vaz-2110"); // console.log(lada, "lada"); // lada.addDetail("kapot"); // // lada.details = []; // lada.printDetailsInformation(); class Mercedes extends Cars { get get_additionalFeatures() { return this.additionalFeatures; } constructor(model: string, private additionalFeatures: string[]) { super("Mercedes", model); this.details = []; } addDetail() { this.details = ["ha ha from ihertianced class"]; } printAdditionalFeatures() { return this.additionalFeatures; } printCarPresentation() { console.log( `The name is ${this.name}, and the new super model is ${this.getModel()}` ); } } // const car = new Cars("lada", "2110"); const mercGl = new Mercedes("gl", ["multiHelm"]); // console.log("lada", lada); console.log("mercGl", mercGl); console.log(Cars.makeSimpleCar("deo", "lanus")); mercGl.printCarPresentation(); //------------------------------- // private constructor - singelton = it's oop pattern class SelfMadeBuggati extends Cars { private static instance: SelfMadeBuggati; private constructor() { super("buggati", "noire"); } printCarPresentation() {} static getItem() { if (!SelfMadeBuggati.instance) { this.instance = new SelfMadeBuggati(); } return this.instance; } } const myCar = SelfMadeBuggati.getItem(); console.log(myCar); myCar.addDetail("brakes"); myCar.addDetail("helm"); console.log(myCar); console.log(myCar.printDetailsInformation());
<template> <a-layout class="layout"> <a-layout-header> <img class="logo" src="https://yupi.icu/logo.png"/> <a-menu v-model:selectedKeys="selectedKeys" theme="dark" mode="horizontal" :style="{ lineHeight: '64px' }" @click="toPage" > <a-menu-item key="/">主页</a-menu-item> <a-menu-item key="/task/create">创建任务</a-menu-item> <a-menu-item key="/analysis">分析</a-menu-item> </a-menu> </a-layout-header> <a-layout-content style="padding: 0 50px"> <router-view/> </a-layout-content> <a-layout-footer style="text-align: center"> 程序员鱼皮 ©2022 </a-layout-footer> </a-layout> </template> <script setup lang="ts"> import {computed, ref, watch} from "vue"; import {useRoute, useRouter} from "vue-router"; const route = useRoute(); const router = useRouter(); const selectedKeys = computed(() => { return [route.path]; }) const toPage = ({key}: { key: string }) => { router.push({ path: key }) } </script> <style scoped> .logo { height: 42px; float: left; margin-top: 12px; margin-right: 12px; } </style>
import { call, all, select, put, takeLatest, takeEvery, take, fork, } from "redux-saga/effects"; import request, { requestWithProgress } from "utils/request"; import { UI_DESIGN_INFO_ENDPOINT, UPLOAD_FILE_ENDPOINT, REMOVE_UPLOADED_FILE_ENDPOINT, JUDGES_COMMENTS_ENDPOINT, UPLOAD_CONTESTANT_PHOTO_ENDPOINT, SUBMISSION_ENTRY_ENDPOINT, TRANSCODER_JOB_STATUS_ENDPOINT } from "./endpoints"; import { LOAD_UI_INFO, UPLOAD_FILE, REMOVE_UPLOADED_FILE, JUDGES_COMMENTS, UPLOAD_CONTESTANT_PHOTO, TRANSCODER_JOB_STATUS } from "redux/actions/types"; import { commonApiActions, contestantFormActions, globalActions, contestantFormTemplateActions, authActions, profileActions } from "redux/actions"; import { initAppSelectors, authSelectors, contestantFormTemplateSelectors, dashboardSelectors, } from "redux/selectors"; import { eventChannel } from "redux-saga"; function createOnTypingChannel() { let emit; /** * * @param {Object} event - Event came from XHR request */ const onProgress = (event) => { emit(Math.round((event.loaded / event.total) * 100)); }; return { onProgress, channel: eventChannel((_emit) => { emit = _emit; // the subscriber must return an unsubscribe function // this will be invoked when the saga calls `channel.close` method const unsubscribe = () => { }; return unsubscribe; }), }; } function* getGetUiDesignInfo() { const level1Token = yield select(initAppSelectors.makeSelectInitAppToken()); const options = { method: "GET", headers: new Headers({ Authorization: `Bearer ${level1Token}`, "Content-Type": "application/json", }), }; try { const res = yield call(request, UI_DESIGN_INFO_ENDPOINT, options); yield put(commonApiActions.uiInfoLoaded(res)); } catch (error) { const err = yield error.response.json(); console.log('Please check Design') } } function* uploadFile(action) { const token = yield select(authSelectors.makeSelectToken()); const bracketId = yield select( contestantFormTemplateSelectors.makeSelectContestantFormTemplateSelectedBracketId() ); const phaseNumber = yield select( dashboardSelectors.makeSelectCurrentPhaseNumber() ); const { type, file, sectionId } = action.payload; const formData = new FormData(); formData.append("file", file); const params = new URLSearchParams({ bracket: bracketId, phaseNumber, }).toString(); const URL = `${UPLOAD_FILE_ENDPOINT}?${params}`; const options = { method: "POST", body: formData, headers: { Authorization: `Bearer ${token}`, sectionId, }, }; const { onProgress, channel } = yield call(createOnTypingChannel); try { yield fork(function* () { try { const res = yield call(requestWithProgress, URL, options, onProgress); yield put(contestantFormActions.contestantFormSaved(res)); yield put( commonApiActions.deleteTranscoderJobStatus() ); //++++++++++++++++++++++++++++++++++ const params2 = new URLSearchParams({ phaseNumber: phaseNumber, bracket: bracketId, }).toString(); const URL2 = `${SUBMISSION_ENTRY_ENDPOINT}?${params2}`; const options2 = { method: "GET", headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json", }), }; const response = yield call(request, URL2, options2); //{type: 'textbox', answer: 'yjhghfjjhfgff', sectionId: 88125} const response2 = response.planList[0].contentList.find((answer) => { return answer.sectionId === sectionId; }) yield put(contestantFormTemplateActions.contestantFormTemplateEntryReloadFileUpload(response)); const { answer } = response2; yield put(contestantFormActions.updateFormField({ type, answer, sectionId })) //++++++++++++++++++++++++++++++++++ yield put( globalActions.requestResponseReturned({ error: null, message: 'File Uploaded Sucessfully', }) ); } catch (error) { yield put( globalActions.requestResponseReturned({ error: true, message: "Unable to upload file", }) ); channel.close(); } yield put(contestantFormActions.contestantFormUploadPhotoDone()); }); let progress = 0; // While the upload is not finished while (progress !== 100) { progress = yield take(channel); yield put( contestantFormActions.contestantFormUploadPhotoProgress( sectionId, progress ) ); } } catch (error) { yield put( globalActions.requestResponseReturned({ error: true, message: "Unable to upload file", }) ); channel.close(); } } function* removeUploadedFile(action) { const { sectionId, planId, type } = action.payload; const token = yield select(authSelectors.makeSelectToken()); const bracketId = yield select( contestantFormTemplateSelectors.makeSelectContestantFormTemplateSelectedBracketId() ); const phaseNumber = yield select( dashboardSelectors.makeSelectCurrentPhaseNumber() ); try { const params = new URLSearchParams({ "locale": "en", "sectionId": sectionId, "planId": planId, }).toString(); const URL = `${REMOVE_UPLOADED_FILE_ENDPOINT}?${params}`; const options = { method: "DELETE", headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json", }), }; const res = yield call(request, URL, options); yield put(contestantFormActions.contestantFormSaved(res)); //++++++++++++++++++++++++++++++++++ const params2 = new URLSearchParams({ phaseNumber: phaseNumber, bracket: bracketId, }).toString(); const URL2 = `${SUBMISSION_ENTRY_ENDPOINT}?${params2}`; const options2 = { method: "GET", headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json", }), }; const response = yield call(request, URL2, options2); yield put(contestantFormTemplateActions.contestantFormTemplateEntryReloadFileUpload(response)); yield put(contestantFormActions.updateFormField({ type, undefined, sectionId })) //++++++++++++++++++++++++++++++++++ yield put( globalActions.requestResponseReturned({ error: null, message: "File Deleted is successfully", }) ); } catch (error) { yield put( globalActions.requestResponseReturned({ error: true, message: "Unable to Remove File", }) ); const { response } = error; if (response && (response.status === 401 || response.status === 419)) { yield put(authActions.sessionExpired()); } } } function* judgesComments(action) { const token = yield select(authSelectors.makeSelectToken()); try { const params = new URLSearchParams({ "planId": action.payload, }).toString(); const URL = `${JUDGES_COMMENTS_ENDPOINT}?${params}`; const options = { method: "GET", headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json", }), }; const res = yield call(request, URL, options); yield put(commonApiActions.setjudgesComments(res)); } catch (error) { console.log(error.message) const { response } = error; if (response && (response.status === 401 || response.status === 419)) { yield put(authActions.sessionExpired()); } } } function* uploadContestantPhoto(action) { const token = yield select(authSelectors.makeSelectToken()); const formData = new FormData(); formData.append("file", action.payload); const URL = `${UPLOAD_CONTESTANT_PHOTO_ENDPOINT}`; const options = { method: "POST", body: formData, headers: { Authorization: `Bearer ${token}`, }, }; const { onProgress, channel } = yield call(createOnTypingChannel); try { yield fork(function* () { try { const res = yield call(requestWithProgress, URL, options, onProgress); yield put(contestantFormActions.contestantFormSaved(res)); } catch (error) { yield put( globalActions.requestResponseReturned({ error: true, message: "Unable to update your profile picture", }) ); channel.close(); } yield put(commonApiActions.uploadContestantPhotoProgressStart()); /* yield put(contestantFormActions.contestantFormUploadPhotoDone()); */ }); let progress = 0; // While the upload is not finished while (progress !== 100) { progress = yield take(channel); yield put( commonApiActions.uploadContestantPhotoProgressDone({ progress })); if (progress === 100) { yield put(commonApiActions.profilePictureUploaded({ loaded: true, })); yield put( globalActions.requestResponseReturned({ error: null, message: "Your profile picture has been updated", }) ); } } } catch (error) { yield put( globalActions.requestResponseReturned({ error: true, message: "Unable to update your profile picture", }) ); channel.close(); } } function* transcoderJobStatus(action) { const token = yield select(authSelectors.makeSelectToken()); if (action.payload) { try { const params = new URLSearchParams({ "jobId": action.payload, }).toString(); const URL = `${TRANSCODER_JOB_STATUS_ENDPOINT}?${params}`; const options = { method: "GET", headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json", }), }; const res = yield call(request, URL, options); yield put(commonApiActions.setTranscoderJobStatus(res)); } catch (error) { console.log(error.message) } } } function* uploadFileSaga() { yield takeLatest(UPLOAD_FILE, uploadFile); } function* removeUploadedFileSaga() { yield takeLatest(REMOVE_UPLOADED_FILE, removeUploadedFile); } function* judgesCommentsSaga() { yield takeLatest(JUDGES_COMMENTS, judgesComments); } function* getGetUiDesignInfoSaga() { yield takeEvery(LOAD_UI_INFO, getGetUiDesignInfo); } function* uploadContestantPhotoSaga() { yield takeLatest(UPLOAD_CONTESTANT_PHOTO, uploadContestantPhoto); } function* transcoderJobStatusSaga() { yield takeLatest(TRANSCODER_JOB_STATUS, transcoderJobStatus); } export default function* rootSaga() { yield all([getGetUiDesignInfoSaga(), uploadFileSaga(), removeUploadedFileSaga(), judgesCommentsSaga(), uploadContestantPhotoSaga(), transcoderJobStatusSaga()]); }
package cz.vse.campuss.model; /** * Třída PolozkaHistorie představuje jednu položku historie uložení v systému. * Obsahuje informace o studentovi, šatně, umístění, stavu uložení a čase změny stavu. */ public class PolozkaHistorie { private final int id; private final String jmenoStudenta; private final String prijmeniStudenta; private final String isicStudenta; private final String satnaNazev; private final TypUmisteni umisteniTyp; private final int umisteniCislo; private final StavUlozeni stav; private final String casZmenyStavu; private final int satnarkaID; private final int umisteniID; /** * Konstruktor třídy PolozkaHistorie * @param id ID záznamu * @param jmenoStudenta Jméno studenta * @param prijmeniStudenta Příjmení studenta * @param isicStudenta ISIC studenta * @param satnaNazev Název šatny * @param umisteniTyp Typ umístění * @param umisteniCislo Číslo umístění * @param stav Stav uložení * @param casZmenyStavu Čas změny stavu * @param satnarkaID ID satnárky * @param umisteniID ID umístění */ public PolozkaHistorie(int id, String jmenoStudenta, String prijmeniStudenta, String isicStudenta, String satnaNazev, TypUmisteni umisteniTyp, int umisteniCislo, StavUlozeni stav, String casZmenyStavu, int satnarkaID, int umisteniID) { this.id = id; this.jmenoStudenta = jmenoStudenta; this.prijmeniStudenta = prijmeniStudenta; this.isicStudenta = isicStudenta; this.satnaNazev = satnaNazev; this.umisteniTyp = umisteniTyp; this.umisteniCislo = umisteniCislo; this.stav = stav; this.casZmenyStavu = casZmenyStavu; this.satnarkaID = satnarkaID; this.umisteniID = umisteniID; } public int getId() { return id; } public String getJmenoStudenta() { return jmenoStudenta; } public String getPrijmeniStudenta() { return prijmeniStudenta; } public String getIsicStudenta() { return isicStudenta; } public String getSatnaNazev() { return satnaNazev; } public TypUmisteni getUmisteniTyp() { return umisteniTyp; } public int getUmisteniCislo() { return umisteniCislo; } public StavUlozeni getStav() { return stav; } public String getCasZmenyStavu() { return casZmenyStavu; } public int getSatnarkaID() { return satnarkaID; } }
import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:intl/intl.dart'; import '../../../core/utils.dart'; import '../../../core/env.dart'; import '../../../core/theme/app_theme.dart'; part 'transaction.freezed.dart'; part 'transaction.g.dart'; enum TransactionStatus { Pending, Success, Fail, Reserved, CalledBack, Recovered, } statusFromJson(int? status) { if (status == null) return null; return TransactionStatus.values[status]; } @freezed class Transaction with _$Transaction { const Transaction._(); factory Transaction({ @JsonKey(name: 'Hash') required String hash, @JsonKey(name: 'ToAddress') required String toAddress, @JsonKey(name: 'FromAddress') required String fromAddress, @JsonKey(name: 'TransactionType') required int type, @JsonKey(name: 'TransactionStatus', fromJson: statusFromJson) TransactionStatus? status, @JsonKey(name: 'Amount') required double amount, @JsonKey(name: 'Nonce') required int nonce, @JsonKey(name: 'Fee') required double fee, @JsonKey(name: 'Timestamp') required int timestamp, @JsonKey(name: 'Data') required dynamic nftData, @JsonKey(name: 'Signature') String? signature, @JsonKey(name: 'Height') required int height, @JsonKey(name: 'UnlockTime') int? unlockTime, }) = _Transaction; factory Transaction.fromJson(Map<String, dynamic> json) => _$TransactionFromJson(json); String get parseTimeStamp { var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); var d12 = DateFormat('MM-dd-yyyy hh:mm a').format(date); return d12; } String get typeLabel { switch (type) { case 0: return "Tx"; case 1: return "Node"; case 2: return "NFT Mint"; case 3: return "NFT Tx"; case 4: return "NFT Burn"; case 5: final data = parseNftData(this); if (data != null) { if (nftDataValue(data, 'Function') == "Sale_Start()") { return "NFT Sale Start"; } else if (nftDataValue(data, 'Function') == "M_Sale_Start()") { return "NFT Sale Start (Manual)"; } else if (nftDataValue(data, 'Function') == "Sale_Complete()") { return "NFT Sale Complete"; } else if (nftDataValue(data, 'Function') == "M_Sale_Complete()") { return "NFT Sale Complete (Manual)"; } } return "NFT Sale"; case 6: return "ADNR"; case 7: return "DST Registration"; case 8: return "Topic Create"; case 9: return "Topic Vote"; case 10: final data = parseNftData(this); if (data != null) { if (nftDataValue(data, 'Function') == "CallBack()") { return "Reserve (Callback)"; } else if (nftDataValue(data, 'Function') == "Register()") { return "Reserve (Register)"; } else if (nftDataValue(data, 'Function') == "Recover()") { return "Reserve (Recover)"; } } return "Reserve"; default: return type.toString(); } } String get statusLabel { switch (status) { case TransactionStatus.Success: return "Success"; case TransactionStatus.Pending: return "Pending"; case TransactionStatus.Fail: return "Fail"; case TransactionStatus.Reserved: return "Reserved"; case TransactionStatus.CalledBack: return "Called Back"; case TransactionStatus.Recovered: return "Recovered"; default: return "-"; } } Color statusColor(BuildContext context) { switch (status) { case TransactionStatus.Success: return Theme.of(context).colorScheme.success; case TransactionStatus.Pending: return Theme.of(context).colorScheme.warning; case TransactionStatus.Fail: return Theme.of(context).colorScheme.danger; case TransactionStatus.Reserved: case TransactionStatus.CalledBack: case TransactionStatus.Recovered: return Colors.deepPurple.shade200; default: return Colors.white; } } Uri get explorerUrl { return Uri.parse("${Env.explorerWebsiteBaseUrl}/transaction/$hash"); } DateTime? get unlockTimeAsDate { if (unlockTime == null) { return null; } if (status != TransactionStatus.Reserved) { return null; } return DateTime.fromMillisecondsSinceEpoch(unlockTime! * 1000); } DateTime? get callbackUntil { if (unlockTime == null) { return null; } if (status != TransactionStatus.Reserved) { return null; } final now = DateTime.now(); if (unlockTimeAsDate!.isBefore(now)) { return null; } return unlockTimeAsDate; } String get parseUnlockTimeAsDate { if (unlockTime == null) { return "-"; } if (status != TransactionStatus.Reserved) { return "-"; } var date = DateTime.fromMillisecondsSinceEpoch(unlockTime! * 1000); var d12 = DateFormat('MM-dd-yyyy hh:mm a').format(date); return d12; } bool get isFromReserveAccount { return fromAddress.startsWith("xRBX"); } bool get isToReserveAccount { return toAddress.startsWith("xRBX"); } }
##prepare the dataset for training with the use the MNIST dataset def get_dataset(rank=0, size=1): from tensorflow import keras from tensorflow.keras.datasets import mnist import numpy as np # Set a random seed for reproducibility np.random.seed(42) # Download MNIST dataset (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data('MNIST-data-%d' % rank) #(x_train, y_train), (x_test, y_test) = mnist.load_data('MNIST-data-%d' % rank) # Pre-process data # Prepare dataset for distributed training x_train = x_train[rank::size] y_train = y_train[rank::size] x_test = x_test[rank::size] y_test = y_test[rank::size] # Reshape and Normalize data for model input x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255.0 x_test /= 255.0 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) return (x_train, y_train), (x_test, y_test)
import { useFormContext } from "react-hook-form" import { HotelFormData } from "./ManageHotelForm" const DetailsSection = () => { const {register, formState: {errors}} = useFormContext<HotelFormData>() return ( <div className="flex flex-col gap-4"> <h1 className="text-3xl font-bold mb-3">Add Hotel</h1> <label htmlFor="" className="text-grat-700 text-sm font-bold flex-1"> Name <input className="border rounded w-full py-1 px-2 font-normal" type="text" {...register('name', {required: 'this field is required'})} /> {errors.name&&( <span className="text-red-500">{errors.name.message}</span> )} </label> <div className="flex gap-4"> <label htmlFor="" className="text-grat-700 text-sm font-bold flex-1"> City <input className="border rounded w-full py-1 px-2 font-normal" type="text" {...register('city', {required: 'this field is required'})} /> {errors.city&&( <span className="text-red-500">{errors.city.message}</span> )} </label> <label htmlFor="" className="text-grat-700 text-sm font-bold flex-1"> Country <input className="border rounded w-full py-1 px-2 font-normal" type="text" {...register('country', {required: 'this field is required'})} /> {errors.country&&( <span className="text-red-500">{errors.country.message}</span> )} </label> </div> <label htmlFor="" className="text-grat-700 text-sm font-bold flex-1"> Description <textarea rows={10} className="border rounded w-full py-1 px-2 font-normal" {...register('description', {required: 'this field is required'})} ></textarea> {errors.description&&( <span className="text-red-500">{errors.description.message}</span> )} </label> <label htmlFor="" className="text-grat-700 text-sm font-bold max-w-[50%]"> Price Per Night <input min={1} className="border rounded w-full py-1 px-2 font-normal" type="number" {...register('pricePerNight', {required: 'this field is required'})} /> {errors.pricePerNight&&( <span className="text-red-500">{errors.pricePerNight.message}</span> )} </label> <label htmlFor="" className="text-grat-700 text-sm font-bold max-w-[50%]"> Star Rating <select className="border rounded w-full p-2 text-gray-700 font-normal" {...register('starRating',{ required: 'This field is required' })}> <option className="text-sm font-bold" value=""> Select as Rating </option> {[1,2,3,4,5].map((num)=>{ return <option value={num}>{num}</option> })} </select> {errors.starRating&&( <span className="text-red-500">{errors.starRating.message}</span> )} </label> </div> ) } export default DetailsSection
<?xml version="1.0" encoding="UTF-8"?> <?oxygen RNGSchema="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="xml"?> <TEI xmlns="http://www.tei-c.org/ns/1.0"> <teiHeader> <fileDesc> <titleStmt> <title>Introduction to the resource</title> </titleStmt> <publicationStmt> <p>Published by the William Godwin's Diary project, University of Oxford</p> </publicationStmt> <sourceDesc> <p>William Godwin's Diary</p> </sourceDesc> </fileDesc> </teiHeader> <text> <body> <div xml:id="Searching" rend="indented"> <head>Searching the resource</head> <p>The project has sought to code the diary so as to retain the richness and diversity of the information. Each element in a day’s entry has been coded so as to distinguish what Godwin read, what he wrote, whom he saw, where he saw them, in what activities or meals they shared, and where he went. It is possible, then, to search for dates, for particular people, for activities, for texts written or read, for events attended, and so on. In the display of the diary transcription many textual elements appear as blue hyperlinks and some (unidentified people) are underlined; the colouring and underlining can be hidden by unchecking the 'Formatting' box. </p> <p>Because Godwin’s entries are cryptic, judgments have been made throughout the coding process as to what particular entries mean. Also, Godwin is often inconsistent in the way he spells or abbreviates people’s names, the titles of works he is writing, and those he is reading. Using the <ref target="/search.html">search</ref> facility for ‘Holcroft’ will identify all instances where he enters ‘Holcroft’ in the diary. But it will not reveal the huge number of cases in which he contracts Holcroft to ‘Ht’ or variations thereof. Nor does this facility currently allow ‘fuzzy’ searching. However, the underlying coding does allow variants to be recognised as instances of the same name if searched for under PEOPLE. As a result, when searching names, we strongly recommend searching both with the open SEARCH facility, and in the People section under ‘<ref target="/people/">People (identified)</ref>’. The former will search for the name as it appears in the diary and in the editorial matter while the latter will search by the underlying coding, rather than by the exact spelling. Users may also find the CTRL+F search function on a PC or the Command+F search function on a Mac helpful on some pages of the resource.</p> <p>The aim of the editorial apparatus has been to clarify Godwin’s entries and to provide additional information that will allow the user to pursue their inquiry further. In the attempt to identify the ~64,000 name entries in the diary we have created files for about 1,110 people and families, which say something about well over three quarters of the total name entries. Where there is a lack of certainty we have indicated what possibilities there are and the reasoning we have used in making an identification, usually based on the particular social contexts for that entry and/or other primary and secondary sources. Biographical information is offered for those identified but where those individuals appear in the <ref target="http://www.oxforddnb.com/"><title>Oxford Dictionary of National Biography</title></ref>, we have kept this to a minimum. We have generally excluded spouses from our identifications unless 1) the spouse is of independent historical interest or 2) Godwin had a significant relationship with them independent of the primary figure (but see also the comments under <ref target="#Abbreviations">Abbreviations and names</ref> for more complex cases). We have prioritized the identification of those who appear frequently in the diary, those we deemed important to Godwin, and those we thought would be of interest to a general audience. These principles have not been followed rigidly as identifications often flowed organically (identifying one person in a group often leads to the identification of others). Users will have further information we lacked and we welcome feedback on our judgments and further information about people and entries in the diary. The editorial matter and coding of the diary will be updated on a regular basis over the first year of public access, and intermittently thereafter.</p> <p>Users of the diary are strongly encouraged to consult <ref target="#Abbreviations">Abbreviations and names</ref> </p> </div> <div xml:id="Abbreviations" rend="indented"> <head>Abbreviations and names</head> <p>Godwin uses abbreviations throughout the diary but especially when referring to people, and he has a range of shorthand entries that qualify what he has written. The abbreviations for people are many and various: He almost wholly refuses to add the second consonant of any name ending in a double consonant. For example: Thelwall is always Thelwal; Crosdill is always Crosdil, except when Godwin records his death!</p> <p>Just as Holcroft becomes ‘Ht’, many others in the diary are contracted to the first and last letters of their names <emph>but they are not consistently contracted </emph>– Godwin can move back and forward between full spellings and contractions; he can also use initials rather than contractions; and he can use the same initials or contractions for different people – so M stands for Marshall, but also for his daughter Mary at one period of her life. Women are more likely to be contracted than men, but certainly not exclusively so. People can also be referred to by, or, more precisely, their presence may be inferred from, a place name. For instance, when Godwin becomes intimate with Mary Wollstonecraft the entry truncates her to ‘chez elle’ or ‘chez moi’. Another example is John Philpott Curran being referred to for much of Godwin’s visit to Ireland in <ref target="/diary/1800.html">1800</ref> as ‘Rathfarnham’ (where Curran lived in Dublin). In addition, we have recognised a problem with Godwin’s referencing, particularly of meals and the presence of the host and spouse or other family member. For example, Godwin dines frequently at Charles Lamb’s. Except when Mary Lamb was in hospital, she would likely be present and active at the dinner, as is testified by letters and diaries from the period and yet Godwin makes no reference to her presence.  The same is true for many other couples. Accordingly, we have taken the editorial decision to presume the presence of significant others when Godwin calls for meals but only mentions the host and <emph>when that significant other has an individual code</emph>.  In some cases this will overstate their presence – we do not know exactly when Mary Lamb was in hospital.  For other couples there is less risk of over-stating the spouse’s presence.  However, when Godwin records an entry such as 'call on Lamb' (as against 'call on Lambs') we have treated this more narrowly and coded only for the named person.</p> <p>A complication of the abbreviations is the fluctuating degree of intimacy that Godwin has with people. This can be particularly difficult to unpick when people share surnames and more so again when it is a common surname. Godwin felt that he had no need to distinguish in his diary between various ‘Smiths’ or ‘Taylors’ who appear throughout the diary, but it seems clear from context that different people are being recorded. In other words, ‘Smith’ in <ref target="/diary/1792.html">1792</ref> is someone different to ‘Smith’ in <ref target="/diary/1802.html">1802</ref>. Often context can help make an identification but occasionally there is no context (e.g. ‘Call on Smith’).</p> <p>Names are usually given without initials. Women’s names may first appear prefixed with Miss or Mrs, but this is not invariably so; and that prefix may then be replaced by an initial or discarded altogether. Those given initials may lose them; those without may gain them, and may lose them again. Even when people with the same surname are involved in Godwin’s circles in the same period, Godwin does not systematically distinguish different people by using initials.</p> <p>For ‘nah’, ‘nit’, ‘adv’ and other abbreviations relating to calls and meetings see <ref target="#Calls">Calls</ref>.</p> </div> <div xml:id="Calls" rend="indented"> <head>Calls</head> <p>Godwin indicates when he calls on others and when they call on him. Entries may be followed, usually in superscript by nah, na, nit, or n. These mean that Godwin does not in fact see them – because they are ‘not at home’, ‘not available’, ‘not in town’, or simply not there. Similarly, callers on Godwin may be recorded with similar notes when Godwin is out or when he does not see them. When looking at an individual person record under <ref target="/people/" >People</ref> users will find results that indicate how many of the calls the person makes on Godwin or Godwin makes on them and of these calls how many do not result in an actual meeting. This example illustrates an important principle of searching the diary: appearance in the diary does not automatically constitute a physical encounter between Godwin and an individual. An individual can appear in the diary as an unsuccessful call, as a topic of conversation, as a correspondent, in a paratextual list, as a death, in an entry where Godwin notes meetings between two or more others where he was not himself present, and so on. In each case the entry is not a contact. Users are directed to be careful in distinguishing actual physical encounters with Godwin from these types of diary entries. </p> <p>Moreover, users should note that there are some ‘meetings’ whose nature cannot be determined and that there is a grey area as to what constitutes a physical encounter in any case. When Godwin attended, for instance, the trial on Thomas Hardy on <ref target="/diary/1794-11-01.html">1 November 1794</ref>, he wrote ‘see <ref target="/people/unidentified/wharton.html">Wharton</ref>, <ref target="/people/unidentified/thomson.html">Thomson</ref>, <ref target="/people/unidentified/walker.html">Walker</ref>, <ref target="/people/unidentified/roberts%20m..html">Roberts M.</ref>, <ref target="/people/VAU01.html">Vaughan</ref>, <ref target="/people/HAR01.html" >Harwood</ref>, <ref target="/people/FRO01.html">Frost</ref>, <ref target="/people/WIL19.html">Williams</ref>, <ref target="/people/BAN03.html" >Banks</ref>, <ref target="/people/SHA01.html">Sharp</ref>, <ref target="/people/FER01.html">Ferguson</ref>, <ref target="/people/SYM01.html" >Symonds</ref>, <ref target="/people/TOW01.html">Towers</ref>, <ref target="/people/MOO06.html">C. Moore</ref>, <ref target="/people/MOO04.html" >G. Moore</ref>, <ref target="/people/unidentified/hawes.html">Hawes</ref>, <ref target="/people/RIT01.html">Ritson</ref>, <ref target="/people/unidentified/gray.html">Gray</ref>, <ref target="/people/WEB01.html">Webb</ref>, <ref target="/people/unidentified/belmano.html">Belmano</ref>, <ref target="/people/MAC03.html">Macdonald</ref>’. It seems improbable that he spoke to all of these but likely he did with some. Does a wave across a crowded courtroom, a nod in the queue to gain entry, or the recognition of someone on the other side of the room constitute a meeting? The editors have taken take the view that all encounters treated by Godwin as a meeting should be acknowledged as a meeting. While it may be tempting to assume that meetings recorded by Godwin as ‘see’ are not actual physical encounters, this is not borne out by considering the use of ‘see’ in the diary as a whole, so there is no distinct subcategory of meetings systematically distinguished from other subcategories, where Godwin sees but does not meet people. </p> <p>Within each person’s file, there is an option to explore the meals and meetings they had with Godwin in more detail. A chronological list is offered of all meals and meetings in which the person features. The user has the opportunity to narrow the encounters listed by category (meal or meeting), subcategory (type of meeting or meal), venue, or number of participants. The user may also determine which meetings the subject of their search attended with other specified persons. For example, if searching for Coleridge, one can then view just the meetings at which Coleridge and Wordsworth appear together and distinguish within those any n/nah/nit instances Godwin notes. One can search for meetings of up to four people (excluding Godwin): for example, if one wanted to see if Godwin, Coleridge, Wordsworth, Charles Lamb, and Thomas De Quincey ever got together, the diary records one such encounter (tea at Coleridge’s on <ref target="/diary/1808-03-03.html">3 March 1808</ref>). Where we have been unable to identify a person who appears in a meeting, the person’s name will be marked by an asterix.</p> <p>When Godwin records calling on a number of people in one entry (call on X, Y, and Z), these calls have been treated as a sequence of individual calls. Similarly, when Godwin records a number of people calling on him (X, Y, and Z call), these have been treated as a sequence of individual calls. The project recognizes that in some cases people may be calling ensemble but there is sufficient evidence that the individual approach is most accurate with some exceptions noted below.</p> <p>When Godwin records calling with someone on others (call, with X, on Y &amp; Z), his companion is deemed to be present at both meetings. However, when Godwin records an entry such as ‘Call on X &amp; Y with Z’, Z is treated as being at the latter meeting only.</p> <p>Most meetings are clear – people call on Godwin, or he calls on them, although the etiquette of calling is complex (see, for example, the discussion in Leonore Davidoff’s <emph>The Best Circles: Society Etiquette and the Season</emph> – although this is based on slightly more formal contexts). </p> <p>The most complex meeting in the diary is the frequently used ‘adv.’ which, from two entries in <ref target="/diary/1792.html">1792</ref> where Godwin spells it out in full, we know to be a contraction of ‘advenae’. The word ‘advena’ (plural ‘advenae’) is something of a rarity in Latin, being a first-declension noun with an ‘-a’ ending, which is usually feminine but here of indeterminate gender, i.e. potentially masculine, feminine or neuter. The standard dictionary of classical Latin (Lewis &amp; Short) defines its primary meaning as ‘one who comes to a place’, but then ‘a foreigner, stranger, or alien’. Godwin uses the term to indicate that he unexpectedly encountered the person at a meal or meeting or at an event. Meals may involve a number of people with whom Godwin dines, followed by ‘adv’ and another list. This suggests that the former were part of an arranged dinner, and the latter call on the host either during or after dinner.</p> <p>When Godwin records a number of people encountered ‘adv’ the individuals have been grouped collectively. Although this differs from our principle of recording other types of meetings such as calls individually, the adv encounter functions as a subset to a wider meeting/meal/activity and as such we have taken the view that individuals listed as adv encounters are more likely to encounter each other within the physical and social confines of the broader meal/meeting/activity’s parameters. The same assumption has been made about participants of an ‘au soir’ meeting who are also grouped collectively.</p> <p>We have also indicated when people function as a venue for a call. This is worth noting not only for the light shed on Godwin’s relationship with the individual (for example, if Godwin calls many times on them but this is not reciprocated, this suggests a particular kind of relationship) but for the light shed on non-Godwin relationships . If, for example, Godwin only meets X when he is visiting Y, then it may suggest that there is a relationship between X and Y that is noteworthy. Users should consider the effect that Godwin’s age, income, marital status would have on the patterns of calling and dining. </p> </div> <div xml:id="Meals" rend="indented"> <head>Meals</head> <p>Godwin is reasonably consistent in identifying meals at which he meets others. ‘X dines’ means what it says; X dines, means that X is Godwin’s guest. It is likely that meals at which Godwin is the host may include meals in inns or coffee houses that Godwin hosts, as well as those in his own home, but we have no way of knowing this for certain. The range of meals: breakfast, dinner, tea, supper are self-explanatory, although readers may wish to refer to scholarly discussions of dining practices in late eighteenth and early nineteenth-century London (see <ref target="/project-bibl.html">bibliography</ref>) The editors have been careful to record each type of meal separately as distinct types suggest a certain level of intimacy which is very useful in mapping changes over time in Godwin’s relationship with people, or indeed, in the relationships between other people in the diary. </p> </div> <div xml:id="List1796" rend="indented"> <head>1796 List</head> <p>The diary’s editorial matter refers frequently to the '<ref target="/diary/1796list.html">1796 list</ref>'. The 1796 list is a series of names and dates that Godwin inserted into the last few pages of his diary notebook for February 1795-September 1796. He compiled the list – probably in 1805 – to map the growth and range of his acquaintance over the years 1773-1805. In some cases the names are underlined, probably an indication that the relationship was one Godwin considered particularly important. One of the pages is of particular interest as Godwin selects twenty-five names from his main chronological list and puts them in order of when he made their acquaintance. It seems probable that Godwin here lists those twenty-five people he considered most significant to his life and is interested in thinking about either the longevity of those relationships or how the sequence of meeting matters or both. ‘Significant’ here has a deliberate (and inescapable) ambiguity as the list excludes, for example, Mary Wollstonecraft. Other names have then been added in the margins, which suggests that Godwin revisited this list subsequently to note other important relationships. The <ref target="/diary/1796list.html">list</ref> appears after the entry for <ref target="/diary/1796-09-24.html">24 September 1796</ref>.</p> </div> <div xml:id="Reading" rend="indented"> <head>Reading</head> <p>Godwin was a voracious reader right up until he died. He noted in his unfinished autobiography that when he was a student at Hoxton Academy he would rise at 5am and read until midnight and the passion for reading never left him. Although the diary commences in <ref target="/diary/1788.html">1788</ref>, he does not record his daily reading until <ref target="/diary/1791.html">1791</ref> when the diary becomes more detailed. </p> <p>There are various subcategories of reading. The overwhelming majority of entries may be found under ‘Texts Read’. Other entries can be found under ‘Cala’ which is when Godwin browses through a text ‘ça et la’; ‘Discussed’ where it appears that Godwin discusses a text with someone or reads a work aloud; ‘Texts Mentioned’ where Godwin refers to a text but is not reading it (e.g. borrowing a book); and ‘Letter Received’ where Godwin notes the receipt of correspondence (which he does not do consistently, since many extant letters do not correspond to an entry in the diary, and for many entries in the diary there is no extant letter).</p> <p>The aim has been to identify the author (and where applicable translator/editor), full title, and first publication date for each item.  There has been no concerted attempt to identify the specific edition that Godwin read.  However, information from the sale catalogue of his library has been provided, as well as notations on his readings in the British Museum (now the British Library), which may serve scholars in tracing specific editions.  Occasionally, we have noted reprints and later editions available to Godwin, especially where his diary explicitly states that he is using a specific edition.</p> <p>The annotations follow a specific sequence.  Each item reproduces the entry from Godwin’s diary, with the date of the entry.  In the annotation, the name of the author (and where applicable translator/editor) is given in boldface, with title in italics below author, and with publication date in roman after.  Comments stand below the bibliographical information.  Because there are many inconsistencies in how titles are recorded in our sources, we have followed the practice of capitalizing only the first word of title, subtitle, proper names, and personal titles such as ‘Earl’.  Spelling has not been modernized unless the source has modernized it.</p> <p>Given Godwin’s cryptic entries, absolutely certain identification has not always been possible.  We have therefore in many cases supplied a brief comment to show the basis of confidence.  When we wished to draw attention to the issue of confidence, we have used the following indicator words: <list> <item>a. ‘probably,’ </item> <item>b. ‘possibly’ (often applied where several candidate identifications are equally possible),  </item> <item>c. ‘unable to identify with certainty’ (usually applied to the title by an identified author),</item> <item>d. and ‘unable to identify’ (applied to both author and title). </item> </list> </p> <p>The basis of confidence in an identification rests on one or more of the following:  Godwin’s own footnotes in published works (though these are sometimes cryptic), listing in his sale catalogue, identification by previous scholars, likelihood from the paucity of alternative candidates, previous mention in the diary, similar topics of works read within the same time period, and already read works by the same author.</p> <p>It has not been possible to check the title pages of all the works Godwin read, especially in their first editions.  For some authors, we have consulted available scholarly editions that give publication dates and titles of first editions or single-author bibliographies.  In an initial search of many items, we have consulted the extensive listing in WorldCat, but since the recording of titles in this source is not always accurate or consistent, we have followed up by consulting listings in the English Short Title Catalogue (ESTC), the British Library Integrated Catalogue, the catalogue of the UCLA Libraries, and the catalogue of the Bibliothèque nationale de France.  We have also found valuable aid in identifying authors in the <emph>Oxford Dictionary of National Biography</emph>. A full list of the sources consulted may be seen in the bibliography.</p> </div> <div xml:id="Writing" rend="indented"> <head>Writing</head> <p>Godwin wrote almost every morning. His rate of composition varied but he usually managed 2-5 pages per day. Users can view Godwin’s writing activities by date, by type of activity or with reference to the writing of particular texts. </p> <p>The editors have distinguished Godwin’s different writing activities according to his own nomenclature so the user can see writing activity under ‘Transcribe’, Translate’, ‘Correct’ and so on. The editors have further incorporated indirect writing activities such as ‘Meditate on Writing’, ‘Notes Made’ and ‘Invent’ so that users can get a comprehensive view of Godwin’s writing process.</p> <p>Searching by text allows the user to see all writing activities, direct and indirect, that have been assigned to a particular text, both published and unpublished, completed and incomplete.</p> <p>When Godwin engages in two different activities on one text (for example, ‘Pol. Justice, 3pp; revise), they have been treated as two separate activities. When he records the completion of a text, it has been coded as a standard ‘write’ entry. </p> </div> <div xml:id="Health" rend="indented"> <head>Health</head> <p>Godwin kept fastidious diary records of his personal health problems, concerns, and moments of well-being. He maintained discretion when recording some of the more sensitive aspects of his health, generally referring to these issues in Latin or French. Godwin has been diagnosed, at various times, as suffering from haemorrhoids and constipation, and might have also had a form of rectal cancer (see St Clair). Another frequent issue is his ‘delerium’ or ‘deliquium’, which has been described by William St Clair as fits sometimes accompanied by vomiting. Latin and French words have been translated, and using context or various sources we have attempted to indicate what Godwin might have meant by some of the health phrases he utilised. Self-explanatory health issues such as ‘fever’ or ‘constipation’ have not been annotated, nor have conjectures been made about ambiguous or uncertain symptoms or treatments such as ‘syringe’ – noted on <ref target="/diary/1792-11-09.html">9</ref> and <ref target="1792-11-10">10 November, 1792</ref> – to cite one such example. When searching for health complaints, users should keep in mind that Godwin often used his own <emph>sui generis</emph> methods of spelling – for example, ‘headache’ is sometimes noted as ‘head ach’ or ‘head-ach’ and sometimes ailments have been abbreviated (such as ‘constip’ for constipation’).</p> </div> <div xml:id="Topics" rend="indented"> <head>Topics</head> <p>Godwin occasionally recorded topics of conversation in his diary. It is unclear why he records some conversations and not others although one may presume that it was because he felt the conversation or the interlocutor was worthy of note. It is also true that he records the topics of conversations more frequently in the mid-1790s than either before or after.</p> </div> <div xml:id="Events" rend="indented"> <head>Events</head> <p>Godwin goes to the theatre and concerts, attends lectures, notes trials and parliamentary and public events, registers personal events, keeps track of the weather and temperature, and visits libraries and gardens. Editorial notes identify these events in the diary and provide background information about them. In the open ‘Search’ editorial matter is kept distinct from the diary, but each may be searched. Place names are also recorded in the diary, and entries relating to visits and activity outside London are also noted.</p> </div> <div xml:id="Formatting" rend="indented"> <head>Formatting and Script</head> <p>Most of the diary entries are written in Godwin’s fluent italic script in black pen. However, many public events are entered below the day’s entry and are written in red ink. Moreover, in a relatively small number of entries additions have been made in pencil. Also, there are a number of cases where Godwin seems to be adding names to a meeting after the initial diary entry, resulting in names appearing in the side margins. Finally, Godwin occasionally enters dates wrongly and does not always retroactively correct them; and sometimes it looks as if he is compiling the diary from sets of notes, which leads him to make transcription mistakes, which he then rectifies by crossings out. In each case, we have tried to signal in the transcript that there is something distinctive about the entry, so as to encourage readers to check the transcribed entry against the scan of the manuscript.</p> </div> <div xml:id="ShortTitles" rend="indented"> <head>Short Titles</head> <p>The editors have had frequent and grateful recourse to the work of Godwin biographers Don Locke, Peter Marshall, and William St Clair. They are referred to in brief by surname in the editorial matter; full information is available in the <ref target="/project-bibl.html">bibliography</ref>.</p> </div> </body> </text> </TEI>
import { useMutation } from "@apollo/client"; import React, { useContext, useState } from "react"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import { AuthContext } from "../../context/userContext"; import { LOGIN_USER_MUTATION, REGISTER_USER_MUTATION, } from "../../models/graphql/mutations"; import { UserCall } from "../../models/objects/User"; function Login() { const [signUp, setSignUp] = useState(false); const [userName, setUserName] = useState(""); const [password, setPassword] = useState(""); const context = useContext(AuthContext); const navigate = useNavigate(); const [registerUser] = useMutation(REGISTER_USER_MUTATION, { variables: { userName, password }, onCompleted(data) { context?.setAuthAndSave(data.addUser); navigate("/"); }, }); const [loginUser] = useMutation(LOGIN_USER_MUTATION, { variables: { userName, password }, onCompleted(data) { context?.setAuthAndSave(data.userLogin); navigate("/"); }, }); const handleSubmit = (e: any) => { e.preventDefault(); if (!password || !userName) { return alert("Please fill in all fields"); } if (signUp) { registerUser(); } else { loginUser(); } }; return ( <AuthFormContainer> <AuthForm> <AuthFormContent> <AuthFormTitle>{`Sign ${signUp ? "Up" : "In"}`}</AuthFormTitle> <div className="form-group mt-3"> <label>Username</label> <input type="username" className="form-control mt-1" placeholder="Enter Username" value={userName} onChange={(e) => setUserName(e.target.value)} /> </div> <div className="form-group mt-3"> <label>Password</label> <input type="password" className="form-control mt-1" placeholder="Enter password" value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <div className="d-grid gap-2 mt-3"> <button className="btn btn-primary" onClick={handleSubmit}> Submit </button> </div> <p className=" text-center mt-2 btn-link" style={{ cursor: "pointer" }} onClick={() => setSignUp(!signUp)} > {signUp ? "Sign In instead?" : "Sign Up instead?"} </p> </AuthFormContent> </AuthForm> </AuthFormContainer> ); } const AuthFormContainer = styled.div` display: flex; justify-content: center; align-items: center; width: 100vw; height: 100vh; label { font-size: 14px; font-weight: 600; color: rgb(34, 34, 34); } `; const AuthForm = styled.form` width: 420px; box-shadow: rgb(0 0 0 / 16%) 1px 1px 10px; padding-top: 30px; padding-bottom: 20px; border-radius: 8px; background-color: white; `; const AuthFormContent = styled.div` padding-left: 12%; padding-right: 12%; `; const AuthFormTitle = styled.h3` text-align: center; margin-bottom: 1em; font-size: 24px; color: rgb(34, 34, 34); font-weight: 800; `; export default Login;
import react, { useEffect } from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/CardMedia"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; import Chip from "@mui/material/Chip"; import Stack from "@mui/material/Stack"; import LocationOnIcon from "@mui/icons-material/LocationOn"; import Grid from "@mui/material/Unstable_Grid2"; import { Link, generatePath } from "react-router-dom"; import { ROUTES } from "../../../../constants/routes"; import { useDispatch, useSelector } from "react-redux"; import { getProductListAction } from "../../../../redux/user/actions"; export default function CustomCard({ keyword }) { const dispatch = useDispatch(); useEffect(() => { dispatch(getProductListAction()); }, []); const { productList } = useSelector((state) => state.productReducer); useEffect(() => { dispatch( getProductListAction( keyword, ) ); }, [keyword]); return productList.data.map((item) => ( <Grid xs={6} key={item.id}> <Link style={{ textDecoration: "none" }} to={generatePath(ROUTES.USER.PRODUCT_DETAIL, { id: item.id, })} > <Card sx={{ cursor: "pointer" }}> <div style={{ position: "relative" }}> <img style={{ width: "100%", height: "300px", objectFit: "cover" }} src="https://www.firstpost.com/wp-content/uploads/2021/12/harley-davidson-sportster-s-launched-india-15-51-lakh-price-india-bike-week-2021-1.jpg" alt="" /> <div style={{ position: "absolute", bottom: "0px", color: "white", padding: "15px 15px 5px", }} > <div> <span style={{ fontSize: 20, fontWeight: 700, textTransform: "uppercase", }} > {item.name} </span> </div> </div> </div> <div style={{ padding: "15px 15px 0px", display: "flex", justifyContent: "space-between", alignItems: "center", }} > <div>Xe Ga</div> <div style={{ color: "#18A450", fontWeight: 700, fontSize: "18px" }} > 120K </div> </div> <Stack style={{ padding: "15px 15px 10px", display: "flex", alignItems: "center", }} direction="row" spacing={1} > <Chip size="small" label="Còn xe" /> <Chip size="small" label="Giao xe tận nơi" /> </Stack> </Card> </Link> </Grid> )); }
<!DOCTYPE html> <html lang="pt"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Doguito Petshop | Criar conta</title> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./assets/css/base/base.css"> <link rel="stylesheet" href="./assets/css/cadastro.css"> <link rel="stylesheet" href="./assets/css/componentes/cartao.css"> <link rel="stylesheet" href="./assets/css/componentes/inputs.css"> <link rel="stylesheet" href="./assets/css/componentes/botao.css"> </head> <body> <main class="container flex flex--coluna flex--centro"> <div class="cadastro-cabecalho"> <img src="./assets/img/doguito.svg" alt="Logo Doguito" class="cadastro-cabecalho__logo"> <h1 class="cadastro-cabecalho__titulo">PetShop</h1> </div> <section class="cartao"> <h2 class="cartao__titulo">Complete seu cadastro</h2> <form action="./cadastro_concluido.html" class="formulario flex flex--coluna"> <fieldset> <legend class="formulario__legenda">Informações básicas</legend> <div class="input-container"> <input name="nome" id="nome" class="input" type="text" placeholder="Nome" minlength="10" data-tipo="nome" title="o nome não deve possuir caracteres especiais como !#$% e deve ter mais que 10 digitos" required > <label class="input-label" for="nome">Nome</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="email" id="email" class="input" type="email" placeholder="Email" minlength="6" data-tipo="email" required title="o e-mail não deve possuir caracteres especiais como !#$% e deve ter mais que 6 digitos" > <label class="input-label" for="email">Email</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="senha" id="senha" class="input" type="text" placeholder="Senha" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?!.*[!@#$%&^*_=+-]).{8,12}$" data-tipo="senha" > <label class="input-label" for="senha">Senha</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> </fieldset> <fieldset> <legend class="formulario__legenda">Informações pessoais</legend> <div class="input-container"> <input name="nascimento" id="nascimento" class="input" type="date" placeholder="Data de nascimento" data-tipo="dataNascimento" required> <label class="input-label" for="nascimento">Data de nascimento</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="cpf" id="cpf" class="input" type="text" data-tipo="cpf" placeholder="CPF" required> <label class="input-label" for="cpf">CPF</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> </fieldset> <fieldset> <legend class="formulario__legenda">Endereço</legend> <div class="input-container"> <input name="cep" id="cep" class="input" type="text" data-tipo="cep" placeholder="CEP" required pattern="[\d]{5}-?[\d]{3}"> <label class="input-label" for="cep">CEP</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="logradouro" id="logradouro" class="input" data-tipo="logradouro" type="text" placeholder="Logradouro" required> <label class="input-label" for="logradouro">Logradouro</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="cidade" id="cidade" class="input" type="text" data-tipo="cidade" required placeholder="Cidade"> <label class="input-label" for="cidade">Cidade</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> <div class="input-container"> <input name="estado" id="estado" class="input" type="text" data-tipo="estado" required placeholder="Estado"> <label class="input-label" for="estado">Estado</label> <span class="input-mensagem-erro">Este campo não está válido</span> </div> </fieldset> <button class="botao">Cadastrar</a> </form> </section> </main> <script src="./js/main.js" type="module"></script> </body> </html>
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class Counter extends ChangeNotifier { int count = 0; void increase() { count++; notifyListeners(); } void decrease() { count--; notifyListeners(); } void reset() { count = 0; notifyListeners(); } } // Providerの定数をグローバルに宣言 final counterProvider = ChangeNotifierProvider((ref) => Counter()); void main() { runApp( const ProviderScope( child: MyApp(), ), ); } class MyApp extends ConsumerWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final counter = ref.watch(counterProvider); final isAbove10 = ref.watch(counterProvider.select((value) => value.state > 10)); return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar(title: const Text('riverpod_example')), body: ListView( children: [ Text('Count: ${counter.count}'), ], ), floatingActionButton: FloatingActionButton( onPressed: counter.increase, child: const Icon(Icons.add), ), )); } }
package com.looker.kenko.ui.plans import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.looker.kenko.R import com.looker.kenko.data.model.Plan import com.looker.kenko.ui.components.BackButton import com.looker.kenko.ui.components.SwipeToDeleteBox import com.looker.kenko.ui.extensions.plus import com.looker.kenko.ui.plans.components.PlanItem import com.looker.kenko.ui.theme.KenkoIcons import com.looker.kenko.ui.theme.KenkoTheme @Composable fun Plan( viewModel: PlanViewModel, onBackPress: () -> Unit, onPlanClick: (Long?) -> Unit, ) { val plans: List<Plan> by viewModel.plans.collectAsStateWithLifecycle() Plan( plans = plans, onBackPress = onBackPress, onSelectPlan = viewModel::switchPlan, onRemove = viewModel::removePlan, onPlanClick = onPlanClick, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun Plan( plans: List<Plan>, onBackPress: () -> Unit, onSelectPlan: (Plan) -> Unit, onRemove: (Long) -> Unit, onPlanClick: (Long?) -> Unit, ) { Scaffold( topBar = { TopAppBar( navigationIcon = { BackButton(onClick = onBackPress) }, title = { Text(text = stringResource(R.string.label_plans_title)) } ) }, floatingActionButton = { FloatingActionButton(onClick = { onPlanClick(null) }) { Icon(imageVector = KenkoIcons.Add, contentDescription = null) } }, containerColor = MaterialTheme.colorScheme.surface, ) { LazyColumn( contentPadding = it + PaddingValues(bottom = 80.dp), verticalArrangement = Arrangement.spacedBy(1.dp), ) { items( items = plans, key = { plan -> plan.id!! }, ) { plan -> SwipeToDeleteBox( modifier = Modifier.animateItem(), onDismiss = { onRemove(plan.id!!) } ) { PlanItem( plan = plan, onClick = { onPlanClick(plan.id!!) }, onActiveChange = { onSelectPlan(plan) }, ) } } } } } @Preview @Composable private fun PlanPreview() { KenkoTheme { Plan( plans = emptyList(), onSelectPlan = {}, onBackPress = {}, onPlanClick = {}, onRemove = {}, ) } }
import React from "react"; import { t } from "ttag"; import cx from "classnames"; import Tooltip from "metabase/components/Tooltip"; import Button from "metabase/components/Button"; export default function QuestionNotebookButton({ className, question, isShowingNotebook, setQueryBuilderMode, ...props }) { return QuestionNotebookButton.shouldRender({ question }) ? ( <Tooltip tooltip={isShowingNotebook ? t`Hide editor` : t`Show editor`}> <Button borderless={!isShowingNotebook} primary={isShowingNotebook} medium className={cx(className, { "text-brand-hover": !isShowingNotebook, })} icon="notebook" onClick={() => setQueryBuilderMode(isShowingNotebook ? "view" : "notebook") } {...props} /> </Tooltip> ) : null; } QuestionNotebookButton.shouldRender = ({ question }) => question.isStructured() && question.query().isEditable();
from django import forms from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.forms.widgets import Select, TextInput if "pinax.notifications" in settings.INSTALLED_APPS and getattr(settings, 'DJANGO_MESSAGES_NOTIFY', True): from pinax.notifications import models as notification else: notification = None from oncourse.libs.django_messages.models import Message from oncourse.libs.django_messages.fields import CommaSeparatedUserField class ComposeForm(forms.Form): """ A simple default form for private messages. """ recipient = CommaSeparatedUserField( label=_(u"Recipient"), widget = TextInput(attrs={'class':'form-control text-muted'})) subject = forms.CharField( label=_(u"Subject"), max_length=140, widget = TextInput(attrs={'class':'form-control text-muted'}) ) body = forms.CharField(label=_(u"Body"), widget=forms.Textarea(attrs={ 'class':'form-control text-muted', 'rows': '12', 'cols':'55'})) def __init__(self, *args, **kwargs): recipient_filter = kwargs.pop('recipient_filter', None) super(ComposeForm, self).__init__(*args, **kwargs) if recipient_filter is not None: self.fields['recipient']._recipient_filter = recipient_filter def save(self, sender, parent_msg=None): recipients = self.cleaned_data['recipient'] subject = self.cleaned_data['subject'] body = self.cleaned_data['body'] message_list = [] for r in recipients: msg = Message( sender = sender, recipient = r, subject = subject, body = body, ) if parent_msg is not None: msg.parent_msg = parent_msg parent_msg.replied_at = timezone.now() parent_msg.save() msg.save() message_list.append(msg) if notification: if parent_msg is not None: notification.send([sender], "messages_replied", {'message': msg,}) notification.send([r], "messages_reply_received", {'message': msg,}) else: notification.send([sender], "messages_sent", {'message': msg,}) notification.send([r], "messages_received", {'message': msg,}) return message_list
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>zx-waterfall demo by capricorncd</title> <style> * { margin: 0; padding: 0; } body { padding-top: 60px; } h2 { position: fixed; z-index: 10; top: 0; left: 0; width: 100%; height: 60px; line-height: 60px; background-color: rgba(0, 0, 0, 0.8); color: #ccc; text-align: center; } .container { position: relative; overflow-x: hidden; overflow-y: scroll; } .container .item { padding: 20px; box-sizing: border-box; background-color: #ccc; border-radius: 4px; overflow: hidden; } .container .item dt { padding-bottom: 10px; } .container .item dt i { padding-right: 10px; font-weight: bold; color: #c00; } .container .item img { width: 100%; height: auto; border-radius: 2px; } .loading { position: fixed; z-index: 9; top: 50%; left: 50%; margin: -60px 0 0 -100px; width: 200px; height: 120px; background-color: #fff; border-radius: 4px; box-shadow: 0 5px 10px rgba(0, 0, 0, 0.5); opacity: 0.9; display: flex; flex-direction: column; justify-content: center; align-items: center; } .loading i { position: relative; display: inline-block; width: 50px; height: 50px; box-sizing: border-box; border: 3px #c00 dashed; border-radius: 50%; animation: rotate 2s linear infinite; } .loading p { margin-top: 10px; } @keyframes rotate { form { transform: rotate(0); } to { transform: rotate(360deg); } } </style> </head> <body> <div id="app"> <h2>{{ title }}</h2> <div class="container" ref="container"> <dl class="item" v-for="(item, index) in list" :key="index" style="display: none;"> <dt><i>#{{ index + 1 }}</i>{{ item.content }}</dt> <dd> <img v-for="(media, i) in item.medias" :key="i" :src="media.thumb" alt=""> </dd> </dl> </div> <div v-show="isNotMore" style="text-align: center;color: red;">没有更多数据了</div> <div class="loading" v-show="loadState && !isNotMore"> <i></i> <p>loading ...</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-polyfills/0.1.42/polyfill.min.js"></script> <!-- 生产环境版本,优化了尺寸和速度 --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="./zx-waterfall.js"></script> <script src="./mock-json.js"></script> <script> // 模拟数据 var mockList = JSON.parse(mockJsonStr); var vm = new Vue({ beforeDestroy: function () { this.waterfall.destroy(); this.$container.removeEventListener('scroll', this.handleScroll); }, data: { title: 'zx-waterfall demo', // 列表数据 list: [], // 瀑布流实例 waterfall: null, // 数据请求页数 page: 1, // 每页数据条数 pageSize: 10, // 容器元素 $container: null, // 数据请求/加载状态 loadState: false, // 没有更多数据了 isNotMore: false }, el: '#app', methods: { getList: function () { // 判断数据是否已加载,或已无更多数据 if (this.loadState) return; this.loadState = true; // 模拟延时请求 var timer = setTimeout(function () { var list = mockList.slice((vm.page - 1) * vm.pageSize, vm.page * vm.pageSize); if (list.length) { vm.list = vm.list.concat(list); vm.page++; // 获取媒体(图片)元素 var medias = [] list.forEach(function (item) { item.medias.forEach(function (val) { medias.push(val.thumb); }) }) // 预加载图片 vm.waterfall.loadMedia(medias).then(function () { // 通知瀑布流,更新视图 vm.waterfall.update(); vm.loadState = false; vm.isNotMore = false; }) } else { vm.isNotMore = true; } clearTimeout(timer); }, 300) }, handleScroll: function () { var $el = this.$container; var scrollTop = $el.scrollTop var scrollHeight = $el.scrollHeight if (scrollHeight - scrollTop - $el.offsetHeight < 100) { vm.getList() } } }, mounted: function () { // 获取容器DOM元素 this.$container = this.$refs.container; // 设置容器高度, 窗口高度 - 头部header高度 - 底部预留20像素距离 this.$container.style.height = window.innerHeight - 60 - 20 + 'px'; // 实例化瀑布流 this.waterfall = new ZxWaterfall({ container: this.$container, itemSelector: '.item' }) // console.log(this.waterfall); // 获取数据 this.getList(); // 添加滚动事件监听 this.$container.addEventListener('scroll', this.handleScroll); } }) </script> </body> </html>
import { Column, DataType, HasMany, Model, Table } from 'sequelize-typescript'; import { DisciplineAcademicPlan } from 'src/core/discipline-academic-plan/domain/entity/discipline-academic-plan.entity'; import { Teacher } from 'src/core/teacher/domain/entity/teacher.entity'; interface IDepartmentCreationAttrs { id: number; title: string; shortTitle: string; } @Table({ tableName: 'departments', timestamps: false, underscored: true }) export class Department extends Model<Department, IDepartmentCreationAttrs> { @Column({ type: DataType.INTEGER, primaryKey: true, unique: true, autoIncrement: true }) id: number; @Column({ type: DataType.STRING, allowNull: false }) title: string; @Column({ type: DataType.STRING, allowNull: false }) shortTitle: string; @HasMany(() => Teacher, 'department_id') teachers: Teacher[]; @HasMany(() => DisciplineAcademicPlan, 'department_id') disciplineAcademicPlans: DisciplineAcademicPlan[]; }
from pathlib import Path from sqlite3 import Connection as SQLite3Connection from typing import List, Tuple, Union import pandas as pd import sqlalchemy from ichor.core.atoms import Atom, Atoms from ichor.core.common.str import get_characters from ichor.core.database.sql.add_to_database import AtomNames, Dataset, Points from sqlalchemy import create_engine, event, func, select from sqlalchemy.engine import Engine from sqlalchemy.orm import Session def create_sqlite_db_engine( db_path: Union[str, Path], echo=False ) -> sqlalchemy.engine.Engine: """Creates an engine to a SQLite3 database and returns the Engine object. :param db_path: Path to SQLite3 database :param echo: Whether to echo SQL queries, defaults to False :return: An egnine object for the SQL database :rtype: sqlalchemy.engine.Engine """ database_path = str(Path(db_path).absolute()) # create database engine and start session engine = create_engine( f"sqlite+pysqlite:///{database_path}", echo=echo, future=True ) return engine def create_sqlite_db_connection( db_path: Union[str, Path], echo=False ) -> sqlalchemy.engine.Connection: """Creates a connection to a SQLite3 database and returns a connection object to be used when executing SQL statements with pandas. :param db_path: Path to SQLite3 database :param echo: Whether to echo SQL queries, defaults to False :return: A connection object to the SQL database :rtype: sqlalchemy.engine.Connection """ database_path = str(Path(db_path).absolute()) # create database engine and start session engine = create_engine( f"sqlite+pysqlite:///{database_path}", echo=echo, future=True ) conn = engine.connect() return conn def raw_one_atom_data_to_df_sqlite( db_path: Union[str, Path], atom_name: str, integration_error: float = 0.001, echo=False, drop_irrelevant_cols=True, ) -> pd.DataFrame: """Returns a pandas DataFrame object containing data for one atom. :param db_path: Path or str to SQLite3 database :param atom_name: string of atom name (e.g. `C1`) :param integration_error: Integration error for AIMAll. Any point with a higher absolute integration error will not be selected, defaults to 0.001 :param echo: Whether to echo the executed SQL queries, defaults to False :param drop_irrelevant_cols: Whether to drop irrelevant columns (id columns that do not contain data) from the DataFrame, defaults to True :return: pd.DataFrame object containing the information for the DataFrame """ conn = create_sqlite_db_connection(db_path, echo=echo) stmt = ( select(Points, Dataset, AtomNames) .join(Points) .join(AtomNames) .where(func.abs(Dataset.integration_error) < integration_error) .where(AtomNames.name == atom_name) ) df = pd.read_sql(stmt, conn) # need to rename because the atom table has column "name" # and points table also has column "name" df = df.rename(columns={"name_1": "atom_name"}) # drop columns which contain IDs and other things from SQLAlchemy query if drop_irrelevant_cols: df = df.drop( ["id", "id_1", "point_id", "atom_id", "atom_name", "id_2"], axis="columns" ) return df def write_raw_one_atom_data_to_csv_sqlite( db_path: Union[str, Path], atom_name: str, integration_error: float = 0.001, echo=False, drop_irrelevant_cols=True, ): """Saves the raw data for one atom as stored in the SQLite3 database to a csv file. :param db_path: Path or str to SQLite3 database :param atom_name: string of atom name (e.g. `C1`) :param integration_error: Integration error for AIMAll. Any point with a higher absolute integration error will not be selected, defaults to 0.001 :param echo: Whether to echo the executed SQL queries, defaults to False :param drop_irrelevant_cols: Whether to drop irrelevant columns (id columns that do not contain data) from the DataFrame, defaults to True """ df = raw_one_atom_data_to_df_sqlite( db_path, atom_name, integration_error, echo, drop_irrelevant_cols ) df.to_csv(f"raw_db_data_{atom_name}.csv") def get_list_of_point_ids_from_sqlite_db( db_path: Union[str, Path], echo=False ) -> List[str]: """Returns a list of all the point names in the database :param db_path: Path or string to database :param echo: Whether to echo SQL queries, defaults to False :return: List of strings of the point names """ conn = create_sqlite_db_connection(db_path, echo=echo) stmt = select(Points) df = pd.read_sql(stmt, conn) return list(df["id"]) def get_list_of_atom_names_from_sqlite_db( db_path: Union[str, Path], echo=False ) -> List[str]: """Returns a list of all the point names in the database :param db_path: Path or string to database :param echo: Whether to echo SQL queries, defaults to False :return: List of strings of the atom names """ conn = create_sqlite_db_connection(db_path, echo=echo) stmt = select(AtomNames) df = pd.read_sql(stmt, conn) return list(df["name"]) def get_full_dataframe_for_all_atoms( db_path: Union[str, Path], echo=False, change_cols=True ) -> pd.DataFrame: """Returns a dataframe containing all the data for all atoms :param db_path: Path or str to database :param echo: Whether to echo SQL statements, defaults to False :param change_cols: Removes some unnecessary columns and also renames some columns to be more clear. :return: A pandas dataframe containing information for all atoms """ conn = create_sqlite_db_connection(db_path=db_path, echo=echo) stmt = ( select(Points, Dataset, AtomNames) .join(Dataset, Dataset.point_id == Points.id) .join(AtomNames, Dataset.atom_id == AtomNames.id) ) # do not check integration error here, just always get full df with all atoms # .where(func.abs(Dataset.integration_error) < integration_error) # ) full_df = pd.read_sql(stmt, conn) # need to rename because the atom table has column "name" # and points table also has column "name" full_df = full_df.rename(columns={"name_1": "atom_name"}) # drop columns which contain IDs and other things from SQLAlchemy query if change_cols: full_df = full_df.drop(["id_1", "point_id", "atom_id", "id_2"], axis="columns") return full_df def get_sqlite_db_information( db_path: Union[str, Path], echo=False ) -> Tuple[List[str], List[str], pd.DataFrame]: """Gets relevant information from database needed to post process data and generate datasets for machine learning :param db_path: Path to SQLite3 database containing `Points`, `AtomNames`, and `Dataset` tables. :param echo: Whether to echo executed SQL statements, defaults to False :return: Tuple of: List of point ids (integers) contained in the db, List of atom names (str) contained in db, a pd.DataFrame object containing all relevant data needed to construct the datasets. :rtype: Tuple[List[str], List[str], pd.DataFrame] """ # get point ids to loop over point_ids = get_list_of_point_ids_from_sqlite_db(db_path=db_path, echo=echo) # get atom names to loop over atom_names = get_list_of_atom_names_from_sqlite_db(db_path, echo=echo) # full dataframe contains all atoms/points below some integration error full_df = get_full_dataframe_for_all_atoms(db_path=db_path, echo=echo) return point_ids, atom_names, full_df def get_atoms_from_sqlite_point_id(full_df, point_id: int) -> "Atoms": """Returns an Atoms instance containing geometry for a point id. :param full_df: see get_df_information function :param point_id: The id of the point for which to get the geometry """ # find geometry which matches the id one_point_df = full_df.loc[full_df["id"] == point_id] # create atoms instance which will be used to calculate features atoms = Atoms() for row_id, row_data in one_point_df.iterrows(): # atoms accepts atom type (but database contains the atom index as well) atom_type = get_characters(row_data.atom_name) atoms.append(Atom(atom_type, row_data.x, row_data.y, row_data.z)) return atoms def delete_sqlite_points_by_id(engine, point_ids: List[int]): # need to enable this for SQLite3 database in order to delete correctly, see # https://stackoverflow.com/a/62327279 @event.listens_for(Engine, "connect") def _set_sqlite_pragma(dbapi_connection, connection_record): if isinstance(dbapi_connection, SQLite3Connection): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON;") cursor.close() session = Session(engine, future=True) session.query(Points).filter(Points.id.in_(point_ids)).delete() session.commit() def trajectory_from_sqlite_database( point_ids, full_df, trajectory_name: str = "trajectory_from_database.xyz" ): """Writes our trajectory from geometries in database.""" from ichor.core.files import Trajectory trajectory_inst = Trajectory(trajectory_name) for point_id in point_ids: atoms = get_atoms_from_sqlite_point_id(full_df, point_id) trajectory_inst.append(atoms) return trajectory_inst def csv_file_with_specific_properties( point_ids, full_df, all_atom_names, properties: List[str] ): """Writes out csv file for each atom containing the given properties""" for atom_name in all_atom_names: with open(f"{atom_name}_properties.csv", "w") as f: f.write(",".join(properties) + "\n") for point_id in point_ids: # find geometry which matches the id one_point_df = full_df.loc[full_df["id"] == point_id] # check that integration error is below threshold, otherwise do not calculate features # for the atom and do not add this point to training set for this atom. # if other atoms have good integration errors, the same point can be used in their training sets. row_with_atom_info = one_point_df.loc[ one_point_df["atom_name"] == atom_name ] results = [str(row_with_atom_info[p]) for p in properties] f.write(",".join(results) + "\n")
<template> <div class="validate-input-container pb-3"> <input v-if="tag !== 'textarea'" type="text" class="form-control" :class="{'is-invalid':inputRef.err}" :value="inputRef.val" @blur="validateInput" @input="updateValue" v-bind="$attrs" /> <textarea v-else type="text" class="form-control" :class="{'is-invalid':inputRef.err}" :value="inputRef.val" @blur="validateInput" @input="updateValue" v-bind="$attrs" /> <span v-if="inputRef.err" class="invalid-feedback">{{inputRef.message}}</span> </div> </template> <script lang="ts"> import { defineComponent, PropType, reactive, onMounted } from 'vue' import { emitter } from './ValidateForm.vue' interface RuleProp { type:'required' | 'email' | 'password' | 'title' | 'content'; message: string } const emailReg = /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/ export type RulesProp = RuleProp[] export type TagType = 'input' | 'textarea' export default defineComponent({ props: { rules: Array as PropType<RulesProp>, modelValue: String, tag: { type: String as PropType<TagType>, default: 'input' } }, inheritAttrs: false, setup (props, context) { const inputRef = reactive({ val: props.modelValue || '', err: false, message: '' }) // 利用特定 prop 和自定义事件 给子组件绑定v-model向父组件传值 const updateValue = (e:KeyboardEvent) => { const targetValue = (e.target as HTMLInputElement).value inputRef.val = targetValue context.emit('update:modelValue', targetValue) } // 子组件接受父组件的prop ‘rules’进行输入合法性判断 const validateInput = () => { if (props.rules) { const allPassed = props.rules.every(rule => { let passed = true inputRef.message = rule.message switch (rule.type) { case 'required': passed = (inputRef.val.trim() !== '') break case 'email': passed = emailReg.test(inputRef.val) break case 'password': passed = (inputRef.val.trim() !== '') break case 'title': passed = (inputRef.val.trim() !== '') break case 'content': passed = (inputRef.val.trim() !== '') break default: break } return passed }) inputRef.err = !allPassed return allPassed } return true } // 每个ValidateInput组件中的输入合法验证结果以自定义事件方式传递出去 onMounted(() => { emitter.emit('formItemCreated', validateInput) }) return { inputRef, validateInput, updateValue } } }) </script> <style> </style>
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add('login', (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) Cypress.Commands.add('checkTextVisibility', (text) => { cy.contains(text, { timeout: 10000 }).should('be.visible'); }) Cypress.Commands.add('clickOnLinkText', (text) => { cy.checkTextVisibility(text); cy.get('a').contains(text).click(); }) Cypress.Commands.add('clickOnButtonWithText', (buttonName) => { cy.checkTextVisibility(buttonName); cy.get('button').contains(buttonName).click(); }) Cypress.Commands.add('selectFromDropDownList', (locatorElement, valueToSelect) => { cy.get(locatorElement).select(valueToSelect).should('have.value', valueToSelect); }) /** * @description This function fill the input field using two arguments and verify if filled value is correct * @param {string} locatorElement - Locator element who gonna be used with functioon get(locatorElement) * @param {number} valueToFill - Value to fill in field */ Cypress.Commands.add('fillInputField', (locatorElement, valueToFill) => { cy.get(locatorElement).type(valueToFill); cy.get(locatorElement).should('have.value', valueToFill); })
import { useSelector } from "react-redux"; import { Routes, Route } from "react-router-dom"; import "bootstrap/dist/css/bootstrap.min.css"; import "./App.css"; import Header from "./component/products/header"; import Home from "./component/products/home"; import Products from "./component/products/product"; import Contact from "./component/products/contact"; import Footer from "./component/products/footer"; import Login from "./component/admin/login"; import CreateProduct from "./component/admin/createProducts"; import Notification from "./component/UI/Notification"; import PageLoader from "./component/UI/PageLoader"; function App() { const notification = useSelector((state) => state.ui.notification); const loader = useSelector((state) => state.ui.loading); // const notification = true; // const loader = false; console.log(notification, "notification in app.js"); return ( <div className="App"> {notification && !loader && ( <Notification status={notification.status} title={notification.title} message={notification.message} /> )} {loader && <PageLoader />} <Header /> <Routes> <Route path="/" element={<Home />} /> <Route path="/home" element={<Home />} /> <Route path="/products" element={<Products />} /> <Route path="/contact" element={<Contact />} /> <Route path="/pragyarosystem" element={<Home />} /> <Route path="/pragyarosystem/home" element={<Home />} /> <Route path="/pragyarosystem/products" element={<Products />} /> <Route path="/pragyarosystem/contact" element={<Contact />} /> <Route path="/admin" element={<Login />} /> <Route path="/product/create" element={<CreateProduct />} /> </Routes> <Footer /> </div> ); } export default App;
import { NavLink, Form, useRouteLoaderData } from 'react-router-dom'; import classes from './MainNavigation.module.css'; function MainNavigation() { const token = useRouteLoaderData('root'); return ( <header className={classes.header}> <nav> <ul className={classes.list}> <li> <NavLink to="/" className={({ isActive }) => isActive ? classes.active : undefined } end > Home </NavLink> </li> { token && <li> <NavLink to="/rockets" className={({ isActive }) => isActive ? classes.active : undefined } > Rockets </NavLink> </li> } {!token && <li> <NavLink to="/auth" className={({ isActive }) => isActive ? classes.active : undefined } > Authentication </NavLink> </li>} {token && <li> <Form action="/logout" method="post"> <button>Logout</button> </Form> </li>} </ul> </nav> </header> ); } export default MainNavigation;
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:well_shift_app/core/common/app_colors.dart'; import 'package:well_shift_app/core/common/app_localization.dart'; import 'package:well_shift_app/core/raw_data/progress_raw.dart'; class WellbeingPage extends StatefulWidget { const WellbeingPage({Key? key}) : super(key: key); @override State<WellbeingPage> createState() => _WellbeingPageState(); } class _WellbeingPageState extends State<WellbeingPage> { @override Widget build(BuildContext context) { return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 12,), Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: AppColors.whiteColor, boxShadow: [ BoxShadow( color: Color(0x330364ad), blurRadius: 8, offset: Offset(0, 4), ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ statWidget(context, title: "resilience", progress: 86, status: "Amazing"), statWidget(context, title: "performance", progress: 50, status: "Not Bad"), statWidget(context, title: "wellbeing", progress: 87, status: "Wow"), ], ), ), SizedBox( height: 24, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( AppLocalizations.of(context).translate("emotions"), style: TextStyle( color: Color(0xff0364ad), fontSize: 18, fontFamily: "Poppins", fontWeight: FontWeight.w500, ), ), Row( children: [ Text( AppLocalizations.of(context).translate('daily_score'), textAlign: TextAlign.center, style: TextStyle( color: Color(0xff0364ad), fontSize: 16, ), ), SizedBox( width: 10, ), InkWell( onTap: () {}, child: Icon(Icons.keyboard_arrow_down), ) ], ), ], ), GridView.builder( padding: const EdgeInsets.only(bottom: 20, top: 12), itemCount: emotions.length, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 20, childAspectRatio: 1.2558139535, mainAxisSpacing: 20), itemBuilder: (context, index) { return _emotionWidget(index); }, ), Text( AppLocalizations.of(context).translate("suggested_for_you"), style: TextStyle( color: Color(0xff0364ad), fontSize: 16, fontFamily: "Poppins", fontWeight: FontWeight.w500, ), ), GridView.builder( padding: const EdgeInsets.only(bottom: 20, top: 12), itemCount: 4, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 20, childAspectRatio: 1.2558139535, mainAxisSpacing: 20), itemBuilder: (context, index) { return _sugesstedWidget(index); }, ), ], ), ); } Container _sugesstedWidget(index) { return Container( alignment: Alignment.bottomLeft, padding: const EdgeInsets.only(left: 10, bottom: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Color(0x330364ad), blurRadius: 8, offset: Offset(0, 4), ), ], image: DecorationImage( image: AssetImage(suggested_for_you[index]["image"]), fit: BoxFit.cover, colorFilter: ColorFilter.mode( Colors.black.withOpacity(0.9), BlendMode.dstATop, ), ), color: Color(0xfffafbff), ), child: Text( suggested_for_you[index]["title"], style: TextStyle( color: Colors.white, fontSize: 14, fontFamily: "Poppins", fontWeight: FontWeight.w600, ), ), ); } Container _emotionWidget(int index) { String getProgressText(String status) { if (status == 'increased') { return "${emotions[index].progress}% increases"; } else if (status == 'decreased') { return "${emotions[index].progress}% decreases"; } else if (status == "stable") { return "Stable"; } else { return ""; } } double previousProgress(int newProgress) { double previousProgress; if (emotions[index].status == "increased") { previousProgress = (newProgress - emotions[index].progress) / 100; print(previousProgress); return previousProgress; } else if (emotions[index].status == "decreased") { previousProgress = (newProgress + emotions[index].progress) / 100; print(previousProgress); return previousProgress; } else { // print(previousProgress = newProgress); return (previousProgress = newProgress.toDouble()) / 100; } } return Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Color(0x330364ad), blurRadius: 8, offset: Offset(0, 4), ), ], color: Color(0xfffafbff), ), child: Column( children: [ Text( emotions[index].title, style: TextStyle( color: Color(0xff0364ad), fontSize: 16, fontFamily: "Poppins", fontWeight: FontWeight.w600, ), ), Row( children: [ emotions[index].status == 'increased' ? Icon( Icons.arrow_upward, color: Colors.green, ) : emotions[index].status == 'decreased' ? Icon( Icons.arrow_downward, color: Colors.red, ) : Icon( Icons.done, color: Colors.orange, ), SizedBox( width: 5, ), Text( getProgressText(emotions[index].status), style: TextStyle( color: Color(0xff52a8ea), fontSize: 16, ), ), ], ), Text( emotions[index].total_progress.toString() + "%", textAlign: TextAlign.right, style: TextStyle( color: Color(0xff0364ad), fontSize: 14, fontFamily: "Poppins", fontWeight: FontWeight.w500, ), ), Container( height: 8, clipBehavior: Clip.antiAlias, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: Color(0xffEEF5FE), ), child: Stack( children: [ emotions[index].status == 'decreased' ? SizedBox( height: 8, child: LinearProgressIndicator( backgroundColor: Colors.transparent, value: previousProgress(emotions[index].total_progress) .toDouble(), color: Color(0xffEE978C)), ) : SizedBox(), SizedBox( height: 8, child: LinearProgressIndicator( backgroundColor: Colors.transparent, value: emotions[index].total_progress / 100, color: emotions[index].status == 'decreased' || emotions[index].status == 'stable' ? Color(0xff3C98DE) : Colors.green, ), ), emotions[index].status == 'increased' ? SizedBox( height: 8, child: LinearProgressIndicator( backgroundColor: Colors.transparent, value: previousProgress(emotions[index].total_progress) .toDouble(), color: Color(0xff3C98DE)), ) : SizedBox(), ], ), ) ], ), ); } ///This widget is for stats that are on the very top of the [WellbeingPage] . Here you need to pass [title], [status] and [progress] of that particular stat or might me a model having these fields Column statWidget(BuildContext context, {required String title, required String status, required int progress}) { return Column( children: [ AutoSizeText( status, textAlign: TextAlign.center, style: TextStyle( color: Color.fromRGBO(82, 168, 234, 1), fontFamily: 'Poppins', fontSize: 16, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.5, /*PERCENT not supported*/ ), ), SizedBox( height: 8, ), Stack( alignment: AlignmentDirectional.center, children: [ SizedBox( width: 48, height: 48, child: CircularProgressIndicator( value: progress / 100, backgroundColor: Color(0xffDEEFFC), color: Color(0xffFFBFB5), ), ), Align( alignment: Alignment.center, child: Text( '$progress%', textAlign: TextAlign.center, style: TextStyle( color: Color.fromRGBO(20, 123, 202, 1), fontFamily: 'Poppins', fontSize: 13, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.w600, // height: 2.3846153846153846, ), ), ) ], ), SizedBox( height: 8, ), AutoSizeText( AppLocalizations.of(context).translate(title), textAlign: TextAlign.center, style: TextStyle( color: Color.fromRGBO(20, 123, 202, 1), fontFamily: 'Poppins', fontSize: 16, letterSpacing: 0 /*percentages not used in flutter. defaulting to zero*/, fontWeight: FontWeight.normal, height: 1.9375, ), ) ], ); } }
import os import imageio import numpy as np from PIL import Image from skimage.metrics import structural_similarity as ssim from html import escape def resize_image(input_path, size): with Image.open(input_path) as img: img_resized = img.resize(size) img_resized.save(input_path) def compare_images(image1_path, image2_path): target_size = (300, 200) resize_image(image1_path, target_size) resize_image(image2_path, target_size) # Load images img1 = imageio.imread(image1_path) img2 = imageio.imread(image2_path) # Convert images to grayscale img1_gray = np.mean(img1, axis=-1) img2_gray = np.mean(img2, axis=-1) # Compute structural similarity index similarity_index, _ = ssim(img1_gray, img2_gray, data_range=img2_gray.max() - img2_gray.min(), full=True) return similarity_index def generate_html_report(image_folder1, image_folder2, output_file='report.html'): # Get the list of image files in the folders images1 = [f for f in os.listdir(image_folder1) if f.endswith('.png') or f.endswith('.jpg')] images2 = [f for f in os.listdir(image_folder2) if f.endswith('.png') or f.endswith('.jpg')] # Generate HTML report html_content = "<html><head><title>Image Comparison Report</title></head><body>" html_content += "<h1>Image Comparison Report</h1>" for image1 in images1: for image2 in images2: image1_path = os.path.join(image_folder1, image1) image2_path = os.path.join(image_folder2, image2) # Compare images similarity_index = compare_images(image1_path, image2_path) # Add information to HTML report if image1 == image2 : html_content += f"<h2>{escape(image1)} vs {escape(image2)}</h2>" html_content += f"<p>Structural Similarity Index: {similarity_index:.4f}</p>" html_content += f"<img src='data:image/png;base64,{imageio.imread(image1_path).tolist()}' alt='Image 1'><br>" html_content += f"<img src='data:image/png;base64,{imageio.imread(image2_path).tolist()}' alt='Image 2'><br>" html_content += "<hr>" html_content += "</body></html>" # Save HTML report to file with open(output_file, 'w') as html_file: html_file.write(html_content) print(f"HTML report generated: {output_file}") # Example usage generate_html_report('data/version_a', 'data/version_b', 'comparison_report.html')
<?php namespace App\Controller; use App\Repository\PlatRepository; use App\Repository\CartRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\Routing\Annotation\Route; #[Route('/commande', name: 'app_commande')] class CommandeController extends AbstractController { #[Route('/ajout', name: 'add')] public function add(SessionInterface $session, PlatRepository $platRepository, EntityManagerInterface $em): Response { $this->denyAccessUnlessGranted('ROLE_USER'); $panier = $session->get('panier', []); if($panier === []){ $this->addFlash('message', 'Votre panier est vide'); return $this->redirectToRoute('app_acueil'); } //Le panier n'est pas vide, on crée la commande $commande = new Commande(); // On remplit la commande $commande->setUtilisateur ($this->setUtilisateur()); $commande->setReference(uniqid()); // On parcourt le panier pour créer les détails de commande foreach($panier as $item => $quantite){ $commande = new Commande(); // On va chercher le produit $plat = $platRepository->find($item); $prix = $plat->getPrix(); // On crée le détail de commande $commande->setPlat($plat); $commande->setPrix($prix); $commande->setQuantite($quantite); $commande->setCommande($commande); } // On persiste et on flush $em->persist($commande); $em->flush(); $session->remove('panier'); $this->addFlash('message', 'Commande créée avec succès'); return $this->redirectToRoute('app_accueil'); } }
%>@ingroup maths %> @file %> @brief Calculates the stability curve for a set of feature subsets %> %> This function is suitable for feature subsets found using Sequential Forward Feature Selection %> %> Kuncheva's "consistency" formula is I_c = (r-k^2/nf)/(k-k^2/nf), where r is the number of common elements in the two sets, and k is the %> number of elements of either sets %> %> %> <h3>References</h3> %> %> Kuncheva, L. I. A stability index for feature selection, 390-395. %> %> @param subsets matrix or cell of subsets. If matrix, each row is a subset. A subset contains feature indexes. If cell of subsets, all %> subsets must have the same number of elements %> @param nf Number of features %> @param type ='kun'. Type of stability measuse. Possibilities are: %> @arg 'kun' Kuncheva's Stability Index %> @arg ... (open for others) %> @param type2='mul' %> @arg 'uni' evaluates position in subsets individually %> @arg 'mul' evaluates considering m-sized subsets (m = 1..k) %> @return y nf x stability curve function y = featurestability(subsets, nf, type, type2) if nargin < 3 || isempty(type) type = 'kun'; end; if nargin < 4 || isempty(type2) type2 = 'mul'; end; flag_uni = strcmp(type2, 'uni'); %> translates type into a function handle switch type case 'kun' f_type = @feacons_kun; otherwise irerror(sprintf('Feature consistency type "%s" not implemented', type)); end; % if cell, converts to matrix if iscell(subsets) subsets = subsets2matrix(subsets); end; [nsub, k] = size(subsets); y = zeros(1, k); for m = 1:k if flag_uni temp = subsets(:, m); else temp = subsets(:, 1:m); end; for i = 1:nsub for j = i+1:nsub y(m) = y(m)+f_type(temp(i, :), temp(j, :), nf); end; end; end; y = y*2/(nsub*(nsub-1)); % takes the average consistency
import { DesktopDatePicker, LocalizationProvider } from '@mui/lab'; import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { Autocomplete, Container, FormControl, FormHelperText, InputLabel, MenuItem, Select, styled, TextField, Typography, } from '@mui/material'; import { EmailValue, Label, Row, Value } from 'app/components/KeyText'; import { translations } from 'locales/translations'; import moment from 'moment'; import { memo, useEffect, useState } from 'react'; import { Controller, useFormContext } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import NumberFormat from 'react-number-format'; import { CustomerKpr } from 'types/CustomerManagement'; import { businessOwnershipType, businessSector, duration, employmentType, idCard, Type, } from '../../slice/data'; export const RootStyle = styled('div')({ margin: '0px 1rem 3rem 1rem', '& .MuiOutlinedInput-root': { borderRadius: '8px', background: '#F6F8FC!important', }, '& .MuiInputLabel-root': { color: '#005FC5', }, '& .MuiFilledInput-root': { border: '1px solid #005FC5', borderRadius: '8px', }, '& .MuiFilledInput-root:after': { right: 'unset', height: '100%', width: '100%', }, '& .MuiFilledInput-root.Mui-error:after': { border: '1px solid #FF4842', borderRadius: '8px', }, '& .MuiFilledInput-root:before': { right: 'unset', content: '""', }, marginRight: '5rem', }); interface Props { customerKprInformation?: CustomerKpr; } export const Warrantor = memo((props: Props) => { const { customerKprInformation } = props; const { t } = useTranslation(); const [formValues, setFormValues] = useState({ insurerIdCardType: '', insurerEmploymentType: '', insurerBusinessSector: '', insurerDuration: '', insurerBusinessOwnershipType: '', }); const { control, setValue, getValues, clearErrors, setError, formState: { errors }, } = useFormContext(); useEffect(() => { if (customerKprInformation) { setFormValues({ ...formValues, insurerIdCardType: customerKprInformation?.dataSet?.insurer?.idCardType || '', insurerEmploymentType: customerKprInformation?.dataSet?.insurer?.insurerEmployment ?.employmentType || '', insurerBusinessSector: customerKprInformation?.dataSet?.insurer?.insurerEmployment ?.businessSector || '', insurerBusinessOwnershipType: customerKprInformation?.dataSet?.insurer?.insurerEmployment ?.businessOwnershipType || '', insurerDuration: customerKprInformation?.dataSet?.insurer?.insurerEmployment ?.duration || '', }); setValue( 'dataSet.insurer.fullName', customerKprInformation?.dataSet?.insurer?.fullName || '', ); } }, [customerKprInformation]); const onChangeDob = (event: any) => { if ( event && event.toString() !== 'Invalid Date' && !moment(event).isAfter(new Date()) ) { setValue('dataSet.insurer.dob', event); clearErrors('dobWarrantor'); } else { setValue('dataSet.insurer.dob', ''); setError('dobWarrantor', { message: 'Invalid Date', }); } }; return ( <Container sx={{ marginTop: '0', minHeight: '600px' }}> <Typography sx={{ fontWeight: 600 }}> {t(translations.customerAccountManagement.warrantorOrSpouseInfo)} </Typography> <RootStyle> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.fullName" render={({ field }) => { return ( <TextField {...field} error={!!errors?.insurerFullName} helperText={errors?.insurerFullName?.message} label={`${t( translations.customerAccountManagement .fullNameAccordingIdCard, )}`} type="text" variant="filled" fullWidth onChange={field.onChange} /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.dob" render={({ field }) => { return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <DesktopDatePicker {...field} label={`${t( translations.developerInformation.dateOfBirth, )}`} inputFormat="dd/MM/yyyy" onChange={onChangeDob} maxDate={new Date()} minDate={new Date(1900, 1, 1)} renderInput={params => { const newParams = { ...params }; delete newParams.error; return ( <TextField {...newParams} variant="filled" error={ !!errors.dobWarrantor || field.value.toString() === 'Invalid Date' } helperText={ errors?.dobWarrantor?.message || field.value.toString() === 'Invalid Date' ? 'Invalid Date' : '' } /> ); }} /> </LocalizationProvider> ); }} control={control} defaultValue="" /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <InputLabel error={!!errors.insurerIdCardType} sx={ formValues?.insurerIdCardType ? { marginTop: '1rem', color: '#005FC5', } : { color: '#005FC5', '&.MuiInputLabel-root': { '&.Mui-focused': { color: '#005FC5', marginTop: '1rem', }, }, } } > {`${t(translations.customerAccountManagement.idCardType)}`} </InputLabel> <Controller name="dataSet.insurer.idCardType" render={({ field }) => { return ( <Select {...field} labelId="insurerIdCardType" variant="filled" error={!!errors.insurerIdCardType} label={`${t( translations.customerAccountManagement.idCardType, )}`} value={formValues?.insurerIdCardType} onChange={e => { field.onChange(e); setFormValues({ ...formValues, insurerIdCardType: e.target.value, }); }} > {(idCard || []).map((item: Type, index) => ( <MenuItem key={item.value} value={item.value}> {item.name} </MenuItem> ))} </Select> ); }} control={control} /> {errors?.insurerIdCardType && ( <FormHelperText style={{ color: 'red' }}> {errors?.insurerIdCardType?.message} </FormHelperText> )} </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.idCardNumber" render={({ field }) => { return ( <NumberFormat type="text" variant="filled" label={`${t( translations.customerAccountManagement.idCardNumber, )}`} customInput={TextField} onChange={field.onChange} helperText={errors?.insurerIdCardNumber?.message} error={!!errors?.insurerIdCardNumber} allowLeadingZeros /> ); }} control={control} /> </FormControl> <Row style={{ margin: '1.5rem 0' }}> <Label> {t(translations.customerAccountManagement.filledIfTheGuarantor)} </Label> </Row> <FormControl fullWidth> <InputLabel error={!!errors.insurerIdCardType} sx={ formValues?.insurerIdCardType ? { marginTop: '1rem', color: '#005FC5', } : { color: '#005FC5', '&.MuiInputLabel-root': { '&.Mui-focused': { color: '#005FC5', marginTop: '1rem', }, }, } } > {`${t( translations.customerAccountManagement.employmentTypeOrStatus, )}`} </InputLabel> <Controller name="dataSet.insurer.insurerEmployment.employmentType" render={({ field }) => { return ( <Select {...field} labelId="insurerEmploymentType" variant="filled" error={!!errors.insurerEmploymentType} label={`${t( translations.customerAccountManagement .employmentTypeOrStatus, )}`} value={formValues?.insurerEmploymentType} onChange={e => { field.onChange(e); setFormValues({ ...formValues, insurerEmploymentType: e.target.value, }); }} > {(employmentType || []).map((item: Type, index) => ( <MenuItem key={item.value} value={item.value}> {item.name} </MenuItem> ))} </Select> ); }} control={control} /> {errors?.insurerEmploymentType && ( <FormHelperText style={{ color: 'red' }}> {errors?.insurerEmploymentType?.message} </FormHelperText> )} </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.insurerEmployment.companyName" render={({ field }) => { return ( <TextField {...field} error={!!errors?.insurerCompanyName} helperText={errors?.insurerCompanyName?.message} label={`${t( translations.customerAccountManagement.companyName, )}`} type="text" variant="filled" fullWidth onChange={field.onChange} /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <InputLabel error={!!errors.insurerBusinessSector} sx={ formValues?.insurerBusinessSector ? { marginTop: '1rem', color: '#005FC5', } : { color: '#005FC5', '&.MuiInputLabel-root': { '&.Mui-focused': { color: '#005FC5', marginTop: '1rem', }, }, } } > {`${t(translations.customerAccountManagement.businessType)}`} </InputLabel> <Controller name="dataSet.insurer.insurerEmployment.businessSector" render={({ field }) => { return ( <Select {...field} labelId="insurerBusinessSector" variant="filled" error={!!errors.insurerBusinessSector} label={`${t( translations.customerAccountManagement.businessType, )}`} value={formValues?.insurerBusinessSector} onChange={e => { field.onChange(e); setFormValues({ ...formValues, insurerBusinessSector: e.target.value, }); }} > {(businessSector || []).map((item: Type, index) => ( <MenuItem key={item.value} value={item.value}> {item.name} </MenuItem> ))} </Select> ); }} control={control} /> {errors?.insurerBusinessSector && ( <FormHelperText style={{ color: 'red' }}> {errors?.insurerBusinessSector?.message} </FormHelperText> )} </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.insurerEmployment.employeeId" render={({ field }) => { return ( <TextField {...field} error={!!errors?.insurerEmployeeId} helperText={errors?.insurerEmployeeId?.message} label={`${t( translations.customerAccountManagement.employeeID, )}`} type="text" variant="filled" fullWidth onChange={field.onChange} /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.insurerEmployment.officeAddress" render={({ field }) => { return ( <TextField {...field} error={!!errors?.insurerOfficeAddress} helperText={errors?.insurerOfficeAddress?.message} label={`${t( translations.customerAccountManagement.officeAddress, )}`} type="text" variant="filled" fullWidth onChange={field.onChange} /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.insurerEmployment.officePhoneNumber" render={({ field }) => { return ( <NumberFormat type="text" variant="filled" label={`${t( translations.customerAccountManagement.officePhone, )}`} customInput={TextField} onChange={field.onChange} helperText={errors?.insurerOfficePhone?.message} error={!!errors?.insurerOfficePhone} allowLeadingZeros /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <Controller name="dataSet.insurer.insurerEmployment.positionOrGrade" render={({ field }) => { return ( <TextField {...field} error={!!errors?.insurerPositionOrGrade} helperText={errors?.insurerPositionOrGrade?.message} label={`${t( translations.customerAccountManagement.positionOrGrade, )}`} type="text" variant="filled" fullWidth onChange={field.onChange} /> ); }} control={control} /> </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <InputLabel error={!!errors.insurerDuration} sx={ formValues?.insurerDuration ? { marginTop: '1rem', color: '#005FC5', } : { color: '#005FC5', '&.MuiInputLabel-root': { '&.Mui-focused': { color: '#005FC5', marginTop: '1rem', }, }, } } > {`${t( translations.customerAccountManagement.durationOfEmployment, )}`} </InputLabel> <Controller name="dataSet.insurer.insurerEmployment.duration" render={({ field }) => { return ( <Select {...field} labelId="insurerDuration" variant="filled" error={!!errors.insurerDuration} label={`${t( translations.customerAccountManagement.durationOfEmployment, )}`} value={formValues?.insurerDuration} onChange={e => { field.onChange(e); setFormValues({ ...formValues, insurerDuration: e.target.value, }); }} > {(duration || []).map((item: Type, index) => ( <MenuItem key={item.value} value={item.value}> {item.name} </MenuItem> ))} </Select> ); }} control={control} /> {errors?.insurerDuration && ( <FormHelperText style={{ color: 'red' }}> {errors?.insurerDuration?.message} </FormHelperText> )} </FormControl> <FormControl fullWidth sx={{ mt: 3 }}> <InputLabel error={!!errors.insurerBusinessOwnershipType} sx={ formValues?.insurerBusinessOwnershipType ? { marginTop: '1rem', color: '#005FC5', } : { color: '#005FC5', '&.MuiInputLabel-root': { '&.Mui-focused': { color: '#005FC5', marginTop: '1rem', }, }, } } > {`${t( translations.customerAccountManagement.businessOwnershipType, )}`} </InputLabel> <Controller name="dataSet.insurer.insurerEmployment.businessOwnershipType" render={({ field }) => { return ( <Select {...field} labelId="insurerBusinessOwnershipType" variant="filled" error={!!errors.insurerBusinessOwnershipType} label={`${t( translations.customerAccountManagement .businessOwnershipType, )}`} value={formValues?.insurerBusinessOwnershipType} onChange={e => { field.onChange(e); setFormValues({ ...formValues, insurerBusinessOwnershipType: e.target.value, }); }} > {(businessOwnershipType || []).map((item: Type, index) => ( <MenuItem key={item.value} value={item.value}> {item.name} </MenuItem> ))} </Select> ); }} control={control} /> {errors?.insurerBusinessOwnershipType && ( <FormHelperText style={{ color: 'red' }}> {errors?.insurerBusinessOwnershipType?.message} </FormHelperText> )} </FormControl> </RootStyle> </Container> ); });
<!DOCTYPE html> <html> <head> <title>Portholes</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> </head> <body<% if params[:controller] == 'folders' %> class="sidebar-content"<% elsif params[:controller] == 'articles' %> class="content-sidebar"<% end %>> <header class="site-header" itemscope itemtype="https://schema.org/WPHeader"> <div class="title-area"> <p class="site-title" itemprop="headline"><%= link_to "Portholes", folder_path("unread") %> RAILS</p> </div> <button class="responsive-menu-icon" aria-expanded="false" aria-controls="navigation">Menu</button> <nav class="navigation" id="navigation" itemscope itemtype="https://schema.org/SiteNavigationElement"> <ul class="menu" data-collapsed="true"> <% if user_signed_in? %> <li class="menu-item"> <a id="add-link" class="button primary small" href="/add-link/"><%= inline_svg('plus-solid.svg') %>Add Link</a> </li> <li class="menu-item"> <%= link_to(new_article_path, class: 'button primary small') do %><%= inline_svg('plus-solid.svg') %>Add Article<% end %> </li> <li class="menu-item"> <a href="/navigation/" class="sub-menu-toggle" aria-expanded="false"> <%= current_user.email %> <svg aria-hidden="true" focusable="false" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"></path></svg> </a> <ul class="sub-menu" data-collapsed="true"> <% if downloadable_folder? %> <li class="menu-item"><%= link_to("Download", download_folder_path) %></li> <% end %> <% if current_page?(folder_path("unread")) %> <li class="menu-item"><a id="archive-all" href="/archive-all/" itemprop="url">Archive All</a></li> <% end %> <%= content_tag(:li, link_to("Settings", edit_user_registration_path), class: "menu-item") %> <%= content_tag(:li, link_to("Help & FAQ", "https://portholes.app/faq/"), class: "menu-item") %> <%= content_tag(:li, link_to("Log Out", destroy_user_session_path, method: :delete), class: "menu-item") %> </ul> </li> <% else %> <%= content_tag(:li, link_to("Log In", new_user_session_path), class: "menu-item") %> <%= content_tag(:li, link_to("Create Account", new_user_registration_path), class: "menu-item") %> <% end %> </ul> </nav> </header> <div class="site-inner"> <%= render "layouts/flash" %> <%= yield %> </div> <div id="add-link-modal" class="modal add-link"> <div class="modal__content"> <div class="modal__header"> Add a New Article <span class="modal__close" data-close="true" title="Close">&times;</span> </div> <div class="modal__body"> <%= form_with(model: @article, url: articles_path, local: true, html: { class: 'article-add' }) do |form| %> <%= form.fields_for 'article' do |link| %> <%= link.label :link, class: "screen-reader-text" %> <%= link.text_field :link, class: "article-add__input" %> <% end %> <% if downloadable_folder? %> <%= hidden_field_tag 'folder', get_name_from_permalink(params[:permalink]) %> <% else %> <%= hidden_field_tag 'folder', 'Unread' %> <% end %> <%= form.submit "Add Article", class: "button primary" %> <% end %> </div> </div> </div> </body> </html>
% Convert a dicom to a grayscale image with [0 nLevels-1]. % % fileName: a char vector specifying the full path of a dicom file, or a structure containing meta % data. % % nLevels: an integer specifying the grayscale ([0 nLevels-1]) of the converted grayscale image. If % nLevels is 256, then I is uint8 ([0 255]); if nLevels is 65536, then I is uint16 ([0 65535]); else % I is double. If nargin == 1, then set nLevels = 256 and use default windowCenter and windowWidth. % If nLevels is [], then set nLevels = windowWidth. % % windowCenter: an integer specifying the window center used for converting. % % windowWidth: an integer specifying the window width used for converting. % % I: a grayscale image with grayscale [0 nLevels-1]. % % info: a structure of meta data representing the dicom file. %
# Copyright 2022-2023 XProbe 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. from __future__ import annotations import builtins from .adapter import MarsEntity, mars_execute from .data import DataRef def _get_mars_entity(ref: DataRef) -> MarsEntity: mars_entity = getattr(ref.data, "_mars_entity", None) if mars_entity is not None: return mars_entity else: # pragma: no cover raise NotImplementedError( f"Unable to execute an instance of {type(ref).__name__} " ) def run(obj: DataRef | list[DataRef] | tuple[DataRef], **kwargs) -> None: """ Manually trigger execution. Parameters ---------- obj : DataRef or collection of DataRefs DataRef or collection of DataRefs to execute. """ refs = [] if isinstance(obj, DataRef): refs.append(obj) else: refs.extend(obj) refs_to_execute = _collect_executable_user_ns_refs(refs) for ref in refs: if id(ref) not in refs_to_execute and need_to_execute(ref): refs_to_execute[id(ref)] = ref mars_tileables = [_get_mars_entity(ref) for ref in refs_to_execute.values()] if mars_tileables: mars_execute(mars_tileables, **kwargs) def need_to_execute(ref: DataRef) -> bool: mars_entity = _get_mars_entity(ref) return ( hasattr(mars_entity, "_executed_sessions") and len(getattr(mars_entity, "_executed_sessions")) == 0 ) def _is_in_final_results(ref: DataRef, results: list[DataRef]): mars_entity = _get_mars_entity(ref) result_mars_entities = [_get_mars_entity(result) for result in results] for result_mars_entity in result_mars_entities: stack = [result_mars_entity] while stack: e = stack.pop() if e.key == mars_entity.key: return True stack.extend(e.inputs) return False def _collect_executable_user_ns_refs(result_refs: list[DataRef]) -> dict[int, DataRef]: """ Collect DataRefs defined in user's interactive namespace that are able to execute. """ def _is_ipython_output_cache(name: str): # _, __, ___ or _<n> where <n> stands for the output line number. return name in ["_", "__", "___"] or name.startswith("_") and name[1:].isdigit() if not _is_interactive() or not _is_ipython_available(): return {} ipython = getattr(builtins, "get_ipython")() return dict( (id(v), v) for k, v in ipython.user_ns.items() if isinstance(v, DataRef) and not _is_ipython_output_cache(k) and need_to_execute(v) and _is_in_final_results(v, result_refs) ) def _is_interactive() -> bool: import sys # See: https://stackoverflow.com/a/64523765/7098025 return hasattr(sys, "ps1") def _is_ipython_available() -> bool: return ( hasattr(builtins, "get_ipython") and getattr(builtins, "get_ipython", None) is not None )
#include <math.h> #include "vectors.hpp" const float ROUNDING_ERROR_f32 = 0.000001f; bool floatIsZero(float val) { return (val + ROUNDING_ERROR_f32 >= 0.0f) && (val - ROUNDING_ERROR_f32 <= 0.0f); } bool floatInUnit(float val) { return (val >= 0.0f) && (val <= 1.0f); } bool Vector2D::isZero() { return floatIsZero(x) && floatIsZero(y); } float Vector2D::length() { return sqrtf(x * x + y * y); } Vector2D Vector2D::toUnit() { float len = 1 / length(); return Vector2D(x * len, y * len); } float Vector2D::distance(const Vector2D& other) const { return sqrtf((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y)); } Vector2D& operator+=(Vector2D& left, const Vector2D& right) { left.x += right.x; left.y += right.y; return left; } Vector2D& operator-=(Vector2D& left, const Vector2D& right) { left.x -= right.x; left.y -= right.y; return left; } Vector2D operator+(Vector2D left, const Vector2D& right) { left += right; return left; } Vector2D operator-(Vector2D left, const Vector2D& right) { left -= right; return left; } Vector2D operator*(const Vector2D& left, const float right) { return Vector2D(left.x * right, left.y * right); } Vector2D operator/(const Vector2D& left, const float right) { return Vector2D(left.x / right, left.y / right); } Vector2D Vector2D::rotate(float angle) { return Vector2D( x * cosf(angle) - y * sinf(angle), x * sinf(angle) + y * cosf(angle)); } float Vector2D::pseudoCross(const Vector2D& other) { return x * other.y - y * other.x; } Vector2D Vector2D::fromPolar(float angle, float radius) { return Vector2D(-radius * sinf(angle), radius * cosf(angle)); }
/* eslint-disable no-unused-vars */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/ban-types */ import { ComputedGetter, ComputedOptions, DefineComponent, EmitsOptions, ExtractDefaultPropTypes, MethodOptions, SlotsType } from 'vue' import { PublicProps, ResolveProps } from '../extra-vue-types' // ---------------------------------------------------------------------------- // Props // ---------------------------------------------------------------------------- export interface WaveBreadcrumbsProps { /** * An array of items to display in the breadcrumbs. Each item must be an object containing a `label` and a `route`. * If no route is found the item will be wrapped in a span instead of a link. * @property {Array<any>} [items] * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ items: Array<any> /** * When set to true, and if the last item has a provided route, the last item will be a link. * @property {boolean} linkLastItem * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ linkLastItem?: boolean /** * Applies a text color to the breadcrumb's links. * Accepts all the color names of the color palette, status colors, or custom colors (learn more about the colors in the `colors` knowledge base page). * Providing a color hex, rgb(a) or hsl(a) will not work. * @property {string} color * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs * @see https://antoniandre.github.io/wave-ui/colors */ color?: string /** * Applies a text color (also applies to icons) to the breadcrumb's separators. * Accepts all the color names of the color palette, status colors, or custom colors (learn more about the colors in the `colors` knowledge base page). * Providing a color hex, rgb(a) or hsl(a) will not work. * @property {string} separatorColor - Default: 'grey-light1' * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs * @see https://antoniandre.github.io/wave-ui/colors */ separatorColor?: string /** * Provide a custom icon for the separators. * @property {string} icon - Default: 'wi-chevron-right' * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ icon?: string /** * The property name (aka "key") in each item object where to find the link of the item. * @property {string} itemRouteKey - Default: 'route' * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ itemRouteKey?: string /** * The property name (aka "key") in each item object where to find the label of the item. * @property {string} itemLabelKey - Default: 'label' * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ itemLabelKey?: string /** * Sets the font size of the items. * @property {boolean} xs * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ xs?: boolean /** * Sets the font size of the items. * @property {boolean} sm * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ sm?: boolean /** * Sets the font size of the items. * @property {boolean} md * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ md?: boolean /** * Sets the font size of the items. * @property {boolean} lg * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ lg?: boolean /** * Sets the font size of the items. * @property {boolean} xl * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ xl?: boolean } // ---------------------------------------------------------------------------- // Emits // ---------------------------------------------------------------------------- export interface WaveBreadcrumbsEmits { } // ---------------------------------------------------------------------------- // Computeds // ---------------------------------------------------------------------------- export interface WaveBreadcrumbsComputeds extends ComputedOptions { /** * TODO: Add Description * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ hasRouter: ComputedGetter<any> /** * TODO: Add Description * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ size: ComputedGetter<any> /** * TODO: Add Description * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ classes: ComputedGetter<any> } // ---------------------------------------------------------------------------- // Methods // ---------------------------------------------------------------------------- export interface WaveBreadcrumbsMethods extends MethodOptions { } // ---------------------------------------------------------------------------- // Slots // ---------------------------------------------------------------------------- export type WaveBreadcrumbsSlots = SlotsType<{ /** * Provide a custom template for the breadcrumbs' separator. * @param {any} index The separator index in the array of items. Starts at 1. * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ 'separator': (_: { index: any }) => any /** * Provide a custom template for the breadcrumbs' item. * @param {any} item The current item object. * @param {any} index The item index in the array of items. Starts at 1. * @param {any} isLast A boolean indicating if the current item is the last one. May be useful if you want a particular template for the current page. * @param {any} key TODO: Describe me! * @see https://antoniandre.github.io/wave-ui/w-breadcrumbs */ 'item': (_: { item: any, index: any, isLast: any, key: any }) => any }> // ---------------------------------------------------------------------------- // Component // ---------------------------------------------------------------------------- export type WBreadcrumbs = DefineComponent< WaveBreadcrumbsProps, {}, {}, WaveBreadcrumbsComputeds, WaveBreadcrumbsMethods, {}, {}, WaveBreadcrumbsEmits & EmitsOptions, string, PublicProps, ResolveProps<WaveBreadcrumbsProps & WaveBreadcrumbsEmits, EmitsOptions>, ExtractDefaultPropTypes<WaveBreadcrumbsProps>, WaveBreadcrumbsSlots >
# Python Game Of Life with Pygame This is a Python implementation of Conway's Game of Life using Pygame. The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It's a zero-player game, meaning its evolution is determined by its initial state, requiring no further input from human players. Players set up the initial configuration of cells on a grid, and then watch as generations evolve over time. The project aims to provide an interactive experience, allowing users to visually explore the behavior of cellular automata through various patterns and configurations. ## Features - **Interactive Grid**: Click to toggle cells between alive and dead states, crafting your initial setup or modifying it on the fly. - **Control Simulation Flow**: Easily start, pause, or reset your simulation with keyboard shortcuts. - **Dynamic Speed Adjustment**: Use keyboard inputs to speed up or slow down the evolution of the generations. - **Random Initialization**: Generate a random starting point to explore unexpected patterns and behaviors. - **Infinite Grid**: Thanks to edge wrapping, experience an unbounded canvas for your cellular automata, allowing patterns to move seamlessly across the grid boundaries. ## How to Run the Program Getting started with the Game of Life simulation is straightforward. After cloning the repository and setting up your environment, you're ready to launch the program and engage with the interactive simulation. Here's your guide to controlling and interacting with the Game of Life: You can begin the simulation (must have pygame installed) in the terminal by the following command: import main - **Start the Simulation**: Press `Enter` to initiate the simulation. Observe as the cells transition through generations, adhering to the Game of Life's rules. - **Pause/Stop the Simulation**: Hit the `Spacebar` to pause the simulation at any moment. - **Create a Random Initial State**: Tap `R` to populate the grid with a random mix of alive and dead cells, perfect for kicking off a new simulation with unforeseen developments. - **Clear the Grid**: Want a clean slate? Press `C` to clear the grid, turning all cells into a dead state. - **Adjust Simulation Speed**: - Increase the pace by pressing `F`, making the generations evolve quicker. - Slow things down with `S`, giving you a closer look at each generation's transformation. - **Toggle Cell States with Mouse Click**: Click on any cell within the grid to toggle its state. Bringing a living cell to death or reviving a dead cell allows you to manually craft or alter patterns and see how they unfold.
// ignore_for_file: constant_identifier_names import 'dart:convert'; import 'package:equatable/equatable.dart'; import 'package:flutter/foundation.dart'; import 'package:volunteersapp/data/models/authentication/auth_accounts_signin_with_password/EmailInfo.dart'; import 'package:volunteersapp/data/models/authentication/auth_accounts_signin_with_password/MfaEnrollment.dart'; import 'package:volunteersapp/data/models/authentication/auth_accounts_signin_with_password/SignInWithPasswordResponseModelNotification.dart'; import 'package:volunteersapp/data/models/authentication/auth_accounts_signin_with_password/TotpInfo.dart'; SignInWithPasswordResponseModel signInWithPasswordResponseModelFromJson(String str) => SignInWithPasswordResponseModel.fromJson(json.decode(str)); String signInWithPasswordResponseModelToJson(SignInWithPasswordResponseModel data) => json.encode(data.toJson()); class SignInWithPasswordResponseModel extends Equatable { final String kind; final String localId; final String email; final String displayName; final String idToken; final bool registered; final String profilePicture; final String oauthAccessToken; final int oauthExpireIn; final String oauthAuthorizationCode; final String refreshToken; final String expiresIn; final String mfaPendingCredential; final List<MfaEnrollment> mfaInfo; final List<SignInWithPasswordResponseModelNotification> signInWithPasswordResponseModelNotifications; const SignInWithPasswordResponseModel({ required this.kind, required this.localId, required this.email, required this.displayName, required this.idToken, required this.registered, required this.profilePicture, required this.oauthAccessToken, required this.oauthExpireIn, required this.oauthAuthorizationCode, required this.refreshToken, required this.expiresIn, required this.mfaPendingCredential, required this.mfaInfo, required this.signInWithPasswordResponseModelNotifications, }); factory SignInWithPasswordResponseModel.fromJson(Map<String, dynamic> json) => SignInWithPasswordResponseModel( kind: json['kind'], localId: json['localId'], email: json['email'], displayName: json['displayName'], idToken: json['idToken'], registered: json['registered'], profilePicture: json['profilePicture'], oauthAccessToken: json['oauthAccessToken'], oauthExpireIn: json['oauthExpireIn'], oauthAuthorizationCode: json['oauthAuthorizationCode'], refreshToken: json['refreshToken'], expiresIn: json['expiresIn'], mfaPendingCredential: json['mfaPendingCredential'], mfaInfo: List<MfaEnrollment>.from(json['mfaInfo'].map((x) => MfaEnrollment.fromJson(x))), signInWithPasswordResponseModelNotifications: List<SignInWithPasswordResponseModelNotification>.from(json['signInWithPasswordResponseModelNotifications'].map((x) => SignInWithPasswordResponseModelNotification.fromJson(x))), ); Map<String, dynamic> toJson() => { 'kind': kind, 'localId': localId, 'email': email, 'displayName': displayName, 'idToken': idToken, 'registered': registered, 'profilePicture': profilePicture, 'oauthAccessToken': oauthAccessToken, 'oauthExpireIn': oauthExpireIn, 'oauthAuthorizationCode': oauthAuthorizationCode, 'refreshToken': refreshToken, 'expiresIn': expiresIn, 'mfaPendingCredential': mfaPendingCredential, 'mfaInfo': List<dynamic>.from(mfaInfo.map((x) => x.toJson())), 'signInWithPasswordResponseModelNotifications': List<dynamic>.from(signInWithPasswordResponseModelNotifications.map((x) => x.toJson())), }; @override List<Object> get props => [ kind, localId, email, displayName, idToken, registered, profilePicture, oauthAccessToken, oauthExpireIn, oauthAuthorizationCode, refreshToken, expiresIn, mfaPendingCredential, mfaInfo, signInWithPasswordResponseModelNotifications, ]; @override bool get stringify => true; SignInWithPasswordResponseModel copyWith({ String? kind, String? localId, String? email, String? displayName, String? idToken, bool? registered, String? profilePicture, String? oauthAccessToken, int? oauthExpireIn, String? oauthAuthorizationCode, String? refreshToken, String? expiresIn, String? mfaPendingCredential, List<MfaEnrollment>? mfaInfo, List<SignInWithPasswordResponseModelNotification>? signInWithPasswordResponseModelNotifications, }) { return SignInWithPasswordResponseModel( kind: kind ?? this.kind, localId: localId ?? this.localId, email: email ?? this.email, displayName: displayName ?? this.displayName, idToken: idToken ?? this.idToken, registered: registered ?? this.registered, profilePicture: profilePicture ?? this.profilePicture, oauthAccessToken: oauthAccessToken ?? this.oauthAccessToken, oauthExpireIn: oauthExpireIn ?? this.oauthExpireIn, oauthAuthorizationCode: oauthAuthorizationCode ?? this.oauthAuthorizationCode, refreshToken: refreshToken ?? this.refreshToken, expiresIn: expiresIn ?? this.expiresIn, mfaPendingCredential: mfaPendingCredential ?? this.mfaPendingCredential, mfaInfo: mfaInfo ?? this.mfaInfo, signInWithPasswordResponseModelNotifications: signInWithPasswordResponseModelNotifications ?? this.signInWithPasswordResponseModelNotifications, ); } @override bool operator ==(Object o) { if (identical(this, o)) return true; return o is SignInWithPasswordResponseModel && o.kind == kind && o.localId == localId && o.email == email && o.displayName == displayName && o.idToken == idToken && o.registered == registered && o.profilePicture == profilePicture && o.oauthAccessToken == oauthAccessToken && o.oauthExpireIn == oauthExpireIn && o.oauthAuthorizationCode == oauthAuthorizationCode && o.refreshToken == refreshToken && o.expiresIn == expiresIn && o.mfaPendingCredential == mfaPendingCredential && listEquals(o.mfaInfo, mfaInfo) && listEquals(o.signInWithPasswordResponseModelNotifications, signInWithPasswordResponseModelNotifications); } @override int get hashCode { return kind.hashCode ^ localId.hashCode ^ email.hashCode ^ displayName.hashCode ^ idToken.hashCode ^ registered.hashCode ^ profilePicture.hashCode ^ oauthAccessToken.hashCode ^ oauthExpireIn.hashCode ^ oauthAuthorizationCode.hashCode ^ refreshToken.hashCode ^ expiresIn.hashCode ^ mfaPendingCredential.hashCode ^ mfaInfo.hashCode ^ signInWithPasswordResponseModelNotifications.hashCode; } @override String toString() { return 'SignInWithPasswordResponseModel{kind: $kind, localId: $localId, email: $email, displayName: $displayName, idToken: $idToken, registered: $registered, profilePicture: $profilePicture, oauthAccessToken: $oauthAccessToken, oauthExpireIn: $oauthExpireIn, oauthAuthorizationCode: $oauthAuthorizationCode, refreshToken: $refreshToken, expiresIn: $expiresIn, mfaPendingCredential: $mfaPendingCredential, mfaInfo: $mfaInfo, signInWithPasswordResponseModelNotifications: $signInWithPasswordResponseModelNotifications}'; } } void main() { // Teste final signInWithPasswordResponse = SignInWithPasswordResponseModel( kind: "", localId: "", email: "", displayName: "", idToken: "", registered: true, profilePicture: "", oauthAccessToken: "", oauthExpireIn: 0, oauthAuthorizationCode: "", refreshToken: "", expiresIn: "", mfaPendingCredential: "", mfaInfo: [ MfaEnrollment( mfaEnrollmentId: "", displayName: "", enrolledAt: "", phoneInfo: "", totpInfo: TotpInfo(), emailInfo: const EmailInfo(emailAddress: ""), unobfuscatedPhoneInfo: "", ), ], signInWithPasswordResponseModelNotifications: const [ SignInWithPasswordResponseModelNotification( notificationCode: NotificationCode.NOTIFICATION_CODE_UNSPECIFIED, notificationMessage: "", ), ], ); if (kDebugMode) { print(signInWithPasswordResponse.toString()); } }
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:jus_mobile_order_app/Helpers/error.dart'; import 'package:jus_mobile_order_app/Helpers/loading.dart'; import 'package:jus_mobile_order_app/Models/membership_stats_model.dart'; import 'package:jus_mobile_order_app/Providers/stream_providers.dart'; class MemberStatsProviderWidget extends ConsumerWidget { final Widget Function(MembershipStatsModel stats) builder; final dynamic loading; final dynamic error; const MemberStatsProviderWidget( {required this.builder, this.loading, this.error, Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final currentUser = ref.watch(currentUserProvider); return currentUser.when( error: (e, _) => error ?? ShowError( error: e.toString(), ), loading: () => loading ?? const Loading(), data: (user) { final memberStats = ref.watch(memberStatsProvider(user.uid ?? '')); return memberStats.when( error: (e, _) => error ?? ShowError( error: e.toString(), ), loading: () => loading ?? const Loading(), data: (stats) => builder(stats), ); }); } }
package controllers import java.text.SimpleDateFormat import java.util.Date import domain.{PkuLog, PkuLogQuery} import javax.inject.{Inject, _} import play.api.mvc._ import services.LogService import utils.JSONUtil import scala.concurrent.ExecutionContext /** * 日志处理 */ @Singleton class LogController @Inject()(logService: LogService,cc: ControllerComponents) (implicit ec: ExecutionContext)extends AbstractController(cc) { implicit val jsonFormats = org.json4s.DefaultFormats /** * Create an Action to render an HTML page. * * The configuration in the `routes` file means that this method * will be called when the application receives a `GET` request with * a path of `/`. */ def log() = Action { implicit request: Request[AnyContent] => Ok(views.html.aipComponentLogs.log_main()) } def list = Action.async { implicit request: Request[AnyContent] => var strategyName = request.body.asFormUrlEncoded.get("strategyName").head var resourceName = request.body.asFormUrlEncoded.get("resourceName").head var result = request.body.asFormUrlEncoded.get("result").head var startTime = request.body.asFormUrlEncoded.get("startTime").head var endTime = request.body.asFormUrlEncoded.get("endTime").head val sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //加上时间 var startDate:Date = null if(!startTime.isEmpty){ startDate = sDateFormat.parse(startTime) } var endDate:Date =null if(!endTime.isEmpty){ endDate = sDateFormat.parse(endTime) } var pkuLogQuery = PkuLogQuery(startTime,endTime,"",strategyName,"",resourceName,result) println(request.body.asFormUrlEncoded.get("strategyName")) println(request.body.asFormUrlEncoded.get("resourceName")) println(request.body.asFormUrlEncoded.get("result")) println(request.body.asFormUrlEncoded.get("startTime")) println(request.body.asFormUrlEncoded.get("endTime")) logService.getList(request.body.asFormUrlEncoded.get("start").head.toInt/10, 10,pkuLogQuery).map { page => val str = JSONUtil.listToJSONString(page) println(str) Ok(str).as("application/json") } } def getById(id:String) = Action { implicit request: Request[AnyContent] => var log = logService.getById(id); val strRes = JSONUtil.toJSONStr(log.get) Ok(strRes).as("application/json") } def getByBatchId(batchId:String) = Action { implicit request: Request[AnyContent] => var log = logService.getByBatchId(batchId); val strRes = JSONUtil.toJSONStr(log.get) Ok(strRes).as("application/json") } def delById(id:String) = Action { implicit request: Request[AnyContent] => var isSuccess = logService.delById(id); val strRes = JSONUtil.toJSONStr(isSuccess.toString) Ok(strRes).as("application/json") } def savaOrUpdate = Action { implicit request: Request[AnyContent] => println(request.body.asJson) val json = request.body.asJson println(json.get.toString) val log = JSONUtil.GSON.fromJson(json.get.toString, classOf[PkuLog]) if(log.id!=null){ logService.updateById(log); }else{ logService.save(log); } val strRes = JSONUtil.toJSONStr(log.id) Ok(strRes).as("application/json") } /** * 查询当天的执行组件消息 */ def findExecuteLogSum = Action { implicit request: Request[AnyContent] => println(request.body.asJson) val json = request.body.asJson var map = logService.getCount(); val strRes = JSONUtil.toJSONStr(map) Ok(strRes).as("application/json") } }
/** * APITable <https://github.com/apitable/apitable> * Copyright (C) 2022 APITable Ltd. <https://apitable.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { BaseEntity } from 'shared/entities/base.entity'; import { Column, Entity } from 'typeorm'; /** * Workbench-Datasheet */ @Entity('datasheet') export class DatasheetEntity extends BaseEntity { @Column({ name: 'dst_id', nullable: true, unique: true, comment: 'datasheet ID', length: 50, }) dstId?: string; @Column({ name: 'node_id', nullable: true, comment: 'node ID (association#node#node_id)', length: 50, }) nodeId?: string; @Column({ name: 'dst_name', nullable: true, comment: 'datasheet name', length: 255, }) dstName!: string; @Column({ name: 'space_id', nullable: true, comment: 'space ID(related#space#space_id)', length: 50, }) spaceId?: string; @Column({ name: 'creator', nullable: true, comment: 'creator ID', }) creator?: string; @Column({ name: 'revision', nullable: true, comment: 'revision', unsigned: true, default: () => 0, type: 'bigint', width: 20, }) revision!: number; }
from numpy import loadtxt import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from keras.regularizers import l2 import tensorflow as tf import shutil import os dataset = loadtxt('data.csv', delimiter=',') X = dataset[:,0:8] y = dataset[:,8:10] class CustomCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): u = logs.get('accuracy') if logs.get('accuracy') >= 99e-2: self.model.stop_training = True callback = CustomCallback() model = Sequential() model.add(Dense(24, input_shape=(8,), activation='sigmoid', kernel_regularizer=l2(0.001), bias_regularizer=l2(0.001))) model.add(Dense(14, activation='gelu')) model.add(Dense(12, activation='gelu')) model.add(Dense(2, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X, y, epochs=20000, batch_size=5000, callbacks=[callback]) _, accuracy = model.evaluate(X, y) print(accuracy) model.save('model') shutil.make_archive('baseDataModel.zip', 'zip', 'model')
/******************************************************************************* * Copyright (c) 2013 Christian Wiwie. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Christian Wiwie - initial API and implementation ******************************************************************************/ /** * */ package de.clusteval.run; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.HierarchicalINIConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.clusteval.paramOptimization.InvalidOptimizationParameterException; import de.clusteval.context.Context; import de.clusteval.context.UnknownContextException; import de.clusteval.data.DataConfig; import de.clusteval.data.DataConfigNotFoundException; import de.clusteval.data.DataConfigurationException; import de.clusteval.data.dataset.DataSetConfigNotFoundException; import de.clusteval.data.dataset.DataSetConfigurationException; import de.clusteval.data.dataset.DataSetNotFoundException; import de.clusteval.data.dataset.IncompatibleDataSetConfigPreprocessorException; import de.clusteval.data.dataset.NoDataSetException; import de.clusteval.data.dataset.format.UnknownDataSetFormatException; import de.clusteval.data.dataset.type.UnknownDataSetTypeException; import de.clusteval.data.distance.UnknownDistanceMeasureException; import de.clusteval.data.goldstandard.GoldStandardConfigNotFoundException; import de.clusteval.data.goldstandard.GoldStandardConfigurationException; import de.clusteval.data.goldstandard.GoldStandardNotFoundException; import de.clusteval.data.preprocessing.UnknownDataPreprocessorException; import de.clusteval.framework.repository.NoRepositoryFoundException; import de.clusteval.framework.repository.RegisterException; import de.clusteval.framework.repository.Repository; import de.clusteval.framework.threading.RunSchedulerThread; import de.clusteval.program.ProgramConfig; import de.clusteval.program.ProgramParameter; import de.clusteval.program.UnknownParameterType; import de.clusteval.program.UnknownProgramParameterException; import de.clusteval.program.UnknownProgramTypeException; import de.clusteval.program.r.UnknownRProgramException; import de.clusteval.quality.QualityMeasure; import de.clusteval.quality.UnknownQualityMeasureException; import de.clusteval.run.result.format.UnknownRunResultFormatException; import de.clusteval.run.runnable.ExecutionRunRunnable; import de.clusteval.run.runnable.InternalParameterOptimizationRunRunnable; import file.FileUtils; /** * A type of execution run that does the same as * {@link ParameterOptimizationRun}, by using a programs internal parameter * optimization mode instead of doing the parameter optimization itself within * the framework. * * @author Christian Wiwie * */ public class InternalParameterOptimizationRun extends ExecutionRun { /** * New objects of this type are automatically registered at the repository. * * @param repository * the repository * @param context * @param changeDate * The date this run was performed. * @param absPath * The absolute path to the file on the filesystem that * corresponds to this run. * @param programConfigs * The program configurations of the new run. * @param dataConfigs * The data configurations of the new run. * @param qualityMeasures * The clustering quality measures of the new run. * @param parameterValues * The parameter values of this run. * @throws RegisterException */ public InternalParameterOptimizationRun(Repository repository, final Context context, long changeDate, File absPath, List<ProgramConfig> programConfigs, List<DataConfig> dataConfigs, List<QualityMeasure> qualityMeasures, List<Map<ProgramParameter<?>, String>> parameterValues) throws RegisterException { super(repository, context, true, changeDate, absPath, programConfigs, dataConfigs, qualityMeasures, parameterValues); } /** * Copy constructor of internal parameter optimization runs. * * @param otherRun * The internal parameter optimization run to be cloned. * @throws RegisterException */ protected InternalParameterOptimizationRun( final InternalParameterOptimizationRun other) throws RegisterException { super(other); } /* * (non-Javadoc) * * @see run.ExecutionRun#createRunRunnableFor(framework.RunScheduler, * run.Run, program.ProgramConfig, data.DataConfig, java.lang.String, * boolean) */ @Override protected ExecutionRunRunnable createRunRunnableFor( RunSchedulerThread runScheduler, Run run, ProgramConfig programConfig, DataConfig dataConfig, String runIdentString, boolean isResume) { return new InternalParameterOptimizationRunRunnable(runScheduler, run, programConfig, dataConfig, runIdentString, isResume); } /* * (non-Javadoc) * * @see run.ExecutionRun#clone() */ @Override public InternalParameterOptimizationRun clone() { try { return new InternalParameterOptimizationRun(this); } catch (RegisterException e) { e.printStackTrace(); } return null; } /** * Parses an internal parameter optimization run from a file. * * <p> * An internal parameter optimization run file contains several options: * <ul> * <li><b>programConfig</b>: The program configurations of this run (see * {@link ExecutionRun#programConfigs})</li> * <li><b>dataConfig</b>: The data configurations of this run (see * {@link ExecutionRun#dataConfigs})</li> * <li><b>qualityMeasures</b>: The clustering quality measures of this run * (see {@link ExecutionRun#qualityMeasures})</li> * <li><b>optimizationMethod</b>: The default parameter optimization method * for all program configurations without an explicit optimization method.</li> * </ul> * * <p> * For every program configuration a section containing parameter values is * optional: * <ul> * <li><b>[programConfigName]</b></li> * <ul> * <li><b>parameterName</b> = parameterValue (for every parameter a value * can be specified)</li> * </ul> * </ul> * * @param absPath * The absolute file path to the *.run file * @throws ConfigurationException * the configuration exception * @throws IOException * Signals that an I/O exception has occurred. * @throws UnknownRunResultFormatException * the unknown run result format exception * @throws UnknownDataSetFormatException * the unknown data set format exception * @throws UnknownQualityMeasureException * the unknown clustering quality measure exception * @throws UnknownProgramParameterException * @throws NoRepositoryFoundException * @throws GoldStandardNotFoundException * @throws InvalidOptimizationParameterException * @throws GoldStandardConfigurationException * @throws DataSetNotFoundException * @throws DataSetConfigurationException * @throws DataSetConfigNotFoundException * @throws GoldStandardConfigNotFoundException * @throws DataConfigNotFoundException * @throws DataConfigurationException * @throws RunException * @throws UnknownRProgramException * @throws UnknownDistanceMeasureException * @throws RegisterException * @throws UnknownDataSetTypeException * @throws NoDataSetException * @throws NumberFormatException * @return The parserd internal parameter optimization run. * @throws UnknownDataPreprocessorException * @throws IncompatibleDataSetConfigPreprocessorException * @throws UnknownContextException * @throws UnknownParameterType */ public static Run parseFromFile(final File absPath) throws ConfigurationException, IOException, UnknownRunResultFormatException, UnknownDataSetFormatException, UnknownQualityMeasureException, UnknownProgramParameterException, NoRepositoryFoundException, GoldStandardNotFoundException, InvalidOptimizationParameterException, GoldStandardConfigurationException, DataSetConfigurationException, DataSetNotFoundException, DataSetConfigNotFoundException, GoldStandardConfigNotFoundException, DataConfigurationException, DataConfigNotFoundException, RunException, UnknownProgramTypeException, UnknownRProgramException, UnknownDistanceMeasureException, RegisterException, UnknownDataSetTypeException, NumberFormatException, NoDataSetException, UnknownDataPreprocessorException, IncompatibleDataSetConfigPreprocessorException, UnknownContextException, UnknownParameterType { Logger log = LoggerFactory.getLogger(Run.class); log.debug("Parsing run \"" + absPath + "\""); Run result; HierarchicalINIConfiguration props = new HierarchicalINIConfiguration( absPath.getAbsolutePath()); Repository repo = Repository.getRepositoryForPath(absPath .getAbsolutePath()); final long changeDate = absPath.lastModified(); Context context; // by default we are in a clustering context if (props.containsKey("context")) context = Context.parseFromString(repo, props.getString("context")); else context = Context.parseFromString(repo, "ClusteringContext"); /* * A run consists of a set of programconfigs and a set of dataconfigs, * that are pairwise combined. */ List<ProgramConfig> programConfigs = new LinkedList<ProgramConfig>(); List<DataConfig> dataConfigs = new LinkedList<DataConfig>(); /* * The quality measures that should be calculated for every pair of * programconfig+dataconfig. */ List<QualityMeasure> qualityMeasures = new LinkedList<QualityMeasure>(); /* * A list with parameter values that are set in the run config. They * will overwrite the default values of the program config. */ List<Map<ProgramParameter<?>, String>> runParamValues = new ArrayList<Map<ProgramParameter<?>, String>>(); for (String programConfig : props.getStringArray("programConfig")) { ProgramConfig newProgramConfig = ProgramConfig .parseFromFile(new File(FileUtils.buildPath( repo.getProgramConfigBasePath(), programConfig + ".config"))); newProgramConfig = repo.getRegisteredObject(newProgramConfig); programConfigs.add(newProgramConfig); Map<ProgramParameter<?>, String> paramMap = new HashMap<ProgramParameter<?>, String>(); /* * parse the overriding parameter-values for this program config */ if (props.getSections().contains(programConfig)) { /* * General parameters, not only for optimization. */ Iterator<String> itParams = props.getSection(programConfig) .getKeys(); while (itParams.hasNext()) { String param = itParams.next(); if (param != null && !param.equals("optimizationParameters") && !param.equals("optimizationMethod")) try { ProgramParameter<?> p = newProgramConfig .getParamWithId(param); paramMap.put(p, props.getSection(programConfig) .getString(param)); } catch (UnknownProgramParameterException e) { log.error("The run " + absPath.getName() + " contained invalid parameter values: " + newProgramConfig.getProgram() + " does not have a parameter " + param); } } } runParamValues.add(paramMap); } if (props.getStringArray("qualityMeasures").length == 0) throw new RunException( "At least one quality measure must be specified"); /** * We catch the exceptions such that all quality measures are tried to * be loaded once so that they are ALL registered as missing in the * repository. */ List<UnknownQualityMeasureException> thrownExceptions = new ArrayList<UnknownQualityMeasureException>(); for (String qualityMeasure : props.getStringArray("qualityMeasures")) { try { qualityMeasures.add(QualityMeasure.parseFromString(repo, qualityMeasure)); } catch (UnknownQualityMeasureException e) { thrownExceptions.add(e); } } if (thrownExceptions.size() > 0) { // just throw the first exception throw thrownExceptions.get(0); } for (String dataConfig : props.getStringArray("dataConfig")) { dataConfigs.add(repo.getRegisteredObject(DataConfig .parseFromFile(new File(FileUtils.buildPath( repo.getDataConfigBasePath(), dataConfig + ".dataconfig"))))); } checkCompatibilityQualityMeasuresDataConfigs(dataConfigs, qualityMeasures); result = new InternalParameterOptimizationRun(repo, context, changeDate, absPath, programConfigs, dataConfigs, qualityMeasures, runParamValues); result = repo.getRegisteredObject(result, false); log.debug("Run parsed"); return result; } /* * (non-Javadoc) * * @see run.config.Run#register() */ @Override public boolean register() throws RegisterException { return this.repository.register(this); } }
#include <AFMotor.h> #include <SoftwareSerial.h> SoftwareSerial BT_Serial(0, 1); // RX, TX AF_DCMotor motor1(3); AF_DCMotor motor2(2); AF_DCMotor motor3(4); AF_DCMotor motor4(1); #define R_S A0 //ir sensor Right #define L_S A2 //ir sensor Left int bt_data; // variable to receive data from the serial port int mode=0; int Speed = 255; void setup() { // turn on motor #2 motor1.setSpeed(255); motor1.run(RELEASE); motor2.setSpeed(255); motor2.run(RELEASE); motor3.setSpeed(255); motor3.run(RELEASE); motor4.setSpeed(255); motor4.run(RELEASE); pinMode(R_S, INPUT); // declare if sensor as input pinMode(L_S, INPUT); // declare ir sensor as input Serial.begin(9600); // start serial communication at 9600bps BT_Serial.begin(9600); delay(500); } void loop(){ if(BT_Serial.available() > 0){ //if some date is sent, reads it and saves in state bt_data = BT_Serial.read(); if(bt_data > 20){Speed = bt_data;} } if(bt_data == 8){mode=1; Speed=130;} //Auto Line Follower Command else if(bt_data == 9){mode=0; Stop();} //Manual Android Application Control Command if(mode==0){ if(bt_data == 1){forward(); } // if the bt_data is '1' the DC motor will go forward else if(bt_data == 2){backward();} // if the bt_data is '2' the motor will Reverse else if(bt_data == 3){turnLeft();} // if the bt_data is '3' the motor will turn left else if(bt_data == 4){turnRight();} // if the bt_data is '4' the motor will turn right else if(bt_data == 5){Stop(); } // if the bt_data '5' the motor will Stop }else{ if((digitalRead(R_S) == 0)&&(digitalRead(L_S) == 0)){forward();} if((digitalRead(R_S) == 1)&&(digitalRead(L_S) == 0)){turnRight();} if((digitalRead(R_S) == 0)&&(digitalRead(L_S) == 1)){turnLeft();} if((digitalRead(R_S) == 1)&&(digitalRead(L_S) == 1)){Stop();} delay(10); } } void forward(){ //forword motor1.setSpeed(255); motor1.run(FORWARD); motor2.setSpeed(255); motor2.run(FORWARD); motor3.setSpeed(255); motor3.run(FORWARD); motor4.setSpeed(255); motor4.run(FORWARD); } void turnRight(){ //turnRight motor1.setSpeed(255); motor1.run(FORWARD); motor2.setSpeed(255); motor2.run(BACKWARD); motor3.setSpeed(255); motor3.run(FORWARD); motor4.setSpeed(255); motor4.run(BACKWARD); } void turnLeft(){ //turnLeft motor1.setSpeed(255); motor1.run(BACKWARD); motor2.setSpeed(255); motor2.run(FORWARD); motor3.setSpeed(255); motor3.run(BACKWARD); motor4.setSpeed(255); motor4.run(FORWARD); } void backward(){ //backward motor1.setSpeed(255); motor1.run(BACKWARD); motor2.setSpeed(255); motor2.run(BACKWARD); motor3.setSpeed(255); motor3.run(BACKWARD); motor4.setSpeed(255); motor4.run(BACKWARD); } void Stop(){ //stop motor1.setSpeed(0); motor1.run(RELEASE); motor2.setSpeed(0); motor2.run(RELEASE); motor3.setSpeed(0); motor3.run(RELEASE); motor4.setSpeed(0); motor4.run(RELEASE); }
import { IsString, IsUrl, IsNotEmpty, IsOptional, IsNumber, IsPositive, } from 'class-validator'; export class UpdateMenuDto { @IsNotEmpty({ message: 'field name must be added' }) @IsString() name?: string; @IsOptional() @IsString() description?: string; @IsOptional() @IsUrl() imageUrl?: string; @IsOptional() @IsNumber() @IsPositive() rating?: number; }
// run all this in browser console as node.js doesn't run http request directly // old method without using fetch api // const xhr = new XMLHttpRequest(); // new http request object // // AJAX (asyncronous javascript and XML) // xhr.onload = function() { // console.log(xhr.responseText); // }; // this function will be called on page load event // xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1'); // xhr.send(); // http request using fetch api fetch('https://jsonplaceholder.typicode.com/todos/1') // by default the fetch method uses the get method. This will make a get request to the url and return a promise .then( (response) => response.json()) // get the response and convert it into a json object since we know that browser backend works on json object .then ( value => console.log( value)) // this will get the return from above and console log the resolved value .catch ( (err) => console.log(err.message)); // handle the error // POST (send data to the backend) const todo = { "userId": 1, "title": "delectus aut autem", "completed": false } // a javascript object, we need to convert it into json fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', body: JSON.stringify(todo) // JSON conversion of the obj }, { headers: { 'Content-Type': 'application/json' } } ) .then( (response) => response.json()) .then ( value => console.log( value));
package smartquizapp.controller; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import org.eclipse.angus.mail.util.MailConnectException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import smartquizapp.dto.*; import smartquizapp.event.RegistrationCompleteEvent; import smartquizapp.exception.InvalidTokenException; import smartquizapp.exception.MailConnectionException; import smartquizapp.exception.UserNotFoundException; import smartquizapp.exception.UserNotVerifiedException; import smartquizapp.model.User; import smartquizapp.model.VerificationToken; import smartquizapp.serviceImpl.EmailServiceImpl; import smartquizapp.serviceImpl.UserServiceImpl; import smartquizapp.utils.GoogleJwtUtils; import smartquizapp.utils.JwtUtils; import smartquizapp.dto.ChangePasswordRequestDto; import java.util.Optional; import java.util.UUID; @RestController @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") @RequestMapping("/api/v1/user") public class AuthController { private final UserServiceImpl userService; private final ApplicationEventPublisher publisher; private JwtUtils jwtUtils; private final GoogleJwtUtils googleJwtUtils; private final EmailServiceImpl emailService; @Autowired public AuthController(ApplicationEventPublisher publisher, UserServiceImpl userService, JwtUtils jwtUtils, GoogleJwtUtils googleJwtUtils, EmailServiceImpl emailService) { this.publisher = publisher; this.jwtUtils = jwtUtils; this.googleJwtUtils = googleJwtUtils; this.emailService = emailService; this.userService = userService; } @PostMapping("/register") public ResponseEntity<String> registerUser(@Valid @RequestBody UserDto userDto, final HttpServletRequest request) throws MailConnectionException { User user = userService.registerUser(userDto); try { publisher.publishEvent(new RegistrationCompleteEvent( user, emailService.applicationUrl(request) )); }catch (Exception e){ throw new MailConnectionException("Error sending mail"); } if(user != null) { return new ResponseEntity<>("Registration Successful", HttpStatus.OK); }else{ throw new UserNotVerifiedException("Registration Unsuccessful"); } } @GetMapping("/google/{token}") public ResponseEntity<String> AuthorizeOauthUser(@PathVariable String token){ return ResponseEntity.ok(googleJwtUtils.googleOAuthUserJWT(token)); } @PostMapping("/login") public ResponseEntity<String> login(@RequestBody LoginDto loginDto){ String result = userService.logInUser(loginDto); return new ResponseEntity<>(result, HttpStatus.OK); } @PostMapping("/logout") public ResponseEntity<String> logout(HttpServletRequest request){ String result = userService.logoutUser(request); return new ResponseEntity<>(result, HttpStatus.OK); } @GetMapping("/verifyRegistration") public ResponseEntity<String> verifyRegistration(@RequestParam("token") String token) { String result = userService.validateVerificationToken(token); if(result.equalsIgnoreCase("valid")){ return new ResponseEntity<>("User verified Successfully", HttpStatus.OK); } throw new UserNotVerifiedException("User is not Verified Successfully"); } @GetMapping("/resendVerifyToken/{oldToken}") public ResponseEntity<String> resendVerificationToken(@PathVariable String oldToken, HttpServletRequest request) throws MailConnectionException { VerificationToken verificationToken = userService.generateNewVerificationToken(oldToken); User user = verificationToken.getUser(); try { emailService.resendVerificationTokenMail(user, emailService.applicationUrl(request), verificationToken); }catch (Exception e){ throw new MailConnectionException("Error sending mail"); } return new ResponseEntity<>("Verification Link Sent", HttpStatus.OK); } @PostMapping("/forgotPassword") public ResponseEntity<String> forgotPassword(@RequestBody PasswordDto passwordDto, HttpServletRequest request) throws MailConnectionException { User user = userService.findUserByEmail(passwordDto.getEmail()); String url = ""; if(user != null){ String token = userService.generateRandomNumber(6); userService.createPasswordResetTokenForUser(user, token); try { url = emailService.passwordResetTokenMail(user, emailService.applicationUrl(request), token); }catch (Exception e){ throw new MailConnectionException("Error sending mail"); } return new ResponseEntity<>("Go to Email to reset Password " + url, HttpStatus.OK); } throw new UserNotFoundException("User with email " + passwordDto.getEmail() + "not found"); } @PostMapping("/resetPassword/{token}") public ResponseEntity<String> resetPassword(@PathVariable String token, @RequestBody ResetPasswordDto passwordDto) { String result = userService.validatePasswordResetToken(token, passwordDto); if (!result.equalsIgnoreCase("valid")) { throw new InvalidTokenException("Invalid Token"); } Optional<User> user = userService.getUserByPasswordReset(token); if (user.isPresent()) { userService.changePassword(user.get(), passwordDto.getNewPassword(), passwordDto.getNewConfirmPassword()); return new ResponseEntity<>("Password Reset Successful", HttpStatus.OK); } else { throw new InvalidTokenException("Invalid Token"); } } @PostMapping("/changePassword") public ResponseEntity<String> changePassword(@RequestBody ChangePasswordRequestDto changePasswordDto){ String response = userService.changePasswordForUser(changePasswordDto); return new ResponseEntity<>(response,HttpStatus.OK); } }
import { Component, ViewChild } from '@angular/core'; import { TableComponent } from 'smart-webcomponents-angular/table'; import { DataService } from 'src/app/services/data.service'; @Component({ selector: 'sm-responsive-table', templateUrl: './responsive-table.component.html', styleUrls: ['./responsive-table.component.scss'] }) export class ResponsiveTableComponent { @ViewChild('responsiveTable', { read: TableComponent, static: false }) responsiveTable!: TableComponent; tableSettings = { dataSource: new window.Smart.DataAdapter({ dataSource: this.dataService.generateData(50), dataFields: [ 'id: number', 'firstName: string', 'lastName: string', 'productName: string', 'quantity: number', 'price: number', 'total: number' ] }), onInit: () => { this.responsiveTable.sortBy('lastName', 'asc'); }, paging: true, sortMode: 'one', tooltip: true, columns: [ { label: 'id', dataField: 'id', dataType: 'number' }, { label: 'First Name', dataField: 'firstName', dataType: 'string', responsivePriority: 4 }, { label: 'Last Name', dataField: 'lastName', dataType: 'string' }, { label: 'Product Name', dataField: 'productName', dataType: 'string' }, { label: 'Quantity', dataField: 'quantity', dataType: 'number', responsivePriority: 3 }, { label: 'Price', dataField: 'price', dataType: 'number', responsivePriority: 3 }, { label: 'Total', dataField: 'total', dataType: 'number' } ] } constructor(private dataService: DataService) { } }
// // JokesView.swift // Jokes // // Created by Graeme Armstrong on 2023-04-14. // import Blackbird import SwiftUI struct JokesView: View { // MARK: Stored properties @Environment(\.blackbirdDatabase) var db: Blackbird.Database? // 0.0 is invisible, 1.0 is visible @State var punchlineOpacity = 0.0 @State var currentJoke: Joke? // track whether joke has been saved to database. @State var saveToDatabase = false var body: some View { NavigationView{ VStack(spacing: 20) { Spacer() if let currentJoke = currentJoke { // show the joke if it can be unwrapped (if current joke is not nil) Text(currentJoke.setup) .font(.title) .multilineTextAlignment(.center) Button(action: { withAnimation(.easeIn(duration: 1.0)){ punchlineOpacity = 1.0 } }, label: { Image(systemName: "arrow.down.circle.fill") .resizable() .scaledToFit() .frame(width: 40) .tint(.black) }) Text(currentJoke.punchline) .font(.title) .multilineTextAlignment(.center) .opacity(punchlineOpacity) } else { // Show a spinning wheel indicator that joke is loading ProgressView() } Spacer() Button(action: { // Reset the interface punchlineOpacity = 0.0 Task { // Get another joke withAnimation { currentJoke = nil } currentJoke = await NetworkService.fetch() // reset to button allows for another joke saveToDatabase = false } }, label: { Text("Fetch another one") }) .disabled(punchlineOpacity == 0.0 ? true : false) .buttonStyle(.borderedProminent) Button(action:{ Task{ // write to database if let currentJoke = currentJoke { try await db!.transaction { core in try core.query("INSERT INTO Joke (id, type, setup, punchline) VALUES (?, ?, ?, ?)", currentJoke.id, currentJoke.type, currentJoke.setup, currentJoke.punchline) // record if joke has been saved saveToDatabase = true } } } }, label: { Text("Save for later") }) // disable button until punchine is shown. .disabled(punchlineOpacity == 0.0 ? true : false) // once saved once can't be saved twice .disabled(saveToDatabase == true ? true : false) .tint(.green) .buttonStyle(.borderedProminent) } .navigationTitle("Fresh Jokes") } // create an asynchronous ask to be preformed as this viewappears .task { if currentJoke == nil { currentJoke = await NetworkService.fetch() } } } } struct JokesView_Previews: PreviewProvider { static var previews: some View { JokesView() .environment(\.blackbirdDatabase, AppDatabase.instance) } }
// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // vi: set et ts=4 sw=4 sts=4: /***************************************************************************** * See the file COPYING for full copying permissions. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * *****************************************************************************/ /*! * \file * \ingroup PoroElastic * \brief Defines a type tag and some properties for the poroelastic geomechanical model */ #ifndef DUMUX_GEOMECHANICS_POROELASTIC_MODEL_HH #define DUMUX_GEOMECHANICS_POROELASTIC_MODEL_HH #include <dune/common/fvector.hh> #include <dumux/common/properties.hh> #include <dumux/geomechanics/elastic/indices.hh> #include <dumux/geomechanics/elastic/model.hh> #include <dumux/flux/hookeslaw.hh> #include <dumux/flux/effectivestresslaw.hh> #include "localresidual.hh" #include "volumevariables.hh" #include "iofields.hh" namespace Dumux { /*! * \ingroup PoroElastic * \brief Specifies a number properties of the poroelastic model */ template< int dim, int numSC, int numFP, int numFC > struct PoroElasticModelTraits { //! export the type encapsulating indices using Indices = ElasticIndices; //! the number of equations is equal to grid dimension static constexpr int numEq() { return dim; } //! This model does not consider fluid phases static constexpr int numFluidPhases() { return numFP; } //! This model does not consider fluid phases static constexpr int numFluidComponents() { return numFC; } //! We have one solid phase here static constexpr int numSolidComponents() { return numSC; } //! Energy balance not yet implemented static constexpr bool enableEnergyBalance() { return false; } }; namespace Properties { //! Type tag for the poro-elastic geomechanical model // Create new type tags namespace TTag { struct PoroElastic { using InheritsFrom = std::tuple<Elastic>; }; } // end namespace TTag //! Use the local residual of the poro-elastic model template<class TypeTag> struct LocalResidual<TypeTag, TTag::PoroElastic> { using type = PoroElasticLocalResidual<TypeTag>; }; //! default vtk output fields specific to this model template<class TypeTag> struct IOFields<TypeTag, TTag::PoroElastic> { using type = PoroElasticIOFields; }; //! The deault model traits of the poro-elastic model template<class TypeTag> struct ModelTraits<TypeTag, TTag::PoroElastic> { private: using GridView = typename GetPropType<TypeTag, Properties::GridGeometry>::GridView; static constexpr int dim = GridView::dimension; static constexpr int numSC = GetPropType<TypeTag, Properties::SolidSystem>::numComponents; static constexpr int numFP = GetPropType<TypeTag, Properties::FluidSystem>::numPhases; static constexpr int numFC = GetPropType<TypeTag, Properties::FluidSystem>::numComponents; public: using type = PoroElasticModelTraits<dim, numSC, numFP, numFC>; }; //! Set the volume variables property template<class TypeTag> struct VolumeVariables<TypeTag, TTag::PoroElastic> { private: using GridView = typename GetPropType<TypeTag, Properties::GridGeometry>::GridView; static constexpr int dim = GridView::dimension; using PV = GetPropType<TypeTag, Properties::PrimaryVariables>; using DV = Dune::FieldVector<typename PV::value_type, dim>; using MT = GetPropType<TypeTag, Properties::ModelTraits>; using SST = GetPropType<TypeTag, Properties::SolidState>; using SSY = GetPropType<TypeTag, Properties::SolidSystem>; // we reuse the elastic volume variable traits here using Traits = ElasticVolumeVariablesTraits<PV, DV, MT, SST, SSY>; public: using type = PoroElasticVolumeVariables<Traits>; }; //! Per default, we use effective stresses on the basis of Hooke's Law template<class TypeTag> struct StressType<TypeTag, TTag::PoroElastic> { private: using Scalar = GetPropType<TypeTag, Properties::Scalar>; using GridGeometry = GetPropType<TypeTag, Properties::GridGeometry>; using ElasticStressType = HookesLaw< Scalar, GridGeometry >; public: using type = EffectiveStressLaw< ElasticStressType, GridGeometry >; }; } // namespace Properties } // namespace Dumux #endif
import { SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import React from 'react'; import {useDispatch, useSelector} from 'react-redux'; // Import hooks from react-redux import {addUser, deleteUsers} from '../../redux/slices/userSlice'; // Import the addUser action from userSlice import {faker} from '@faker-js/faker'; const Login = () => { const dispatch = useDispatch(); // useDispatch is used to dispatch actions to the Redux store const data = useSelector(state => state.users); // useSelector is used to access the state from the Redux store console.log('userData ', data); const generateRandomName = () => { const name = faker.internet.userName(); // Generate a random full name dispatch(addUser(name)); // Dispatch the addUser action with the payload 'Gaurav' }; return ( <SafeAreaView style={{flex:1}}> <View style={{ flex: 1, backgroundColor: 'cyan', justifyContent: 'center', alignItems: 'center', }}> <ScrollView> {data.map((res, id) => ( <View key={id}> <Text onPress={()=>{dispatch(deleteUsers(id))}}>{res}</Text> </View> ))} </ScrollView> <TouchableOpacity style={{ padding: 20, backgroundColor: 'red', borderRadius: 9, position: 'relatove', bottom: '0', }} onPress={() => { generateRandomName(); }}> <Text>Add</Text> </TouchableOpacity> </View> </SafeAreaView> ); }; export default Login; const styles = StyleSheet.create({});
package lua import ( "io" "strings" "code.linenisgreat.com/zit/src/alfa/errors" "code.linenisgreat.com/zit/src/alfa/schnittstellen" "code.linenisgreat.com/zit/src/bravo/pool" lua "github.com/yuin/gopher-lua" lua_ast "github.com/yuin/gopher-lua/ast" lua_parse "github.com/yuin/gopher-lua/parse" ) type VM struct { *lua.LState *lua.LTable schnittstellen.Pool[LTable, *LTable] } func MakeVMPool(script string) (ml *VMPool, err error) { ml = &VMPool{} if err = ml.Set(script); err != nil { err = errors.Wrap(err) return } return } type VMPool struct { schnittstellen.Pool[VM, *VM] } func (sp *VMPool) Set(script string) (err error) { reader := strings.NewReader(script) if err = sp.SetReader(reader); err != nil { err = errors.Wrap(err) return } return } func (sp *VMPool) SetReader(reader io.Reader) (err error) { var chunks []lua_ast.Stmt if chunks, err = lua_parse.Parse(reader, ""); err != nil { err = errors.Wrap(err) return } var compiled *lua.FunctionProto if compiled, err = lua.Compile(chunks, ""); err != nil { err = errors.Wrap(err) return } sp.Pool = pool.MakePool( func() (vm *VM) { vm = &VM{ LState: lua.NewState(), } vm.Pool = pool.MakePool( func() (t *lua.LTable) { t = vm.NewTable() return }, func(t *lua.LTable) { // TODO reset table }, ) lfunc := vm.NewFunctionFromProto(compiled) vm.Push(lfunc) errors.PanicIfError(vm.PCall(0, 1, nil)) retval := vm.LState.Get(1) vm.Pop(1) if retvalTable, ok := retval.(*LTable); ok { vm.LTable = retvalTable } return vm }, func(vm *VM) { vm.SetTop(0) }, ) return }
/*! \mainpage TradingApp This manual is divided in the following sections: - \subpage quickstart - \subpage usersguide - \subpage developersguide - \subpage knownissues - \subpage license - \subpage copyright */ /** \page quickstart Quick Start - \subpage installation - \subpage qsivte */ /** \page installation Installation \htmlinclude installation.htm */ /** \page qsivte The Integrated Visual Trading Environment \htmlinclude \quickstart\ivte.htm */ /** \page knownissues Known Issues \htmlinclude known_issues.htm */ //----------------------------------------------------------- /** \page usersguide User's Guide - \subpage overviewuserguide - \subpage ivte - \subpage plugin */ /** \page developersguide Developer's Guide - \subpage plugindevguide - \subpage tradingsystem - \subpage miscellaneous */ /** \page plugindevguide Writing Plug-ins - \subpage pluginapi - \subpage pluginconfigurationapi - \subpage pluginhelperclasses - \subpage sessioneventapi - \subpage runnabledevguide - \subpage datasourcedevguide - \subpage symbolsourcedevguide - \subpage signalhandlerdevguide - \subpage slippagedevguide - \subpage commissiondevguide */ /** \page pluginapi Plug-in API \htmlinclude pluginapi.htm */ /** \page pluginconfigurationapi Plug-in Configuration API \htmlinclude pluginconfigurationapi.htm */ /** \page sessioneventapi Session Events API \htmlinclude sessioneventapi.htm */ /** \page pluginhelperclasses Plug-in Helper Classes \htmlinclude pluginhelperclasses.htm */ /** \page runnabledevguide Runnable \htmlinclude runnable_dev_guide.htm */ /** \page datasourcedevguide Data Source \htmlinclude datasource_dev_guide.htm */ /** \page symbolsourcedevguide Symbols Source \htmlinclude symbol_source_dev_guide.htm */ /** \page signalhandlerdevguide Signal Handler \htmlinclude signal_handler_dev_guide.htm */ /** \page slippagedevguide Slippage \htmlinclude slippage.htm */ /** \page commissiondevguide Commission \htmlinclude commission.htm */ /** \page tradingsystem Trading System \subpage tradingsystemoverview \subpage multisymboltradingsystem \subpage simpletradingsystem */ /** \page tradingsystemoverview Overview \htmlinclude trading_system_dev_guide_overview.htm */ /** \page multisymboltradingsystem Multi-symbol Trading Systems \htmlinclude multi_symbol_system.htm */ /** \page simpletradingsystem A Simple Trading System \htmlinclude simple_trading_system.htm */ /** \page miscellaneous Miscellaneous \htmlinclude misc.htm */ /** \page license License Agreement \htmlinclude license.htm */ /** \page copyright Copyright Notices and Acknowledgments \htmlinclude acknowledgments.htm */ //----------------------------------------------------------- /** \page overviewuserguide Overview \htmlinclude userguide\overview.htm */ /** \page ivte Integrated Visual Trading Environment \htmlinclude "ivte\ivte1.htm" \image html plugin_explorer.jpg \htmlinclude ivte/ivte2.htm \image html properties_bar.jpg \htmlinclude ivte/ivte3.htm \image html session_window.jpg \htmlinclude ivte/ivte4.htm */ /** \page plugin Plug-ins - \subpage pluginoverview - \subpage pluginconfigurations - \subpage typesofplugins - \subpage filedatasourceplugin - \subpage filesymbolssourceplugin - \subpage filesignalhandlerplugin */ /** \page pluginoverview Overview \htmlinclude .\plugins\overview.htm */ /** \page pluginconfigurations Plug-in Configurations \htmlinclude .\plugins\pluginconfigurations.htm */ /** \page typesofplugins Types of plug-ins \htmlinclude .\plugins\typesofplugins.htm */ /** \page filedatasourceplugin File DataSource Plug-in \htmlinclude .\plugins\filedatasourceplugin\file_data_source_plugin1.htm \image html filedatasourcedlg.jpg \htmlinclude .\plugins\filedatasourceplugin\file_data_source_plugin2.htm */ /** \page filesymbolssourceplugin File Symbols Source Plug-in \htmlinclude .\plugins\filesymbolssourceplugin\file_symbols_source_plugin1.htm \image html filesymbolslistdlg.jpg \htmlinclude .\plugins\filesymbolssourceplugin\file_symbols_source_plugin2.htm */ /** \page filesignalhandlerplugin File Signal Handler and Statistics Plug-in \htmlinclude .\plugins\filesignalhandlerplugin\file_signal_handler_plugin1.htm \image html filesignalhandlerdlg.jpg \htmlinclude .\plugins\filesignalhandlerplugin\file_signal_handler_plugin2.htm \image html filesignalhandlerui.jpg \htmlinclude .\plugins\filesignalhandlerplugin\file_signal_handler_plugin2.htm */
package jpabook.jpashop.service; import jpabook.jpashop.domain.Member; import jpabook.jpashop.repository.MemberRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional(readOnly = true) //jpa로직에 있어서 무조건적으로 있어야함 스프링 프레임워크에서 제공하는 Transactional 이 더 기능이 많음 @RequiredArgsConstructor// final 있는 애를 가지고 생성자를 만들어줌 public class MemberService { private final MemberRepository memberRepository; @Transactional public Long join(Member member){ validateDuplicateMember(member); memberRepository.save(member); return member.getId(); } private void validateDuplicateMember(Member member) { List<Member> findMembers = memberRepository.findByName(member.getName()); if(!findMembers.isEmpty()){ throw new IllegalStateException("이미 존재하는 회원입니다."); } } //회원 전체 조회 public List<Member> findMembers(){ return memberRepository.findAll(); } //조회할떄는 성능 최적화 public Member findOne(Long memberId){ return memberRepository.findOne(memberId); } @Transactional public void update(Long id, String name) { Member member = memberRepository.findOne(id); member.setName(name); } }
import { nanoid } from "nanoid" import React, { useState } from "react"; import Form from "./components/Form"; import FilterButton from "./components/FilterButton"; import Todo from "./components/Todo"; const FILTER_MAP = { All: () => true, Active: task => !task.completed, Completed: task => task.completed }; const FILTER_NAMES = Object.keys(FILTER_MAP); function App(props) { const [tasks, setTasks] = useState(props.tasks); const [filter, setFilter] = useState('All'); const filterList = FILTER_NAMES.map(name => ( <FilterButton key={name} name={name} isPressed={name === filter} setFilter={setFilter} /> )); function editTask(id, newName) { const editedTaskList = tasks.map(task => { if (id === task.id) { return {...task, name: newName} } return task; }); setTasks(editedTaskList); } function toggleTaskCompleted(id) { const updatedTasks = tasks.map( task => { if (id === task.id) { return {...task, completed: !task.completed} } return task; }); setTasks(updatedTasks); } const taskList = tasks .filter(FILTER_MAP[filter]) .map(task => ( <Todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggleTaskCompleted={toggleTaskCompleted} deleteTask={deleteTask} editTask={editTask} /> ) ); function addTask(name) { const newTask = {id: "todo-" + nanoid(), name: name, completed: false }; setTasks([...tasks, newTask]); } function deleteTask(id) { const remainingTasks= tasks.filter( task => id !== task.id); setTasks(remainingTasks); } const tasksNoun = taskList.length !== 1 ? 'tasks' : 'task'; const headingText = `${taskList.length} ${tasksNoun} remaining`; return ( <div className="todoapp stack-large"> <h1>TodoMatic</h1> <Form addTask={addTask} /> <div className="filters btn-group stack-exception"> {filterList} </div> <h2 id="list-heading">{headingText}</h2> <ul role="list" className="todo-list stack-large stack-exception" aria-labelledby="list-heading" > {taskList} </ul> </div> ); } export default App;
mod iter; mod prefix; mod range; pub use self::iter::{RoIter, RoRevIter, RwIter, RwRevIter}; pub use self::prefix::{RoPrefix, RoRevPrefix, RwPrefix, RwRevPrefix}; pub use self::range::{RoRange, RoRevRange, RwRange, RwRevRange}; #[cfg(test)] mod tests { use std::ops; #[test] fn prefix_iter_last_with_byte_255() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Str>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0, 254, 119, 111, 114, 108, 100], "world").unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 104, 101, 108, 108, 111], "hello").unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 119, 111, 114, 108, 100], "world").unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0, 119, 111, 114, 108, 100], "world").unwrap(); db.put(&mut wtxn, &[255, 255, 0, 254, 119, 111, 114, 108, 100], "world").unwrap(); db.put(&mut wtxn, &[255, 255, 0, 255, 104, 101, 108, 108, 111], "hello").unwrap(); db.put(&mut wtxn, &[255, 255, 0, 255, 119, 111, 114, 108, 100], "world").unwrap(); db.put(&mut wtxn, &[255, 255, 1, 0, 119, 111, 114, 108, 100], "world").unwrap(); // Lets check that we properly get the last entry. let iter = db.prefix_iter(&wtxn, &[0, 0, 0, 255]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], "world")) ); // Lets check that we can prefix_iter on that sequence with the key "255". let mut iter = db.prefix_iter(&wtxn, &[0, 0, 0, 255]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0u8, 0, 0, 255, 104, 101, 108, 108, 111][..], "hello")) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], "world")) ); assert_eq!(iter.next().transpose().unwrap(), None); drop(iter); // Lets check that we properly get the last entry. let iter = db.prefix_iter(&wtxn, &[255]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[255, 255, 1, 0, 119, 111, 114, 108, 100][..], "world")) ); // Lets check that we can prefix_iter on that sequence with the key "255". let mut iter = db.prefix_iter(&wtxn, &[255]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 254, 119, 111, 114, 108, 100][..], "world")) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 255, 104, 101, 108, 108, 111][..], "hello")) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 255, 119, 111, 114, 108, 100][..], "world")) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 1, 0, 119, 111, 114, 108, 100][..], "world")) ); assert_eq!(iter.next().transpose().unwrap(), None); drop(iter); wtxn.abort(); } #[test] fn iter_last() { use crate::byteorder::BigEndian; use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<BEI32, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); type BEI32 = I32<BigEndian>; // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &1, &()).unwrap(); db.put(&mut wtxn, &2, &()).unwrap(); db.put(&mut wtxn, &3, &()).unwrap(); db.put(&mut wtxn, &4, &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((4, ()))); let mut iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.last().transpose().unwrap(), Some((4, ()))); let mut iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.last().transpose().unwrap(), None); let mut iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.next().transpose().unwrap(), None); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &1, &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((1, ()))); let mut iter = db.iter(&wtxn).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn range_iter_last() { use crate::byteorder::BigEndian; use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<BEI32, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); type BEI32 = I32<BigEndian>; // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &1, &()).unwrap(); db.put(&mut wtxn, &2, &()).unwrap(); db.put(&mut wtxn, &3, &()).unwrap(); db.put(&mut wtxn, &4, &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((4, ()))); let mut iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.last().transpose().unwrap(), Some((4, ()))); let mut iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.last().transpose().unwrap(), None); let mut iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.next().transpose().unwrap(), None); assert_eq!(iter.last().transpose().unwrap(), None); let range = 2..=4; let mut iter = db.range(&wtxn, &range).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.last().transpose().unwrap(), Some((4, ()))); let range = 2..4; let mut iter = db.range(&wtxn, &range).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.last().transpose().unwrap(), Some((3, ()))); let range = 2..4; let mut iter = db.range(&wtxn, &range).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.last().transpose().unwrap(), None); let range = 2..2; let iter = db.range(&wtxn, &range).unwrap(); assert_eq!(iter.last().transpose().unwrap(), None); #[allow(clippy::reversed_empty_ranges)] let range = 2..=1; let iter = db.range(&wtxn, &range).unwrap(); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &1, &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((1, ()))); let mut iter = db.range(&wtxn, &(..)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn range_iter_last_with_byte_255() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 1], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 2], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0], &()).unwrap(); // Lets check that we properly get the last entry. let iter = db .range( &wtxn, &(ops::Bound::Excluded(&[0, 0, 0][..]), ops::Bound::Included(&[0, 0, 1, 0][..])), ) .unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((&[0, 0, 1, 0][..], ()))); // Lets check that we can range_iter on that sequence with the key "255". let mut iter = db .range( &wtxn, &(ops::Bound::Excluded(&[0, 0, 0][..]), ops::Bound::Included(&[0, 0, 1, 0][..])), ) .unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 0, 1][..], ()))); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 0, 2][..], ()))); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 1, 0][..], ()))); assert_eq!(iter.next().transpose().unwrap(), None); drop(iter); wtxn.abort(); } #[test] fn prefix_iter_last() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0, 254, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 104, 101, 108, 108, 111], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0, 119, 111, 114, 108, 100], &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 254, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 254, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); let iter = db.prefix_iter(&wtxn, &[0, 0, 1]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 1, 0, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.prefix_iter(&wtxn, &[0, 0, 1]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 1, 0, 119, 111, 114, 108, 100][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn rev_prefix_iter_last() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0, 254, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 104, 101, 108, 108, 111], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0, 119, 111, 114, 108, 100], &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.rev_prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 254, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.rev_prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 254, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.rev_prefix_iter(&wtxn, &[0, 0, 0]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 254, 119, 111, 114, 108, 100][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); let iter = db.rev_prefix_iter(&wtxn, &[0, 0, 1]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 1, 0, 119, 111, 114, 108, 100][..], ())) ); let mut iter = db.rev_prefix_iter(&wtxn, &[0, 0, 1]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 1, 0, 119, 111, 114, 108, 100][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn rev_prefix_iter_last_with_byte_255() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0, 254, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 104, 101, 108, 108, 111], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 255, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[255, 255, 0, 254, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[255, 255, 0, 255, 104, 101, 108, 108, 111], &()).unwrap(); db.put(&mut wtxn, &[255, 255, 0, 255, 119, 111, 114, 108, 100], &()).unwrap(); db.put(&mut wtxn, &[255, 255, 1, 0, 119, 111, 114, 108, 100], &()).unwrap(); // Lets check that we can get last entry on that sequence ending with the key "255". let iter = db.rev_prefix_iter(&wtxn, &[0, 0, 0, 255]).unwrap(); assert_eq!( iter.last().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); // Lets check that we can prefix_iter on that sequence ending with the key "255". let mut iter = db.rev_prefix_iter(&wtxn, &[0, 0, 0, 255]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[0, 0, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); let mut iter = db.rev_prefix_iter(&wtxn, &[255, 255]).unwrap(); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 1, 0, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 255, 119, 111, 114, 108, 100][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 255, 104, 101, 108, 108, 111][..], ())) ); assert_eq!( iter.next().transpose().unwrap(), Some((&[255, 255, 0, 254, 119, 111, 114, 108, 100][..], ())) ); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn rev_range_iter_last() { use crate::byteorder::BigEndian; use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<BEI32, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); type BEI32 = I32<BigEndian>; // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &1, &()).unwrap(); db.put(&mut wtxn, &2, &()).unwrap(); db.put(&mut wtxn, &3, &()).unwrap(); db.put(&mut wtxn, &4, &()).unwrap(); // Lets check that we properly get the last entry. let iter = db.rev_range(&wtxn, &(1..=3)).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((1, ()))); let mut iter = db.rev_range(&wtxn, &(0..4)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.last().transpose().unwrap(), Some((1, ()))); let mut iter = db.rev_range(&wtxn, &(0..=5)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((3, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((2, ()))); assert_eq!(iter.next().transpose().unwrap(), Some((1, ()))); assert_eq!(iter.last().transpose().unwrap(), None); let iter = db.rev_range(&wtxn, &(0..=5)).unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((1, ()))); let mut iter = db.rev_range(&wtxn, &(4..=4)).unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((4, ()))); assert_eq!(iter.last().transpose().unwrap(), None); wtxn.abort(); } #[test] fn rev_range_iter_last_with_byte_255() { use crate::types::*; use crate::EnvOpenOptions; let dir = tempfile::tempdir().unwrap(); let env = unsafe { EnvOpenOptions::new() .map_size(10 * 1024 * 1024) // 10MB .max_dbs(3000) .open(dir.path()) .unwrap() }; let mut wtxn = env.write_txn().unwrap(); let db = env.create_database::<Bytes, Unit>(&mut wtxn, None).unwrap(); wtxn.commit().unwrap(); // Create an ordered list of keys... let mut wtxn = env.write_txn().unwrap(); db.put(&mut wtxn, &[0, 0, 0], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 1], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 0, 2], &()).unwrap(); db.put(&mut wtxn, &[0, 0, 1, 0], &()).unwrap(); // Lets check that we properly get the last entry. let iter = db .rev_range( &wtxn, &(ops::Bound::Excluded(&[0, 0, 0][..]), ops::Bound::Included(&[0, 0, 1, 0][..])), ) .unwrap(); assert_eq!(iter.last().transpose().unwrap(), Some((&[0, 0, 0, 1][..], ()))); // Lets check that we can range_iter on that sequence with the key "255". let mut iter = db .rev_range( &wtxn, &(ops::Bound::Excluded(&[0, 0, 0][..]), ops::Bound::Included(&[0, 0, 1, 0][..])), ) .unwrap(); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 1, 0][..], ()))); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 0, 2][..], ()))); assert_eq!(iter.next().transpose().unwrap(), Some((&[0, 0, 0, 1][..], ()))); assert_eq!(iter.next().transpose().unwrap(), None); drop(iter); wtxn.abort(); } }