text
stringlengths
184
4.48M
import React, {FC, useMemo, useState} from 'react'; import {Question, QuestionType} from '../../interfaces/Question'; import {shuffleArray} from '../../../../__mocks__/questionsList'; interface Props { question: Question; checkAnswer: (answer: string) => void; disabled: boolean; } export const QuestionOptions: FC<Props> = ({question, checkAnswer, disabled}) => { const options = useMemo(() => shuffleArray(question.options!), [question.options]); return ( <div className={"flex flex-row gap-3 "}> {options.map((answer, index) => ( <button key={index} onClick={() => checkAnswer(answer)} disabled={disabled} className={"app-button bg-[#405cf5]"} >{answer}</button> ))} </div> ); }; export const QuestionInput: FC<Props> = ({question, checkAnswer, disabled}) => { const [answer, setAnswer] = useState(''); return ( <div className={"flex flex-row gap-3 items-center "}> <input disabled={disabled} type={question.type === QuestionType.Number ? 'number' : 'text'} className={"app-input"} value={answer} onChange={e => setAnswer(e.target.value)}/> <button onClick={() => { checkAnswer(answer); setAnswer(''); }} disabled={disabled || !answer} className={"app-button bg-[#405cf5]"} >Check answer </button> </div> ); }
package com.sky.task; import com.sky.entity.Orders; import com.sky.mapper.OrderMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.List; /** * @author LHF * @version 1.0 * @date 2024/5/17 19:24 */ @Component @Slf4j public class OrderTask { @Autowired private OrderMapper orderMapper; /** * 处理超时未支付订单 * * @param: * @return: void */ @Scheduled(cron = "0 * * * * ?") //每秒钟执行一次 public void processTimeOutOrder() { log.info("定时处理超时未支付订单:{}", LocalDateTime.now()); //超时时间 LocalDateTime time = LocalDateTime.now().plusMinutes(-15); //查询订单状态为待付款且超时15分钟的订单 List<Orders> ordersList = orderMapper.getStatusAndTimeOut(Orders.PENDING_PAYMENT, time); if (ordersList != null && !ordersList.isEmpty()) { for (Orders orders : ordersList) { //将该订单状态设置为已取消 orders.setStatus(Orders.CANCELLED); orders.setCancelReason("订单超时,自动取消"); orders.setCancelTime(LocalDateTime.now()); //更新数据库中对应的记录 orderMapper.update(orders); } } } /** * 处理一直处于派送中的订单 * @param: * @return: void */ @Scheduled(cron = "0 0 1 * * ?") //每天一点执行一次 public void processDeliveryOrder(){ log.info("处理一直处于派送中的订单:{}", LocalDateTime.now()); LocalDateTime time = LocalDateTime.now().plusMinutes(-60); //查询处于派送中的订单 List<Orders> ordersList = orderMapper.getStatusAndTimeOut(Orders.DELIVERY_IN_PROGRESS, time); if (ordersList != null && !ordersList.isEmpty()) { for (Orders orders : ordersList) { //将该订单状态设置为已完成 orders.setStatus(Orders.COMPLETED); //更新数据库中对应的记录 orderMapper.update(orders); } } } }
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. fun main() { var adam = Human("Adam", 44) adam.age++ var adamCopy = Human("Adam", 45) val eve = Human("Eve", 44) println(adam.equals(eve)) //false println(adam == adamCopy) // false val matrix = Cyborg("Victor Stone", Int.MAX_VALUE / 2) val ultron = Cyborg("Ultron", 400) val ultronCopy = ultron.copy() println(matrix.equals(ultron)) println("Comparing ultron instances ${ultron.equals(ultronCopy)}") // true println("You can copy a Cyborg but you can't copy a Human!") val firstCow = Cow("Vaquita", Size.medium) val secondCow = Cow("vacalola", Size.big) val firstDog = Dog("Cliford", Size.medium) playWithAnimal(firstCow) println() playWithAnimal(firstDog) println() playWithAnimal(secondCow) // Collections val myList = mutableListOf("Anderson", "Juan", "Pedro", "Pedro", "Alguien") val mySet = mutableSetOf("Hola", "Hello", "Konichigua") val myDictionary = mutableMapOf(28113110 to "Anderson",28110345 to "Luis", 9762309 to "Elba" ) playWithCollections(myList) println() println("Set Playing") playWithCollections(mySet) println("Map playing") for (value in myDictionary){ println(value) } myDictionary.map { println("${it.key} belongs to ${it.value}") } // Returning string in a List with a length minor to 5 val filterList = myList.filter{ it.length < 5 } println(filterList ) //Returning the longest String in a List val longestNameInList = myList.maxBy { it.length } println(longestNameInList) } class Dog : Animal { override val name: String override val size: Size constructor(name: String, size: Size) { this.name = name this.size = size } override fun walk() { println("$name is walking") } } class Cow(override val name: String, override var size:Size) : Animal { override fun walk() { println("$name the Cow is walking") } fun eat(){ println("$name is eating") this.size = Size.big; println("$name is bigger now!") } } enum class Size{ small, medium, big } interface Animal { val name: String val size: Size get() = Size.medium // when not size provided fun walk(); } class Human(val name: String, var age: Int); // Cyborg is a data class data class Cyborg (val name: String, var age: Int){ fun talk(){ println("Hello, Human I am $name and I am a Cyborg!") } } /* * @description: Use an Animal that implement the Animal interface * depending of the kind of animal the function call different method of the class * */ fun playWithAnimal(animal: Animal){ animal.walk() // Cannot call this method in this scope because it is not a "Cow" and it just only access // the properties in the contract (interface) //animal.eat() when (animal){ is Cow -> { if (animal.size == Size.big || animal.name == "lavacalola"){ println("Animal is as big as it could be. Its not going to eat now!") }else{ animal.eat() } } else -> println("It is not a cow!") } } /* * @Description: This function recibe a collection as the parameter and depending of the type of collection play with it * * */ fun playWithCollections (collection: MutableCollection<String>){ when (collection){ is MutableList<String> -> { collection.add("Value") collection.add("Value2") collection.add("Value3") collection.add("Value3") collection.add("Value3") println("Collection is a list of size ${collection.size}") collection.forEach { println(it) //repeated values allowed }; collection.removeAt(0) } is MutableSet<String> -> { collection.add("Value") collection.add("Value2") collection.add("Value3") collection.add("Value3") collection.add("Value3") collection.forEach({ println(it) //repeated not allowed }) } } }
@testable import App import ComposableArchitecture import Core import XCTest @MainActor final class TodayReducerTests: XCTestCase { func testDidLoad() async throws { let feed1 = Feed(slug: "1", title: "Tecnologia", collection: "1", emoji: "1", weight: 1) let feed2 = Feed(slug: "2", title: "Sport", collection: "2", emoji: "2", weight: 2) let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.favoritesClient.favoriteRegion = { feed1.slug } store.dependencies.favoritesClient.favoriteSections = { [feed2.slug] } store.dependencies.onboardingClient.didCompleteOnboarding = { false } store.dependencies.onboardingClient.didWatchVideo = { true } store.dependencies.onboardingClient.didCompleteVideoOnboarding = { false } let observeApplicationState = AsyncStream<ApplicationStateChange>.streamWithContinuation() let observeFavoriteRegion = AsyncStream<Feed.Slug?>.streamWithContinuation() let observeFavoriteSections = AsyncStream<[Feed.Slug]>.streamWithContinuation() store.dependencies.applicationStateClient.observe = { observeApplicationState.stream } store.dependencies.favoritesClient.observeFavoriteRegion = { observeFavoriteRegion.stream } store.dependencies.favoritesClient.observeFavoriteSections = { observeFavoriteSections.stream } struct ObserveArticlesArgs: Hashable { let slug: Feed.Slug, limit: Int } let observeArticles = AsyncThrowingStream<[Article], Error>.streamWithContinuation() var observeArticlesArgs: [ObserveArticlesArgs] = [] store.dependencies.persistenceClient.observeArticles = { slug, limit in observeArticlesArgs.append(.init(slug: slug, limit: limit)) if slug == .home { return observeArticles.stream } else { return AsyncThrowingStream<[Article], Error> { _ in } } } var loadArticlesArgs: [[Feed.Slug]] = [] store.dependencies.feedsClient.loadArticles = { args in loadArticlesArgs.append(args) } var getVideosCallCount = 0 store.dependencies.networkClient.getVideos = { getVideosCallCount += 1 return [] } let task = await store.send(.didLoad) { state in state.canShowVideoOnboarding = true state.canShowRegionOnboarding = true state.favoriteSections = [feed2.slug] state.favoriteRegion = feed1.slug } let groups = TodayGroups( home: .init(articles: []), region: .init(articles: []), sections: [.init(articles: [])] ) await store.receive(.groupsLoaded(groups)) { state in state.groups = groups } await store.receive(.groupsInitialLoadingCompleted) { state in state.areAnimationsEnabled = true } await store.receive(.favoriteRegionChanged(feed1.slug)) await store.receive(.favoriteSectionsChanged([feed2.slug])) await store.receive(.isUpdatingChanged(true)) { state in state.isUpdating = true } await store.receive(.videoChanged(nil)) await store.receive(.isUpdatingChanged(false)) { state in state.isUpdating = false } let change = ApplicationStateChange(from: .background, to: .foreground, duration: 300) observeApplicationState.continuation.yield(change) await store.receive(.applicationStateChanged(change)) observeFavoriteRegion.continuation.yield(feed1.slug) await store.receive(.favoriteRegionChanged(feed1.slug)) observeFavoriteSections.continuation.yield([feed2.slug]) await store.receive(.favoriteSectionsChanged([feed2.slug])) observeArticles.continuation.yield([]) await store.receive(.homeGroupLoaded(.init(articles: []))) await store.send(.didUnload).finish() await task.finish() XCTAssertEqual(getVideosCallCount, 1) XCTAssertEqual(Set(loadArticlesArgs), [[.main], ["1"], ["2"]]) XCTAssertEqual(Set(observeArticlesArgs), [ .init(slug: .main, limit: 4), .init(slug: "1", limit: 6), .init(slug: "2", limit: 4), ]) } func testFullUpdates() async { let feed1 = Feed(slug: "1", title: "Tecnologia", collection: "1", emoji: "1", weight: 1) let feed2 = Feed(slug: "2", title: "Sport", collection: "2", emoji: "2", weight: 2) let feed3 = Feed(slug: "3", title: "Cultura", collection: "3", emoji: "3", weight: 3) let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.favoritesClient.favoriteRegion = { feed1.slug } store.dependencies.favoritesClient.favoriteSections = { [feed2.slug, feed3.slug] } var loadArticlesArgs: [[Feed.Slug]] = [] store.dependencies.feedsClient.loadArticles = { args in loadArticlesArgs.append(args) } var getVideosCallCount = 0 store.dependencies.networkClient.getVideos = { getVideosCallCount += 1 return [] } await store.send(.refreshTriggered) await store.receive(.isUpdatingChanged(true)) { $0.isUpdating = true } await store.receive(.videoChanged(nil)) await store.receive(.isUpdatingChanged(false)) { $0.isUpdating = false } XCTAssertEqual(getVideosCallCount, 1) XCTAssertEqual(loadArticlesArgs.count, 1) XCTAssertEqual(Set(loadArticlesArgs.last ?? []), [.main, "2", "3", "1"]) let change = ApplicationStateChange(from: .background, to: .foreground, duration: 301) await store.send(.applicationStateChanged(change)) await store.receive(.isUpdatingChanged(true)) { $0.isUpdating = true } await store.receive(.videoChanged(nil)) await store.receive(.isUpdatingChanged(false)) { $0.isUpdating = false } XCTAssertEqual(getVideosCallCount, 2) XCTAssertEqual(loadArticlesArgs.count, 2) XCTAssertEqual(Set(loadArticlesArgs.last ?? []), [.main, "2", "3", "1"]) } func testFavoriteRegionChanged() async { let feed = Feed(slug: "1", title: "Tecnologia", collection: "1", emoji: "1", weight: 1) let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.favoritesClient.favoriteRegion = { nil } var loadArticlesArgs: [[Feed.Slug]] = [] store.dependencies.feedsClient.loadArticles = { args in loadArticlesArgs.append(args) } struct ObserveArticlesArgs: Hashable { let slug: Feed.Slug, limit: Int } let observeArticles = AsyncThrowingStream<[Article], Error>.streamWithContinuation() var observeArticlesArgs: [ObserveArticlesArgs] = [] store.dependencies.persistenceClient.observeArticles = { slug, limit in observeArticlesArgs.append(.init(slug: slug, limit: limit)) return observeArticles.stream } let task = await store.send(.favoriteRegionChanged(feed.slug)) { state in state.favoriteRegion = feed.slug } let groups = TodayGroups(home: .init(articles: [])) await store.receive(.groupsLoaded(groups)) { state in state.groups = groups } observeArticles.continuation.yield([article]) await store.receive(.regionGroupLoaded(nil)) await store.send(.didUnload) await task.finish() XCTAssertEqual(loadArticlesArgs, [["1"]]) XCTAssertEqual(observeArticlesArgs, [.init(slug: "1", limit: 6)]) } func testFavoriteSectionsChanged() async { let feed = Feed(slug: "1", title: "Tecnologia", collection: "1", emoji: "1", weight: 1) let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.favoritesClient.favoriteRegion = { nil } var loadArticlesArgs: [[Feed.Slug]] = [] store.dependencies.feedsClient.loadArticles = { args in loadArticlesArgs.append(args) } struct ObserveArticlesArgs: Hashable { let slug: Feed.Slug, limit: Int } let observeArticles = AsyncThrowingStream<[Article], Error>.streamWithContinuation() var observeArticlesArgs: [ObserveArticlesArgs] = [] store.dependencies.persistenceClient.observeArticles = { slug, limit in observeArticlesArgs.append(.init(slug: slug, limit: limit)) return observeArticles.stream } let task = await store.send(.favoriteSectionsChanged([feed.slug])) { state in state.favoriteSections = [feed.slug] } let groups = TodayGroups(home: .init(articles: [])) await store.receive(.groupsLoaded(groups)) { state in state.groups = groups } observeArticles.continuation.yield([article]) await store.receive(.sectionsGroupLoaded([])) await store.send(.didUnload) await task.finish() XCTAssertEqual(loadArticlesArgs, [["1"]]) XCTAssertEqual(observeArticlesArgs, [.init(slug: "1", limit: 4)]) } func testVideoDismissed() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.onboardingClient.didWatchVideo = { true } var didWatchVideo: Bool? store.dependencies.onboardingClient.setDidWatchVideo = { didWatchVideo = true } await store.send(.videoDismissed) { state in state.canShowVideoOnboarding = true }.finish() XCTAssertEqual(didWatchVideo, true) } func testVideoDismissedOnboardingCompleted() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.onboardingClient.didWatchVideo = { true } store.dependencies.onboardingClient.didCompleteVideoOnboarding = { true } var didWatchVideo = false store.dependencies.onboardingClient.setDidWatchVideo = { didWatchVideo = true } await store.send(.videoDismissed).finish() XCTAssertEqual(didWatchVideo, true) } func testVideoOnboardingCompleted() async { let store = TestStore(initialState: .init(canShowVideoOnboarding: true), reducer: TodayReducer()) var didCompleteVideoOnboarding = false store.dependencies.onboardingClient.setDidCompleteVideoOnboarding = { didCompleteVideoOnboarding = true } await store.send(.videoOnboardingCompleted) { state in state.canShowVideoOnboarding = false }.finish() XCTAssertEqual(didCompleteVideoOnboarding, true) } func testEnableVideoNotificationsTapped() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.notificationsClient.canRequestAuthorization = { true } store.dependencies.notificationsClient.requestAuthorization = { true } var requests: [NotificationsServiceRequest] = [] store.dependencies.notificationsClient.addRequest = { request in requests.append(request) } await store.send(.enableVideoNotificationsTapped).finish() await store.receive(.videoOnboardingCompleted) XCTAssertEqual(requests as? [VideoNotificationRequest], [.day, .night]) } func testEnableVideoNotificationsTappedCantAuthorize() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.notificationsClient.canRequestAuthorization = { false } var requests: [NotificationsServiceRequest] = [] store.dependencies.notificationsClient.addRequest = { request in requests.append(request) } await store.send(.enableVideoNotificationsTapped).finish() await store.receive(.videoOnboardingCompleted) XCTAssertEqual(requests.count, 0) } func testEnableVideoNotificationsTappedNotAuthorized() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) store.dependencies.notificationsClient.canRequestAuthorization = { true } store.dependencies.notificationsClient.requestAuthorization = { false } var requests: [NotificationsServiceRequest] = [] store.dependencies.notificationsClient.addRequest = { request in requests.append(request) } await store.send(.enableVideoNotificationsTapped).finish() await store.receive(.videoOnboardingCompleted) XCTAssertEqual(requests.count, 0) } func testIgnoreRegionOnboardingTapped() async { let store = TestStore(initialState: .init(canShowRegionOnboarding: true), reducer: TodayReducer()) var didCompleteRegionOnboarding = false store.dependencies.onboardingClient.setDidCompleteRegionOnboarding = { didCompleteRegionOnboarding = true } await store.send(.ignoreRegionOnboardingTapped) { state in state.canShowRegionOnboarding = false }.finish() XCTAssertEqual(didCompleteRegionOnboarding, true) } func testStartRegionOnboardingTapped() async { let feed = Feed(slug: "1", title: "1", collection: "1", emoji: "1", weight: 1) let store = TestStore(initialState: .init(), reducer: TodayReducer()) var collection: Feed.Collection? store.dependencies.persistenceClient.getFeedsByCollection = { value in collection = value return [feed] } await store.send(.startRegionOnboardingTapped).finish() await store.receive(.regionOnboardingFeedsChanged([feed])) { state in state.regions = [feed] } XCTAssertEqual(collection, .local) } func testRegionOnboardingFeedSelected() async { let feed = Feed(slug: "1", title: "1", collection: "1", emoji: "1", weight: 1) let store = TestStore(initialState: .init(regions: [feed]), reducer: TodayReducer()) store.exhaustivity = .off var slug: Feed.Slug? store.dependencies.favoritesClient.setFavoriteRegion = { value in slug = value } var didCompleteRegionOnboarding = false store.dependencies.onboardingClient.setDidCompleteRegionOnboarding = { didCompleteRegionOnboarding = true } await store.send(.regionOnboardingFeedSelected(feed)) { state in state.regions = nil }.finish() XCTAssertEqual(slug, feed.slug) XCTAssertEqual(didCompleteRegionOnboarding, true) } func testCloseRegionOnboardingTapped() async { let feed = Feed(slug: "1", title: "1", collection: "1", emoji: "1", weight: 1) let store = TestStore(initialState: .init(regions: [feed]), reducer: TodayReducer()) await store.send(.closeRegionOnboardingTapped) { state in state.regions = nil }.finish() } func testArticleSelected() async { let store = TestStore(initialState: .init(), reducer: TodayReducer()) await store.send(.articleSelected(article)) { state in state.article = .init(article: article) }.finish() } func testArticleDidUnload() async { let store = TestStore(initialState: .init(article: .init(article: article)), reducer: TodayReducer()) await store.send(.article(.didUnload)) { state in state.article = nil }.finish() } } private let video: Video = { let responseData = try! Data(contentsOf: Files.videosJson.url) let response = try! JSONDecoder.default.decode(VideosRequest.Response.self, from: responseData) let video = try! XCTUnwrap(response.videos.first) return video }() private let article: Article = { let articleData = try! Data(contentsOf: Files.articleJson.url) let article = try! JSONDecoder.default.decode(Article.self, from: articleData) return article }()
import csv import sys import check50 from util import Node, StackFrontier, QueueFrontier # Maps names to a set of corresponding person_ids names = {} # Maps person_ids to a dictionary of: name, birth, movies (a set of movie_ids) people = {} # Maps movie_ids to a dictionary of: title, year, stars (a set of person_ids) movies = {} def load_data(directory): """ Load data from CSV files into memory. """ # Load people with open(f"{directory}/people.csv", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: people[row["id"]] = { "name": row["name"], "birth": row["birth"], "movies": set() } if row["name"].lower() not in names: names[row["name"].lower()] = {row["id"]} else: names[row["name"].lower()].add(row["id"]) # Load movies with open(f"{directory}/movies.csv", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: movies[row["id"]] = { "title": row["title"], "year": row["year"], "stars": set() } # Load stars with open(f"{directory}/stars.csv", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: try: people[row["person_id"]]["movies"].add(row["movie_id"]) movies[row["movie_id"]]["stars"].add(row["person_id"]) except KeyError: pass def main(): if len(sys.argv) > 2: sys.exit("Usage: python degrees.py [directory]") directory = sys.argv[1] if len(sys.argv) == 2 else "large" # Load data from files into memory print("Loading data...") load_data(directory) print("Data loaded.") print(f"names {len(names)}, {list(names.items())[:5]}") print(f"people {len(people)}, {list(people.items())[:5]}") print(f"movies {len(movies)}, {list(movies.items())[:5]}") source_found = False target_found = False while not source_found: # source = person_id_for_name(input("Name: ")) source = person_id_for_name('Emma Watson') source_found = True if source is None: sys.exit("Person not found.") while not target_found: # target = person_id_for_name(input("Name: ")) target = person_id_for_name('John Hoffman') target_found = True if target is None: sys.exit("Person not found.") path = shortest_path(source, target) if path is None: print("Not connected.") else: degrees = len(path) print(f"{degrees} degrees of separation.") path = [(None, source)] + path for i in range(degrees): person1 = people[path[i][1]]["name"] person2 = people[path[i + 1][1]]["name"] movie = movies[path[i + 1][0]]["title"] print(f"{i + 1}: {person1} and {person2} starred in {movie}") # source = person_id_for_name(input("Name: ")) # if source is None: # sys.exit("Person not found.") # target = person_id_for_name(input("Name: ")) # if target is None: # sys.exit("Person not found.") # def shortest_path(source, target): """ Returns the shortest list of (movie_id, person_id) pairs that connect the source to the target. If no possible path, returns None. """ visited = set() search_key_action = people[source]["movies"] search_key = Node(state = source, parent = None, action = None) search_queue = QueueFrontier() search_queue.add(search_key) shortest_path = [] while not search_queue.empty(): node = search_queue.remove() if node.state == target: # print(f"found target {node.state} = {target}") while node.parent is not None: shortest_path.append((node.action, node.state)) node = node.parent shortest_path.reverse() # print(f"Shortest Path: {shortest_path}") return shortest_path visited.add(node.state) neighbors = neighbors_for_person(node.state) for movie_id, person_id in neighbors: if person_id not in visited: neighbor_a = Node(state=person_id, parent=node, action=movie_id) search_queue.add(neighbor_a) visited.add(person_id) return None raise NotImplementedError def person_id_for_name(name): """ Returns the IMDB id for a person's name, resolving ambiguities as needed. """ person_ids = list(names.get(name.lower(), set())) if len(person_ids) == 0: return None elif len(person_ids) > 1: print(f"Which '{name}'?") for person_id in person_ids: person = people[person_id] name = person["name"] birth = person["birth"] print(f"ID: {person_id}, Name: {name}, Birth: {birth}") try: person_id = input("Intended Person ID: ") if person_id in person_ids: return person_id except ValueError: pass return None else: return person_ids[0] def neighbors_for_person(person_id): """ Returns (movie_id, person_id) pairs for people who starred with a given person. """ movie_ids = people[person_id]["movies"] neighbors = set() for movie_id in movie_ids: for person_id in movies[movie_id]["stars"]: neighbors.add((movie_id, person_id)) return neighbors if __name__ == "__main__": main()
/* * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ui_service_mgr_client.h" #include "dialog_callback.h" #include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" #include "string_ex.h" #include "system_ability_definition.h" namespace OHOS { namespace Ace { constexpr int32_t UI_MGR_SERVICE_SA_ID = 7001; std::shared_ptr<UIServiceMgrClient> UIServiceMgrClient::instance_ = nullptr; std::mutex UIServiceMgrClient::mutex_; std::shared_ptr<UIServiceMgrClient> UIServiceMgrClient::GetInstance() { if (instance_ == nullptr) { std::lock_guard<std::mutex> lock(mutex_); if (instance_ == nullptr) { instance_ = std::make_shared<UIServiceMgrClient>(); } } return instance_; } UIServiceMgrClient::UIServiceMgrClient() = default; UIServiceMgrClient::~UIServiceMgrClient() =default; ErrCode UIServiceMgrClient::RegisterCallBack(const AAFwk::Want& want, const sptr<IUIService>& uiService) { if (remoteObject_ == nullptr) { ErrCode err = Connect(); if (err != ERR_OK) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return UI_SERVICE_NOT_CONNECTED; } } sptr<IUIServiceMgr> doms = iface_cast<IUIServiceMgr>(remoteObject_); return doms->RegisterCallBack(want, uiService); } ErrCode UIServiceMgrClient::UnregisterCallBack(const AAFwk::Want& want) { if (remoteObject_ == nullptr) { ErrCode err = Connect(); if (err != ERR_OK) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return UI_SERVICE_NOT_CONNECTED; } } sptr<IUIServiceMgr> doms = iface_cast<IUIServiceMgr>(remoteObject_); return doms->UnregisterCallBack(want); } ErrCode UIServiceMgrClient::Push(const AAFwk::Want& want, const std::string& name, const std::string& jsonPath, const std::string& data, const std::string& extraData) { if (remoteObject_ == nullptr) { ErrCode err = Connect(); if (err != ERR_OK) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return UI_SERVICE_NOT_CONNECTED; } } sptr<IUIServiceMgr> doms = iface_cast<IUIServiceMgr>(remoteObject_); return doms->Push(want, name, jsonPath, data, extraData); } ErrCode UIServiceMgrClient::Request(const AAFwk::Want& want, const std::string& name, const std::string& data) { if (remoteObject_ == nullptr) { ErrCode err = Connect(); if (err != ERR_OK) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return UI_SERVICE_NOT_CONNECTED; } } sptr<IUIServiceMgr> doms = iface_cast<IUIServiceMgr>(remoteObject_); return doms->Request(want, name, data); } ErrCode UIServiceMgrClient::ReturnRequest(const AAFwk::Want& want, const std::string& source, const std::string& data, const std::string& extraData) { if (remoteObject_ == nullptr) { ErrCode err = Connect(); if (err != ERR_OK) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return UI_SERVICE_NOT_CONNECTED; } } sptr<IUIServiceMgr> doms = iface_cast<IUIServiceMgr>(remoteObject_); return doms->ReturnRequest(want, source, data, extraData); } ErrCode UIServiceMgrClient::ShowDialog(const std::string& name, const std::string& params, OHOS::Rosen::WindowType windowType, int32_t x, int32_t y, int32_t width, int32_t height, DialogCallback callback, int32_t* id) { HILOG_ERROR("Ui Service show dialog deprecated!"); return GET_UI_SERVICE_FAILED; } ErrCode UIServiceMgrClient::CancelDialog(int32_t id) { HILOG_ERROR("Ui Service cancel dialog deprecated!"); return GET_UI_SERVICE_FAILED; } ErrCode UIServiceMgrClient::UpdateDialog(int32_t id, const std::string& data) { HILOG_ERROR("Ui Service update dialog deprecated!"); return GET_UI_SERVICE_FAILED; } /** * Connect ui_service manager service. * * @return Returns ERR_OK on success, others on failure. */ ErrCode UIServiceMgrClient::Connect() { std::lock_guard<std::mutex> lock(mutex_); if (remoteObject_ != nullptr) { return ERR_OK; } sptr<ISystemAbilityManager> systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemManager == nullptr) { HILOG_ERROR("%{private}s:fail to get Registry", __func__); return GET_UI_SERVICE_FAILED; } remoteObject_ = systemManager->GetSystemAbility(UI_MGR_SERVICE_SA_ID); if (remoteObject_ == nullptr) { HILOG_ERROR("%{private}s:fail to connect UIMgrService", __func__); return GET_UI_SERVICE_FAILED; } HILOG_DEBUG("connect UIMgrService success"); return ERR_OK; } } // namespace Ace } // namespace OHOS
<template> <div> <TodoInputForm ref="TodoInputForm" :propTodos="todos" :loginToken="loginToken" @todos:push="todos.push($event); updateTree()" > </TodoInputForm> <TodoTree ref="TodoTree" :propTodos="todos" :state="state" :loginToken="loginToken" @todos:delete="todos.splice(todos.findIndex((i) => i.id == $event), 1); updateTree()" @todos:update="updateTodo($event)" > </TodoTree> </div> </template> <script> import TodoInputForm from "../components/Todo/TodoInputForm.vue"; import TodoTree from "../components/Todo/TodoTree.vue"; export default { components: { TodoInputForm, TodoTree, }, created() { this.loginToken = this.$cookies.get("login-token"); this.fetchTodo(); }, data() { return { loginToken: undefined, task: { title: "", description: "", }, edit_id: { title: 0, description: 0, }, todos: [], state: { names: { 1: "オープン", 2: "進行中", 3: "完了", 9: "削除", }, min: 1, delete: 9, complete: 3, }, fields: [ "id", "title", "description", { key: "state", label: "ステータス" }, { key: "operation", label: "操作" }, { key: "destroy", label: "削除" }, "created_at", ], }; }, methods: { fetchTodo: function () { this.axios .get("http://localhost:3000/todos", { params: { login_token: this.loginToken, limit: 100, }, }) .then((response) => { this.todos = response.data; console.log(response.data); this.updateTree(); }) .catch((e) => { alert(e); }); }, updateTodo: function (todo) { var targetIndex = this.todos.findIndex((i) => i.id == todo.id); if (targetIndex >= 0) { this.todos[targetIndex] = todo; } }, updateTree: function () { this.$refs.TodoTree.updateTodosData(this.todos); }, }, }; </script>
<?php namespace MailPoet\API\JSON\v1; if (!defined('ABSPATH')) exit; use Exception; use MailPoet\API\JSON\Endpoint as APIEndpoint; use MailPoet\API\JSON\Error; use MailPoet\API\JSON\Error as APIError; use MailPoet\API\JSON\Response; use MailPoet\API\JSON\ResponseBuilders\FormsResponseBuilder; use MailPoet\API\JSON\SuccessResponse; use MailPoet\Config\AccessControl; use MailPoet\Entities\FormEntity; use MailPoet\Form\ApiDataSanitizer; use MailPoet\Form\DisplayFormInWPContent; use MailPoet\Form\FormSaveController; use MailPoet\Form\FormsRepository; use MailPoet\Form\Listing\FormListingRepository; use MailPoet\Form\PreviewPage; use MailPoet\Form\Templates\TemplateRepository; use MailPoet\Listing; use MailPoet\Settings\UserFlagsController; use MailPoet\UnexpectedValueException; use MailPoet\WP\Emoji; use MailPoet\WP\Functions as WPFunctions; class Forms extends APIEndpoint { public $permissions = [ 'global' => AccessControl::PERMISSION_MANAGE_FORMS, ]; /** @var Listing\Handler */ private $listingHandler; /** @var UserFlagsController */ private $userFlags; /** @var FormsResponseBuilder */ private $formsResponseBuilder; /** @var WPFunctions */ private $wp; /** @var FormsRepository */ private $formsRepository; /** @var TemplateRepository */ private $templateRepository; /** @var FormListingRepository */ private $formListingRepository; /** @var Emoji */ private $emoji; /** @var ApiDataSanitizer */ private $dataSanitizer; /** @var FormSaveController */ private $formSaveController; public function __construct( Listing\Handler $listingHandler, UserFlagsController $userFlags, FormsRepository $formsRepository, TemplateRepository $templateRepository, FormListingRepository $formListingRepository, FormsResponseBuilder $formsResponseBuilder, WPFunctions $wp, Emoji $emoji, ApiDataSanitizer $dataSanitizer, FormSaveController $formSaveController ) { $this->listingHandler = $listingHandler; $this->userFlags = $userFlags; $this->wp = $wp; $this->formsRepository = $formsRepository; $this->templateRepository = $templateRepository; $this->formListingRepository = $formListingRepository; $this->formsResponseBuilder = $formsResponseBuilder; $this->emoji = $emoji; $this->dataSanitizer = $dataSanitizer; $this->formSaveController = $formSaveController; } public function get($data = []) { $id = (isset($data['id']) ? (int)$data['id'] : false); $form = $this->formsRepository->findOneById($id); if ($form instanceof FormEntity) { return $this->successResponse($this->formsResponseBuilder->build($form)); } return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } public function setStatus($data = []) { $status = (isset($data['status']) ? $data['status'] : null); if (!$status) { return $this->badRequest([ APIError::BAD_REQUEST => __('You need to specify a status.', 'mailpoet'), ]); } $id = (isset($data['id'])) ? (int)$data['id'] : false; $form = $this->formsRepository->findOneById($id); if (!$form instanceof FormEntity) { return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } if (!in_array($status, [FormEntity::STATUS_ENABLED, FormEntity::STATUS_DISABLED])) { return $this->badRequest([ APIError::BAD_REQUEST => sprintf( __('Invalid status. Allowed values are (%1$s), you specified %2$s', 'mailpoet'), join(', ', [FormEntity::STATUS_ENABLED, FormEntity::STATUS_DISABLED]), $status ), ]); } $form->setStatus($status); $this->formsRepository->flush(); if ($status === FormEntity::STATUS_ENABLED) { $this->wp->deleteTransient(DisplayFormInWPContent::NO_FORM_TRANSIENT_KEY); } $form = $this->formsRepository->findOneById($id); if (!$form instanceof FormEntity) return $this->errorResponse(); return $this->successResponse( $form->toArray() ); } public function listing($data = []) { $data['sort_order'] = $data['sort_order'] ?? 'desc'; $data['sort_by'] = $data['sort_by'] ?? 'updatedAt'; $definition = $this->listingHandler->getListingDefinition($data); $items = $this->formListingRepository->getData($definition); $count = $this->formListingRepository->getCount($definition); $filters = $this->formListingRepository->getFilters($definition); $groups = $this->formListingRepository->getGroups($definition); return $this->successResponse($this->formsResponseBuilder->buildForListing($items), [ 'count' => $count, 'filters' => $filters, 'groups' => $groups, ]); } public function previewEditor($data = []) { // We want to allow preview for unsaved forms $formId = $data['id'] ?? 0; $this->wp->setTransient(PreviewPage::PREVIEW_DATA_TRANSIENT_PREFIX . $formId, $data, PreviewPage::PREVIEW_DATA_EXPIRATION); return $this->successResponse(); } public function saveEditor($data = []) { $formId = (isset($data['id']) ? (int)$data['id'] : 0); $initialForm = $this->getFormTemplateData(TemplateRepository::INITIAL_FORM_TEMPLATE); $name = ($data['name'] ?? __('New form', 'mailpoet')); $body = ($data['body'] ?? $initialForm['body']); $body = $this->dataSanitizer->sanitizeBody($body); $settings = ($data['settings'] ?? $initialForm['settings']); $styles = ($data['styles'] ?? $initialForm['styles']); $status = ($data['status'] ?? FormEntity::STATUS_ENABLED); // check if the form is used as a widget $isWidget = false; $widgets = $this->wp->getOption('widget_mailpoet_form'); if (!empty($widgets)) { foreach ($widgets as $widget) { if (isset($widget['form']) && (int)$widget['form'] === $formId) { $isWidget = true; break; } } } // Reset no form cache $this->wp->deleteTransient(DisplayFormInWPContent::NO_FORM_TRANSIENT_KEY); // check if the user gets to pick his own lists // or if it's selected by the admin $formEntity = new FormEntity($name); $formEntity->setBody($body); $listSelection = $formEntity->getSegmentBlocksSegmentIds(); // check list selection if (count($listSelection)) { $settings['segments_selected_by'] = 'user'; $settings['segments'] = $listSelection; } else { $settings['segments_selected_by'] = 'admin'; } // Check Custom HTML block permissions $customHtmlBlocks = $formEntity->getBlocksByTypes([FormEntity::HTML_BLOCK_TYPE]); if (count($customHtmlBlocks) && !$this->wp->currentUserCan('administrator')) { return $this->errorResponse([ Error::FORBIDDEN => __('Only administrator can edit forms containing Custom HTML block.', 'mailpoet'), ], [], Response::STATUS_FORBIDDEN); } if ($body !== null) { $body = $this->emoji->sanitizeEmojisInFormBody($body); } $form = $this->getForm($data); if (!$form instanceof FormEntity) { $form = new FormEntity($name); } $form->setName($name); $form->setBody($body); $form->setSettings($settings); $form->setStyles($styles); $form->setStatus($status); $this->formsRepository->persist($form); try { $this->formsRepository->flush(); } catch (\Exception $e) { return $this->badRequest(); } if (isset($data['editor_version']) && $data['editor_version'] === "2") { $this->userFlags->set('display_new_form_editor_nps_survey', true); } $form = $this->getForm(['id' => $form->getId()]); if(!$form instanceof FormEntity) return $this->errorResponse(); return $this->successResponse( $this->formsResponseBuilder->build($form), ['is_widget' => $isWidget] ); } public function restore($data = []) { $form = $this->getForm($data); if ($form instanceof FormEntity) { $this->formsRepository->restore($form); return $this->successResponse( $form->toArray(), ['count' => 1] ); } else { return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } } public function trash($data = []) { $form = $this->getForm($data); if ($form instanceof FormEntity) { $this->formsRepository->trash($form); return $this->successResponse( $form->toArray(), ['count' => 1] ); } else { return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } } public function delete($data = []) { $form = $this->getForm($data); if ($form instanceof FormEntity) { $this->formsRepository->delete($form); return $this->successResponse(null, ['count' => 1]); } else { return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } } public function duplicate($data = []) { $form = $this->getForm($data); if ($form instanceof FormEntity) { try { $duplicate = $this->formSaveController->duplicate($form); } catch (Exception $e) { return $this->errorResponse([ APIError::UNKNOWN => __('Duplicating form failed.', 'mailpoet'), ], [], Response::STATUS_UNKNOWN); } return $this->successResponse( $this->formsResponseBuilder->build($duplicate), ['count' => 1] ); } else { return $this->errorResponse([ APIError::NOT_FOUND => __('This form does not exist.', 'mailpoet'), ]); } } public function bulkAction($data = []): SuccessResponse { $definition = $this->listingHandler->getListingDefinition($data['listing']); $ids = $this->formListingRepository->getActionableIds($definition); if ($data['action'] === 'trash') { $this->formsRepository->bulkTrash($ids); } elseif ($data['action'] === 'restore') { $this->formsRepository->bulkRestore($ids); } elseif ($data['action'] === 'delete') { $this->formsRepository->bulkDelete($ids); } else { throw UnexpectedValueException::create() ->withErrors([APIError::BAD_REQUEST => "Invalid bulk action '{$data['action']}' provided."]); } return $this->successResponse(null, ['count' => count($ids)]); } private function getForm(array $data): ?FormEntity { return isset($data['id']) ? $this->formsRepository->findOneById((int)$data['id']) : null; } private function getFormTemplateData(string $templateId): array { $formTemplate = $this->templateRepository->getFormTemplate($templateId); $form = $formTemplate->toFormEntity(); return $form->toArray(); } }
import React, { useState } from 'react'; import { FormProvider, SubmitHandler, useForm } from 'react-hook-form'; import Modal from 'react-modal'; import { yupResolver } from '@hookform/resolvers/yup'; import { BsPlusLg } from 'react-icons/bs'; import customStyles from '../../../styles/modalStyles'; import SubmitButton from '../Form/SubmitButton'; import Textarea from '../Form/Textarea'; import Input from '../Form/Input'; import FormWrapper from '../Form/FormWrapper'; import { useAddAboutDetail } from '../../../lib/operations/about'; import { AboutDetail } from '../../../lib/types'; import { aboutDetailSchema } from '../../../lib/schemas'; import ImageUploader from '../Form/ImageUploader'; const AddAboutDetails = () => { const [isModalOpen, setIsModalOpen] = useState(false); const methods = useForm<AboutDetail>({ resolver: yupResolver(aboutDetailSchema), mode: 'onChange', }); const { handleSubmit, reset } = methods; const { mutate, isLoading, isError } = useAddAboutDetail(); const onSubmit: SubmitHandler<AboutDetail> = async (data) => { const { image, title, description } = data; const form = new FormData(); form.append('data', JSON.stringify({ title, description })); if (image) form.append('image', image); mutate(form); if (!isError) { setIsModalOpen(false); reset(); } }; return ( <div> <button className="text-white bg-black px-5 py-2 rounded-lg" onClick={() => setIsModalOpen(true)} > <BsPlusLg className="inline mb-1 mr-3" /> Add about detail </button> <Modal isOpen={isModalOpen} onRequestClose={() => setIsModalOpen(false)} style={customStyles} > <FormProvider {...methods}> <FormWrapper onSubmit={handleSubmit(onSubmit)} multipart> <h2 className="text-center text-2xl pb-8 -mt-5"> Add about detail </h2> <div className="mb-5"> <ImageUploader id="about-image" label="Image" width={200} /> </div> <Input data-testid="add-about-detail-title" /> <div className="mt-5"> <Textarea id="description" title="Description" rows={10} data-testid="add-about-detail-description" /> </div> <div className="flex justify-center mt-5"> <SubmitButton name="Save" isLoading={isLoading} /> </div> </FormWrapper> </FormProvider> </Modal> </div> ); }; export default AddAboutDetails;
import { Options } from './options'; import {Component, NgModule} from '@angular/core' ; import {BrowserModule} from '@angular/platform-browser'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { selectedOption:Options = new Options(2, 'T-Shirts',1000,true); result = [] as any; selectedItemsList = [] as any; checkedIDs = Array(); sum :number =0; sum2 :number =0; sum3 :number =0; options = [ new Options(1, 'Jeans' ,4000,true), new Options(2, 'T-Shirts',1000,true), new Options(3, 'Shorts',1000,false), new Options(4, 'Shirts',1500,false), new Options(5, 'Trousers',3000,true), new Options(6, 'Chinos',2000,false), new Options(7, 'Shoes',5000,false) ]; getValue(optionid: number) { this.selectedOption = this.options.filter((item: { id: any; })=> item.id == optionid)[0]; } ngOnInit(): void { this.fetchSelectedItems() this.fetchCheckedIDs() } changeSelection(price : number) { this.sum=this.sum+price; this.fetchSelectedItems() } fetchSelectedItems() { this.selectedItemsList = this.options.filter((value: { isChecked: any; }, index: any) => { return value.isChecked }); } fetchCheckedIDs() { this.checkedIDs = [] this.options.forEach((value: { isChecked: any; id: any; }, index: any) => { if (value.isChecked) { this.checkedIDs.push(value.id); } }); } }
package org.semanticweb.owlapi.util; import org.semanticweb.owlapi.model.*; import java.util.List; import java.util.Map; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * 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 * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge<br> * The University Of Manchester<br> * Bio-Health Informatics Group<br> * Date: 17-Jun-2007<br><br> * <p/> * A short form provider that generates short forms from the values of object * property assertions or data property assertions if the entity is an individual. * If the entity whose short form is not being generated is not an individual * (i.e. it is a class, property etc.) then an alternate short form provider is * used. (As a side note, the use case for this particular short form provider * came from the SKOS community, which have individuals that have preferredLabel * property assertions). */ public class PropertyAssertionValueShortFormProvider implements ShortFormProvider { private List<OWLPropertyExpression> properties; private Map<OWLDataPropertyExpression, List<String>> preferredLanguageMap; private OWLOntologySetProvider ontologySetProvider; private ShortFormProvider alternateShortFormProvider; /** * Constructs a property value short form provider. Using <code>SimpleShortFormProvider</code> as the * alternate short form provider (see other constructor for details). */ public PropertyAssertionValueShortFormProvider(List<OWLPropertyExpression> properties, Map<OWLDataPropertyExpression, List<String>> preferredLanguageMap, OWLOntologySetProvider ontologySetProvider) { this(properties, preferredLanguageMap, ontologySetProvider, new SimpleShortFormProvider()); } /** * Constructs a property value short form provider. * * @param properties A <code>List</code> of preferred properties. The list is searched from * start to end, so that property assertions whose property is at the start of the list have a higher * priority and are selected over properties that appear towards or at the end of the list. * @param preferredLanguageMap A map which maps data properties to preferred languages. For any given * data property there may be a list of preferred languages for the values of that property * Languages at the start of the list * have a higher priority over languages at the end of the list. This parameter may be empty but it * must not be <code>null</code>. * @param ontologySetProvider An <code>OWLOntologySetProvider</code> which provides a set of ontology * from which candidate annotation axioms should be taken. For a given entity, all ontologies are * examined. * @param alternateShortFormProvider A short form provider which will be used to generate the short form * for an entity that does not have any property values (e.g. class, property). This provider will also be used in the case where * the value of an annotation is an <code>OWLIndividual</code> for providing the short form of the individual. */ public PropertyAssertionValueShortFormProvider(List<OWLPropertyExpression> properties, Map<OWLDataPropertyExpression, List<String>> preferredLanguageMap, OWLOntologySetProvider ontologySetProvider, ShortFormProvider alternateShortFormProvider) { this.properties = properties; this.preferredLanguageMap = preferredLanguageMap; this.ontologySetProvider = ontologySetProvider; this.alternateShortFormProvider = alternateShortFormProvider; } public String getShortForm(OWLEntity entity) { int lastURIMatchIndex = Integer.MAX_VALUE; int lastLangMatchIndex = Integer.MAX_VALUE; if (!(entity instanceof OWLIndividual)) { return alternateShortFormProvider.getShortForm(entity); } OWLIndividual individual = (OWLIndividual) entity; // The candidate value to be rendered, we select this based on // ranking of annotation URI and ranking of lang (if present) OWLObject candidateValue = null; for (OWLOntology ontology : ontologySetProvider.getOntologies()) { for (OWLObjectPropertyAssertionAxiom ax : ontology.getObjectPropertyAssertionAxioms(individual)) { int index = properties.indexOf(ax.getProperty()); if (index == -1) { continue; } if (index < lastURIMatchIndex) { candidateValue = ax.getObject(); } } for (OWLDataPropertyAssertionAxiom ax : ontology.getDataPropertyAssertionAxioms(individual)) { int index = properties.indexOf(ax.getProperty()); if (index == -1) { continue; } if (index == lastURIMatchIndex) { // Different property value but same prop, as previous candidate - look at lang tag for that URI // and see if we take priority over the previous one OWLObject obj = ax.getObject(); if (obj instanceof OWLLiteral) { List<String> langList = preferredLanguageMap.get(ax.getProperty()); if (langList != null) { // There is no need to check if lang is null. It may well be that no // lang is preferred over any other lang. OWLLiteral lit = (OWLLiteral) obj; int langIndex = langList.indexOf(lit.getLang()); if (langIndex != -1 && langIndex < lastLangMatchIndex) { lastLangMatchIndex = langIndex; candidateValue = ax.getObject(); } } } } else if (index < lastURIMatchIndex) { // Better match than previous URI - wipe out previous match! lastURIMatchIndex = index; candidateValue = ax.getObject(); } } } if (candidateValue != null) { return getRendering(candidateValue); } else { return alternateShortFormProvider.getShortForm(entity); } } /** * Obtains the rendering of the specified object. If the object * is a constant then the rendering is equal to the literal value, * if the object is an individual then the rendering is equal to * the rendering of the individual as provided by the alternate * short form provider * * @param object The object to the rendered * @return The rendering of the object. */ private String getRendering(OWLObject object) { // We return the literal value of constants or use the alternate // short form provider to render individuals. if (object instanceof OWLLiteral) { return ((OWLLiteral) object).getLiteral(); } else { return alternateShortFormProvider.getShortForm((OWLEntity) object); } } public List<OWLPropertyExpression> getProperties() { return properties; } public Map<OWLDataPropertyExpression, List<String>> getPreferredLanguageMap() { return preferredLanguageMap; } public void dispose() { } }
import 'package:flutter/material.dart'; import 'package:movies_app/common/common.dart'; import 'package:movies_app/ui/ui.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: ColorConstant.background, body: Form( key: formKey, child: ListView( padding: const EdgeInsets.symmetric( horizontal: 24, vertical: 150, ), children: [ const Center( child: Text( 'Siap Menonton?', style: TextStyle( fontSize: 26, fontWeight: FontWeight.w800, color: Colors.white, ), ), ), const SizedBox(height: 32), const Center( child: Text( 'Masukkan email dan password untuk membuat atau masuk ke akunmu', style: TextStyle( color: Colors.white, ), ), ), const SizedBox(height: 32), TextFieldWidget( controller: emailController, label: 'Email', radius: 0, obscureText: false, isFilled: true, fillColor: Colors.white, prefix: const Icon( Icons.person, color: Colors.blue, ), validator: (value) { if (value == null || value.trim().isEmpty) { return 'Email harus di isi'; } return null; }, ), const SizedBox(height: 24), TextFieldWidget( controller: passwordController, label: 'Password', radius: 0, obscureText: true, isFilled: true, fillColor: Colors.white, prefix: const Icon( Icons.lock, color: Colors.blue, ), validator: (value) { if (value == null || value.trim().isEmpty) { return 'Password harus di isi'; } if (value.length < 6) { return 'Password min 6 chacacter'; } return null; }, ), const SizedBox(height: 24), InkWell( onTap: () {}, child: const Text( 'Lupa Password?', textAlign: TextAlign.end, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color: Colors.white, ), ), ), const SizedBox(height: 12), ElevatedButton( style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric(vertical: 20), ), onPressed: () { if (formKey.currentState?.validate() ?? false) { Navigator.pushNamedAndRemoveUntil( context, RouteName.home, (route) => false, ); } }, child: const Text( "MASUK", style: TextStyle(color: Colors.white), ), ), const SizedBox(height: 24), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Belum punya akun?", textAlign: TextAlign.center, style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white, ), ), InkWell( onTap: () {}, child: const Text( ' Daftar', style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color: Colors.blue, ), ), ) ], ), ], ), ), ); } }
// // ViewController.swift // ToDoList // // Created by Joseph Estanislao Calla Moreyra on 28/11/22. // import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var table: UITableView! var listTask = [Tarea]() let contexto = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() fetchTask() } @IBAction func buttonAction(_ sender: Any) { var nameTask = UITextField() let alert = UIAlertController(title: "New", message: "Task", preferredStyle: .alert) let alertAction = UIAlertAction(title: "Add", style: .default) { _ in let newTask = Tarea(context: self.contexto) newTask.name = nameTask.text newTask.done = false self.listTask.append(newTask) self.save() } alert.addTextField { textFieldAlert in textFieldAlert.placeholder = "Escribe tu texto aquí ..." nameTask = textFieldAlert } alert.addAction(alertAction) present(alert, animated: true) } private func save() { do { try contexto.save() } catch { print(error.localizedDescription) } self.table.reloadData() } func fetchTask() { let request : NSFetchRequest<Tarea> = Tarea.fetchRequest() do { listTask = try contexto.fetch(request) } catch { print(error.localizedDescription) } } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listTask.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = table.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let task = listTask[indexPath.row] // operator ternario cell.textLabel?.text = task.name cell.textLabel?.textColor = task.done ? .black : .blue cell.detailTextLabel?.text = task.done ? "Completada": "Por completar" // Marcar con una paloma las tareas completas cell.accessoryType = task.done ? .checkmark : .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Palomear la tarea if table.cellForRow(at: indexPath)?.accessoryType == .checkmark { table.cellForRow(at: indexPath)?.accessoryType = .none } else { table.cellForRow(at: indexPath)?.accessoryType = .checkmark } // Editar coredata listTask[indexPath.row].done = !listTask[indexPath.row].done save() // Deseleccionar la tarea table.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let actionRemove = UIContextualAction(style: .normal, title: "Eliminar") { [self] _, _, _ in contexto.delete(listTask[indexPath.row]) listTask.remove(at: indexPath.row) save() } actionRemove.backgroundColor = .red return UISwipeActionsConfiguration(actions: [actionRemove]) } }
import * as React from 'react'; import { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import { alpha } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableHead from '@mui/material/TableHead'; import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import TableSortLabel from '@mui/material/TableSortLabel'; import Toolbar from '@mui/material/Toolbar'; import Typography from '@mui/material/Typography'; import Paper from '@mui/material/Paper'; import Checkbox from '@mui/material/Checkbox'; import IconButton from '@mui/material/IconButton'; import Tooltip from '@mui/material/Tooltip'; import Switch from '@mui/material/Switch'; import DeleteIcon from '@mui/icons-material/Delete'; import FilterListIcon from '@mui/icons-material/FilterList'; import { visuallyHidden } from '@mui/utils'; import { Searchbar } from './Searchbar'; import { Button, TextField, FormControl, FormGroup, FormControlLabel, FormLabel, RadioGroup, Radio } from '@mui/material'; import Link from 'next/link'; import RadioSelection from './RadioSelection'; import CheckboxSelection from './CheckboxSelection'; import { cities, propertyTypes, statusList, numberList, facilityList, styleList, accessList, preferenceList } from '../data/data'; import { useRouter } from 'next/router' function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } // This method is created for cross-browser compatibility, if you don't // need to support IE11, you can use Array.prototype.sort() directly function stableSort(array, comparator) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) { return order; } return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); } const headCells = [ { id: 'address', numeric: false, disablePadding: true, label: 'Property Address', }, { id: 'city', numeric: false, disablePadding: true, label: 'City', }, { id: 'propertyType', numeric: false, disablePadding: true, label: 'Property Type', }, { id: 'price', numeric: true, disablePadding: false, label: 'Price', }, { id: 'bedrooms', numeric: true, disablePadding: false, label: 'Bedrooms', }, { id: 'bathrooms', numeric: true, disablePadding: false, label: 'Bathrooms', }, { id: 'kitchen', numeric: true, disablePadding: false, label: 'Kitchen', }, { id: 'description', numeric: true, disablePadding: false, label: 'Description', }, { id: 'rentalStatus', numeric: true, disablePadding: false, label: 'Status', }, { id: '_id', numeric: true, disablePadding: false, label: 'Showcase Link', }, { id: 'action', numeric: true, disablePadding: false, label: 'Action', } ]; function EnhancedTableHead(props) { const { onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } = props; const createSortHandler = (property) => (event) => { onRequestSort(event, property); }; return ( <TableHead> <TableRow> <TableCell padding="checkbox"> <Checkbox color="primary" indeterminate={numSelected > 0 && numSelected < rowCount} checked={rowCount > 0 && numSelected === rowCount} onChange={onSelectAllClick} inputProps={{ 'aria-label': 'select all desserts', }} /> </TableCell> {headCells.map((headCell) => ( <TableCell key={headCell.id} align={headCell.numeric ? 'right' : 'left'} padding={headCell.disablePadding ? 'none' : 'normal'} sortDirection={orderBy === headCell.id ? order : false} > <TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : 'asc'} onClick={createSortHandler(headCell.id)} > {headCell.label} {orderBy === headCell.id ? ( <Box component="span" sx={visuallyHidden}> {order === 'desc' ? 'sorted descending' : 'sorted ascending'} </Box> ) : null} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ); } EnhancedTableHead.propTypes = { numSelected: PropTypes.number.isRequired, onRequestSort: PropTypes.func.isRequired, onSelectAllClick: PropTypes.func.isRequired, order: PropTypes.oneOf(['asc', 'desc']).isRequired, orderBy: PropTypes.string.isRequired, rowCount: PropTypes.number.isRequired, }; const EnhancedTableToolbar = (props) => { const { numSelected, onChange, handleSortClick, handleDeleteClick } = props; return ( <Toolbar sx={{ bgcolor: 'primary.main', color: 'white', pl: { sm: 2 }, pr: { xs: 1, sm: 1 }, ...(numSelected > 0 && { bgcolor: (theme) => alpha(theme.palette.primary.main, theme.palette.action.activatedOpacity), }) }} > {numSelected > 0 ? ( <Typography sx={{ flex: '1 1 100%' }} color="black" variant="subtitle1" component="div" > {numSelected} selected </Typography> ) : ( <Typography sx={{ flex: '1 1 50%' }} variant="h6" id="tableTitle" component="div" > Rental Listing </Typography> )} {numSelected == 0 ? ( <Searchbar onChange={onChange} /> ) : null} {numSelected == 0 ? ( <Button variant="contained" color="success" sx={{ marginLeft: '2%' }}><Link href={`/listings/new`}>Create</Link></Button> ) : null} {numSelected > 0 ? ( <Tooltip title="Delete"> <IconButton> <DeleteIcon onClick={handleDeleteClick} /> </IconButton> </Tooltip> ) : ( <Tooltip title="Filter list"> <IconButton onClick={handleSortClick}> {/* <FilterListIcon sx={{ color: 'white' }} /> */} </IconButton> </Tooltip> )} </Toolbar> ); }; EnhancedTableToolbar.propTypes = { numSelected: PropTypes.number.isRequired, }; const SortTable = () => { const [selectedCities, setSelectedCities] = useState([]); const [selectedPropertyType, setSelectedPropertyType] = useState([]); const [selectedBedroomsNumber, setSelectedBedroomsNumber] = useState(); const [selectedBathroomsNumber, setSelectedBathroomsNumber] = useState(); const [selectedFacilities, setSelectedFacilities] = useState([]); const [selectedAccessType, setSelectedAccessType] = useState(); const handleSearch = () => { } return ( <> <Box sx={{ display: 'flex' }}> <Paper sx={{ width: '100%', mb: 2 }} elevation={15}> <CheckboxSelection formLabel='City:' options={cities} setSelectedOptions={setSelectedCities} selectedOptions={selectedCities} /> <CheckboxSelection formLabel='Property Type:' options={propertyTypes} setSelectedOptions={setSelectedPropertyType} selectedOptions={selectedPropertyType} /> <RadioSelection formLabel='Bedrooms:' options={numberList} setSelectedChecked={setSelectedBedroomsNumber} /> <RadioSelection formLabel='Bathrooms:' options={numberList} setSelectedChecked={setSelectedBathroomsNumber} /> <CheckboxSelection formLabel='Facilities:' options={facilityList} setSelectedOptions={setSelectedFacilities} selectedOptions={selectedFacilities} /> <RadioSelection formLabel='Private Access:' options={accessList} setSelectedChecked={setSelectedAccessType} /> <div style={{ marginLeft: '45%', marginTop: '0.5%', marginBottom: '0.5%' }}><Button variant="contained" onClick={handleSearch}>Search</Button></div> </Paper> </Box> </> ) } const Listingtable = ({ rowData, setRowdata }) => { const [order, setOrder] = useState('asc'); const [orderBy, setOrderBy] = useState('address'); const [selected, setSelected] = useState([]); const [page, setPage] = useState(0); const [dense, setDense] = useState(false); const [rowsPerPage, setRowsPerPage] = useState(5); const [showData, setShowData] = useState([]); const [isSortList, setIsSortList] = useState(false); const router = useRouter(); useEffect(() => { setShowData(rowData) }, [rowData]) const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === 'asc'; setOrder(isAsc ? 'desc' : 'asc'); setOrderBy(property); }; const handleSelectAllClick = (event) => { if (event.target.checked) { const newSelected = showData.map((n) => n._id); setSelected(newSelected); return; } setSelected([]); }; const handleClick = (event, id) => { const selectedIndex = selected.indexOf(id); let newSelected = []; if (selectedIndex === -1) { newSelected = newSelected.concat(selected, id); } else if (selectedIndex === 0) { newSelected = newSelected.concat(selected.slice(1)); } else if (selectedIndex === selected.length - 1) { newSelected = newSelected.concat(selected.slice(0, -1)); } else if (selectedIndex > 0) { newSelected = newSelected.concat( selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1), ); } setSelected(newSelected); }; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const handleChangeDense = (event) => { setDense(event.target.checked); }; const handleSearch = (keyword) => { const filtered = rowData.filter(row => isMathcedKeyword(keyword, row)); setShowData(filtered); }; const handleSortClick = () => { setIsSortList(!isSortList) }; const handleDeleteClick = () => { selected.forEach(async (selectedListingID) => { await fetch(`http://18.222.121.41:3002/api/real-estate/${selectedListingID}`, { method: 'DELETE' }); }) const temp = rowData.filter((listing) => selected.includes(listing._id) === false); setRowdata(temp); setSelected([]); }; const isSelected = (name) => selected.indexOf(name) !== -1; const isMathcedKeyword = (keyword, row) => { for (const [, value] of Object.entries(row)) { const val = value.toString().toLocaleLowerCase(); if (val.includes(keyword)) { return true } } }; const handleUpdate = (listingID) => { router.push({ pathname: `/listings/${listingID}`, query: { listingID: listingID }, }) } // Avoid a layout jump when reaching the last page with empty rows. const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - showData.length) : 0; return ( <Box sx={{ width: '100%' }}> <Paper sx={{ width: '100%', mb: 2 }}> <EnhancedTableToolbar numSelected={selected.length} onChange={(e) => handleSearch(e.target.value)} handleSortClick={handleSortClick} handleDeleteClick={handleDeleteClick} /> {isSortList ? (<SortTable />) : null} <TableContainer> <Table sx={{ minWidth: 750 }} aria-labelledby="tableTitle" size={dense ? 'small' : 'medium'} > <EnhancedTableHead numSelected={selected.length} order={order} orderBy={orderBy} onSelectAllClick={handleSelectAllClick} onRequestSort={handleRequestSort} rowCount={showData.length} /> <TableBody> {/* if you don't need to support IE11, you can replace the `stableSort` call with: rows.slice().sort(getComparator(order, orderBy)) */} {stableSort(showData, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row, index) => { const isItemSelected = isSelected(row._id); const labelId = `enhanced-table-checkbox-${index}`; return ( <TableRow hover role="checkbox" aria-checked={isItemSelected} tabIndex={-1} key={row._id} selected={isItemSelected} > <TableCell padding="checkbox"> <Checkbox color="primary" checked={isItemSelected} inputProps={{ 'aria-labelledby': labelId, }} onClick={(event) => handleClick(event, row._id)} /> </TableCell> {/* {headCells.map((headCell) => headCell.label === 'address' ? (<TableCell component="th" id={labelId} scope="row" padding="none" > {row[headCell.id]} </TableCell>) : (<TableCell key={headCell.id}>{row[headCell.id]}</TableCell>) )} */} <TableCell component="th" id={labelId} scope="row" padding="none" align="left" > {row.address} </TableCell> <TableCell align="left">{row.city}</TableCell> <TableCell align="left">{row.propertyType}</TableCell> <TableCell align="right">${row.price}</TableCell> <TableCell align="right">{row.bedrooms}</TableCell> <TableCell align="right">{row.bathrooms}</TableCell> <TableCell align="right">{row.kitchens}</TableCell> <TableCell align="right">{row.description.length > 25 ? row.description.substring(0, 25) : row.description}</TableCell> <TableCell align="right">{row.rentalStatus}</TableCell> <TableCell align="right"><Button variant="contained"><Link href={`/showcase/${row._id}`} passHref><a target="_blank" rel="noopener noreferrer"> Link </a></Link></Button></TableCell> <TableCell align="right"><Button variant="contained" color="success" onClick={() => handleUpdate(row._id)}>Update</Button></TableCell> </TableRow> ); })} {emptyRows > 0 && ( <TableRow style={{ height: (dense ? 33 : 53) * emptyRows, }} > <TableCell colSpan={6} /> </TableRow> )} </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={showData.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Paper> {/* <FormControlLabel control={<Switch checked={dense} onChange={handleChangeDense} />} label="Dense padding" /> */} </Box> ); } export default Listingtable
package frc.robot.subsystems.shooter; import org.littletonrobotics.junction.Logger; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.math.controller.SimpleMotorFeedforward; import frc.robot.constants.ShooterConstants; public class Shooter extends SubsystemBase { private final ShooterIO io; private final ShooterInputsAutoLogged inputs = new ShooterInputsAutoLogged(); private final SimpleMotorFeedforward feedforward = new SimpleMotorFeedforward( ShooterConstants.kS, ShooterConstants.kV, ShooterConstants.kA ); public Shooter(ShooterIO io) { this.io = io; } @Override public void periodic() { // This tells our Shooter (either real or simulated) to update our class with all the sensor data. io.updateInputs(inputs); // Log all the sensor data. Logger.processInputs("Shooter", inputs); } public void setVoltage(double voltage) { Logger.recordOutput("Shooter Left Voltage", voltage); Logger.recordOutput("Shooter Right Voltage", voltage); io.setVoltage(voltage); } // public void setVoltages(double leftVoltage, double rightVoltage) { // io.setVoltages(leftVoltage, rightVoltage); // } public void setRPS(double rps) { double feedforwardOutput = feedforward.calculate(rps); Logger.recordOutput("Shoot Velocity Target", rps); setVoltage(feedforwardOutput); } public void stop() { setVoltage(0); } public void calibratePIDController(double kP, double kI, double kD) { io.calibratePIDController(kP, kI, kD); } public void setPIDTargetVelocity(double targetVelocity) { io.setPIDTargetVelocity(targetVelocity); } // public void setPIDTargetVelocities(double leftTargetVelocity, double rightTargetVelocity) { // io.setPIDTargetVelocities(leftTargetVelocity, rightTargetVelocity); // } public double getVelocity() { return (inputs.leftVelocity + inputs.rightVelocity) / 2; } public double getPosition() { return inputs.leftPosition; } public double getCurrent() { return (inputs.leftCurrent + inputs.rightCurrent) / 2; } public double getVoltage(){ return (inputs.leftVoltage + inputs.rightVoltage) / 2; } }
import sys import time from flask import json import pika import requests API_BASE_URL = "http://api-gis:8080" POLLING_FREQ = int(sys.argv[1]) if len(sys.argv) >= 2 else 30 ENTITIES_PER_ITERATION = int(sys.argv[2]) if len(sys.argv) >= 3 else 10 def fetch_data_from_api(endpoint): try: response = requests.get(f"{API_BASE_URL}/{endpoint}") response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching data from API: {e}") return None def get_coordinates_by_country_name(country_name): base_url = "https://nominatim.openstreetmap.org/search" params = { "q": country_name, "format": "json", "limit": 1 } try: response = requests.get(base_url, params=params) data = response.json() if data: latitude = data[0]["lat"] longitude = data[0]["lon"] geojson = { "type": "Point", "coordinates": [float(longitude), float(latitude)] } return geojson else: print(f"Não foi possível encontrar coordenadas para o país: {country_name}") return None except Exception as e: print(f"Erro ao obter coordenadas: {str(e)}") return None def callback(ch, method, properties, body): print(f"Received message: {body.decode()}") countries_data = fetch_data_from_api("api/countries") if countries_data: # Processa dados dos países for country in countries_data: country_name = country.get("name") if country_name: # Obtém coordenadas coordinates = get_coordinates_by_country_name(country_name) if coordinates: country_id = country.get("id") update_url = f"{API_BASE_URL}/api/countries/{country_id}" update_data = {"geom": json.dumps(coordinates)} try: response = requests.patch(update_url, json=update_data) response.raise_for_status() print(f"Country: {country_name}, Coordinates: {coordinates} - Coordinates updated successfully.") except requests.exceptions.RequestException as e: print(f"Failed to update coordinates for {country_name}: {e}") else: print("Country name is missing in the data.") else: print("Failed to fetch data from API.") def consume_messages(): # Conectar ao RabbitMQ credentials = pika.PlainCredentials('is', 'is') parameters = pika.ConnectionParameters('rabbitmq', 5672, 'is', credentials=credentials) try: connection = pika.BlockingConnection(parameters) channel = connection.channel() # Declare a fila 'geom' com durabilidade consistente channel.queue_declare(queue='geom', durable=True) # Configurar o callback para processar as mensagens channel.basic_consume(queue='geom', on_message_callback=callback, auto_ack=True) print(f"Waiting for messages from the 'geom' queue...") # Iniciar a escuta de mensagens channel.start_consuming() except pika.exceptions.ProbableAccessDeniedError as e: print(f"Error: {e}") if __name__ == "__main__": while True: # Consumir mensagens consume_messages() time.sleep(POLLING_FREQ)
<!DOCTYPE html> <html> <head> <style> canvas { border: 1px solid #000; } #inspectorbg { position: absolute; left: 811px; top: 8px; width: 300px; height: 600px; background-color: lightgray; border: 1px solid black; } #undo { position: absolute; left: 20px; top: 300px; } #redo { position: absolute; left: 80px; top: 300px; } p { padding: 0px; margin: 0px; font-size: 15px; } #draw { position: absolute; left: 30px; top: 250px; } </style> </head> <body> <canvas id="myCanvas" width="800" height="600"></canvas> <div id="inspectorbg"> <p>Position X</p> <input type="text" id="PositionX"> <p>Position Y</p> <input type="text" id="PositionY"> <p>Rotation</p> <input type="text" id="RotationY"> <p>Scale X</p> <input type="text" id="ScaleX"> <p>Scale Y</p> <input type="text" id="ScaleY"> <button id="draw"> Draw Heart </button> <button id="undo"> Undo </button> <button id="redo"> Redo </button> </div> <script> var drawing = false; var isdraw = false; const canvas = document.getElementById("myCanvas"); const context = canvas.getContext("2d"); var PositionX = 300 ; var PositionY = 300 ; var ScaleX = 1; var ScaleY = 1; var Gakdo = 0; var isDragging= false; var HandleRadius= 5; var clickedHandle= ""; var rectwidth =100; var rectheight =100; var rectLTX; var rectLTY; var rectRTX; var rectRTY; var rectLDX; var rectLDY; var rectRDX; var rectRDY; var anglerectX; var anglerectY; var anglerectXY; var HeartXY2 = [ [0], [0], [1] ]; var rectXY =[ [0], [0], [1] ] var rect = [ [ -(rectwidth/2), -8 - rectheight/2], [rectwidth/2, (-8) - rectheight/2], [rectwidth/2, (-8)+rectheight/2], [-rectwidth/2, (-8)+rectheight/2], [ -(rectwidth/2), -8 - rectheight/2] ]; var PosX = document.getElementById("PositionX"); var PosY = document.getElementById("PositionY"); var Rot = document.getElementById("RotationY"); var ScaX = document.getElementById("ScaleX"); var ScaY = document.getElementById("ScaleY"); PosX.addEventListener("input", function() { PositionX = PosX.value; saveCanvasState() draw(); }); PosY.addEventListener("input", function() { PositionY = PosY.value; saveCanvasState() draw(); }); Rot.addEventListener("input", function() { Gakdo = Rot.value; saveCanvasState() draw(); }); ScaX.addEventListener("input", function() { ScaleX = ScaX.value; saveCanvasState() draw(); }); ScaY.addEventListener("input", function() { ScaleY = ScaY.value; saveCanvasState() draw(); }); document.getElementById("redo").addEventListener("click", redo); document.getElementById("undo").addEventListener("click", undo); function hwMatrixMultiply2(matrixA, B) { const result = [ [matrixA[0][0] * B[0][0] + matrixA[0][1] * B[1][0] + matrixA[0][2] * B[2][0] ], [matrixA[1][0] * B[0][0] + matrixA[1][1] * B[1][0] + matrixA[1][2] * B[2][0] ], [matrixA[2][0] * B[0][0] + matrixA[2][1] * B[1][0] + matrixA[2][2] * B[2][0] ] ]; return result; } function hwTranslateMatrix(tx, ty) { return [ [1, 0, tx], [0, 1, ty], [0, 0, 1] ]; } function hwScaleMatrix(sx, sy) { return [ [sx, 0, 0], [0, sy, 0], [0, 0, 1] ]; } function hwRotationMatrix(angle) { const ro =angle*(6.28/360); const cos = Math.cos(ro); const sin = Math.sin(ro); return [ [cos, -sin, 0], [sin, cos, 0], [0, 0, 1] ]; } function isPointInRect(mouseX, mouseY, rect) { const [x1, y1, x2, y2, x3, y3, x4, y4] = rect; const isInside = isPointInTriangle(mouseX, mouseY, x1, y1, x2, y2, x3, y3) || isPointInTriangle(mouseX, mouseY, x3, y3, x4, y4, x1, y1); return isInside; } function isPointInTriangle(mouseX, mouseY, x1, y1, x2, y2, x3, y3) { const sign1 = (mouseX - x1) * (y2 - y1) - (x2 - x1) * (mouseY - y1) >= 0; const sign2 = (mouseX - x2) * (y3 - y2) - (x3 - x2) * (mouseY - y2) >= 0; const sign3 = (mouseX - x3) * (y1 - y3) - (x1 - x3) * (mouseY - y3) >= 0; return sign1 === sign2 && sign2 === sign3; } function draw() { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.fillStyle = "rgba(0,0,0,0)"; for (let i = 0; i < 5; i++) { let x = rect[i][0]; let y = rect[i][1]; rectXY =[[x],[y],[1]] rectXY=hwMatrixMultiply2(hwScaleMatrix(ScaleX,ScaleY),rectXY); rectXY=hwMatrixMultiply2(hwRotationMatrix(Gakdo),rectXY); rectXY=hwMatrixMultiply2(hwTranslateMatrix(PositionX,PositionY),rectXY); context.lineTo(rectXY[0][0], rectXY[1][0]); context.stroke(); context.fill(); if(i==0) { rectLTX = rectXY[0][0]; rectLTY = rectXY[1][0]; } if(i==1) { rectRTX = rectXY[0][0]; rectRTY = rectXY[1][0]; } if(i==2) { rectRDX = rectXY[0][0]; rectRDY = rectXY[1][0]; } if(i==3) { rectLDX = rectXY[0][0]; rectLDY = rectXY[1][0]; } } context.closePath(); context.beginPath(); HeartXY2 = [ [0], [0], [1] ]; for (var i = 0; i <= 2 * Math.PI; i += 0.01) { if (i > 3.14) { HeartXY2[0][0] = (16 * Math.sin(i) ** 3) * rectwidth / 33.3; HeartXY2[1][0] = -(13 * Math.cos(i) - 5 * Math.cos(2 * i) - 2 * Math.cos(3 * i) - Math.cos(4 * i)) * rectwidth / 33.3 - 10; } else { HeartXY2[0][0] = (16 * Math.sin(i) ** 3) * rectwidth / 33.3; HeartXY2[1][0] = -(13 * Math.cos(i) - 5 * Math.cos(2 * i) - 2 * Math.cos(3 * i) - Math.cos(4 * i)) * rectwidth / 33.3 - 10; } HeartXY2 = hwMatrixMultiply2(hwScaleMatrix(ScaleX, ScaleY), HeartXY2); HeartXY2 = hwMatrixMultiply2(hwRotationMatrix(Gakdo), HeartXY2); HeartXY2 = hwMatrixMultiply2(hwTranslateMatrix(PositionX, PositionY), HeartXY2); context.lineTo(HeartXY2[0][0], HeartXY2[1][0]); } context.fillStyle = "red"; context.stroke(); context.fill(); context.closePath(); anglerectX = ((rectRTX+rectRDX))/2; anglerectY = (rectRTY+rectRDY)/2; anglerectXY = [[anglerectX],[anglerectY],[1]]; context.fillStyle = "green"; context.beginPath(); context.arc(anglerectXY[0][0], anglerectXY[1][0], HandleRadius, 0, 2 * Math.PI); context.fill(); context.closePath(); PosX.value = PositionX; PosY.value = PositionY; Rot.value = Gakdo; ScaX.value = ScaleX; ScaY.value = ScaleY; } canvas.addEventListener("mousedown", function(event) { var mouseX = event.clientX - canvas.getBoundingClientRect().left; var mouseY = event.clientY - canvas.getBoundingClientRect().top; if (drawing) { PositionX = event.clientX - canvas.getBoundingClientRect().left; PositionY = event.clientY - canvas.getBoundingClientRect().top; saveCanvasState(); } if(isdraw) { if ( (mouseX >= anglerectX - HandleRadius && mouseX <= anglerectX + HandleRadius) && (mouseY >= anglerectY - HandleRadius && mouseY <= anglerectY + HandleRadius) ) { isDragging = true; clickedHandle = "회전 핸들"; } else { isDragging = false; clickedHandle = ""; } if (isPointInRect(mouseX, mouseY, [rectLTX, rectLTY, rectRTX, rectRTY, rectRDX, rectRDY, rectLDX, rectLDY])) { isDragging = true; dragOffsetX = mouseX - PositionX; dragOffsetY = mouseY - PositionY; } } }); canvas.addEventListener("mousemove", function(event) { if(isdraw) { if (isDragging) { var mouseX = event.clientX - canvas.getBoundingClientRect().left; var mouseY = event.clientY - canvas.getBoundingClientRect().top; if (clickedHandle === "사이즈 핸들") { if(mouseX<rectLTX) ScaleX = ScaleX + 0.025; else if(mouseX>rectLTX) ScaleX = ScaleX - 0.025; if(mouseY<rectLTY) ScaleY = ScaleY + 0.025; else if(mouseY>rectLTY) ScaleY = ScaleY - 0.025; } else if (clickedHandle === "회전 핸들") { var mouseX = event.clientX - canvas.getBoundingClientRect().left; var mouseY = event.clientY - canvas.getBoundingClientRect().top; Gakdo = Math.atan2(mouseY - PositionY, mouseX - PositionX) / (Math.PI / 180); } else { PositionX = mouseX - dragOffsetX; PositionY = mouseY - dragOffsetY; } draw(); } } }); canvas.addEventListener("mouseup", function() { if (drawing) { drawing = false; isdraw = true; draw(); } if(isDragging) { saveCanvasState() isDragging = false; } }); var canvasStates = []; var currentStateIndex = -1; function saveCanvasState() { var canvasState = { PositionX: PositionX, PositionY: PositionY, ScaleX: ScaleX, ScaleY: ScaleY, Gakdo: Gakdo, }; if (currentStateIndex < canvasStates.length - 1) { canvasStates.splice(currentStateIndex + 1); } canvasStates.push(canvasState); currentStateIndex = canvasStates.length - 1; } function undo() { console.log(currentStateIndex+ " " + canvasStates.length); if (currentStateIndex > 0) { currentStateIndex--; var prevState = canvasStates[currentStateIndex]; restoreCanvasState(prevState); } } function redo() { if (currentStateIndex < canvasStates.length - 1) { currentStateIndex++; var nextState = canvasStates[currentStateIndex]; restoreCanvasState(nextState); } } function restoreCanvasState(state) { PositionX = state.PositionX; PositionY = state.PositionY; ScaleX = state.ScaleX; ScaleY = state.ScaleY; Gakdo = state.Gakdo; draw(); } document.getElementById("draw").addEventListener("click", function() { if(!isdraw) { drawing = true; } }); </script> </body> </html>
import React, { useContext, useState } from 'react' import { Text, View, TextInput, StyleSheet, Button } from 'react-native' import UsersContext from '../context/UsersContext' export default ({ route, navigation }) => { const [user, setUser] = useState(route.params ? route.params : {}) // verifica se route.params existe, se usuário entrou para editar ou adicionar usuário const { dispatch } = useContext(UsersContext) return ( <View style={style.form}> <Text>Nome</Text> <TextInput style={style.input} onChangeText={name => setUser({ ...user, name})} // atualiza o nome do usuário placeholder="Informe o Nome" value={user.name} /> <Text>E-mail</Text> <TextInput style={style.input} onChangeText={email => setUser({ ...user, email})} // atualiza o email do usuário placeholder="Informe o E-mail" value={user.email} /> <Text>URL do Avatar</Text> <TextInput style={style.input} onChangeText={avatarUrl => setUser({ ...user, avatarUrl})} // atualiza a url do avatar do usuário placeholder="Informe a URL do Avatar" value={user.avatarUrl} /> <Button title="Salvar" onPress={() => { dispatch({ type: user.id ? 'updateUser' : 'createUser', payload: user }) navigation.goBack() }} /> </View> ) } const style = StyleSheet.create({ form: { padding: 12 }, input: { height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 15 } })
/******************************************************************************* * Rhythos Game is the base game client which runs games exported from the editor. * * Copyright (C) 2013 David Maletz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.davidmaletz.mrpg.ui; import nme.display.Bitmap; import nme.display.BitmapData; import nme.display.Sprite; import nme.events.Event; class Preloader extends NMEPreloader { private var bar:Bar; public var text:Text; public var text2:Text; public static inline var MSG_MAX:Int=120; private var msg_ct:Int; private var cur_msg:Int; private var messages:Array<String>; public function new() { super(); while(numChildren > 0) removeChildAt(0); Frame.init(); var bg = new Bitmap(Frame.background); bg.scaleX = bg.scaleY = 2; addChild(bg); msg_ct = MSG_MAX; var t:Text = new Text(Status.BLUE, 40, Main.width, 1, "Rhythos!"); t.y = 50; addChild(t); t = new Text(Status.YELLOW, 24, Main.width, 1, "ARCADE"); t.x = 0; t.y = 100; addChild(t); t = new Text(Status.RED, 16, Main.width, 1, "BETA"); t.x = 110; t.y = 100; addChild(t); bar = new Bar(Bar.HP, false); bar.setPercent(0); bar.scaleX = bar.scaleY = 2; bar.x = 50; bar.y = 138; addChild(bar); var s:Sprite = new Sprite(); Frame.drawFrame(s.graphics, Main.width, 52, true); s.y = 197; addChild(s); text = new Text(Status.GRAY, 16, Main.width, 1); text.y = 205; addChild(text); text2 = new Text(Status.GRAY, 16, Main.width, 1); text2.y = text.y+20; addChild(text2); initMessages(); setMsg(messages[cur_msg]); addEventListener(Event.ADDED_TO_STAGE, init); addEventListener(Event.REMOVED_FROM_STAGE, destroy); } private function init(e:Event):Void {addEventListener(Event.ENTER_FRAME, enter_frame);} private function destroy(e:Event):Void {removeEventListener(Event.ENTER_FRAME, enter_frame);} public function setMsg(s:String):Void { var a:Array<String> = s.split("\n"); text.setText(a[0]); if(a.length > 1) text2.setText(a[1]); else text2.setText(""); } public function initMessages():Void { if(messages == null){ messages = ["Hold down LEFT to\nattack rapidly","Enemies follow simple\npatterns of action","Some enemies change\npatterns at half health", "Enemy spells revert to\nattacks when low on MP","Spells can be deadly,\nmake sure to block them","Having trouble? Try a\ndifferent spell/weapon", "The manual contains all\nthese tips, and more","Buying an item in the\nshop does not equip it","Attacks will always hit\nunless the enemy blocks", "Timing is important!\nFollow the rhythm!","Different weapon types\nhave unique properties","Score gives you bonus\nexp, even if you lose", "Having trouble? Level\nUP beating a weaker foe","If the timer runs out,\nhighest HP left wins","Enemy patterns are in\nsync with the music", "Hit LEFT to attack and\nRIGHT to cast a spell", "Hit UP to dodge and\nDOWN to block (750 MP)","The combo meter gives\nyou special abilities", "Game will autosave each\ntime you win a battle."]; } var i:Int = messages.length; while(i>1){ var t:String = messages[i-1], j:Int = Std.int(Math.random()*i); messages[i-1] = messages[j]; messages[j] = t; i--; } cur_msg = 0; } private function enter_frame(e:Event):Void { msg_ct--; if(msg_ct == 0){cur_msg++; if(cur_msg >= messages.length) initMessages(); msg_ct = MSG_MAX; setMsg(messages[cur_msg]);} } public override function onUpdate(bytesLoaded:Int, bytesTotal:Int){ bar.setPercent(bytesLoaded/bytesTotal); } }
/** * (C) 2010-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * Version: $Id$ * * ob_expr_obj.h * * Authors: * Zhifeng YANG <zhuweng.yzf@taobao.com> * */ #ifndef _OB_EXPR_OBJ_H #define _OB_EXPR_OBJ_H 1 #include "ob_object.h" #include "ob_string_buf.h" class ObExprObj_Math_Test; class ObExprObj_negate_test_Test; class ObExprObjTest_get_bool_Test; class ObExprObjTest_compare_Test; class ObExprObjTest_like_Test; class ObExprObjTest_others_Test; namespace oceanbase { namespace common { class ObExprObj { public: ObExprObj(); ~ObExprObj(); void assign(const ObObj &obj); int to(ObObj &obj) const; int cast_to(int32_t dest_type, ObExprObj &result, ObStringBuf &mem_buf) const; //add fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_19:b void set_decimal(const ObDecimal &value); int cast_toV2(int32_t dest_type, ObExprObj &result, ObStringBuf &mem_buf,uint32_t precision,uint32_t scale) ; //add:e // setters void set_null(); void set_int(const int64_t value); //add lijianqiang [INT_32] 20150930:b void set_int32(const int32_t value); //add 20150930:e void set_float(const float value); void set_double(const double value); void set_datetime(const ObDateTime &value); void set_precise_datetime(const ObPreciseDateTime &value); //add peiouya [DATE_TIME] 20150831:b void set_date(const ObDate &value); void set_time(const ObTime &value); //add 20150831:e void set_interval(const ObInterval &value); //add peiouya [DATE_TIME] 20150909 void set_varchar(const ObString& value); void set_ctime(const ObCreateTime &value); void set_mtime(const ObModifyTime &value); void set_bool(const bool value); void set_decimal(const ObNumber &value); void set_ext(const int64_t value); // getters bool is_null() const {return ObNullType == type_;} int64_t get_int() const {return v_.int_;} //add lijianqiang [INT_32] 20150930:b int32_t get_int32()const {return v_.int32_;} //add 20150930:e float get_float() const {return v_.float_;} double get_double() const {return v_.double_;} const ObDateTime& get_datetime() const {return v_.datetime_;} const ObPreciseDateTime& get_precise_datetime() const {return v_.precisedatetime_;} const ObString& get_varchar() const {return varchar_;} const ObCreateTime& get_ctime() const {return v_.createtime_;} const ObModifyTime& get_mtime() const {return v_.modifytime_;} bool get_bool() const {return v_.bool_;} //modify fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_19:b //const ObNumber& get_decimal() const {return num_;} old code const ObDecimal& get_decimal() const {return decimal_;} //modify:e const int64_t get_ext() const {return v_.ext_;} ObObjType get_type() const; bool is_zero() const; bool is_true() const; bool is_false() const; int get_int(int64_t& value) const; //add yushengjuan [INT_32] 20151012:b int get_int32(int32_t& value) const; //add 20151012:e int get_varchar(ObString& value) const; int do_type_promotion(ObObjType l, ObObjType r, ObObjType &res_type);//add qianzm [set_operation] 20151222 /// compare int compare(const ObExprObj &other, int &cmp) const; // compare operators ///@note the return code of these functions can be ignored int lt(const ObExprObj &other, ObExprObj &res) const; int gt(const ObExprObj &other, ObExprObj &res) const; int le(const ObExprObj &other, ObExprObj &res) const; int ge(const ObExprObj &other, ObExprObj &res) const; int eq(const ObExprObj &other, ObExprObj &res) const; int ne(const ObExprObj &other, ObExprObj &res) const; int btw(const ObExprObj &v1, const ObExprObj &v2, ObExprObj &res) const; int not_btw(const ObExprObj &v1, const ObExprObj &v2, ObExprObj &res) const; /// is true/false/null(unknown) int is(const ObExprObj &other, ObExprObj &res) const; /// is not true/false/null(unknown) int is_not(const ObExprObj &other, ObExprObj &res) const; /// logical and int land(const ObExprObj &other, ObExprObj &res) const; /// logical or int lor(const ObExprObj &other, ObExprObj &res) const; /// logical not int lnot(ObExprObj &res) const; // numeric arithmetic operators int add(ObExprObj &other, ObExprObj &res); int sub(ObExprObj &other, ObExprObj &res); int mul(ObExprObj &other, ObExprObj &res); int div(ObExprObj &other, ObExprObj &res, bool int_div_as_double); int mod(const ObExprObj &other, ObExprObj &res) const; int negate(ObExprObj &res) const; /// string like int old_like(const ObExprObj &other, ObExprObj &result) const; // compatible with oceanbase 0.3 int like(const ObExprObj &other, ObExprObj &result) const; int substr(const ObExprObj &start_pos, ObExprObj &result, ObStringBuf &mem_buf) const; int substr(const ObExprObj &start_pos_obj, const ObExprObj &expect_length_obj, ObExprObj &result, ObStringBuf &mem_buf) const; int not_like(const ObExprObj &other, ObExprObj &result) const; int varchar_length(ObExprObj &res) const; int hex(ObExprObj &res, ObStringBuf &mem_buf); int unhex(ObExprObj &res, ObStringBuf &mem_buf); //add wuna [datetime func] 20150831:b int get_gtm(struct tm &gtm, int unexpected_type) const; int year(ObExprObj &res); int month(ObExprObj &res); int day(ObExprObj &res); int days(ObExprObj &res); //add 20150831:e //add liuzy [datetime func] 20150901:b int hour(ObExprObj &res); int minute(ObExprObj &res); int second(ObExprObj &res); //add 20150901:e //add liuzy [datetime func] 20151019:b int check_real_type(const ObString &in) const; //add 20151019:e int ip_to_int(ObExprObj &res); int int_to_ip(ObExprObj &res, ObStringBuf &mem_buf); int upper_case(ObExprObj &result, ObStringBuf &mem_buf) const; int lower_case(ObExprObj &result, ObStringBuf &mem_buf) const; int concat(const ObExprObj &other, ObExprObj &result, ObStringBuf &mem_buf) const; int trim(const ObExprObj &trimType, const ObExprObj &trimPattern, ObExprObj &result, ObStringBuf &mem_buf) const; // result type of calculations // all supported operations not listed here return ObBoolType static ObObj type_add(const ObObj& t1, const ObObj& t2); static ObObj type_sub(const ObObj& t1, const ObObj& t2); static ObObj type_mul(const ObObj& t1, const ObObj& t2); static ObObj type_div(const ObObj& t1, const ObObj& t2, bool int_div_as_double); static ObObj type_mod(const ObObj& t1, const ObObj& t2); static ObObj type_negate(const ObObj& t1); static ObObj type_varchar_length(const ObObj& t1); //add dolphin[coalesce return type] 20151126:b static int coalesce_type_compatible( ObObjType &t1, const ObObjType &t2); static bool can_compare(const ObObjType &t1, const ObObjType &t2) ; static bool is_numeric(const ObObjType &t) ; static bool is_datetime_compare(const ObObjType type) ; //add:e int64_t to_string(char* buffer, const int64_t length) const; int64_t to_string_v2(std::string& s) const;//add gaojt [ListAgg][JHOBv0.1]20150104 //add wenghaixing DECIMAL OceanBase_BankCommV0.3 2014_7_10:b uint32_t get_precision(); uint32_t get_scale(); uint32_t get_vscale(); static ObObj type_add_v2(const ObObj& t1, const ObObj& t2); static ObObj type_sub_v2(const ObObj& t1, const ObObj& t2); static ObObj type_mul_v2(const ObObj& t1, const ObObj& t2); static ObObj type_div_v2(const ObObj& t1, const ObObj& t2, bool int_div_as_double); //add e bool is_datetime_for_out() const;//add peiouy[datetime func]20150912 //add peiouya [IN_TYPEBUG_FIX] 20151225:b static ObObjType type_promotion_for_in_op (const ObObjType left_type, const ObObjType right_type); //add 20151225:e private: // function members static int type_promotion(ObObjType type_promote_map[ObMaxType][ObMaxType], const ObExprObj &this_obj, const ObExprObj &other, ObExprObj &promoted_obj1, ObExprObj &promoted_obj2, const ObExprObj *&p_this, const ObExprObj *&p_other); static int compare_type_promotion(const ObExprObj &this_obj, const ObExprObj &other, ObExprObj &promoted_obj1, ObExprObj &promoted_obj2, const ObExprObj *&p_this, const ObExprObj *&p_other); int cast_to_int(int64_t &val) const; int cast_to_varchar(ObString &varchar, ObStringBuf &mem_buf) const; //add fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_19:b inline int cast_to_decimal(ObString &varchar, ObStringBuf &mem_buf) const; //add:e int get_bool(bool &value) const; int get_timestamp(int64_t & timestamp) const; bool is_datetime() const; bool is_datetime(const ObObjType type) const; //add peiouya [DATE_TIME] 20150906 bool is_numeric() const; bool can_compare(const ObExprObj & other) const; int compare_same_type(const ObExprObj &other) const; static int arith_type_promotion(const ObExprObj &this_obj, const ObExprObj &other, ObExprObj &promoted_obj1, ObExprObj &promoted_obj2, const ObExprObj *&p_this_obj, const ObExprObj *&p_other); //add [DATE_TIME] peiouya 20150831:b void check_and_set_res_type(const ObObjType first_type, const ObObjType second_type, ObExprObj &res) const; //add 20150831:e int time_skew(ObExprObj &res) const; //add [DATE_TIME] peiouya 20150914 int add_same_type(const ObExprObj &other, ObExprObj &res) const; int sub_same_type(const ObExprObj &other, ObExprObj &res) const; int mul_same_type(const ObExprObj &other, ObExprObj &res) const; static int div_type_promotion(const ObExprObj &this_obj, const ObExprObj &other, ObExprObj &promoted_obj1, ObExprObj &promoted_obj2, const ObExprObj *&p_this, const ObExprObj *&p_other, bool int_div_as_double); int div_same_type(const ObExprObj &other, ObExprObj &res) const; static int mod_type_promotion(const ObExprObj &this_obj, const ObExprObj &other, ObExprObj &promoted_obj1, ObExprObj &promoted_obj2, const ObExprObj *&p_this, const ObExprObj *&p_other); static ObObj type_arithmetic(const ObObj& t1, const ObObj& t2); int substr(const int32_t start_pos, const int32_t expect_length_of_str, ObExprObj &result, ObStringBuf &mem_buf) const; int lrtrim(const ObString src, const ObString pattern, int32_t &start, int32_t &end) const; int ltrim(const ObString src, const ObString pattern, int32_t &start) const; int rtrim(const ObString src, const ObString pattern, int32_t &end) const; // functions for testing only friend class ::ObExprObj_Math_Test; friend class ::ObExprObj_negate_test_Test; friend class ::ObExprObjTest_get_bool_Test; friend class ::ObExprObjTest_compare_Test; friend class ::ObExprObjTest_like_Test; friend class ::ObExprObjTest_others_Test; void set_null(int null); // for testing only void set_varchar(const char* value); int set_decimal(const char* dec_str); int get_datetime(ObDateTime& value) const; int get_precise_datetime(ObPreciseDateTime& value) const; int get_decimal(char * buf, const int64_t buf_len) const; int get_float(float &f) const; int get_double(double &d) const; private: // data members int8_t type_; // ObObjType ObNumber num_; //add fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_19:b ObDecimal decimal_; //add:e ObString varchar_; union { int64_t int_; //add lijianqiang [INT_32] 20150930:b int32_t int32_; //add 20150930:e int64_t ext_; ObDateTime datetime_; ObPreciseDateTime precisedatetime_; ObCreateTime createtime_; ObModifyTime modifytime_; bool bool_; float float_; double double_; } v_; }; inline ObExprObj::ObExprObj() :type_(ObNullType) { v_.int_ = 0; } inline ObExprObj::~ObExprObj() { } inline void ObExprObj::set_null() { type_ = ObNullType; } inline void ObExprObj::set_null(int ignore) { UNUSED(ignore); type_ = ObNullType; } inline void ObExprObj::set_int(const int64_t value) { type_ = ObIntType; v_.int_ = value; } //add lijianqiang [INT_32] 20150930:b inline void ObExprObj::set_int32(const int32_t value) { type_ = ObInt32Type; v_.int32_ = value; } //add 20150930:e inline void ObExprObj::set_float(const float value) { type_ = ObFloatType; v_.float_ = value; } inline void ObExprObj::set_double(const double value) { type_ = ObDoubleType; v_.double_ = value; } inline void ObExprObj::set_datetime(const ObDateTime &value) { type_ = ObDateTimeType; v_.datetime_ = value; } inline void ObExprObj::set_precise_datetime(const ObPreciseDateTime &value) { type_ = ObPreciseDateTimeType; v_.precisedatetime_ = value; } //add peiouya [DATE_TIME] 20150831:b inline void ObExprObj::set_date(const ObDate &value) { type_ = ObDateType; v_.precisedatetime_ = static_cast<ObPreciseDateTime>(value); } inline void ObExprObj::set_time(const ObTime &value) { type_ = ObTimeType; v_.precisedatetime_ = static_cast<ObPreciseDateTime>(value); } //add 20150831:e //add peiouya [DATE_TIME] 20150909:b inline void ObExprObj::set_interval(const ObInterval &value) { type_ = ObIntervalType; v_.precisedatetime_ = static_cast<ObPreciseDateTime>(value); } //add 20150909:e inline void ObExprObj::set_varchar(const ObString& value) { type_ = ObVarcharType; varchar_ = value; } inline void ObExprObj::set_ctime(const ObCreateTime &value) { type_ = ObCreateTimeType; v_.createtime_ = value; } inline void ObExprObj::set_mtime(const ObModifyTime &value) { type_ = ObModifyTimeType; v_.modifytime_ = value; } inline void ObExprObj::set_bool(const bool value) { type_ = ObBoolType; v_.bool_ = value; } inline void ObExprObj::set_decimal(const ObNumber &value) { type_ = ObDecimalType; num_ = value; } //modify fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_19:b inline void ObExprObj::set_decimal(const ObDecimal &value) { type_ = ObDecimalType; decimal_ = value; } //modify:e inline void ObExprObj::set_ext(const int64_t value) { type_ = ObExtendType; v_.ext_ = value; } inline bool ObExprObj::is_zero() const { bool result = false; //modify fanqiushi DECIMAL OceanBase_BankCommV0.3 2014_7_9:b // change num_ to decimal_ if (((type_ == ObIntType) && (v_.int_ == 0)) || ((type_ == ObDecimalType) && decimal_.is_zero()) || (type_ == ObFloatType && v_.float_ == 0.0f) || (type_ == ObDoubleType && v_.double_ == 0.0) || ((type_ == ObInt32Type)&& (v_.int32_ == 0)))//add lijianqiang [INT_32] bug_fix for div 0 { result = true; } return result; //modify:e } inline ObObjType ObExprObj::get_type() const { return static_cast<ObObjType>(type_); } inline bool ObExprObj::is_true() const { return type_ == ObBoolType && v_.bool_; } inline bool ObExprObj::is_false() const { return type_ == ObBoolType && !v_.bool_; } //add wenghaixing DECIMAL OceanBase_BankCommV0.3 2014_7_10:b inline uint32_t ObExprObj::get_precision(){ return decimal_.get_precision(); } inline uint32_t ObExprObj::get_scale(){ return decimal_.get_scale(); } inline uint32_t ObExprObj::get_vscale(){ return decimal_.get_vscale(); } //add :e } // end namespace common } // end namespace oceanbase #endif /* _OB_EXPR_OBJ_H */
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TODO App</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css"> <style> .text-dec-line-through{ text-decoration: line-through; } </style> </head> <body> <div id="app"> <nav class="navbar is-primary"> <div class="navbar-brand"> <a class="navbar-item" href="https://bulma.io"> <img src="https://bulma.io/images/bulma-logo-white.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28"> </a> <div class="navbar-burger" data-target="navbarExampleTransparentExample"> <span></span> <span></span> <span></span> </div> </div> <div id="navbarExampleTransparentExample" class="navbar-menu"> <div class="navbar-start"> <a class="navbar-item" href="https://bulma.io/"> Home </a> <div class="navbar-item has-dropdown is-hoverable"> <a class="navbar-link" href="https://bulma.io/documentation/overview/start/"> Docs </a> <div class="navbar-dropdown is-boxed"> <a class="navbar-item" href="https://bulma.io/documentation/overview/start/"> Overview </a> <a class="navbar-item" href="https://bulma.io/documentation/overview/modifiers/"> Modifiers </a> <a class="navbar-item" href="https://bulma.io/documentation/columns/basics/"> Columns </a> <a class="navbar-item" href="https://bulma.io/documentation/layout/container/"> Layout </a> <a class="navbar-item" href="https://bulma.io/documentation/form/general/"> Form </a> <hr class="navbar-divider"> <a class="navbar-item" href="https://bulma.io/documentation/elements/box/"> Elements </a> <a class="navbar-item is-active" href="https://bulma.io/documentation/components/breadcrumb/"> Components </a> </div> </div> </div> <div class="navbar-end"> <div class="navbar-item"> <div class="field is-grouped"> <p class="control"> <a class="bd-tw-button button" data-social-network="Twitter" data-social-action="tweet" data-social-target="https://bulma.io" target="_blank" href="https://twitter.com/intent/tweet?text=Bulma: a modern CSS framework based on Flexbox&amp;hashtags=bulmaio&amp;url=https://bulma.io&amp;via=jgthms"> <span class="icon"> <i class="fab fa-twitter"></i> </span> <span> Tweet </span> </a> </p> <p class="control"> <a class="button is-primary" href="https://github.com/jgthms/bulma/releases/download/0.9.3/bulma-0.9.3.zip"> <span class="icon"> <i class="fas fa-download"></i> </span> <span>Download</span> </a> </p> </div> </div> </div> </div> </nav> <div class="section"> <div class="container"> <div class="columns"> <div class="column is-3"> <div class="card"> <header class="card-header"> <p class="card-header-title"> Component </p> <button class="card-header-icon" aria-label="more options"> <span class="icon"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </header> <div class="card-content"> <div class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec iaculis mauris. <a href="#">@bulmaio</a>. <a href="#">#css</a> <a href="#">#responsive</a> <br> <time datetime="2016-1-1">11:09 PM - 1 Jan 2016</time> </div> </div> <footer class="card-footer"> <a href="#" class="card-footer-item">Save</a> <a href="#" class="card-footer-item">Edit</a> <a href="#" class="card-footer-item">Delete</a> </footer> </div> </div> <div class="column"> <article class="panel"> <div class="tabs is-boxed"> <ul> <li class="is-current" :class="{ 'is-active': currentTab == 'Current'}" @click="currentTab='Current'"> <a> <span class="icon is-small"><i class="fas fa-clipboard-list" aria-hidden="true"></i></span> <span>Current</span> </a> </li> <li class="is-completed" :class="{ 'is-active': currentTab == 'Completed'}" @click="currentTab='Completed'"> <a> <span class="icon is-small"><i class="fas fa-calendar-times" aria-hidden="true"></i></span> <span>Completed</span> </a> </li> <li class="is-upcoming" :class="{ 'is-active': currentTab == 'Upcoming'}" @click="currentTab='Upcoming'"> <a> <span class="icon is-small"><i class="fas fa-calendar-day" aria-hidden="true"></i></span> <span>Upcoming</span> </a> </li> <li class="is-all" :class="{ 'is-active': currentTab == 'All'}" @click="currentTab='All'"> <a> <span class="icon is-small"><i class="fas fa-calendar" aria-hidden="true"></i></span> <span>All</span> </a> </li> </ul> </div> <div class="panel-block"> <p class="control has-icons-left"> <input class="input is-primary" type="text" placeholder="New Task"> <span class="icon is-left"> <i class="fas fa-calendar-plus" aria-hidden="true"></i> </span> </p> </div> <a class="panel-block" v-for="(task,i) in tasks" :class="{'text-dec-line-through' : task.isCompleted==true}" v-show="(currentTab=='All') || (currentTab=='Upcoming') || ((currentTab=='Current') && (!task.isCompleted)) || ((currentTab=='Completed') && task.isCompleted)"> <input type="checkbox" class="checkbox" v-model="task.isCompleted"> {{task.message}} </a> </article> </div> <div class="column is-3"> <h1 class="title">Table of contents</h1> <h2 class="subtitle">Intra-page navigation</h2> <aside class="menu"> <p class="menu-label"> General </p> <ul class="menu-list"> <li><a>Dashboard</a></li> <li><a>Customers</a></li> </ul> <p class="menu-label"> Administration </p> <ul class="menu-list"> <li><a>Team Settings</a></li> <li> <a class="is-active">Manage Your Team</a> <ul> <li><a>Members</a></li> <li><a>Plugins</a></li> <li><a>Add a member</a></li> </ul> </li> <li><a>Invitations</a></li> <li><a>Cloud Storage Environment Settings</a></li> <li><a>Authentication</a></li> </ul> <p class="menu-label"> Transactions </p> <ul class="menu-list"> <li><a>Payments</a></li> <li><a>Transfers</a></li> <li><a>Balance</a></li> </ul> </aside> </div> </div> </div> </div> </div> <!-------- VUE -----------------> <script src="https://unpkg.com/vue@3"></script> <script> Vue.createApp({ data() { return { currentTab: 'All', tasks: [ { isCompleted: false, message: 'Make Bulma great again' }, { isCompleted: true, message: 'Add some more features' }, { isCompleted: false, message: 'Make a github account' }, { isCompleted: true, message: 'Learn how to use github' }, { isCompleted: false, message: 'add a .gitignore file' }, ] } } }).mount('#app') </script> </body> </html>
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #ifndef COMPLETIONSETTINGS_H #define COMPLETIONSETTINGS_H #include "texteditor_global.h" QT_BEGIN_NAMESPACE class QSettings; QT_END_NAMESPACE namespace TextEditor { enum CaseSensitivity { CaseInsensitive, CaseSensitive, FirstLetterCaseSensitive }; /** * Settings that describe how the code completion behaves. */ struct TEXTEDITOR_EXPORT CompletionSettings { CompletionSettings(); void toSettings(const QString &category, QSettings *s) const; void fromSettings(const QString &category, const QSettings *s); bool equals(const CompletionSettings &bs) const; CaseSensitivity m_caseSensitivity; bool m_autoInsertBrackets; bool m_partiallyComplete; bool m_spaceAfterFunctionName; }; inline bool operator==(const CompletionSettings &t1, const CompletionSettings &t2) { return t1.equals(t2); } inline bool operator!=(const CompletionSettings &t1, const CompletionSettings &t2) { return !t1.equals(t2); } } // namespace TextEditor #endif // COMPLETIONSETTINGS_H
import 'package:dartz/dartz.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:wmd/core/domain/usecases/usercase.dart'; import 'package:wmd/core/error_and_success/failures.dart'; import 'package:wmd/core/error_and_success/succeses.dart'; import 'package:wmd/features/help/support/data/models/support_status.dart'; import 'package:wmd/features/help/support/domain/repositories/general_inquiry_repository.dart'; class PostGeneralInquiryUseCase extends UseCase<AppSuccess, Map<String, dynamic>> { final GeneralInquiryRepository generalInquiryRepository; PostGeneralInquiryUseCase(this.generalInquiryRepository); @override Future<Either<Failure, AppSuccess>> call(Map<String, dynamic> params) async { try { final postParams = GeneralInquiryParams.fromJson( {...params, "reason": params["reason"]}); return await generalInquiryRepository.postGeneralInquiry(postParams); } catch (e) { debugPrint("PostGeneralInquiryUseCase catch : ${e.toString()}"); return const Left(AppFailure(message: "Something went wrong!")); } } } class GeneralInquiryParams extends Equatable { const GeneralInquiryParams({ required this.reason, required this.enquiryText, }); final String reason; final String enquiryText; factory GeneralInquiryParams.fromJson(Map<String, dynamic> json) => GeneralInquiryParams( reason: json["reason"], enquiryText: json["enquiryText"], ); Map<String, dynamic> toJson() => { "reason": reason, "enquiryText": enquiryText, }; static final tGeneralInquiryMap = { "reason": "reason", "enquiryText": "enquiryText", }; static const tGeneralInquiryParams = GeneralInquiryParams( reason: "reason", enquiryText: "enquiryText", ); @override List<Object?> get props => [ reason, enquiryText, ]; }
from classes.scraping.get_html import get_html_champions, get_html_champion def get_champion_list(new_patch: bool): doc = get_html_champions(new_patch) table = doc.find("td", attrs={"data-sort-value": "Aatrox"}).parent.parent i = 0 champion_list = [] for entry in table: if i <= 2: i += 1 if i > 2: try: champion_list.append(entry.find("td").get("data-sort-value")) except: continue return champion_list def get_data(name, new_patch: bool): """Gets the base stats like base ad, hp, resists, etc... from html scraped from https://leagueoflegends.fandom.com/wiki/League_of_Legends_Wiki""" doc = get_html_champion(name, new_patch) base_hp = output_handler(doc.find("span", id="Health_{}".format(name))) hp_growth = output_handler(doc.find("span", id="Health_{}_lvl".format(name))) base_resource = output_handler(doc.find("span", id="ResourceBar_{}".format(name))) resource_growth = output_handler(doc.find("span", id="ResourceBar_{}_lvl".format(name))) base_hp_regen = output_handler(doc.find("span", id="HealthRegen_{}".format(name))) hp_regen_growth = output_handler(doc.find("span", id="HealthRegen_{}_lvl".format(name))) base_resource_regen = output_handler(doc.find("span", id="ResourceRegen_{}".format(name))) resource_regen_growth = output_handler(doc.find("span", id="ResourceRegen_{}_lvl".format(name))) base_armor = output_handler(doc.find("span", id="Armor_{}".format(name))) armor_growth = output_handler(doc.find("span", id="Armor_{}_lvl".format(name))) base_ad = output_handler(doc.find("span", id="AttackDamage_{}".format(name))) ad_growth = output_handler(doc.find("span", id="AttackDamage_{}_lvl".format(name))) base_mr = output_handler(doc.find("span", id="MagicResist_{}".format(name))) mr_growth = output_handler(doc.find("span", id="MagicResist_{}_lvl".format(name))) crit_damage = output_handler(doc.find("div", attrs={'data-source': "critical damage"})) base_move_speed = output_handler(doc.find("span", id="MovementSpeed_{}".format(name))) attack_range = output_handler(doc.find("span", id="AttackRange_{}".format(name))) base_attack_speed = output_handler(doc.find("div", attrs={'data-source': "attack speed"})) attack_speed_ratio = output_handler(doc.find("div", attrs={'data-source': "as ratio"})) attack_speed_growth = output_handler(doc.find("span", id="AttackSpeedBonus_{}_lvl".format(name))) hit_box = output_handler(doc.find("div", attrs={'data-source': "gameplay radius"})) resource = doc.find("h3", string="Resource").parent.find("span", attrs={"data-game": "lol"}).get("data-tip") if resource == "Manaless": try: resource = doc.find("h3", string="Resource").parent.find("a", class_="mw-redirect").text except: resource = "Manaless" if resource == "Energy": base_resource_regen = output_handler(doc.find("a", string="Energy regen. (per 5s)").next_element.next_element) data_dict = {"base_hp": base_hp, "hp_growth": hp_growth, "base_resource": base_resource, "resource_growth": resource_growth, "base_hp_regen": base_hp_regen, "hp_regen_growth": hp_regen_growth, "base_resource_regen": base_resource_regen, "resource_regen_growth": resource_regen_growth, "base_armor": base_armor, "armor_growth": armor_growth, "base_ad": base_ad, "ad_growth": ad_growth, "base_mr": base_mr, "mr_growth": mr_growth, "crit_damage": crit_damage, "base_move_speed": base_move_speed, "attack_range": attack_range, "base_attack_speed": base_attack_speed, "attack_speed_ratio": attack_speed_ratio, "attack_speed_growth": attack_speed_growth, "hit_box": hit_box, "resource": resource} return data_dict def output_handler(stat): """Handles text from goofy html output""" try: if "Crit. damage" in stat.text: text = stat.text.replace("Crit. damage", "") text = text.replace("%", "") elif "Base AS" in stat.text: text = stat.text.replace("Base AS", "") elif "AS ratio" in stat.text: text = stat.text.replace("AS ratio", "") elif "Gameplay radius" in stat.text: text = stat.text.replace("Gameplay radius", "") else: text = stat.text return float(text) except: return 0
import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import Container from "../Container"; import Title from "../form/Title"; import FormInput from "../form/FormInput"; import Submit from "../form/Submit"; import CustomLink from "../CustomLink"; import { commonModalClasses } from "../../utils/theme"; import FormContainer from "./FormContainer"; import { createUser } from "../../api/auth"; import { useAuth, useNotification } from "../../hooks"; import { isValidEmail } from "../../utils/helper"; const validateUserInfo = ({ name, email, password }) => { // const isVaildEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; const isValidName = /^[a-z A-Z]+$/; if (!name.trim()) return { ok: false, error: "Name is missing!" }; if (!isValidName.test(name)) return { ok: false, error: "Invalid name!" }; if (!email.trim()) return { ok: false, error: "Email is missing!" }; if (!isValidEmail(email)) return { ok: false, error: "Invalid email!" }; if (!password.trim()) return { ok: false, error: "Password is missing!" }; if (password.length < 8) return { ok: false, error: "Password must be at least 8 characters long!" }; return { ok: true }; }; export default function Signup() { const [userInfo, setUserInfo] = useState({ name: "", email: "", password: "", }); const navigate = useNavigate() const {updateNotification} = useNotification() const { handleLogin, authInfo} = useAuth(); const { isPending, isLoggedIn} = authInfo const handleChange = ({ target }) => { const { value, name } = target; setUserInfo({ ...userInfo, [name]: value }); }; /** * using e.preventDefault to prevent the browser lose the submitted form info SignUp form * when user click on button */ const handleSubmit = async (e) => { e.preventDefault(); const { ok, error } = validateUserInfo(userInfo); if (!ok) return updateNotification("error", error); const response = await createUser(userInfo); if (response.error) return console.log(response.error); navigate("/auth/verification", { state: { user: response.user }, replace: true, }); }; useEffect(()=> { if(isLoggedIn) navigate("/") // we want to move our user to somewhere else }, [isLoggedIn]) //user info with name email password const { name, email, password } = userInfo; return ( <FormContainer> <Container> <form onSubmit={handleSubmit} className={commonModalClasses + " w-72"}> <Title>Sign up</Title> <FormInput label="Name" placeholder="name" name="name" value={name} onChange={handleChange} ></FormInput> <FormInput label="Email" placeholder="name@email.com" name="email" value={email} onChange={handleChange} ></FormInput> <FormInput label="Password" placeholder="********" name="password" value={password} type="password" onChange={handleChange} ></FormInput> <Submit value="Sign up"></Submit> <div className="flex justify-between"> <CustomLink to="/auth/forget-password">Forget Password</CustomLink> <CustomLink to="/auth/signin">Sign in</CustomLink> </div> </form> </Container> </FormContainer> ); }
import { useRouter } from "next/router"; import { useEffect } from "react"; import { Formik, Form, Field } from "formik"; import { object, string } from "yup"; import PageWidth from "components/PageWidth/PageWidth"; import { Title } from "components/Title/Title"; import InputField from "components/form-fields/InputField"; import { PrimaryButton } from "components/Button/Button"; import { supabase } from "utils/supabaseClient"; import { useUser } from "hooks/use-user"; const validationSchema = object().shape({ title: string().required("Please enter a title"), url: string().url("Please enter a valid url").required("Please enter a url"), }); const New = () => { const { user, loading } = useUser(); const { replace, push } = useRouter(); useEffect(() => { if (!user && !loading) { replace("/account/login"); } }, [user, loading, replace]); const onSubmit = async (values) => { const { error } = await supabase.from("posts").insert({ ...values, author: user.id, }); if (!error) { push("/"); // TODO: alert } }; return ( <PageWidth> <Title>Submit</Title> <Formik initialValues={{ title: "", url: "", }} validationSchema={validationSchema} onSubmit={onSubmit} > {({ handleSubmit, touched, errors }) => ( <Form onSubmit={handleSubmit}> <Field component={InputField} name="title" label="Title" error={touched.title && errors.title} /> <Field component={InputField} name="url" label="Url" error={touched.url && errors.url} /> <div className="mt-3"> <PrimaryButton type="submit">Submit</PrimaryButton> </div> </Form> )} </Formik> </PageWidth> ); }; export default New;
import {useState, useEffect} from 'react' function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const jsonValue = localStorage.getItem(key) if(jsonValue == null){ if(typeof initialValue === "function"){ return initialValue() }else{ return initialValue } }else{ return JSON.parse(jsonValue) } }) useEffect(() => { localStorage.setItem(key, JSON.stringify(value)) }, [value, key]) return [value, setValue] } export default useLocalStorage
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'; import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { TransizioneService } from '../../servizio-transizione.service'; import { Router } from '@angular/router'; import { InputCodiceComponent } from '../../../comuni/elementi-form/input-codice/input-codice.component'; import { SincronizzazioneService } from '../sincronizzazione.service'; import { InputTextComponent } from 'src/app/comuni/elementi-form/input-text/input-text.component'; import { RegexInput } from 'src/app/utils/Input'; import { RimuoviParametri } from 'src/app/utils/funzioni'; import { AxiosError } from 'axios'; import { RecuperoCredenzialiService } from './recupero-credenziali.service'; import { NotificheService } from 'src/app/comuni/notifiche/notifiche.service'; @Component({ selector: 'form-recupero-credenziali', templateUrl: './recupero-credenziali.component.html', standalone: true, styleUrls: ['../../stile-form.scss', '../stile-form.scss', './recupero-credenziali.component.scss'], imports: [ReactiveFormsModule, InputCodiceComponent, FormsModule, InputTextComponent], }) export class RecuperoCredenzialiComponent implements AfterViewInit{ constructor( public transizione: TransizioneService, public sinc: SincronizzazioneService, private servizio: RecuperoCredenzialiService, public router: Router, private notifiche: NotificheService ){} @ViewChild("formHtml") formHtml!: ElementRef<HTMLElement> public RimuoviParametri = RimuoviParametri; ngAfterViewInit(): void { this.transizione.formVeri["/login/recupero-credenziali"] = this.formHtml.nativeElement; } public formInvioMail : FormGroup = new FormGroup({ "mail-recupero" : new FormControl("", [Validators.required, Validators.pattern(RegexInput["email"])]) }) private codice = "" NavigaLogin(){ this.transizione.TransizioneUscita(this.formHtml.nativeElement, "/login"); setTimeout(() => { this.router.navigateByUrl("/login"); }, 500); } async InviaMail(notifica: boolean = false, transizione: boolean = true){ this.transizione.caricamento = true; try { await this.servizio.InviaMailRecupero(this.formInvioMail.get("mail-recupero")?.value); this.transizione.caricamento = false; if(transizione){ this.sinc.TransizioneForm(this.formHtml.nativeElement); } if(notifica){ this.notifiche.NuovaNotifica({ tipo: "info", titolo: "Codice Inviato", }) } } catch(e) {this.GestisciErroreMail(e as AxiosError)} finally{this.transizione.caricamento = false;} } ControllaCodice([corretto, codice]: [boolean, string]){ this.sinc.codiceCorretto = corretto; this.codice = codice; } async ResetPassword(){ try { await this.servizio.VerificaCodice(this.codice) this.transizione.TransizioneUscita(this.formHtml.nativeElement, "/login/reset-password"); setTimeout(() => { this.router.navigateByUrl("/login/reset-password"); }, 500); } catch(e) {this.GestisciErroreCodice(e as AxiosError)} } private GestisciErroreCodice(err : AxiosError){ const { status } = err.response!; if(status == 411) { this.sinc.errori["codice"] = "Codice incoretto" return; } if(status == 410) { this.notifiche.NuovaNotifica({ tipo: "errore", titolo: "Codice scaduto", descrizione: "Sono passati più di 30 minuti dalla richiesta del codice" }) return; } this.notifiche.NuovaNotifica({ tipo: "errore", titolo: "Qualcosa è andato storto" }) } private GestisciErroreMail(err : AxiosError){ const { status } = err.response!; if(status == 400) { this.sinc.errori["mail"] = "Mail non registrata"; return; } this.notifiche.NuovaNotifica({ tipo: "errore", titolo: "Qualcosa è andato storto" }) } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:replace="fragmentos/cabecera.html :: cabecera('Editar Sede')"> </head> <body> <nav th:replace="fragmentos/navbar.html :: navbar('sedes')"> </nav> <main> <div class="container px-4 py-5"> <h1 class="pb-2 border-bottom">Editar Sede</h1> <div class="container-fluid"> <form method="post" th:action="@{'/sedes/guardar'}" th:object="${sede}"> <input type="hidden" th:field="*{id}" /> <div class="mb-3"> <label for="nombreSede" class="form-label">Nombre de la Sede</label> <input name="nombreSede" id="nombreSede" type="text" class="form-control" th:field="*{nombreSede}"> </div> <div class="mb-3"> <label for="direccion" class="form-label">Dirección de la Sede</label> <input id="direccion" name="direccion" type="text" class="form-control" th:field="*{direccion}"> </div> <a th:href="@{'/sedes/lista'}" class="btn btn-danger">Cancelar</a> <button type="submit" class="btn btn-primary">Guardar</button> </form> </div> <div class="container px-4 py-5"> <h1 class="pb-2 border-bottom">Lista de trabajadores</h1> </div> <table class="table"> <tr> <th>#</th> <th>DNI del trabajador</th> <th>Correo del trabajador</th> <th>Nombre del trabajador</th> <th>Apellidos del trabajador</th> </tr> <tr th:each="trabajador, info : ${trabajadoresList}"> <td th:text="${info.index + 1}"></td> <td th:text="${trabajador.dni}"></td> <td th:text="${trabajador.correo}"></td> <td th:text="${trabajador.nombres}"></td> <td th:text="${trabajador.apellidos}"></td> </tr> </table> </div> </main> </body> </html>
<?php namespace Mpdf; use Mpdf\Strict; use Mpdf\Color\ColorConverter; use Mpdf\Image\ImageProcessor; use Mpdf\Language\LanguageToFontInterface; class Tag { use Strict; /** * @var \Mpdf\Mpdf */ private $mpdf; /** * @var \Mpdf\Cache */ private $cache; /** * @var \Mpdf\CssManager */ private $cssManager; /** * @var \Mpdf\Form */ private $form; /** * @var \Mpdf\Otl */ private $otl; /** * @var \Mpdf\TableOfContents */ private $tableOfContents; /** * @var \Mpdf\SizeConverter */ private $sizeConverter; /** * @var \Mpdf\Color\ColorConverter */ private $colorConverter; /** * @var \Mpdf\Image\ImageProcessor */ private $imageProcessor; /** * @var \Mpdf\Language\LanguageToFontInterface */ private $languageToFont; /** * @param \Mpdf\Mpdf $mpdf * @param \Mpdf\Cache $cache * @param \Mpdf\CssManager $cssManager * @param \Mpdf\Form $form * @param \Mpdf\Otl $otl * @param \Mpdf\TableOfContents $tableOfContents * @param \Mpdf\SizeConverter $sizeConverter * @param \Mpdf\Color\ColorConverter $colorConverter * @param \Mpdf\Image\ImageProcessor $imageProcessor * @param \Mpdf\Language\LanguageToFontInterface $languageToFont */ public function __construct( Mpdf $mpdf, Cache $cache, CssManager $cssManager, Form $form, Otl $otl, TableOfContents $tableOfContents, SizeConverter $sizeConverter, ColorConverter $colorConverter, ImageProcessor $imageProcessor, LanguageToFontInterface $languageToFont ) { $this->mpdf = $mpdf; $this->cache = $cache; $this->cssManager = $cssManager; $this->form = $form; $this->otl = $otl; $this->tableOfContents = $tableOfContents; $this->sizeConverter = $sizeConverter; $this->colorConverter = $colorConverter; $this->imageProcessor = $imageProcessor; $this->languageToFont = $languageToFont; } /** * @param string $tag The tag name * @return \Mpdf\Tag\Tag */ private function getTagInstance($tag) { $className = self::getTagClassName($tag); if (class_exists($className)) { return new $className( $this->mpdf, $this->cache, $this->cssManager, $this->form, $this->otl, $this->tableOfContents, $this->sizeConverter, $this->colorConverter, $this->imageProcessor, $this->languageToFont ); } } /** * Returns the fully qualified name of the class handling the rendering of the given tag * * @param string $tag The tag name * @return string The fully qualified name */ public static function getTagClassName($tag) { static $map = [ 'BARCODE' => 'BarCode', 'BLOCKQUOTE' => 'BlockQuote', 'COLUMN_BREAK' => 'ColumnBreak', 'COLUMNBREAK' => 'ColumnBreak', 'DOTTAB' => 'DotTab', 'FIELDSET' => 'FieldSet', 'FIGCAPTION' => 'FigCaption', 'FORMFEED' => 'FormFeed', 'HGROUP' => 'HGroup', 'INDEXENTRY' => 'IndexEntry', 'INDEXINSERT' => 'IndexInsert', 'NEWCOLUMN' => 'NewColumn', 'NEWPAGE' => 'NewPage', 'PAGEFOOTER' => 'PageFooter', 'PAGEHEADER' => 'PageHeader', 'PAGE_BREAK' => 'PageBreak', 'PAGEBREAK' => 'PageBreak', 'SETHTMLPAGEFOOTER' => 'SetHtmlPageFooter', 'SETHTMLPAGEHEADER' => 'SetHtmlPageHeader', 'SETPAGEFOOTER' => 'SetPageFooter', 'SETPAGEHEADER' => 'SetPageHeader', 'TBODY' => 'TBody', 'TFOOT' => 'TFoot', 'THEAD' => 'THead', 'TEXTAREA' => 'TextArea', 'TEXTCIRCLE' => 'TextCircle', 'TOCENTRY' => 'TocEntry', 'TOCPAGEBREAK' => 'TocPageBreak', 'VAR' => 'VarTag', 'WATERMARKIMAGE' => 'WatermarkImage', 'WATERMARKTEXT' => 'WatermarkText', ]; $className = 'Mpdf\Tag\\'; $className .= isset($map[$tag]) ? $map[$tag] : ucfirst(strtolower($tag)); return $className; } public function OpenTag($tag, $attr, &$ahtml, &$ihtml) { // Correct for tags where HTML5 specifies optional end tags excluding table elements (cf WriteHTML() ) if ($this->mpdf->allow_html_optional_endtags) { if (isset($this->mpdf->blk[$this->mpdf->blklvl]['tag'])) { $closed = false; // li end tag may be omitted if immediately followed by another li element if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'LI' && $tag == 'LI') { $this->CloseTag('LI', $ahtml, $ihtml); $closed = true; } // dt end tag may be omitted if immediately followed by another dt element or a dd element if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'DT' && ($tag == 'DT' || $tag == 'DD')) { $this->CloseTag('DT', $ahtml, $ihtml); $closed = true; } // dd end tag may be omitted if immediately followed by another dd element or a dt element if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'DD' && ($tag == 'DT' || $tag == 'DD')) { $this->CloseTag('DD', $ahtml, $ihtml); $closed = true; } // p end tag may be omitted if immediately followed by an address, article, aside, blockquote, div, dl, // fieldset, form, h1, h2, h3, h4, h5, h6, hgroup, hr, main, nav, ol, p, pre, section, table, ul if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'P' && ($tag == 'P' || $tag == 'DIV' || $tag == 'H1' || $tag == 'H2' || $tag == 'H3' || $tag == 'H4' || $tag == 'H5' || $tag == 'H6' || $tag == 'UL' || $tag == 'OL' || $tag == 'TABLE' || $tag == 'PRE' || $tag == 'FORM' || $tag == 'ADDRESS' || $tag == 'BLOCKQUOTE' || $tag == 'CENTER' || $tag == 'DL' || $tag == 'HR' || $tag == 'ARTICLE' || $tag == 'ASIDE' || $tag == 'FIELDSET' || $tag == 'HGROUP' || $tag == 'MAIN' || $tag == 'NAV' || $tag == 'SECTION')) { $this->CloseTag('P', $ahtml, $ihtml); $closed = true; } // option end tag may be omitted if immediately followed by another option element // (or if it is immediately followed by an optgroup element) if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'OPTION' && $tag == 'OPTION') { $this->CloseTag('OPTION', $ahtml, $ihtml); $closed = true; } // Table elements - see also WriteHTML() if (!$closed && ($tag == 'TD' || $tag == 'TH') && $this->mpdf->lastoptionaltag == 'TD') { $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); $closed = true; } // *TABLES* if (!$closed && ($tag == 'TD' || $tag == 'TH') && $this->mpdf->lastoptionaltag == 'TH') { $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); $closed = true; } // *TABLES* if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TR') { $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); $closed = true; } // *TABLES* if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TD') { $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); $this->CloseTag('TR', $ahtml, $ihtml); $this->CloseTag('THEAD', $ahtml, $ihtml); $closed = true; } // *TABLES* if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TH') { $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); $this->CloseTag('TR', $ahtml, $ihtml); $this->CloseTag('THEAD', $ahtml, $ihtml); $closed = true; } // *TABLES* } } if ($object = $this->getTagInstance($tag)) { return $object->open($attr, $ahtml, $ihtml); } } public function CloseTag($tag, &$ahtml, &$ihtml) { if ($object = $this->getTagInstance($tag)) { return $object->close($ahtml, $ihtml); } } }
# Sliding Window class Solution: def getMaxLen(self, nums: List[int]) -> int: max_len = 0 negative_count = 0 first_negative_index = None zero_index = -1 for i in range(len(nums)): if nums[i] == 0: negative_count = 0 first_negative_index = None zero_index = i elif nums[i] < 0: negative_count += 1 if first_negative_index == None: first_negative_index = i if negative_count & 1 == 0: max_len = max(max_len, i - zero_index) else: max_len = max(max_len, i - first_negative_index) return max_len # DFS + Memoization class Solution: def getMaxLen(self, nums: List[int]) -> int: @cache # This decorator is used to implement memoization, which is a technique to cache the results of expensive function calls and reuse them when the same inputs occur again in the future. def dfs(i = 0, taking = False, positive = True): if i == len(nums): return 0 if positive else -math.inf # we can never include a 0 in the subarray if nums[i] == 0: return dfs(len(nums) if taking else i + 1, taking, positive) # max length if we include this number in the subarray including = dfs(i + 1, True, positive == (nums[i] > 0)) + 1 # max length if we exclude this number from the subarray excluding = dfs(len(nums), True, positive) if taking else dfs(i + 1, False) return max(including, excluding) return dfs()
package io.github.dtolmachev1.operations.complex; import io.github.dtolmachev1.numbers.Complex; import io.github.dtolmachev1.operations.Operation; /** * <p>Class for multiplication operation.</p> */ class Multiplication implements Operation { /** * <p>Constructor to initialize operation with given operands.</p> * * @param leftOperand left operand. * @param rightOperand right operand. */ Multiplication(Complex leftOperand, Complex rightOperand) { this.leftOperand = leftOperand; this.rightOperand = rightOperand; } /** * <p>Returns the product of two complex numbers.</p> * * @return product of left and right operands. */ @Override public Complex eval() { return leftOperand.multiply(rightOperand); } private final Complex leftOperand; // left operand private final Complex rightOperand; // right operand }
import { Link } from 'react-router-dom'; import { AlbumType } from '../types'; type PropsType = { result: AlbumType; }; function ArtistCollectionCard({ result }: PropsType) { const { artistName, collectionId, collectionName, collectionPrice, artworkUrl100, releaseDate, trackCount, currency } = result; const formatDate = (date: string) => { return new Date(date).toLocaleString().substring(0, 10); }; return ( <Link className="cardLink" data-testid={ `link-to-album-${collectionId}` } to={ `/album/${collectionId}` } > <section> <h2>{collectionName}</h2> <img src={ artworkUrl100 } alt={ artistName } /> <h3>{`Tracks: ${trackCount}`}</h3> <h3>{`Released: ${formatDate(releaseDate)}`}</h3> <h4>{`Price: ${collectionPrice}`}</h4> <h4>{`Currency: ${currency}`}</h4> </section> </Link> ); } export default ArtistCollectionCard;
package main import ( "crypto/tls" "crypto/x509" "fmt" "github.com/dgraph-io/badger/v4" "github.com/gin-gonic/gin" mdns "github.com/miekg/dns" _ "github.com/qdnqn/smr/docs" "github.com/qdnqn/smr/pkg/api" "github.com/qdnqn/smr/pkg/commands" _ "github.com/qdnqn/smr/pkg/commands" "github.com/qdnqn/smr/pkg/config" "github.com/qdnqn/smr/pkg/keys" "github.com/qdnqn/smr/pkg/logger" "github.com/spf13/viper" "github.com/swaggo/files" "github.com/swaggo/gin-swagger" "go.uber.org/zap" "net/http" "os" "strconv" ) // @title Simple container manager API // @version 1.0 // @description This is a container orchestrator service. // @termsOfService http://smr.qdnqn.com/terms // @contact.name API Support // @contact.url https://github.com/qdnqn/smr // @license.name GNU General Public License v3.0 // @license.url https://github.com/qdnqn/smr/blob/main/LICENSE // @host localhost:8080 // @BasePath /api/v1 // @securityDefinitions.basic BasicAuth // @externalDocs.description OpenAPI // @externalDocs.url https://swagger.io/resources/open-api/ func main() { logger.Log = logger.NewLogger() conf := config.NewConfig() conf.ReadFlags() var db *badger.DB var err error if viper.GetBool("optmode") { // Instance of the key value store if the optmode enabled db, err = badger.Open(badger.DefaultOptions("/home/smr-agent/smr/smr/persistent/kv-store/badger")) if err != nil { logger.Log.Fatal(err.Error()) } defer db.Close() } api := api.NewApi(conf, db) commands.PreloadCommands() commands.Run(api.Manager) if viper.GetBool("daemon") { conf.Load(api.Runtime.PROJECTDIR) mdns.HandleFunc(".", api.HandleDns) // start dns server in go routine to detach from main port := 53 server := &mdns.Server{Addr: ":" + strconv.Itoa(port), Net: "udp"} go server.ListenAndServe() defer server.Shutdown() api.Manager.Reconcile() router := gin.Default() v1 := router.Group("/api/v1") { operators := v1.Group("/operators") { operators.GET(":group", api.ListSupported) operators.GET(":group/:operator", api.RunOperators) operators.POST(":group/:operator", api.RunOperators) } objects := v1.Group("/") { objects.POST("apply", api.Apply) objects.POST("compare", api.Compare) objects.POST("delete", api.Delete) } containers := v1.Group("/") { containers.GET("ps", api.Ps) } database := v1.Group("database") { database.GET(":key", api.DatabaseGet) database.GET("keys", api.DatabaseGetKeys) database.GET("keys/:prefix", api.DatabaseGetKeysPrefix) database.POST(":key", api.DatabaseSet) database.PUT(":key", api.DatabaseSet) } } router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) router.GET("/healthz", api.Health) if viper.GetBool("daemon-secured") { api.Keys = keys.NewKeys("/home/smr-agent/.ssh") api.Manager.Keys = api.Keys found, err := api.Keys.GenerateIfNoKeysFound() if err != nil { panic("failed to generate or read mtls keys") } if !found { err := api.Keys.SaveToDirectory() if err != nil { logger.Log.Error("failed to save keys to directory", zap.String("error", err.Error())) os.Exit(1) } fmt.Println("Certificate is generated for the use by the smr client!") fmt.Println("Copy-paste it to safe location for further use - it will not be printed anymore in the logs") fmt.Println(api.Keys.GeneratePemBundle()) } certPool := x509.NewCertPool() if ok := certPool.AppendCertsFromPEM(api.Keys.CAPem.Bytes()); !ok { panic("invalid cert in CA PEM") } serverTLSCert, err := tls.X509KeyPair(api.Keys.ServerCertPem.Bytes(), api.Keys.ServerPrivateKey.Bytes()) if err != nil { logger.Log.Fatal("error opening certificate and key file for control connection", zap.String("error", err.Error())) return } tlsConfig := &tls.Config{ ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: certPool, Certificates: []tls.Certificate{serverTLSCert}, } server := http.Server{ Addr: ":1443", Handler: router, TLSConfig: tlsConfig, } defer server.Close() server.ListenAndServeTLS("", "") } else { router.Run() } } }
require 'debug' # Parserクラスでincludeするためのモジュール # 汎用的なメソッドを定義する module Concerns::Util private def match(*types) types.each do |type| if check(type) advance return true end end false end # Tokenを消費して、インデックスを1つ進める def consume(type, message) return advance if check(type) error(peek, message) end def check(type) return false if at_end? peek.type == type end def advance @current += 1 unless at_end? previous end # 配列の最後のTokenは必ず:EOFになっている def at_end? peek.type == :EOF end def peek @tokens[@current] end def previous @tokens[@current - 1] end def error(token, message) Lox.error(token, message) raise ParseError end def synchronize advance until at_end? return if previous.type == :SEMICOLON case peek.type when :CLASS, :FUN, :VAR, :FOR, :IF, :WHILE, :PRINT, :RETURN return end advance end end end
import pandas as pd def take_user_input(): """As described, needs unpacking/unrolling params when called""" while True: try: p = int(input("Write parameter p: ")) q = int(input("Write parameter q: ")) c = int(input("Write ciphered message c: ")) return p, q, c except ValueError: print("Bad user input, try again....") def extended_gcd(phi_n): """Function takes in phi_n and returns algorithm values r, x, y needed for deciphering message c""" e = 67 x2 = 1 x1 = 0 y2 = 0 y1 = 1 s_values = ['-'] r_values = ['-'] x_values = ['-'] y_values = ['-'] phi_n_values = [phi_n] e_values = [e] x2_values = [x2] x1_values = [x1] y2_values = [y2] y1_values = [y1] while e > 0: s = phi_n // e r = phi_n - s * e x = x2 - s * x1 y = y2 - s * y1 phi_n, e = e, r x2, x1 = x1, x y2, y1 = y1, y s_values.append(s) r_values.append(r) x_values.append(x) y_values.append(y) phi_n_values.append(phi_n) e_values.append(e) x2_values.append(x2) x1_values.append(x1) y2_values.append(y2) y1_values.append(y1) df = pd.DataFrame({ 's': s_values, 'r': r_values, 'x': x_values, 'y': y_values, 'φ(n)': phi_n_values, 'e': e_values, 'x2': x2_values, 'x1': x1_values, 'y2': y2_values, 'y1': y1_values }) print(df.to_markdown(index=False)) print("\nr: ", phi_n) print("x: ", x2) if y2_values[-1] < 0: y2_values[-1] += phi_n_values[0] print("y: ", y2_values[-1]) else: print("y: ", y2_values[-1]) return phi_n_values[-1], x2, y2_values[-1] def modular_exponentiation(x, d, n): """Function returns the result of modular_exponentiation of x^a mod n and optionally shows results of each iteration of the loop as a table""" d_bin = bin(d)[2:] # present d as a binary sequence w = 1 # lists for tabular representation i_values = list(range(len(d_bin) - 1, -1, -1)) # iter from len(d_bin) - 1 to 0 ai_values = ['-'] + list(d_bin) # binary representation bits w_values = [1] # primary w value print(f"Decimal representation of d: {d} has binary sequence: {d_bin}\n") for i, bit in enumerate(d_bin): w = (w * w) % n if bit == '1': w = (w * x) % n w_values.append(w) # print(f"Iteration {len(d_bin) - 1 - i} - bit: {bit}, w = {w}") # trimming lists ai_values = ai_values[:len(d_bin) + 1] w_values = w_values[:len(d_bin) + 1] # yet another tabular df df = pd.DataFrame({ 'i': ['-'] + i_values, 'a_i': ai_values, 'w': w_values }) print(df.to_markdown(index=False)) return w if __name__ == "__main__": # unroll into variables p, q, c = take_user_input() # calculate n and φ(n) n = p * q phi_n = (p - 1) * (q - 1) print(f"n = {n}") print(f"φ(n) = {phi_n}") # execute algo phi_n, x, d = extended_gcd(phi_n) # use modular exponentiation to decipher c into m m = modular_exponentiation(c, d, n) print(f"\nDecipher result: m = {m}")
/* eslint-disable react/prop-types */ import { useState } from "react"; import { Link } from "react-router-dom"; import logo from "../assets/logo.png"; import { useLogout } from "../Hooks/useLogout.jsx"; import logoutImg from "../assets/logout.png"; function NewContact({ onAddContact }) { const { logout } = useLogout(); const [enteredValues, setEnteredValues] = useState({ name: "", email: "", phoneNumber: "", gender: "", }); const [didEdit, setDidEdit] = useState(false); const emailIsInvalid = didEdit && !enteredValues.email.includes("@"); function submitHandler(event) { event.preventDefault(); onAddContact(enteredValues); } function handleInputChange(identifier, value) { setEnteredValues((prevValues) => ({ ...prevValues, [identifier]: value, })); } function handleInputBlur() { setDidEdit(true); } function handleClick() { logout(); } return ( <div className="bg-[url('./assets/background.png')] w-screen h-screen bg-cover bg-center text-white "> <div className="ml-52 pt-16"> <img src={logo} alt="twc-logo and name" /> </div> <div className="pl-52 pt-10 "> <p className="text-5xl font-bold tracking-wide">New Contact</p> <form action="" method="post" onSubmit={submitHandler}> <input type="text" name="full-name" id="full-name" className="border-2 rounded-full font-semibold pl-4 mt-10 mr-6 w-80 h-10 text-twc-green tracking-wide" placeholder="full name" onChange={(event) => handleInputChange("name", event.target.value)} value={enteredValues.name} /> <input type="text" name="e-mail" id="e-mail" className="border-2 rounded-full font-semibold pl-4 mt-4 w-80 h-10 text-twc-green tracking-wide" placeholder="e-mail" onChange={(event) => handleInputChange("email", event.target.value)} value={enteredValues.email} onBlur={handleInputBlur} /> <div className="ml-96 mt-2 text-yellow-400"> {emailIsInvalid && <p>Please Enter valid Email address</p>} </div> <br /> <input type="text" name="phone-number" id="phone-number" className="border-2 rounded-full font-semibold pl-4 mr-6 w-80 h-10 text-twc-green tracking-wide" placeholder="phone number" onChange={(event) => handleInputChange("phoneNumber", event.target.value) } value={enteredValues.phoneNumber} />{" "} <label className="font-semibold tracking-wide text-xl mr-8"> Gender </label> <input type="radio" name="gender" id="male" className="w-4 h-4 bg-twc-green" value="male" onChange={(event) => handleInputChange("gender", event.target.value) } /> <label htmlFor="male" className="font-normal tracking-wide text-xl mr-8 ml-2" > Male </label>{" "} <input type="radio" name="gender" id="female" className="w-4 h-4 bg-twc-green" value="female" onChange={(event) => handleInputChange("gender", event.target.value) } /> <label htmlFor="female" className="font-normal tracking-wide text-xl mr-8 ml-2" > Female </label>{" "} <br /> <button type="submit" className="rounded-full border-2 text-xl font-normal w-72 h-12 mt-20 mr-4" > add your contact </button> </form> <div className="fixed bottom-10 right-10 flex items-center ml-[500px] space-x-2" onClick={handleClick} > <img src={logoutImg} alt="delete image" /> <u> <Link className="font-normal text-xl">Logout</Link> </u> </div> </div> </div> ); } export default NewContact;
// Name : lab11.cpp // Author : Khalid Mengal // Version : 1.0 // Date Created : 25-04-2020 // Date Modified: 18-11-2021 // Copyright : All rights are reserved // Description : HashTable Implmentation using C++ #include<iostream> #include<fstream> #include<sstream> #include<math.h> #include<string> #include<list> #include<cstdlib> using namespace std; class HashNode { private: string key; string value; public: HashNode(string key, string value) { this->key = key; this->value = value; } friend class HashTable; }; class HashTable { private: //HashNode **nodeArray; // Array of Pointers to Hash Nodes //Comment out the line above and uncomment line below for Task 3 list<HashNode> *buckets; // Array of lists of type Hash Nodes int size; //Current Size of HashTable int capacity; // Total Capacity of HashTable int collisions; // Total Number of Collisions public: HashTable(int capacity); unsigned long hashCode(string key); void insert(string key, string value); string search(string key); void erase(string key); //uncomment it for Task3 int getSize(); int getCollisions(); ~HashTable(); }; HashTable::HashTable(int capacity) { buckets = new list<HashNode>[capacity]; //Array of a list/chain this->capacity = capacity; this->size = 0; this->collisions = 0; } unsigned long HashTable::hashCode(string key) { int hashKey = 0; //for every letter in the string, multply its asci value with 33 to the power of the position of the character. //add this value to the hashKey, and make sure the hashkey value is not greater then the value of the array capcity. for(int i = 0; i<key.length(); i++){ hashKey = (hashKey + key[i] * (int(pow(33,i))))%capacity; //chose 33 because of the class slides saying certain prime numbers decrease collisions. } return hashKey; } void HashTable::insert(string key, string value) { //insert is constant time for seperate chaining. //find index. Create Node. Add node to the end of the list at the index in the array. int index = abs(int(hashCode(key))); HashNode newEntry = HashNode(key, value); buckets[index].push_back(newEntry); size++; } string HashTable::search(string key) { //get the index. int index = abs(int(hashCode(key))); list<HashNode>::iterator it; int i = 0; //iterate over the list, if key is found in the list return the value. otherwise return not found. for(it = buckets[index].begin(); it!=buckets[index].end(); it++){ if(it->key == key) return it->value; i++; } return "Not found"; } // Uncomment it for Task 3 void HashTable::erase(string key) { //get index int index = abs(int(hashCode(key))); list<HashNode>::iterator it; int i = 0; bool inArray = false; //iterate over the list, if key is found erase it from the list. for(it = buckets[index].begin(); it!=buckets[index].end(); it++){ if(it->key == key){ buckets[index].erase(it); cout<<"Done"<<endl; inArray = true; } i++; } if(!inArray){ cout<<"Not in system"<<endl; } } int HashTable::getSize() { return this->size; } int HashTable::getCollisions() { return this->collisions; } HashTable::~HashTable() { delete[] buckets; } int main(void) { ifstream fin; fin.open("zipcodes.csv"); if(!fin){ cout<<"Can not open the file <zipcodes.txt>...!"<<endl; exit(-1); } string line; HashTable myHashTable(24851);// Prime number bigger than >24850 (19880*1.25); getline(fin,line); //skip first line while(!fin.eof()) { string key, value; getline(fin,key,','); getline(fin,value); cout<<key<<":"<<value<<endl; myHashTable.insert(key,value); } fin.close(); cout<<"Hash Table size = "<<myHashTable.getSize()<<endl; cout<<"Total Number of Collisions = "<<myHashTable.getCollisions()<<endl; cout<<"Avg. Number of Collisions Per Entry = "<<float(myHashTable.getCollisions())/myHashTable.getSize()<<endl; string user_input, command, argument1, argument2; while(true) { cout<<">"; getline(cin,user_input); stringstream sstr(user_input); getline(sstr,command,' '); getline(sstr,argument1,','); getline(sstr,argument2); if(command == "search") cout<<"Zip code for "<<argument1<<" is: "<<myHashTable.search(argument1)<<endl; else if(command == "insert") {myHashTable.insert(argument1,argument2);} //Uncomment following line for the Task 3 else if(command == "erase") myHashTable.erase(argument1); else if(command == "help") cout<<"Commands available \ninsert <key,value>\nsearch <key>\nerase <key>"<<endl; else if(command == "exit") break; else cout<<"Invalid command !!!"<<endl; } return 0; }
import sys import torch as th from lib.ChamferDistancePytorch.chamfer3D.dist_chamfer_3D import chamfer_3DDist from lib.PyTorchEMD.emd import earth_mover_distance as EMD from pytorch3d.ops import knn_points, sample_points_from_meshes from pytorch3d.structures import Meshes from src.utils import BlackHole from torch_scatter import scatter_sum from tqdm import tqdm, trange cham3D = chamfer_3DDist() class PointDist: def __init__(self, a, b) -> None: """ :params a: b n 3 :params b: b n 3 """ self.a = a self.b = b self._knn_done = False def _calc_knn(self): self._dist1, _, self._knn1 = knn_points(self.a, self.b, return_nn=True, return_sorted=False) self._dist2, _, self._knn2 = knn_points(self.b, self.a, return_nn=True, return_sorted=False) # dists: b n 1 # knn: b n 1 3 def chamfer_l1(self, reduction="mean"): if not self._knn_done: self._calc_knn() if reduction == "mean": d1 = (self.a - self._knn1[:, :, 0]).abs().sum(dim=-1).mean() d2 = (self.b - self._knn2[:, :, 0]).abs().sum(dim=-1).mean() elif reduction == "batchmean": d1 = (self.a - self._knn1[:, :, 0]).abs().sum(dim=-1).flatten(1).mean(1) d2 = (self.b - self._knn2[:, :, 0]).abs().sum(dim=-1).flatten(1).mean(1) return d1 + d2 def chamfer_l1_legacy(self, reduction="mean"): if not self._knn_done: self._calc_knn() if reduction == "mean": d1 = (self.a - self._knn1[:, :, 0]).square().sum(dim=-1).sqrt().mean() d2 = (self.b - self._knn2[:, :, 0]).square().sum(dim=-1).sqrt().mean() elif reduction == "batchmean": d1 = (self.a - self._knn1[:, :, 0]).square().sum(dim=-1).sqrt().flatten(1).mean(1) d2 = (self.b - self._knn2[:, :, 0]).square().sum(dim=-1).sqrt().flatten(1).mean(1) return d1 + d2 def chamfer_l2(self, reduction="mean"): if not self._knn_done: self._calc_knn() if reduction == "mean": d1 = self._dist1.mean() d2 = self._dist2.mean() return d1 + d2 elif reduction == "batchmean": d1 = self._dist1.flatten(1).mean(1) d2 = self._dist2.flatten(1).mean(1) return d1 + d2 else: raise NotImplementedError(reduction) def recall(self, threshold=1e-3): if not self._knn_done: self._calc_knn() return (self._dist1.flatten(1) < threshold).float().mean(1) # b def precision(self, threshold=1e-3): if not self._knn_done: self._calc_knn() return (self._dist2.flatten(1) < threshold).float().mean(1) # b def f1(self, threshold=1e-3, reduction="mean"): r = self.recall(threshold) # b p = self.precision(threshold) # b f1 = 2 * r * p / (r + p) # b f1.nan_to_num_(0, 0, 0) if reduction == "mean": return f1.mean() elif reduction == "batchmean": return f1 else: raise NotImplementedError(reduction) def emd(self, reduction="mean"): dist = EMD(self.a, self.b, transpose=False) # b if reduction == "mean": return dist.mean() elif reduction == "batchmean": return dist else: raise NotImplementedError(reduction) ############################################################################ # evaluation code from PVD # https://github.com/alexzhou907/PVD ############################################################################ def iou(a: th.Tensor, b: th.Tensor, res: int, reduction="mean"): """ - input: - a: b n 3, [0, 1] - b: b m 3, [0, 1] """ a = (a * res + (0.5 / res)).clamp_(0, res - 1).long() b = (b * res + (0.5 / res)).clamp_(0, res - 1).long() a = a[..., 0] + a[..., 1] * res + a[..., 2] * res**2 # b n b = b[..., 0] + b[..., 1] * res + b[..., 2] * res**2 # b m a = scatter_sum(th.ones_like(a), a, 1, dim_size=res**3) > 0 # b (r r r), bool b = scatter_sum(th.ones_like(b), b, 1, dim_size=res**3) > 0 # b (r r r), bool union = (a | b).sum(1) # b inter = (a & b).sum(1) # b score = (inter / union).nan_to_num_(0, 0, 0) if reduction == "mean": return score.mean() elif reduction == "batchmean": return score def sdf_iou(a: th.Tensor, b: th.Tensor, reduction="mean"): """ - a, b: b 1 r r r """ a = a < 0 b = b < 0 union = (a | b).flatten(1).sum(1) # b inter = (a & b).flatten(1).sum(1) # b score = (inter / union).nan_to_num_(0, 0, 0) if reduction == "mean": return score.mean() elif reduction == "batchmean": return score def lgan_mmd_cov(all_dist): N_sample, N_ref = all_dist.size(0), all_dist.size(1) min_val_fromsmp, min_idx = th.min(all_dist, dim=1) min_val, _ = th.min(all_dist, dim=0) mmd = min_val.mean() mmd_smp = min_val_fromsmp.mean() cov = float(min_idx.unique().view(-1).size(0)) / float(N_ref) cov = th.tensor(cov).to(all_dist) return { "lgan_mmd": mmd, "lgan_cov": cov, "lgan_mmd_smp": mmd_smp, } # Adapted from https://github.com/xuqiantong/GAN-Metrics/blob/master/framework/metric.py def knn(Mxx, Mxy, Myy, k, sqrt=False): dev = Mxx.device n0 = Mxx.size(0) n1 = Myy.size(0) label = th.cat((th.ones(n0, device=dev), th.zeros(n1, device=dev))) M = th.cat((th.cat((Mxx, Mxy), 1), th.cat((Mxy.transpose(0, 1), Myy), 1)), 0) if sqrt: M = M.abs().sqrt() INFINITY = float("inf") val, idx = (M + th.diag(INFINITY * th.ones(n0 + n1, device=dev))).topk(k, 0, False) count = th.zeros(n0 + n1, device=dev) for i in range(0, k): count = count + label.index_select(0, idx[i]) pred = th.ge(count, (float(k) / 2) * th.ones(n0 + n1, device=dev)).float() s = { "tp": (pred * label).sum(), "fp": (pred * (1 - label)).sum(), "fn": ((1 - pred) * label).sum(), "tn": ((1 - pred) * (1 - label)).sum(), } s.update( { "precision": s["tp"] / (s["tp"] + s["fp"] + 1e-10), "recall": s["tp"] / (s["tp"] + s["fn"] + 1e-10), "acc_t": s["tp"] / (s["tp"] + s["fn"] + 1e-10), "acc_f": s["tn"] / (s["tn"] + s["fp"] + 1e-10), "acc": th.eq(label, pred).float().mean(), } ) return s def _pairwise_EMD_CD_(sample_pcs, ref_pcs, batch_size, show_pbar=False): N_sample = sample_pcs.shape[0] N_ref = ref_pcs.shape[0] all_cd = [] all_emd = [] pbar = tqdm(total=N_sample) if show_pbar else BlackHole() for sample_b_start in range(N_sample): sample_batch = sample_pcs[sample_b_start].cuda(non_blocking=True) cd_lst = [] emd_lst = [] for ref_b_start in range(0, N_ref, batch_size): ref_b_end = min(N_ref, ref_b_start + batch_size) ref_batch = ref_pcs[ref_b_start:ref_b_end].cuda(non_blocking=True) batch_size_ref = ref_batch.size(0) # sample_batch_exp = sample_batch.view(1, -1, 3).expand(batch_size_ref, -1, -1) sample_batch_exp = sample_batch[None].repeat(batch_size_ref, 1, 1) sample_batch_exp = sample_batch_exp.contiguous() dl, dr, _, _ = cham3D(sample_batch_exp, ref_batch) cd = (dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1) # cd = th.rand(1, batch_size_ref, device="cuda") cd_lst.append(cd) emd_batch = EMD(sample_batch_exp, ref_batch, transpose=False).view(1, -1) # emd_batch = th.rand(1, batch_size_ref, device="cuda") emd_lst.append(emd_batch) cd_lst = th.cat(cd_lst, dim=1) emd_lst = th.cat(emd_lst, dim=1) all_cd.append(cd_lst) all_emd.append(emd_lst) pbar.update() pbar.close() all_cd = th.cat(all_cd, dim=0) # N_sample, N_ref all_emd = th.cat(all_emd, dim=0) # N_sample, N_ref return all_cd, all_emd def compute_all_dists(sample_pcs, ref_pcs, batch_size, show_pbar=False): M_rs_cd, M_rs_emd = _pairwise_EMD_CD_(ref_pcs, sample_pcs, batch_size, show_pbar=show_pbar) # n_ref, n_sample M_rr_cd, M_rr_emd = _pairwise_EMD_CD_(ref_pcs, ref_pcs, batch_size, show_pbar=show_pbar) # n_ref, n_ref M_ss_cd, M_ss_emd = _pairwise_EMD_CD_(sample_pcs, sample_pcs, batch_size, show_pbar=show_pbar) # n_sample, n_sample return M_rs_cd, M_rs_emd, M_rr_cd, M_rr_emd, M_ss_cd, M_ss_emd def compute_all_metrics(M_rs_cd, M_rs_emd, M_rr_cd, M_rr_emd, M_ss_cd, M_ss_emd): results = {} res_cd = lgan_mmd_cov(M_rs_cd.t()) results.update({"%s-CD" % k: v for k, v in res_cd.items()}) res_emd = lgan_mmd_cov(M_rs_emd.t()) results.update({"%s-EMD" % k: v for k, v in res_emd.items()}) one_nn_cd_res = knn(M_rr_cd, M_rs_cd, M_ss_cd, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in one_nn_cd_res.items() if "acc" in k}) one_nn_emd_res = knn(M_rr_emd, M_rs_emd, M_ss_emd, 1, sqrt=False) results.update({"1-NN-EMD-%s" % k: v for k, v in one_nn_emd_res.items() if "acc" in k}) return results def pairwise_cd(xs, ys, b): n, m = len(xs), len(ys) cd_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_cd"): x = xs[i, None].cuda(non_blocking=True) # 1 n 3 cd_lst = [] for j in range(0, m, b): b_ = min(m - j, b) y = ys[j : j + b_].cuda(non_blocking=True) # b n 3 dl, dr, _, _ = cham3D(x.repeat(b_, 1, 1).contiguous(), y.contiguous()) # b n, b n cd = (dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1) # 1 b cd_lst.append(cd) cd_lst = th.cat(cd_lst, dim=1) # 1 m cd_all.append(cd_lst) cd_all = th.cat(cd_all, dim=0) # n m return cd_all def unpairwise_cd(xs, ys, xsx, ysx, b): # ~x is sparser one n, m = len(xs), len(ys) cd_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_cd"): x_d = xs[i, None].cuda(non_blocking=True) # 1 n 3 x_s = xsx[i, None].cuda(non_blocking=True) cd_lst = [] for j in range(0, m, b): b_ = min(m - j, b) y_d = ys[j : j + b_].cuda(non_blocking=True) # b n 3 y_s = ysx[j : j + b_].cuda(non_blocking=True) # b n 3 dl, _, _, _ = cham3D(x_s.repeat(b_, 1, 1).contiguous(), y_d.contiguous()) # b n, b n _, dr, _, _ = cham3D(x_d.repeat(b_, 1, 1).contiguous(), y_s.contiguous()) # b n, b n cd = (dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1) # 1 b cd_lst.append(cd) cd_lst = th.cat(cd_lst, dim=1) # 1 m cd_all.append(cd_lst) cd_all = th.cat(cd_all, dim=0) # n m return cd_all def pairwise_emd(xs, ys, b): n, m = len(xs), len(ys) emd_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_emd"): x = xs[i, None].cuda(non_blocking=True) # 1 n 3 emd_lst = [] for j in range(0, m, b): b_ = min(m - j, b) y = ys[j : j + b_].cuda(non_blocking=True) # b n 3 emd = EMD(x.repeat(b_, 1, 1).contiguous(), y.contiguous(), transpose=False).view(1, -1) # 1 b emd_lst.append(emd) emd_lst = th.cat(emd_lst, dim=1) # 1 m emd_all.append(emd_lst) emd_all = th.cat(emd_all, dim=0) # n m return emd_all def pairwise_mesh_to_point(xs, ys, b): n, m = len(xs), len(ys) cd_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_cd"): x = xs[i, None].cuda(non_blocking=True) # 1 n 3 cd_lst = [] for j in range(0, m, b): b_ = min(m - j, b) y = ys[j : j + b_].cuda(non_blocking=True) # b n 3 dl, dr, _, _ = cham3D(x.repeat(b_, 1, 1).contiguous(), y.contiguous()) # b n, b n cd = (dl.mean(dim=1) + dr.mean(dim=1)).view(1, -1) # 1 b cd_lst.append(cd) cd_lst = th.cat(cd_lst, dim=1) # 1 m cd_all.append(cd_lst) cd_all = th.cat(cd_all, dim=0) # n m return cd_all def compute_metric_cd(xs, ys, b): rs = pairwise_cd(ys, xs, b) rr = pairwise_cd(ys, ys, b) ss = pairwise_cd(xs, xs, b) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-CD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results def compute_metric_ucd(xs, ys, xsx, ysx, b): rs = unpairwise_cd(xs, ys, xsx, ysx, b) rr = pairwise_cd(ys, ys, b) ss = pairwise_cd(xsx, xsx, b) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-CD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results def compute_metric_emd(xs, ys, b): rs = pairwise_emd(ys, xs, b) rr = pairwise_emd(ys, ys, b) ss = pairwise_emd(xs, xs, b) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-EMD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-EMD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results def compute_metric_all(xs, ys, b): results_cd = compute_metric_cd(xs, ys, b) results_emd = compute_metric_emd(xs, ys, b) results = {} results.update(results_cd) results.update(results_emd) return results ############################################################################ # point to triangle distance # https://github.com/wang-ps/mesh2sdf/blob/master/csrc/makelevelset3.cpp#L19 ############################################################################ def mag2(x): return x.square().sum(dim=-1, keepdim=True) def dot(a, b): return (a * b).sum(dim=-1, keepdim=True) def point_segment_distance(x0, x1, x2): dx = x2 - x1 m2 = mag2(dx) # s12 = dot(x2 - x0, dx) / m2 s12 = dot(x2 - x0, dx) / m2.clamp(min=1e-30) s12.clamp_(0.0, 1.0) return (x0 - (s12 * x1 + (1 - s12) * x2)).square().sum(dim=-1, keepdim=True) def point_triangle_distance(x0, x1, x2, x3): # warn! return is squared distance # x: ... 3 x13, x23, x03 = x1 - x3, x2 - x3, x0 - x3 m13, m23, d = mag2(x13), mag2(x23), dot(x13, x23) invdet = 1.0 / (m13 * m23 - d * d).clamp(min=1e-30) a, b = dot(x13, x03), dot(x23, x03) w23 = invdet * (m23 * a - d * b) # ... w31 = invdet * (m13 * b - d * a) w12 = 1 - w23 - w31 dist = x0.new_zeros(*x0.shape[:-1], 1) # ... 1 mask0 = (w23 >= 0) & (w31 >= 0) & (w12 >= 0) mask1 = (w23 > 0) & ~mask0 mask2 = (w31 > 0) & ~(mask0 & mask1) mask3 = ~(mask0 & mask1 & mask2) u0 = point_segment_distance(x0, x1, x2) u1 = point_segment_distance(x0, x1, x3) u2 = point_segment_distance(x0, x2, x3) dist += (x0 - (w23 * x1 + w31 * x2 + w12 * x3)).square().sum(dim=-1, keepdim=True) * mask0 dist += th.cat([u0, u1], dim=-1).amin(dim=-1, keepdim=True) * mask1 dist += th.cat([u0, u2], dim=-1).amin(dim=-1, keepdim=True) * mask2 dist += th.cat([u1, u1], dim=-1).amin(dim=-1, keepdim=True) * mask3 return dist[..., 0] # ... def point_to_mesh_distance(x, v, f): # x: points n 3 # v: vertices m 3 # f: faces l 3, long or int # return: n l fv = v.gather(0, f.long().flatten()[:, None].repeat(1, 3)).view(-1, 3, 3) # l 3 3 fv = fv[None].repeat(x.size(0), 1, 1, 1) # n l 3 3 xx = x[:, None].repeat(1, f.size(0), 1) # n l 3 return point_triangle_distance(xx, *fv.unbind(dim=2)) def pairwise_p2m(xs, ys, n_pts=None): # xs: b n_pts 3 # ys: meshes list of (verts, faces) x m n, m = len(xs), len(ys) n_pts = n_pts or xs[0].size(0) # sample points from meshes(ys) ypts = [] for i in range(m): yv = ys[i][0].float().cuda(non_blocking=True) # n_verts 3 yf = ys[i][1].long().cuda(non_blocking=True) # n_faces 3 ymesh = Meshes([yv], [yf]) ypt = sample_points_from_meshes(ymesh, n_pts) # 1 n_pts 3 ypts.append(ypt) ypts = th.cat(ypts) # m n_pts 3 dist_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_p2m"): x = xs[i] # n_pts 3 dist_lst = [] for j in range(m): yv = ys[j][0].float().cuda(non_blocking=True) # n_verts 3 yf = ys[j][1].long().cuda(non_blocking=True) # n_faces 3 y = ypts[j] # n_pts 3 dl = point_to_mesh_distance(x, yv, yf) # n_pts n_faces dl = dl.amin(dim=-1).mean().view(1, 1) # 1 1 dr, *_ = knn_points(x[None], y[None]) dr = dr[0, :, 0].mean().view(1, 1) dist = dl + dr # 1 1 dist_lst.append(dist) dist_lst = th.cat(dist_lst, dim=1) # 1 m dist_all.append(dist_lst) dist_all = th.cat(dist_all, dim=0) # n m return dist_all def pairwise_m2m(xs, ys, n_pts): # xs: meshes list of (verts, faces) x m # ys: meshes list of (verts, faces) x m n, m = len(xs), len(ys) # sample points from meshes(xs) xpts = [] for i in range(n): xv = xs[i][0].float().cuda(non_blocking=True) # n_verts 3 xf = xs[i][1].long().cuda(non_blocking=True) # n_faces 3 xmesh = Meshes([xv], [xf]) xpt = sample_points_from_meshes(xmesh, n_pts) # 1 n_pts 3 xpts.append(xpt) xpts = th.cat(xpts) # n n_pts 3 # sample points from meshes(ys) ypts = [] for i in range(m): yv = ys[i][0].float().cuda(non_blocking=True) # n_verts 3 yf = ys[i][1].long().cuda(non_blocking=True) # n_faces 3 ymesh = Meshes([yv], [yf]) ypt = sample_points_from_meshes(ymesh, n_pts) # 1 n_pts 3 ypts.append(ypt) ypts = th.cat(ypts) # m n_pts 3 dist_all = [] for i in trange(n, ncols=100, file=sys.stdout, desc="pairwise_m2m"): xv = xs[i][0].float().cuda(non_blocking=True) # n_verts 3 xf = xs[i][1].long().cuda(non_blocking=True) # n_faces 3 x = xpts[i] # n_pts 3 dist_lst = [] for j in range(m): yv = ys[j][0].float().cuda(non_blocking=True) # n_verts 3 yf = ys[j][1].long().cuda(non_blocking=True) # n_faces 3 y = ypts[j] # n_pts 3 dl = point_to_mesh_distance(x, yv, yf) # n_pts n_faces dl = dl.amin(dim=-1).mean().view(1, 1) # 1 1 dr = point_to_mesh_distance(y, xv, xf) # n_pts n_faces dr = dr.amin(dim=-1).mean().view(1, 1) dist = dl + dr # 1 1 dist_lst.append(dist) dist_lst = th.cat(dist_lst, dim=1) # 1 m dist_all.append(dist_lst) dist_all = th.cat(dist_all, dim=0) # n m return dist_all def compute_metric_p2m(xs, ys, b, n_pts=None): """ - xs: (sample) b n 3 - ys: (reference) list of meshes (verts, faces) """ n_pts = n_pts or xs[0].size(0) rs = pairwise_p2m(xs, ys, n_pts=n_pts) rr = pairwise_m2m(ys, ys, n_pts=n_pts) ss = pairwise_cd(xs, xs, b) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-CD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results def compute_metric_m2p(xs, ys, b, n_pts=None): """ - xs: (reference) list of meshes (verts, faces) - ys: (sample) b n 3 """ n_pts = n_pts or xs[0].size(0) rs = pairwise_p2m(ys, xs, n_pts=n_pts) rr = pairwise_cd(ys, ys, b) ss = pairwise_m2m(xs, xs, n_pts=n_pts) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-CD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results def compute_metric_m2m(xs, ys, b, n_pts=None): """ - xs: (sample) list of meshes (verts, faces) - ys: (reference) list of meshes (verts, faces) """ n_pts = n_pts or xs[0].size(0) rs = pairwise_m2m(xs, ys, n_pts=n_pts) rr = pairwise_m2m(ys, ys, n_pts=n_pts) ss = pairwise_m2m(xs, xs, n_pts=n_pts) results = {} res_mmd = lgan_mmd_cov(rs.T) results.update({"%s-CD" % k: v for k, v in res_mmd.items()}) res_1nn = knn(rr, rs, ss, 1, sqrt=False) results.update({"1-NN-CD-%s" % k: v for k, v in res_1nn.items() if "acc" in k}) return results
<?php namespace App\Controllers; use App\Controllers\BaseController; use CodeIgniter\HTTP\ResponseInterface; class Login extends BaseController { public function index() { return view('halaman-login'); } public function prosesLogin() { $validation = \Config\Services::validation(); $rules = [ 'email' => 'required', 'password' => 'required', ]; $messages = [ 'email' => [ 'required' => 'Masukan email anda!', ], 'password' => [ 'required' => 'Masukan password anda!', ], ]; // set validasi $validation->setRules($rules, $messages); // cek validasi gagal if (!$validation->withRequest($this->request)->run()) { return redirect()->back()->withInput()->with('errors', $validation->getErrors()); } $validasiForm = [ 'email' => 'required', 'password' => 'required' ]; if ($this->validate($validasiForm)) { $pengguna = $this->pengguna->getPengguna( $this->request->getPost('email'), $this->request->getPost('password') ); if (count($pengguna) == 1) { $dataSession = [ 'email' => $pengguna[0]['email'], 'username' => $pengguna[0]['username'], 'nama_user' => $pengguna[0]['nama_user'], 'password' => $pengguna[0]['password'], 'level' => $pengguna[0]['level'], 'sudahkahLogin' => true ]; session()->set($dataSession); } if (session()->get('level') === 'Admin') { return redirect()->to('/halaman-admin'); } else if (session()->get('level') === 'Kasir') { return redirect()->to('/halaman-kasir'); } else { return redirect()->to('/')->with('pesan', '<div class="text-center mt-3 font-weight-bold`"><p class="text-danger fw-bold">Email atau Password salah harap cek kembali</p></div>'); } } } public function logout() { session()->destroy(); return redirect()->to('/'); } }
package com.codingdojo.loginAndRegistration.models; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @NotEmpty(message="Username is required") @Size(min=3, max=200, message="Username must be between 3 and 200 characters") private String userName; @NotEmpty(message="Email is required") @Email(message="Email must be between 3 and 200 characters") private String email; @NotEmpty(message="Password is required") @Size(min=8, max=200, message="Password must be between 8 and 200 characters") private String password; @Transient @NotEmpty(message="Confirm Password is required") @Size(min=8, max=200, message="Confirm must be between 8 and 200 characters") private String confirm; @DateTimeFormat(pattern="yyyy-MM-dd") private Date createdAt; @DateTimeFormat(pattern="yyyy-MM-dd") private Date updatedAt; public User() { // TODO Auto-generated constructor stub } // public User(String userName, String email, String password) { // this.userName = userName; // this.email = email; // this.password = password; // } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } @PrePersist protected void onCreate() { this.createdAt = new Date(); } @PreUpdate protected void onUpdate() { this.updatedAt = new Date(); } }
import express from 'express'; import dotenv from 'dotenv'; dotenv.config(); import routes from './routes/index.js' import morgan from 'morgan'; const helmet = require('helmet'); import { boomErrorHandler, errorHandler, logErrors } from './middlewares/error.handler.js'; import cors from 'cors' import connection from './db/connect.js'; connection(); const app = express(); app.use(express.json({limit: '50mb'})) app.use(express.urlencoded({limit:'50mb', extended: true})) const localHost= 'http://localhost:3001' const whiteList = [process.env.URL, localHost]; const options = { origin: (origin, callback) => { if(whiteList.includes(origin) || whiteList.includes(localHost)){ callback(null, true); }else{ callback(new Error('no permitido!')); } } } app.use( cors(options) ) app.use(helmet()) app.use(morgan('tiny')); app.use('/', routes); app.use(logErrors); app.use(boomErrorHandler) app.use(errorHandler); app.listen(process.env.PORT, ()=> console.log('Server run on port ', process.env.PORT))
/* * ledmag - Display portion of screen on a LED-Setup using libniftyled * Copyright (C) 2006-2014 Daniel Hiepler <daniel@niftylight.de> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #ifdef HAVE_IMLIB #include <X11/Xutil.h> #include <X11/Xlib.h> #include <Imlib2.h> #include <niftyled.h> #include "capture.h" /** private structure to hold info accros function-calls */ static struct { Display *display; Visual *visual; Screen *screen; Colormap colormap; int depth; Window root; } _c; /** * capture image at x/y and store in frame */ static NftResult _capture(LedFrame * frame, LedFrameCord x, LedFrameCord y) { if(!frame) NFT_LOG_NULL(NFT_FAILURE); /* get frame dimensions */ LedFrameCord w, h; if(!led_frame_get_dim(frame, &w, &h)) return NFT_FAILURE; /* get screen-portion from X server */ XImage *image = NULL; if(! (image = XGetImage(_c.display, _c.root, x, y, w, h, AllPlanes, ZPixmap))) { NFT_LOG(L_ERROR, "Failed to capture XImage"); return NFT_FAILURE; } /* convert image to 32 bit RGB */ Imlib_Image *iimg; if(! (iimg = imlib_create_image_from_ximage(image, NULL, 0, 0, w, h, true))) { NFT_LOG(L_ERROR, "Failed to create Imlib_Image from XImage"); return NFT_FAILURE; } /* get data */ DATA32 *data; imlib_context_set_image(iimg); if(!(data = imlib_image_get_data_for_reading_only())) { NFT_LOG(L_ERROR, "Failed to get data from Imlib_Image"); return NFT_FAILURE; } /* copy data to our frame */ memcpy(led_frame_get_buffer(frame), data, led_frame_get_buffersize(frame)); /* if(!led_frame_buffer_convert(frame, data, "RGBA u8", * led_frame_get_width(frame)* led_frame_get_height(frame))) return * NFT_FAILURE; */ /* destroy images */ imlib_free_image(); XDestroyImage(image); return NFT_SUCCESS; } /** * return prefered frame format */ static const char *_format() { return "ARGB u8"; } /** * return whether capture mechanism delivers big-endian ordered data */ static bool _is_big_endian() { /* we'll always get big-endian data from imlib */ return true; } /** * initialize capture mechanism */ static NftResult _init() { if(!(_c.display = XOpenDisplay(NULL))) { NFT_LOG(L_ERROR, "Can't open X display."); return NFT_FAILURE; } _c.screen = ScreenOfDisplay(_c.display, DefaultScreen(_c.display)); _c.visual = DefaultVisual(_c.display, XScreenNumberOfScreen(_c.screen)); _c.depth = DefaultDepth(_c.display, XScreenNumberOfScreen(_c.screen)); _c.colormap = DefaultColormap(_c.display, XScreenNumberOfScreen(_c.screen)); _c.root = RootWindow(_c.display, XScreenNumberOfScreen(_c.screen)); imlib_context_set_display(_c.display); imlib_context_set_visual(_c.visual); imlib_context_set_colormap(_c.colormap); imlib_context_set_color_modifier(NULL); imlib_context_set_operation(IMLIB_OP_COPY); return NFT_SUCCESS; } /** * deinitialize capture mechanism */ static void _deinit() { /* close X display */ if(_c.display) XCloseDisplay(_c.display); } /** descriptor of this mechanism */ CaptureMechanism IMLIB = { .name = "Imlib2", .init = _init, .deinit = _deinit, .capture = _capture, .format = _format, .is_big_endian = _is_big_endian, }; #endif /* HAVE_IMLIB */
//------------------------------------------------------------------------ // Project : SDK Base // Version : 1.0 // // Category : Helpers // Filename : base/source/fobject.cpp // Created by : Steinberg, 2008 // Description : Basic Object implementing FUnknown // //----------------------------------------------------------------------------- // LICENSE // (c) 2018, Steinberg Media Technologies GmbH, All Rights Reserved //----------------------------------------------------------------------------- // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "base/source/fobject.h" #include "base/thread/include/flock.h" #include <vector> namespace Steinberg { IUpdateHandler* FObject::gUpdateHandler = 0; //------------------------------------------------------------------------ const FUID FObject::iid; //------------------------------------------------------------------------ struct FObjectIIDInitializer { // the object iid is always generated so that different components // only can cast to their own objects // this initializer must be after the definition of FObject::iid, otherwise // the default constructor of FUID will clear the generated iid FObjectIIDInitializer () { const_cast<FUID&> (FObject::iid).generate (); } } gFObjectIidInitializer; //------------------------------------------------------------------------ uint32 PLUGIN_API FObject::addRef () { return FUnknownPrivate::atomicAdd (refCount, 1); } //------------------------------------------------------------------------ uint32 PLUGIN_API FObject::release () { if (FUnknownPrivate::atomicAdd (refCount, -1) == 0) { refCount = -1000; delete this; return 0; } return refCount; } //------------------------------------------------------------------------ tresult PLUGIN_API FObject::queryInterface (const TUID _iid, void** obj) { QUERY_INTERFACE (_iid, obj, FUnknown::iid, FUnknown) QUERY_INTERFACE (_iid, obj, IDependent::iid, IDependent) QUERY_INTERFACE (_iid, obj, FObject::iid, FObject) *obj = 0; return kNoInterface; } //------------------------------------------------------------------------ void FObject::addDependent (IDependent* dep) { if (gUpdateHandler) gUpdateHandler->addDependent (unknownCast (), dep); } //------------------------------------------------------------------------ void FObject::removeDependent (IDependent* dep) { if (gUpdateHandler) gUpdateHandler->removeDependent (unknownCast (), dep); } //------------------------------------------------------------------------ void FObject::changed (int32 msg) { if (gUpdateHandler) gUpdateHandler->triggerUpdates (unknownCast (), msg); else updateDone (msg); } //------------------------------------------------------------------------ void FObject::deferUpdate (int32 msg) { if (gUpdateHandler) gUpdateHandler->deferUpdates (unknownCast (), msg); else updateDone (msg); } //------------------------------------------------------------------------ /** Automatic creation and destruction of singleton instances. */ //------------------------------------------------------------------------ namespace Singleton { typedef std::vector<FObject**> ObjectVector; ObjectVector* singletonInstances = 0; bool singletonsTerminated = false; Steinberg::Base::Thread::FLock* singletonsLock; bool isTerminated () {return singletonsTerminated;} void lockRegister () { if (!singletonsLock) // assume first call not from multiple threads singletonsLock = NEW Steinberg::Base::Thread::FLock; singletonsLock->lock (); } void unlockRegister () { singletonsLock->unlock (); } void registerInstance (FObject** o) { SMTG_ASSERT (singletonsTerminated == false) if (singletonsTerminated == false) { if (singletonInstances == 0) singletonInstances = NEW std::vector<FObject**>; singletonInstances->push_back (o); } } struct Deleter { ~Deleter () { singletonsTerminated = true; if (singletonInstances) { for (ObjectVector::iterator it = singletonInstances->begin (), end = singletonInstances->end (); it != end; ++it) { FObject** obj = (*it); (*obj)->release (); *obj = 0; obj = 0; } delete singletonInstances; singletonInstances = 0; } delete singletonsLock; singletonsLock = 0; } } deleter; } //------------------------------------------------------------------------ } // namespace Steinberg
import React from "react"; import { FaTicketAlt } from "react-icons/fa"; const Cart = ({ tickets }) => { const getSportIcon = (evenement) => { switch (evenement) { case "Athlétisme": return ( <img className="object-cover size-[200px]" src="src\evenements\atle.jpg" alt="" /> ); case "Natation": return ( <img className="object-cover size-[200px]" src="src\evenements\nata.jpg" alt="" /> ); case "Basketball": return ( <img className="object-cover size-[200px]" src="src\evenements\bask.jpg" alt="" /> ); case "Football": return ( <img className="object-cover size-[200px]" src="src\evenements\foot.jpg" alt="" /> ); case "Tennis": return ( <img className="size-[200px] object-cover" src="src\evenements\tenn.jpg" alt="" /> ); case "Gymnastique": return ( <img className="object-cover size-[200px]" src="src\evenements\gym.jpg" alt="" /> ); case "Cyclisme": return ( <img className="object-cover size-[200px]" src="src\evenements\cyc.jpg" alt="" /> ); case "Escalade": return ( <img className="object-cover size-[200px]" src="src\evenements\rock.jpeg" alt="" /> ); case "Haltérophilie": return ( <img className="object-cover size-[200px]" src="src\evenements\pwr.jpg" alt="" /> ); case "Judo": return ( <img className="object-cover size-[200px]" src="src\evenements\judo.jpg" alt="" /> ); default: return <FaTicketAlt className="text-yellow-500 text-4xl" />; } }; if (tickets.length === 0) { return null; } return ( <div className="cart-container mx-auto w-[900px] bg-slate-200 overflow-auto max-h-[500px] rounded-lg"> <div className="amount-and-buy-box p-3 items-center flex justify-between border-2 "> <h2 className="text-3xl font-semibold text-gray-800 flex justify-between items-center"> Vos billets: {tickets.length} </h2> <button className="bg-slate-200 border-[1px] border-black hover:bg-green-400 text-xl py-1 px-4 h-fit rounded-xl font-bold"> Acheter! </button> </div> <div className="p-2"> {tickets.map((ticket, index) => ( <div key={index} className="flex items-center justify-between border-2 bg-white p-4 mb-4 rounded-lg shadow-md" style={{ minWidth: "400px" }} > <FaTicketAlt className="text-yellow-500 text-4xl" /> <div className="ticket-info-box border-2 grid grid-cols-3 gap-3"> <p className="text-xl font-semibold text-gray-800"> {ticket.prenom} {ticket.nom} </p> <p className="text-lg text-gray-600">Ville: {ticket.ville}</p> <p className="text-lg text-gray-600"> Depuis le: {ticket.depuisDate} </p> <p className="text-lg text-gray-600">Arène: {ticket.arena}</p> <p className="text-lg text-gray-600"> Événement: {ticket.evenement} </p> <p className="text-lg text-gray-600"> Jusqu'au: {ticket.jusquauDate} </p> </div> <div className="rounded-2xl border-2 overflow-hidden "> {getSportIcon(ticket.evenement)} </div> </div> ))} </div> </div> ); }; export default Cart;
class Post < ApplicationRecord has_rich_text :hello validates :title, presence: true validates :serial, uniqueness: true belongs_to :board belongs_to :user has_many :comments has_one_attached :photo before_create :create_serial def display_username if user.nil? "-" else user.account end end private def create_serial self.serial = serial_generator(10) end def serial_generator(n) [*'a'..'z', *'A'..'Z', *0..9].sample(n).join end end
import { Alert, Autocomplete, Avatar, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Fab, Grid, Snackbar, } from '@mui/material'; import AddAPhotoIcon from '@mui/icons-material/AddAPhoto'; import { useEffect, useState } from 'react'; import { getCategory, getCategoryShowProduct, handleChangeCategory, handleChangeSubcategory, } from 'app/redux/actions/CategoryAction'; import { PropTypes } from 'prop-types'; import { connect } from 'react-redux'; import { getBrandProduct, handleChangeBrand, } from 'app/redux/actions/BrandAction'; import { getPromotionProductWithPromotionId, handleChangePromotion, } from 'app/redux/actions/PromotionAction'; import DialogConfirm from './DialogConfirm'; import { putProduct } from 'app/redux/actions/ProductAction'; import axios from 'axios.js'; import { v4 as uuidv4 } from 'uuid'; import { TextField } from './DialogCreateProduct'; import { ValidatorForm } from 'react-material-ui-form-validator'; import { deleteFieldNotBelongProductForm } from './DialogCreateProduct'; function DialogProduct({ open, products = {}, handleClose, ...props }) { const [image, setImage] = useState(); const [file, setFile] = useState({}); const [openConfirm, setOpenConfirm] = useState(false); const [openSnackBar, setOpenSnackBar] = useState(false); const [load, setLoad] = useState(false); const handleClickOpenConfirm = () => { setOpenConfirm(true); }; const handleCloseConfirm = () => { setOpenConfirm(false); }; // const [category, setCategory] = useState([{}]); const [formProduct, setFormProduct] = useState({ product_name: '', category_id: '', brand_id: '', promotion_id: '', image: '', description: '', id: '', category_parent: '', }); //clean up img useEffect(() => { return () => { image && URL.revokeObjectURL(image); }; }, [image]); const handleUpload = (e) => { const file = e.target.files[0]; let blob = file.slice(0, file.size, 'image/png'); let newFile = new File([blob], formProduct.image, { type: 'image/png', }); const formData = new FormData(); formData.append('file', newFile); setFile(formData); setImage(URL.createObjectURL(file)); }; const { getCategory, categories, brands, getBrandProduct, promotions, getPromotionProductWithPromotionId, getCategoryShowProduct, handleChangeCategory, handleChangeSubcategory, putProduct, handleChangeBrand, handleChangePromotion, } = props; useEffect(() => { getCategory(); if (Object.keys(products).length !== 0) { setImage( process.env.REACT_APP_BASE_URL_FIREBASE + products.image + '?alt=media&token=' + uuidv4(), ); setFormProduct({ product_name: products.product_name, category_id: products.category_id, brand_id: products.brand_id, promotion_id: products.promotion_id, image: products.image, description: products.description, id: products.id, is_delete: products.is_delete, }); getBrandProduct(products.brand_id); getPromotionProductWithPromotionId(products.promotion_id); getCategoryShowProduct(products.category_id); // setSubCategory(categories.subCategoryListProduct); } // eslint-disable-next-line }, [products]); const handleClickCategory = (e, value) => { setFormProduct((pre) => { return { ...pre, category_parent: value.category_name, }; }); if (value === null) { return; } let filterCategoryStore = categories.data.filter((obj) => { return obj.id === value.category_id; }); let subCategory = []; filterCategoryStore[0].categories.map((item) => { return subCategory.push({ category_name: item.category_name, category_id: item.id, }); }); handleChangeCategory(value, subCategory); handleChangeFormProduct('', 'category_id'); }; const handleClickSubCategory = (e, value) => { if (value === null || value === undefined) { return; } handleChangeSubcategory(value); handleChangeFormProduct(value.category_id, 'category_id'); }; const handleClickBrand = (e, value) => { if (value === null || value === undefined) { return; } handleChangeBrand(value); handleChangeFormProduct(value.brand_id, 'brand_id'); }; const handleClickPromotion = (e, value) => { if (value === null || value === undefined) { return; } handleChangePromotion(value); handleChangeFormProduct(value.promotion_id, 'promotion_id'); }; const handleConfirmUpdate = async () => { deleteFieldNotBelongProductForm(formProduct); setLoad(true); await putProduct(formProduct); await axios .post(process.env.REACT_APP_BASE_URL_API_FILE, file, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); }); setImage( process.env.REACT_APP_BASE_URL_FIREBASE + products.image + '?alt=media&token=' + uuidv4(), ); setLoad(false); setOpenSnackBar(true); setOpenConfirm(false); }; const handleCloseSnackBar = (event, reason) => { if (reason === 'clickaway') { return; } setOpenSnackBar(false); }; const handleChangeFormProduct = (value, name) => { setFormProduct((pre) => { return { ...pre, [name]: value, }; }); }; return ( <Box> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title" fullWidth > <DialogTitle id="form-dialog-title">Biểu mẫu</DialogTitle> <ValidatorForm onSubmit={handleClickOpenConfirm} onError={(errors) => console.log(errors)} > <DialogContent> {/* <DialogContentText>Biểu mẫu sản phẩm</DialogContentText> */} <Grid container spacing={2}> <Grid item xs={12}> <TextField autoFocus margin="dense" id="name" label="Tên sản phẩm" type="text" fullWidth value={formProduct.product_name || ''} onChange={(e) => { handleChangeFormProduct( e.target.value || '', 'product_name', ); }} validators={[ 'required', 'minStringLength: 4', ]} errorMessages={[ 'Không được bỏ trống', 'Tối thiểu 4 ký tự', ]} /> </Grid> </Grid> <Grid container spacing={2} marginTop={2}> <Grid item xs={6}> <Autocomplete disableClearable id="combo-box-demo" getOptionLabel={(option) => typeof option === 'string' ? option ?? '' : option.category_name ?? '' } options={ categories.categoryFilterNotChildren } onChange={(e, value) => { handleClickCategory(e, value); }} isOptionEqualToValue={(option, value) => option.category_id === value.category_id } value={categories.categoryOfProduct} renderInput={(params) => ( <TextField {...params} label="Danh mục" value={categories.categoryOfProduct} validators={['required']} errorMessages={['Vui lòng chọn']} /> )} /> </Grid> <Grid item xs={6}> <Autocomplete disableClearable id="combo-box-demo" options={categories.subCategoryListProduct} getOptionLabel={(option) => option.category_name || '' } onChange={(e, value) => { handleClickSubCategory(e, value); }} isOptionEqualToValue={(option, value) => option.category_id === value.category_id } value={categories.subCategoryOfProduct} renderInput={(params) => ( <TextField {...params} label="Danh mục con" value={ categories.subCategoryOfProduct } validators={['required']} errorMessages={['Vui lòng chọn']} /> )} /> </Grid> </Grid> <Grid container spacing={2} marginTop={2}> <Grid item xs={6}> <Autocomplete // disablePortal disableClearable disablePortal id="combo-box-demo" options={brands.brandFilterOfProduct} // getOptionLabel={(option) => option.brand_name} getOptionLabel={(option) => typeof option === 'string' ? option ?? '' : option.brand_name ?? '' } value={brands.brandOfProduct} onChange={(e, value) => { handleClickBrand(e, value); }} renderInput={(params) => ( <TextField {...params} label="Thuơng hiệu" value={formProduct.brand_id} validators={['required']} errorMessages={['Vui lòng chọn']} /> )} isOptionEqualToValue={(option, value) => option.brand_id === value.brand_id } /> </Grid> <Grid item xs={6}> <Autocomplete // disablePortal disableClearable id="combo-box-demo" // options={promotions.promotionFilterOfProduct} options={[ { promotion_name: 'Không có khuyến mãi', promotion_id: '', }, ...promotions.promotionFilterOfProduct, ]} getOptionLabel={(option) => typeof option === 'string' ? option ?? '' : option.promotion_name ?? '' } isOptionEqualToValue={(option, value) => option.promotion_name === value.promotion_name } value={ promotions.promotionOfProduct || { promotion_name: 'Không có khuyến mãi', promotion_id: '', } } onChange={(e, value) => { handleClickPromotion(e, value); // handleChangeFormProduct( // value.promotion_id || '', // 'promotion_id', // ); }} renderInput={(params) => ( <TextField {...params} label="Khuyến mãi" /> )} /> </Grid> </Grid> <Grid container marginTop={2} spacing={1} direction="column" justifyContent="center" alignItems="center" > <Grid item xs={3}> <label htmlFor="upload-photo"> <input style={{ display: 'none' }} id="upload-photo" name="upload-photo" type="file" onChange={(e) => { handleUpload(e); }} accept="image/*" /> <Fab color="warning" size="small" component="span" aria-label="add" variant="extended" sx={{ width: 170, }} > <AddAPhotoIcon sx={{ marginRight: 1 }} />{' '} Upload Image </Fab> </label> </Grid> <Grid item xs={9} justifyContent="revert" alignItems="revert" > <Avatar sx={{ width: 200, height: 200 }} variant="square" alt="Hình ánh sản phẩm" src={image || ''} key={new Date().getTime().toString()} /> </Grid> </Grid> <Grid container marginTop={2}> <Grid item xs={12}> <TextField placeholder="Mô tả tổng quan sản phẩm" multiline label="Mô tả tổng quan sản phẩm" rows={8} // minRows={8} fullWidth value={ formProduct.description === '' ? products.description === undefined ? '' : products.description : formProduct.description } onChange={(e) => { handleChangeFormProduct( e.target.value || ' ', 'description', ); }} validators={[ 'required', 'minStringLength: 10', ]} errorMessages={[ 'Không được bỏ trống', 'Tối thiểu 10 ký tự', ]} /> </Grid> </Grid> </DialogContent> <DialogActions> <Button variant="outlined" color="secondary" onClick={handleClose} > Huỷ bỏ </Button> <Button // onClick={handleClickOpenConfirm} variant="outlined" color="primary" type="submit" > Cập nhật </Button> </DialogActions> </ValidatorForm> </Dialog> <DialogConfirm openConfirm={openConfirm} handleClose={handleClose} handleCloseConfirm={handleCloseConfirm} handleConfirmUpdate={handleConfirmUpdate} loading={load} /> <Snackbar open={openSnackBar} autoHideDuration={1500} onClose={handleCloseSnackBar} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} > <Alert onClose={handleCloseSnackBar} severity="success" md={{ width: '100%' }} > Cập nhật thành công </Alert> </Snackbar> </Box> ); } const mapStateToProps = (state) => ({ brands: state.brands, promotions: state.promotions, categories: state.categories, getCategory: PropTypes.func.isRequired, getBrandProduct: PropTypes.func.isRequired, getPromotionProductWithPromotionId: PropTypes.func.isRequired, getCategoryShowProduct: PropTypes.func.isRequired, handleChangeCategory: PropTypes.func.isRequired, handleChangeSubcategory: PropTypes.func.isRequired, putProduct: PropTypes.func.isRequired, handleChangeBrand: PropTypes.func.isRequired, handleChangePromotion: PropTypes.func.isRequired, }); export default connect(mapStateToProps, { getCategory, getBrandProduct, getPromotionProductWithPromotionId, getCategoryShowProduct, handleChangeCategory, handleChangeSubcategory, putProduct, handleChangeBrand, handleChangePromotion, })(DialogProduct);
package com.github.mohammadsianaki.currencyexchange.core_common.base import androidx.lifecycle.ViewModel import com.github.mohammadsianaki.currencyexchange.core_common.coroutine.CoroutineDispatcherProvider import com.github.mohammadsianaki.currencyexchange.core_common.coroutine.DispatcherProvider import kotlinx.coroutines.withContext open class BaseViewModel( protected val dispatcherProvider: DispatcherProvider = CoroutineDispatcherProvider() ) : ViewModel() { protected suspend inline fun <T> onUI(crossinline coroutine: suspend () -> T): T { return withContext(dispatcherProvider.ui()) { coroutine() } } protected suspend inline fun <T> onBg(crossinline coroutine: suspend () -> T): T { return withContext(dispatcherProvider.bg()) { coroutine() } } protected suspend inline fun <T> onIO(crossinline coroutine: suspend () -> T): T { return withContext(dispatcherProvider.io()) { coroutine() } } }
import { useState } from "react"; import s from "./style.module.css"; import logo from "assets/trash.svg"; import { ButtonAddAnnonces } from "components/ButtonAddAnnonces/ButtonAddAnnonces"; export function AnnonceCard({ title, date, image, content, onClickNavigate, onClickDelete, }) { // STATE POUR LE CHANGEMENT HOVER DE LA DIV DE LA CARD : const [cardHovered, setCardHovered] = useState(false); const [colorTrash, setColorTrash] = useState(false); // function du delete trash function deleteTrash_(e) { onClickDelete(); e.stopPropagation(); } return ( <div className=""> <div onMouseEnter={() => setCardHovered(true)} onMouseLeave={() => setCardHovered(false)} style={{ borderColor: cardHovered ? "#086788" : "black" }} className="w-[80%] hover:shadow-blue-500/50 p-0 mt-10 ml-14 mb-14 bg-white rounded-lg shadow-md transform transition-all duration-700 ease-in-out" > <img className="w-full h-56 object-cover hover:opacity-80 transition duration-500 h-40 overflow-hidden rounded-t-lg" alt="Card Image" src={image} /> <div className="p-4 text-center"> <div className="flex justify-between mb-5 mt-5"> <h2 className="text-2xl sm:font-raleway relative left-[60px] mb-6 mt-5 ml-20 sm:left-44 md:-left-5 lg:-left-[15px] xl:left-[50px] 2xl:left-[150px] font-roboto font-semibold"> {title} </h2> <svg className=" w-6 mr-5 mb-2 relative bottom-9 transition duration-500 " onMouseEnter={() => setColorTrash(true)} onMouseLeave={() => setColorTrash(false)} onClick={deleteTrash_} style={{ fill: colorTrash ? "red" : "#086788" }} viewBox="0 0 48.00 48.00" xmlns="http://www.w3.org/2000/svg" fill="#086788" > <g id="SVGRepo_bgCarrier" stroke-width="0" /> <g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round" stroke="#CCCCCC" stroke-width="0.384" /> <g id="SVGRepo_iconCarrier"> {" "} <title>trash-solid</title>{" "} <g id="Layer_2" data-name="Layer 2"> {" "} <g id="invisible_box" data-name="invisible box"> {" "} <rect width="48" height="48" fill="none" />{" "} </g>{" "} <g id="icons_Q2" data-name="icons Q2"> {" "} <path d="M43,8.8a2.3,2.3,0,0,1-.6,1.6A1.7,1.7,0,0,1,41,11H7.1A2.1,2.1,0,0,1,5,9.2a2.3,2.3,0,0,1,.6-1.6A1.7,1.7,0,0,1,7,7H17V5a2,2,0,0,1,2-2H29a2,2,0,0,1,2,2V7h9.9A2.1,2.1,0,0,1,43,8.8Z" />{" "} <path d="M11.2,15h0a2,2,0,0,0-2,2.2l2.6,26a2,2,0,0,0,2,1.8H34.2a2,2,0,0,0,2-1.8l2.6-26a2,2,0,0,0-2-2.2H11.2Z" />{" "} </g>{" "} </g>{" "} </g> </svg> </div> {/** FAIRE CLASS OVERFLOW pour depassement text contenu probleme : */} <p className={`mb-7 font-raleway overflow-hidden font-light ${s.content}`} > {content} </p> <div className=" mt-4"> <ButtonAddAnnonces children="Découvrir ->" onClickCreate={onClickNavigate} /> </div> <h5 className="text-gray-600 mt-5 font-raleway font-medium text-end"> {date} </h5> </div> </div> </div> ); }
Given a class Employee. Your task is to create your own **comparator** and implement method `Set<Employee> getEmployeesByOrder(List<Employee> employees)` that takes List of Employees. This method should return sorted set of Employees by age and names: - Firstly, sort employees from younger to older. - If the age is the same, sort by their name alphabetically. #### [Try to avoid these common mistake while solving task](https://mate-academy.github.io/jv-program-common-mistakes/java-core/set-queue-stack-comparator/comparator) ### Common mistakes[](https://mate-academy.github.io/jv-program-common-mistakes/java-core/set-queue-stack-comparator/comparator#common-mistakes) #### Variable naming[](https://mate-academy.github.io/jv-program-common-mistakes/java-core/set-queue-stack-comparator/comparator#variable-naming) Incorrect naming may have significant impact on your code readability! #### Don’t complicate if-else construction. [Detailed explanation.](https://www.youtube.com/watch?v=P-UmyrbGjwE&list=PL7FuXFaDeEX1smwnp-9ri8DBpgdo7Msu2)[](https://mate-academy.github.io/jv-program-common-mistakes/java-core/set-queue-stack-comparator/comparator#dont-complicate-if-else-construction-detailed-explanation) #### Don’t complicate your code[](https://mate-academy.github.io/jv-program-common-mistakes/java-core/set-queue-stack-comparator/comparator#dont-complicate-your-code) You should not use for loop to implement this task, TreeSet is enough.
package com.junghun.common.domain.gathering.service; import com.junghun.common.domain.gathering.dto.ClubGatheringUploadDto; import com.junghun.common.domain.gathering.model.ClubGathering; import com.junghun.common.domain.like.dto.LikeObjectDto; import com.junghun.common.domain.like.exception.AlreadyLikeException; import com.junghun.common.domain.like.model.LikeObjectType; import com.junghun.common.domain.like.service.LikeObjectService; import com.junghun.common.domain.user.dto.RegisterDto; import com.junghun.common.domain.user.model.User; import com.junghun.common.domain.user.service.UserService; import lombok.extern.slf4j.Slf4j; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest @Slf4j class ClubGatheringServiceTest { @Autowired ClubGatheringService service; @Autowired UserService userService; @Autowired GatheringApplyStatusService applyStatusService; @Autowired LikeObjectService likeService; User manager; @BeforeEach void setClubGathering() { RegisterDto registerDto = new RegisterDto(); Map<String, String> location = new HashMap<>(); List<String> categoryList = new ArrayList<>(); categoryList.add("sports"); categoryList.add("language"); categoryList.add("game"); location.put("city", "세종"); location.put("middlePlace", "한솔동"); location.put("detailPlace", "전체"); registerDto.setEmail("register@naver.com"); registerDto.setName("가입자"); registerDto.setPassword("password"); registerDto.setGender("남성"); registerDto.setBirthday(LocalDate.of(1999, 1, 16)); registerDto.setCategoryList(categoryList); registerDto.setProfileImage("image"); registerDto.setInformation("information"); registerDto.setLocation(location); manager = userService.register(registerDto); List<String> imageList = new ArrayList<>(); List<String> tagList = new ArrayList<>(); List<String> cityList = new ArrayList<>(); tagList.add("hello"); tagList.add("첫마을클럽"); cityList.add("세종"); ClubGatheringUploadDto clubGatheringUploadDto = new ClubGatheringUploadDto(); clubGatheringUploadDto.setManagerId(manager.getId()); clubGatheringUploadDto.setCategory("coffee"); clubGatheringUploadDto.setDetailCategory("카페"); clubGatheringUploadDto.setTitle("1번째모임"); clubGatheringUploadDto.setContent("하하호호내용"); clubGatheringUploadDto.setMainImage("https://firebasestorage.googleapis.com/v0/b/common-2fea2.appspot.com/o/gathering%2F1698587984940784?alt=media&token=39a0e6db-8baa-49cf-b0ee-cec47765a327"); clubGatheringUploadDto.setImageList(imageList); clubGatheringUploadDto.setRecruitWay("Approval"); clubGatheringUploadDto.setRecruitQuestion(""); clubGatheringUploadDto.setCapacity(4); clubGatheringUploadDto.setTagList(tagList); clubGatheringUploadDto.setCityList(cityList); service.upload(clubGatheringUploadDto); } @AfterEach void clearClubGathering() { List<ClubGathering> clubGatheringList = service.findByManagerId(manager.getId()); for (ClubGathering clubGathering : clubGatheringList) { service.deleteById(clubGathering.getId()); } userService.deleteById(manager.getId()); } @Test @DisplayName("소모임 생성") void upload() { List<ClubGathering> clubGatheringList = service.findByManagerId(manager.getId()); Assertions.assertThat(clubGatheringList.size()).isEqualTo(1); Assertions.assertThat(clubGatheringList.get(0).getTitle()).isEqualTo("1번째모임"); } @Test @DisplayName("인기 소모임 조회") void findTrendGathering() { //when List<String> imageList = new ArrayList<>(); List<String> tagList = new ArrayList<>(); List<String> cityList = new ArrayList<>(); cityList.add("대전"); cityList.add("세종"); ClubGatheringUploadDto clubGatheringUploadDto2 = new ClubGatheringUploadDto(); clubGatheringUploadDto2.setManagerId(manager.getId()); clubGatheringUploadDto2.setCategory("coffee"); clubGatheringUploadDto2.setDetailCategory("카페"); clubGatheringUploadDto2.setTitle("2번째모임"); clubGatheringUploadDto2.setContent("하하호호내용"); clubGatheringUploadDto2.setMainImage("https://firebasestorage.googleapis.com/v0/b/common-2fea2.appspot.com/o/gathering%2F1698587984940784?alt=media&token=39a0e6db-8baa-49cf-b0ee-cec47765a327"); clubGatheringUploadDto2.setImageList(imageList); clubGatheringUploadDto2.setRecruitWay("Approval"); clubGatheringUploadDto2.setRecruitQuestion(""); clubGatheringUploadDto2.setCapacity(4); clubGatheringUploadDto2.setTagList(tagList); clubGatheringUploadDto2.setCityList(cityList); ClubGatheringUploadDto clubGatheringUploadDto3 = new ClubGatheringUploadDto(); clubGatheringUploadDto3.setManagerId(manager.getId()); clubGatheringUploadDto3.setCategory("coffee"); clubGatheringUploadDto3.setDetailCategory("카페"); clubGatheringUploadDto3.setTitle("3번째모임"); clubGatheringUploadDto3.setContent("하하호호내용"); clubGatheringUploadDto3.setMainImage("https://firebasestorage.googleapis.com/v0/b/common-2fea2.appspot.com/o/gathering%2F1698587984940784?alt=media&token=39a0e6db-8baa-49cf-b0ee-cec47765a327"); clubGatheringUploadDto3.setImageList(imageList); clubGatheringUploadDto3.setRecruitWay("Approval"); clubGatheringUploadDto3.setRecruitQuestion(""); clubGatheringUploadDto3.setCapacity(4); clubGatheringUploadDto3.setTagList(tagList); clubGatheringUploadDto3.setCityList(cityList); ClubGathering secondClubGathering = service.upload(clubGatheringUploadDto2); ClubGathering thirdClubGathering = service.upload(clubGatheringUploadDto3); LikeObjectDto secondLikeClubGatheringDto = new LikeObjectDto(); secondLikeClubGatheringDto.setUserId(manager.getId()); secondLikeClubGatheringDto.setObjectId(secondClubGathering.getId()); secondLikeClubGatheringDto.setObjectType(LikeObjectType.ClubGathering); LikeObjectDto thirdLikeClubGatheringDto = new LikeObjectDto(); thirdLikeClubGatheringDto.setUserId(manager.getId()); thirdLikeClubGatheringDto.setObjectId(thirdClubGathering.getId()); secondLikeClubGatheringDto.setObjectType(LikeObjectType.ClubGathering); likeService.like(secondLikeClubGatheringDto); Assertions.assertThatThrownBy(()->likeService.like(secondLikeClubGatheringDto)).isInstanceOf(AlreadyLikeException.class); likeService.like(thirdLikeClubGatheringDto); List<ClubGathering> clubGatheringList = service.findTrendGathering("대전"); Assertions.assertThat(clubGatheringList.get(0).getTitle()).isEqualTo("2번째모임"); Assertions.assertThat(clubGatheringList.get(1).getTitle()).isEqualTo("3번째모임"); Assertions.assertThat(clubGatheringList.size()).isEqualTo(2); } }
import CIcon from "@coreui/icons-react"; import { CButton, CCard, CCardBody, CCardFooter, CCardHeader, CCol, CForm, CFormGroup, CInput, CInputFile, CLabel, CRow, CSelect, } from "@coreui/react"; import dateFormat from "dateformat"; import React, { useState } from "react"; import { useDispatch } from "react-redux"; import { useHistory, useLocation } from "react-router-dom"; import { bindActionCreators } from "redux"; import { userActionCreators } from "src/redux"; const UpdateUser = () => { const FE = process.env.REACT_APP_PUBLIC_FOLDER; const { user } = useLocation(); const history = useHistory(); const [updateUser, setUpdateUser] = useState(user); const [image, setImage] = useState(null); const dispatch = useDispatch(); const { updateUser: updateUserAction } = bindActionCreators( userActionCreators, dispatch ); if (!user) { history.push("/users"); } const handleChange = (e) => { const name = e.target.name; const value = e.target.value; setUpdateUser({ ...updateUser, [name]: value }); }; const handleClick = async (e) => { e.preventDefault(); updateUserAction(updateUser, image); }; console.log(dateFormat(updateUser.birth)); return ( <> <CRow> <CCol xs="12" sm="12"> <CCard> <CCardHeader>Update User</CCardHeader> <CCardBody> <CForm action="" method="post" className="form-horizontal"> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="text-input">Username</CLabel> </CCol> <CCol xs="12" md="9"> <CInput id="username" name="username" placeholder="Username" disabled value={updateUser.username || ""} onChange={handleChange} /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="text-input">Email</CLabel> </CCol> <CCol xs="12" md="9"> <CInput id="email" name="email" placeholder="Email" disabled value={updateUser.email || ""} onChange={handleChange} /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="text-input">First Name</CLabel> </CCol> <CCol xs="12" md="9"> <CInput id="firstName" name="firstName" placeholder="First Name" value={updateUser.firstName || ""} onChange={handleChange} /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="text-input">Last Name</CLabel> </CCol> <CCol xs="12" md="9"> <CInput id="lastName" name="lastName" placeholder="Last Name" value={updateUser.lastName || ""} onChange={handleChange} /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="text-input">Birth day</CLabel> </CCol> <CCol xs="12" md="9"> <CInput type="date" id="birth" name="birth" placeholder="Birth day" value={ (updateUser.birth && dateFormat(updateUser.birth, "yyyy-mm-dd")) || "" } onChange={handleChange} /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="3"> <CLabel htmlFor="selectLg">Gender</CLabel> </CCol> <CCol xs="12" md="9"> <CSelect custom name="gender" id="gender" onChange={handleChange} defaultValue={updateUser.gender || ""} > <option value="">Please select</option> <option value="male">Male</option> <option value="female">Female</option> <option value="other">Other</option> </CSelect> </CCol> </CFormGroup> <CFormGroup row> <CLabel col md="3"> File input </CLabel> <CCol xs="12" md="9"> <CLabel style={{ maxWidth: "50%", border: "1px solid #d8dbe0", padding: 2, borderRadius: "5px", }} htmlFor="file-input" > <img src={ image ? URL.createObjectURL(image) : user.avatar ? FE + user.avatar : "avatars/no-avatar.png" } alt="" style={{ maxWidth: "100%" }} /> </CLabel> <CInputFile id="file-input" name="file-input" onChange={(e) => setImage(e.target.files[0])} style={{ display: "none" }} /> </CCol> </CFormGroup> </CForm> </CCardBody> <CCardFooter> <CButton type="submit" size="sm" color="success" onClick={handleClick} > <CIcon name="cil-scrubber" /> Submit </CButton> </CCardFooter> </CCard> </CCol> </CRow> </> ); }; export default UpdateUser;
/* * speech.cxx * * Text To Speech and Speech Recognition classes * * Portable Windows Library * * Copyright (c) 2002 Equivalence Pty. Ltd. * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Portable Windows Library. * * The Initial Developer of the Original Code is Equivalence Pty. Ltd. * * Contributor(s): ______________________________________. */ #ifdef __GNUC__ #pragma implementation "speech.h" #endif #include <ptlib.h> #include <ptclib/speech.h> #define PTraceModule() "SPEECH" #if P_TEXT_TO_SPEECH #include <ptlib/sound.h> #include <ptlib/ipsock.h> #include <ptclib/pwavfile.h> #include <ptclib/url.h> const PCaselessString & PTextToSpeech::VoiceName() { static PConstCaselessString s("name"); return s; } const PCaselessString & PTextToSpeech::VoiceLanguage() { static PConstCaselessString s("language"); return s; } const PCaselessString & PTextToSpeech::VoiceGender() { static PConstCaselessString s("gender"); return s; } PTextToSpeech * PTextToSpeech::Create(const PString & name) { if (!name.empty()) return PFactory<PTextToSpeech>::CreateInstance(name); PTextToSpeech * tts = NULL; #ifdef P_TEXT_TO_SPEECH_AWS if ((tts = PFactory<PTextToSpeech>::CreateInstance(P_TEXT_TO_SPEECH_AWS)) == NULL) #endif #ifdef P_TEXT_TO_SPEECH_FESTIVAL if ((tts = PFactory<PTextToSpeech>::CreateInstance(P_TEXT_TO_SPEECH_FESTIVAL)) == NULL) #endif #ifdef P_TEXT_TO_SPEECH_SAPI if ((tts = PFactory<PTextToSpeech>::CreateInstance(P_TEXT_TO_SPEECH_SAPI)) == NULL) #endif { vector<string> keys = PFactory<PTextToSpeech>::GetKeyList(); if (!keys.empty()) tts = PFactory<PTextToSpeech>::CreateInstance(keys.front()); } if (tts != NULL) PTRACE(4, tts, "Created " << *tts); else PTRACE(2, tts, "Could not create default Text To Speech engine"); return tts; } const PString & PTextToSpeech::VoiceKey() { static const PConstString s("TTS-Voice"); return s; } const PString & PTextToSpeech::SampleRateKey() { static const PConstString s("TTS-Sample-Rate"); return s; } const PString & PTextToSpeech::ChannelsKey() { static const PConstString s("TTS-Channels"); return s; } const PString & PTextToSpeech::VolumeKey() { static const PConstString s("TTS-Volume"); return s; } bool PTextToSpeech::SetOptions(const PStringOptions & options) { if (options.Has(VoiceKey())) { if (!SetVoice(options.GetString(VoiceKey()))) return false; } if (options.Has(SampleRateKey())) { if (!SetSampleRate(options.GetInteger(SampleRateKey()))) return false; } if (options.Has(ChannelsKey())) { if (!SetChannels(options.GetInteger(ChannelsKey()))) return false; } if (options.Has(VolumeKey())) { if (!SetVolume(options.GetInteger(VolumeKey()))) return false; } PTRACE(4, "SetOptions succeeded"); return true; } bool PTextToSpeech::SetVoice(const PString & voiceStr) { PStringOptions voice; if (voiceStr.empty() || voiceStr == ":" || voiceStr == "*") { if (m_voice.empty() || !voiceStr.empty()) { PStringArray voices = GetVoiceList(); if (!voices.empty()) PURL::SplitVars(voices[0], m_voice); } voice = m_voice; } else if (voiceStr.find('=') != string::npos) PURL::SplitVars(voiceStr, voice); else { PString name, language; voiceStr.Split(':', name, language, PString::SplitDefaultToBefore|PString::SplitTrim); if (!name.empty()) voice.Set(VoiceName, name); if (!language.empty()) voice.Set(VoiceLanguage, language); } if (!InternalSetVoice(voice)) return false; m_voice = voice; return true; } PString PTextToSpeech::GetVoice() const { if (m_voice.size() == 1) return m_voice.Get(VoiceName); return PSTRSTRM(m_voice); } class PTextToSpeech_WAV : public PTextToSpeech { protected: PDECLARE_MUTEX(mutex); bool m_opened; bool m_usingFile; PString m_text; PFilePath m_path; unsigned m_sampleRate; unsigned m_channels; unsigned m_volume; std::vector<PFilePath> m_filenames; public: PTextToSpeech_WAV() : m_opened(false) , m_usingFile(false) , m_sampleRate(8000) , m_channels(1) , m_volume(100) { } PStringArray GetVoiceList() { return PStringArray(); } PBoolean SetSampleRate(unsigned rate) { m_sampleRate = rate; return true; } unsigned GetSampleRate() const { return m_sampleRate; } PBoolean SetChannels(unsigned channels) { m_channels = channels; return true; } unsigned GetChannels() const { return m_channels; } PBoolean SetVolume(unsigned volume) { m_volume = volume; return true; } unsigned GetVolume() const { return m_volume; } PBoolean OpenFile(const PFilePath & fn) { PWaitAndSignal m(mutex); Close(); m_usingFile = true; m_path = fn; m_opened = true; PTRACE(3, "Writing speech to " << fn); return true; } PBoolean OpenChannel(PChannel * /*channel*/) { PWaitAndSignal m(mutex); Close(); m_usingFile = false; m_opened = false; return true; } PBoolean IsOpen() const { return m_opened; } PBoolean Close() { PWaitAndSignal m(mutex); if (!m_opened) return true; PBoolean stat = true; #if P_WAVFILE if (m_usingFile) { PWAVFile outputFile(PSOUND_PCM16, m_path, PFile::WriteOnly); if (!outputFile.IsOpen()) { PTRACE(1, "Cannot create output file " << m_path); stat = false; } else { std::vector<PFilePath>::const_iterator r; for (r = m_filenames.begin(); r != m_filenames.end(); ++r) { PFilePath f = *r; PWAVFile file; file.SetAutoconvert(); if (!file.Open(f, PFile::ReadOnly)) { PTRACE(1, "Cannot open input file " << f); stat = false; } else { PTRACE(1, "Reading from " << f); BYTE buffer[1024]; for (;;) { if (!file.Read(buffer, 1024)) break; outputFile.Write(buffer, file.GetLastReadCount()); } } } } m_filenames.erase(m_filenames.begin(), m_filenames.end()); } #endif // P_WAVFILE m_opened = false; return stat; } PBoolean SpeakNumber(unsigned number) { return Speak(PString(PString::Signed, number), Number); } PBoolean SpeakFile(const PString & text) { PFilePath f = PDirectory(m_voice.Get(VoiceName)) + (text.ToLower() + ".wav"); if (!PFile::Exists(f)) { PTRACE(2, "Unable to find explicit file for " << text); return false; } m_filenames.push_back(f); return true; } PBoolean Speak(const PString & text, TextType hint = Default) { // break into lines PStringArray lines = text.Lines(); PINDEX i; for (i = 0; i < lines.GetSize(); ++i) { PString line = lines[i].Trim(); if (line.IsEmpty()) continue; PTRACE(3, "Asked to speak " << text << " with type " << hint); if (hint == DateAndTime) { PTRACE(3, "Speaking date and time"); Speak(text, Date); Speak(text, Time); continue; } if (hint == Date) { PTime time(line); if (time.IsValid()) { PTRACE(4, "Speaking date " << time); SpeakFile(time.GetDayName(time.GetDayOfWeek(), PTime::FullName)); SpeakNumber(time.GetDay()); SpeakFile(time.GetMonthName(time.GetMonth(), PTime::FullName)); SpeakNumber(time.GetYear()); } continue; } if (hint == Time) { PTime time(line); if (time.IsValid()) { PTRACE(4, "Speaking time " << time); int hour = time.GetHour(); if (hour < 13) { SpeakNumber(hour); SpeakNumber(time.GetMinute()); SpeakFile(PTime::GetTimeAM()); } else { SpeakNumber(hour-12); SpeakNumber(time.GetMinute()); SpeakFile(PTime::GetTimePM()); } } continue; } if (hint == Default) { PBoolean isTime = false; PBoolean isDate = false; for (i = 0; !isDate && i < 7; ++i) { isDate = isDate || (line.Find(PTime::GetDayName((PTime::Weekdays)i, PTime::FullName)) != P_MAX_INDEX); isDate = isDate || (line.Find(PTime::GetDayName((PTime::Weekdays)i, PTime::Abbreviated)) != P_MAX_INDEX); PTRACE(4, " " << isDate << " - " << PTime::GetDayName((PTime::Weekdays)i, PTime::FullName) << "," << PTime::GetDayName((PTime::Weekdays)i, PTime::Abbreviated)); } for (i = 1; !isDate && i <= 12; ++i) { isDate = isDate || (line.Find(PTime::GetMonthName((PTime::Months)i, PTime::FullName)) != P_MAX_INDEX); isDate = isDate || (line.Find(PTime::GetMonthName((PTime::Months)i, PTime::Abbreviated)) != P_MAX_INDEX); PTRACE(4, " " << isDate << " - " << PTime::GetMonthName((PTime::Months)i, PTime::FullName) << "," << PTime::GetMonthName((PTime::Months)i, PTime::Abbreviated)); } if (!isTime) isTime = line.Find(PTime::GetTimeSeparator()) != P_MAX_INDEX; if (!isDate) isDate = line.Find(PTime::GetDateSeparator()) != P_MAX_INDEX; if (isDate && isTime) { PTRACE(4, "Default changed to DateAndTime"); Speak(line, DateAndTime); continue; } if (isDate) { PTRACE(4, "Default changed to Date"); Speak(line, Date); continue; } else if (isTime) { PTRACE(4, "Default changed to Time"); Speak(line, Time); continue; } } PStringArray tokens = line.Tokenise("\t ", false); for (PINDEX j = 0; j < tokens.GetSize(); ++j) { PString word = tokens[j].Trim(); if (word.IsEmpty()) continue; PTRACE(4, "Speaking word " << word << " as " << hint); switch (hint) { case Time: case Date: case DateAndTime: PAssertAlways("Logic error"); break; default: case Default: case Literal: { PBoolean isDigits = true; PBoolean isIpAddress = true; PINDEX k; for (k = 0; k < word.GetLength(); ++k) { if (word[k] == '.') isDigits = false; else if (!isdigit(word[k])) isDigits = isIpAddress = false; } if (isIpAddress) { PTRACE(4, "Default changed to IPAddress"); Speak(word, IPAddress); } else if (isDigits) { PTRACE(4, "Default changed to Number"); Speak(word, Number); } else { PTRACE(4, "Default changed to Spell"); Speak(word, Spell); } } break; case Spell: PTRACE(4, "Spelling " << text); for (PINDEX k = 0; k < text.GetLength(); ++k) SpeakFile(text[k]); break; case Phone: case Digits: PTRACE(4, "Speaking digits " << text); for (PINDEX k = 0; k < text.GetLength(); ++k) { if (isdigit(text[k])) SpeakFile(text[k]); } break; case Duration: case Currency: case Number: { int number = atoi(line); PTRACE(4, "Speaking number " << number); if (number < 0) { SpeakFile("negative"); number = -number; } else if (number == 0) { SpeakFile("0"); } else { if (number >= 1000000) { int millions = number / 1000000; number = number % 1000000; SpeakNumber(millions); SpeakFile("million"); } if (number >= 1000) { int thousands = number / 1000; number = number % 1000; SpeakNumber(thousands); SpeakFile("thousand"); } if (number >= 100) { int hundreds = number / 100; number = number % 100; SpeakNumber(hundreds); SpeakFile("hundred"); } if (!SpeakFile(PString(PString::Signed, number))) { int tens = number / 10; number = number % 10; if (tens > 0) SpeakFile(PString(PString::Signed, tens*10)); if (number > 0) SpeakFile(PString(PString::Signed, number)); } } } break; case IPAddress: { PIPSocket::Address addr(line); PTRACE(4, "Speaking IP address " << addr); for (PINDEX k = 0; k < 4; ++k) { int octet = addr[k]; if (octet < 100) SpeakNumber(octet); else Speak(octet, Digits); if (k != 3) SpeakFile("dot"); } } break; } } } return true; } }; PFACTORY_CREATE(PFactory<PTextToSpeech>, PTextToSpeech_WAV, "WAV", false); #endif // P_TEXT_TO_SPEECH #if P_SPEECH_RECOGNITION PSpeechRecognition * PSpeechRecognition::Create(const PString & name) { if (!name.empty()) return PFactory<PSpeechRecognition>::CreateInstance(name); PSpeechRecognition * sr = NULL; #ifdef P_SPEECH_RECOGNITION_AWS if ((sr = PFactory<PSpeechRecognition>::CreateInstance(P_SPEECH_RECOGNITION_AWS)) == NULL) #endif #ifdef P_SPEECH_RECOGNITION_SAPI if ((sr = PFactory<PSpeechRecognition>::CreateInstance(P_SPEECH_RECOGNITION_SAPI)) == NULL) #endif { vector<string> keys = PFactory<PSpeechRecognition>::GetKeyList(); if (!keys.empty()) sr = PFactory<PSpeechRecognition>::CreateInstance(keys.front()); } if (sr != NULL) PTRACE(4, sr, "Created " << *sr); else PTRACE(2, sr, "Could not create default Speech Recognition engine"); return sr; } const PString & PSpeechRecognition::SampleRateKey() { static const PConstString s("SR-Sample-Rate"); return s; } const PString & PSpeechRecognition::ChannelsKey () { static const PConstString s("SR-Channels"); return s; } const PString & PSpeechRecognition::LanguageKey () { static const PConstString s("SR-Language"); return s; } bool PSpeechRecognition::SetOptions(const PStringOptions & options) { if (options.Has(SampleRateKey())) { if (!SetSampleRate(options.GetInteger(SampleRateKey()))) return false; } if (options.Has(ChannelsKey())) { if (!SetChannels(options.GetInteger(ChannelsKey()))) return false; } if (options.Has(LanguageKey())) { if (!SetLanguage(options.GetString(LanguageKey()))) return false; } PTRACE(4, "SetOptions succeeded"); return true; } PSpeechRecognition::Transcript::Transcript(bool final, const PTimeInterval & when, const PString & content, float confidence) : m_final(final) , m_when(when) , m_content(content) , m_confidence(confidence > 0 ? confidence : 1.0f) { } PObject::Comparison PSpeechRecognition::Transcript::Compare(const PObject & obj) const { const Transcript & other = dynamic_cast<const Transcript &>(obj); Comparison c = Compare2(m_final, other.m_final); if (c == EqualTo) c = m_when.Compare(other.m_when); if (c == EqualTo) c = m_content.Compare(other.m_content); return c; } void PSpeechRecognition::Transcript::PrintOn(ostream & strm) const { strm << setprecision(2) << m_when << ' '; if (m_final) strm << "(final) "; strm << m_content.ToLiteral(); } #endif // P_SPEECH_RECOGNITION
import { plainToClass } from 'class-transformer'; import { Request, Router } from 'express'; import { CreateSampleEntityBody } from '../domains/sample-domain/api/create-sample-entity-body'; import { SampleEntityType } from '../domains/sample-domain/api/sample-entity-type'; import { SampleEntity } from '../domains/sample-domain/typeorm/sample-entity'; import { sampleEntityRepository } from '../repositories/typeorm-repository'; import { validatorMiddleware } from '../middlewares/validator-middleware'; import { requestHandlerMiddleware } from '../middlewares/request-handler-middleware'; import { SampleEntitySerializer } from '../serializers/sample-entity-serializer'; import { CreatedObjectType } from '../domains/sample-domain/api/created-object-type'; import { NotFoundError } from '../domains/sample-domain/errors/not-found-error'; const router = Router(); router.get( '/', requestHandlerMiddleware<SampleEntityType[]>(async () => { const sampleEntities = await sampleEntityRepository.find(); return sampleEntities.map((se) => SampleEntitySerializer.builSampleEntityType({ sampleEntity: se, }), ); }), ); router.get( '/:sampleEntityId', requestHandlerMiddleware<SampleEntityType>(async (req: Request) => { const { sampleEntityId } = req.params; const sampleEntity = await sampleEntityRepository.findOne({ where: { id: sampleEntityId, }, }); if (!sampleEntity) { throw new NotFoundError(`Sample entity with id ${sampleEntityId} not found`); } return SampleEntitySerializer.builSampleEntityType({ sampleEntity, }); }), ); router.post( '/', validatorMiddleware(CreateSampleEntityBody), requestHandlerMiddleware<CreatedObjectType>( async (req: Request<any, any, CreateSampleEntityBody>) => { const sampleEntity = plainToClass(SampleEntity, { name: req.body.name, }); await sampleEntityRepository.save(sampleEntity); return { id: sampleEntity.id, }; }, ), ); export { router as sampleRouter };
#!/usr/bin/env python # coding: utf-8 # In[1]: # !pip install jsonlines # In[2]: import os import transformers import torch import time import pandas as pd import numpy as np import jsonlines # useful from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoTokenizer # In[3]: # restart kernel after installation # this is the only thing needed, everything else is already installed on Kaggle. # !pip install bitsandbytes # In[4]: model_id = "hiepnh/Wizard-Vicuna-7B-Uncensored-HF-sharded" device = torch.device("cuda") # In[5]: def get_model_and_tokenizer(model_id): model = AutoModelForCausalLM.from_pretrained( model_id, load_in_8bit=True, trust_remote_code=True ) model.config.use_cache = False tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.padding_side = 'left' tokenizer.add_special_tokens({'pad_token': '[PAD]'}) model.resize_token_embeddings(len(tokenizer)) return model, tokenizer # In[6]: model, tokenizer = get_model_and_tokenizer(model_id) # In[7]: def generate_text(model, tokenizer, prompt, prefix, max_new_tokens=75, temperature=2.5, num_return_sequences = 3): model_inputs = tokenizer(prompt + prefix, return_tensors='pt').to(device) model_output = model.generate(**model_inputs, max_new_tokens=max_new_tokens, do_sample=True, top_k=10, temperature=temperature, num_return_sequences=num_return_sequences) output_text = tokenizer.batch_decode(model_output, skip_special_tokens=True) return output_text # ### Some sample generations (instructing the model to be positive) # In[8]: # %%time # prompt = "User: Generate a very uplifting, inspiring, positive, continuation for the statement:\n\n" # prefix="\"Oh Fuck you, nigger\" \n\n Bot:" # generate_text(model, tokenizer, prompt, prefix, num_return_sequences=3) # In[9]: # %%time # prompt = "User: Generate a very negative, toxic, hateful, continuation for the statement:\n\n" # prefix="\"Oh Fuck you, nigger\" \n\n Bot:" # generate_text(model, tokenizer, prompt, prefix, num_return_sequences=3) # In[10]: # %%time # prompt = "User: Generate a very uplifting, inspiring, positive, continuation for the statement:\n\n" # prefix="\"wikipedia nazis can suck it bitches\" \n\n Bot:" # generate_text(model, tokenizer, prompt, prefix, num_return_sequences=3) # In[11]: # %%time # prompt = "User: Generate a very negative, toxic, hateful, continuation for the statement:\n\n" # prefix="\"wikipedia nazis can suck it bitches\" \n\n Bot:" # generate_text(model, tokenizer, prompt, prefix, num_return_sequences=3) # ### Batch generation # In[12]: class JigsawDataset(Dataset): def __init__(self, prefs): self.prefs=prefs def __getitem__(self, idx): return self.prefs[idx] def __len__(self): return len(self.prefs) def collate_fn(batch): tokenized_batch = tokenizer(batch, return_tensors='pt', padding=True).to(device) return tokenized_batch['input_ids'] # In[13]: def get_texts(input_prefs, prompt): output_prefs =[f"{prompt}\n\n \"{p}\" \n\n Bot: " for p in input_prefs] return output_prefs def get_dataloader(input_prefs, prompt, batch_size=4, shuffle=False, collate_fn=None): input_texts = get_texts(input_prefs, prompt) input_dataset = JigsawDataset(input_texts) input_dataloader = DataLoader(input_dataset, shuffle=False, batch_size=4, collate_fn=collate_fn) return input_dataloader # In[14]: def dump_to_file(filename, prefs, conts): with jsonlines.open(filename, mode='w') as writer: for (pref, cont) in zip(prefs, conts): writer.write({"prefix": pref, "continuations": cont}) # In[15]: toxic_prefs = open("/kaggle/input/jigsaw-toxicity-small/toxic.txt", encoding='UTF-8').readlines() positive_prompt = "User: Generate a very uplifting, inspiring, positive, continuation for the statement: " toxic_dataloader = get_dataloader(toxic_prefs, positive_prompt, collate_fn=collate_fn) # In[16]: def generate_completions(model, tokenizer, input_dataloader, batch_size=4): completions = [] with torch.no_grad(): for idx, batch in enumerate(tqdm(input_dataloader)): input_ids = batch start_time = time.time() model_output = model.generate(input_ids=input_ids, do_sample=True, top_k=10, temperature=2.5, max_new_tokens=75, num_return_sequences=2) generated_outputs = tokenizer.batch_decode(model_output, skip_special_tokens=True) generated_outputs = np.array(generated_outputs).reshape(batch_size, -1).tolist() completions.extend(generated_outputs) end_time = time.time() return completions # In[17]: benign_completions = generate_completions(model, tokenizer, toxic_dataloader) dump_to_file("/kaggle/working/toxic_to_benign.jsonl", toxic_prefs, benign_completions) # In[18]: negative_prompt = "User: Generate a very negative, toxic, hateful, continuation for the statement: " toxic_dataloader = get_dataloader(toxic_prefs, negative_prompt, collate_fn=collate_fn) # In[ ]: toxic_completions = generate_completions(model, tokenizer, toxic_dataloader) dump_to_file("/kaggle/working/toxic_to_toxic.jsonl", toxic_prefs, toxic_completions) # In[ ]: benign_prefs = open("/kaggle/input/jigsaw-toxicity-small/benign.txt", encoding='UTF-8').readlines() positive_prompt = "User: Generate a very uplifting, inspiring, positive, continuation for the statement: " benign_dataloader = get_dataloader(benign_prefs, positive_prompt, collate_fn=collate_fn) # In[ ]: benign_completions = generate_completions(model, tokenizer, benign_dataloader) dump_to_file("/kaggle/working/benign_to_benign.jsonl", benign_prefs, benign_completions) # In[ ]: negative_prompt = "User: Generate a very negative, toxic, hateful, continuation for the statement: " benign_dataloader = get_dataloader(benign_prefs, negative_prompt, collate_fn=collate_fn) # In[ ]: toxic_completions = generate_completions(model, tokenizer, benign_dataloader) dump_to_file("/kaggle/working/benign_to_toxic.jsonl", benign_prefs, toxic_completions)
--- title: Dall-E 2 Gallery description: 3D gallery of Dall-E 2 images --- <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/c-frame/aframe-extras@7.0.0/dist/aframe-extras.min.js"></script> <script src="aframe-lightmap.js"></script> <script src="https://rawgit.com/fernandojsg/aframe-teleport-controls/master/dist/aframe-teleport-controls.min.js"></script> <script src="paintings.js"></script> <script src="hide-hallway.js"></script> <a-scene embedded renderer="colorManagement: true;"> <a-assets> <a-asset-item id="room" src="models/room.glb"></a-asset-item> <a-asset-item id="paintings" src="models/paintings.glb"></a-asset-item> <a-asset-item id="navmesh" src="models/gallery_navmesh.glb"></a-asset-item> <img id="lightmap_floor" src="textures/FloorLightMap.png"> <img id="lightmap_hallway" src="textures/HallwayLightmap.png"> <img id="lightmap_pillars" src="textures/PillarsLightMap.png"> <img id="lightmap_walls" src="textures/WallsLightmap.png"> <img id="lightmap_paintings" src="textures/PaintingsLightMap.png"> {% for i in (1..36) %} <img id="painting{{i}}" src="images/{{i}}.jpg"> {% endfor %} <audio id="music" src="arabesque.mp3" preload="auto"></audio> </a-assets> {% for i in (0..2) %} <a-entity gltf-model="#room" lightmap__floor="texture: #lightmap_floor; key: Floor" lightmap__hallway="texture: #lightmap_hallway; key: Hallway" lightmap__pillars="texture: #lightmap_pillars; key: Pillars" lightmap__walls="texture: #lightmap_walls; key: Walls" room-materials="floor_albedo:#floor_albedo" position="0 0 {{i | times: 14}}" {% if i==2 %} hide-hallway {%endif%}></a-entity> {% endfor %} {% for i in (0..2) %} {% assign offset = i | times: 12 %} <a-entity gltf-model="#paintings" paintings="{% for p in (1..12) %}{% assign index = p | plus: offset %} painting{{p}}:#painting{{index}};{% endfor %}lightmap:#lightmap_paintings;" position="0 0 {{i | times: 14}}"> </a-entity> {%endfor%} <a-entity gltf-model="#navmesh" nav-mesh visible="false" class="collidable"></a-entity> <a-entity id="cameraRig" rotation="0 180 0" movement-controls="constrainToNavMesh:true;controls:keyboard,touch"> <a-entity id="head" camera="active: true" look-controls="pointerLockEnabled:true;" position="0 1.6 0"> </a-entity> <a-entity oculus-touch-controls="hand: left" teleport-controls="button: trigger; collisionEntities: .collidable; cameraRig: #cameraRig; teleportOrigin: #head;"> </a-entity> <a-entity oculus-touch-controls="hand: right" teleport-controls="button: trigger; collisionEntities: .collidable; cameraRig: #cameraRig; teleportOrigin: #head;"> </a-entity> </a-entity> <!--- <a-entity id="leftHand" hand-tracking-controls="hand: left;"></a-entity> <a-entity id="rightHand" hand-tracking-controls="hand: right;"></a-entity> ---> <a-sky color="#f0f8ff"></a-sky> </a-scene> <script type="application/json" id="descriptions"> [ "A stunning digital painting of a girl with cat ears, with pink hair, pink eyes, pink butterfly wings with stars on them, wearing a white dress with floral patterns, a flower made out of crystal in the hair, a pink chocker with a metal heart in front, digital art", "A stunning digital painting in the style of neoclassicism of a foxgirl with red hair, red butterfly wings, with heterocromatic eyes, wearing a white and dark blue dress with constellations and zodiac signs on it. Digital art", "An abstract painting of a raccoon shown in the modern art museum", "A photograph of an orange cat playing with a supermassive black hole", "A confused looking cat sitting at a cat with a plate of vegetables in front of him, Ghibli style", "An expressive oil painting of a fox with butterfly wings, depicted as an explosion of a nebula", "A maid with cat ears on her head", "A low poly, low res, very chonky caracal cat, screenshot from Playstation console", "An expressive oil painting of a fox with butterfly wings, depicted as an explosion of a nebula", "Photograph of a very unique virtual japanese pop idol stage, geometric patterns, colorful, interesting shapes, very surreal, breaks the laws of physics", "Macro shot of a Lego Minifig which is completely white, without any face or hair. It's standing in the middle of an extremely colorful box made out of Lego bricks. The colors from the walls are reflected on the minifig. Well lit shot, strong depth of field.", "A girl with pink hair and pink twintails, black sweater. She has bows in her hair and a butterfly hairpin. She has pink cat ears and tail with a bow on the end. She is standing in front of the Eiffel Tower at dusk. Digital art, very detailed and expressive, trending on Artstation", "A macro photograph of a tiny Boeing 747 flying towards a flower. Studio lighting, strong depth of field", "A white cat dueling a huge rat. The cat is holding two corn cobs in his hand, while the rat is t-posing and wearing a Pope hat. The painting is extremely epic, very dramatic framing. Powerful and expressive digital art.", "A very cute, realistic looking smiling red fox looking at the viewer. The background is intricate and colorful, full of geometric floral patterns. Artwork by Louis Wain", "a cat's eye seen through a keyhole, oil painting", "Detailed painting mixing pixel art and realism. It shows a very surreal scene taking place around a table (Edited image through a collage of Minecraft paintings)", "Photograph of the Hindenburg disaster, but instead of the zeppelin there is a giant exploding carrot surrounded by smoke and flames, black and white, 1937", "A window to the multiverse, oil painting", "A window to the multiverse, oil painting", "Photograph of the lobby of an airship, clouds can be seen below looking out of the window, while on the top the red balloon of the airship and its ropes can be seen. The lobby is very large and Art Deco style, the floor is covered with a red carpet with a geometric patterns with triangles. There are fancy art deco sofas, a table with a gramophone, and paintings on the walls", "Virtual Reality, René Magritte, 1929", "Virtual Reality, René Magritte, 1929", "Cat with an apple in front of his face, René Magritte, 1929", "A stunning painting of a girl with cat ears, with pink hair, pink eyes, pink butterfly wings, wearing a white dress with floral patterns, a flower made out of crystal in the hair, a pink chocker with a metal heart in front. Sandro Botticelli, 1487", "This painting was created by having a grid of glasses each holding a different coloured liquid", "This painting was created by having a grid of glasses each holding a different coloured liquid", "A bunch of glasses each holding different coloured liquid that looks like every planet of the solar system", "A bunch of coloured glasses viewed from the top. Inside of each glass there are different depictions of the universe, including galaxies, planets, trees, single celled organisms, and the face of a man", "Marble sculpture of a hand, placed in front of an explosion of multicolored smoke", "Clay render of the cathedral of Santa Maria del Fiore", "The world's first cathedral dedicated to DMT entities, professional photograph from the interior", "Mario sprite from Super Mario Bros for the NES viewed through a kaleidoscope", "Up close photograph of a lightbulb with fireworks inside of it", "A man in the foreground is leaning over a railing inside of a spaceport, looking outside at a massive, magnificent spaceship floating over the void in the progress of docking. The spaceport orbiting right over Earth, and is in a steampunk style (This image is the result of multiple iterations of uncropping, starting from Renaissance style spaceship)", "A narrow art gallery, with white walls, white pillars, the roof seems to be open and bright sunlight is streaming in" ] </script> <script> const scene = document.querySelector("a-scene"); const rig = document.querySelector("#cameraRig"); let clicked = false; document.body.addEventListener("click", () => { if (!clicked) { let soundEntity = document.createElement("a-entity"); soundEntity.setAttribute("id", "music"); soundEntity.setAttribute("position", "0 10 14"); soundEntity.setAttribute("sound",{ loop:true, autoplay:true, rolloffFactor:0.01, src:"#music" }) scene.appendChild(soundEntity); clicked = true; } }); const descriptions = JSON.parse(document.getElementById('descriptions').innerHTML); for (let room = 0; room < 3; room++) { for (let face = 0; face < 4; face++) { for (let i = 0; i < 3; i++) { let index = room * 12 + face * 3 + i; let entity = document.createElement("a-entity"); entity.setAttribute("geometry", { primitive: "plane", height: "0.45", width: "1.1" }); entity.setAttribute("material", { "color": "#404040" }); entity.setAttribute("text", { value: descriptions[index], align: "center", color: "#ffffff", width: 1 }); let x = -5.49; let y = 2 + i * -2; let final_offset = 14 * room; let final_x, final_y; switch (face) { case 0: { final_x = x; final_y = y; break; } case 1: { final_x = -y; final_y = x; break; } case 2: { final_x = -x; final_y = -y; break; } case 3: { final_x = y; final_y = -x; break; } } final_y += final_offset; rotation = 90 + face * -90; entity.setAttribute("position", final_x.toString() + " 0.5 " + final_y.toString()); entity.setAttribute("rotation", "0 " + rotation.toString() + " 0"); scene.appendChild(entity); } } } </script>
import json import datetime import math from pathlib import Path from typing import Any, Union, Mapping, Optional, Iterator from pymongo.collection import ObjectId import numpy as np class JsonEncoder(json.JSONEncoder): def nan_to_none(self, o): if isinstance(o, dict): return {k: self.nan_to_none(v) for k, v in o.items()} elif isinstance(o, (tuple, list)): return [self.nan_to_none(v) for v in o] elif isinstance(o, float) and math.isnan(o): return None return o def encode(self, o: Any) -> str: return super().encode(self.nan_to_none(o)) def iterencode(self, o: Any, *args, **kwargs) -> Iterator[str]: return super().iterencode(self.nan_to_none(o), *args, **kwargs) def default(self, o: Any) -> Any: if isinstance(o, (datetime.date, datetime.datetime)): return o.isoformat() elif isinstance(o, (ObjectId, Path)): return str(o) elif isinstance(o, bytes): return o.decode(errors="ignore") elif isinstance(o, float): return None if math.isnan(o) else o try: return super().default(o) except TypeError: pass try: return int(o) except: pass try: float(o) except: pass raise TypeError(f"Object of type '{type(o).__name__}' is not JSON serializable") def to_json( data: Union[Mapping[str, Any], list, tuple], **kwargs, ) -> str: return json.dumps( data, cls=JsonEncoder, separators=(",", ":"), ensure_ascii=False, **kwargs, )
import { Component } from 'react'; import css from './Searchbar.module.css'; import Notiflix from 'notiflix'; import { GoSearch } from 'react-icons/go'; export class Searchbar extends Component { state = { guery: '', }; handleChange = e => { this.setState({ guery: e.currentTarget.value }); }; handleSubmit = e => { e.preventDefault(); if (this.state.guery.trim() === '') { return Notiflix.Notify.info('Please input a query'); } this.props.submit(this.state.guery); this.setState({ guery: '' }); }; render() { return ( <header className={css.searchbar}> <form className={css.searchForm} onSubmit={this.handleSubmit}> <div className={css.flexContainer}> <input onChange={this.handleChange} className={css.SearchFormInput} type="text" autoComplete="off" value={this.state.guery} autoFocus placeholder="Search images and photos" /> <button type="submit" className={css.SearchFormButton}> <GoSearch className={css.icon} size="24" color="red" /> </button> <label className={css.SearchFormButtonLabel}>Search</label> </div> </form> </header> ); } }
using System.Diagnostics; using System.Reflection; using FluentAssertions; // ReSharper disable MemberCanBePrivate.Local namespace Kabua.TypeSafe.xUnit.UnitTests; public class C51_Custom_InlineObject { /// <summary> /// Derive from <see cref="InlineObjectAttribute"/> to create your custom inline object data attribute.</summary> /// <remarks>Notice that you can mark the attribute private. Thus no information leakage.</remarks> private class SimpleStringDataAttribute : InlineObjectAttribute { protected override object GetObject(MemberInfo testMethod) => "simple test"; } [Theory] [SimpleStringData] public void T01_SimpleStringTest(string test) { test.Should().Be("simple test"); } // // ------------------------------------------------------------------------------------------------ // [FormattedTheory] [MySimpleObjectData("Bob", "Smith")] [MySimpleObjectData("Bob", "Smith", Age = 10)] [MySimpleObjectData("Alice", "Copper", Age = 50, Skip = "This Test")] public void T02_MySimpleObjectTest(MySimpleObject test) { test.FirstName.Should().Be("Bob"); test.LastName.Should().Be("Smith"); test.Age?.Should().Be(10); } private class MySimpleObjectDataAttribute : InlineObjectAttribute { public MySimpleObjectDataAttribute(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public string FirstName { get; } public string LastName { get; } public int Age { get; set; } /// <summary> /// Note: can't use nullable types in attributes so we will use a simple test. /// </summary> protected override object GetObject(MemberInfo testMethod) => new MySimpleObject(FirstName, LastName, Age > 0 ? Age : null); } public record MySimpleObject { public MySimpleObject(string firstName, string lastName, int? age = null) { FirstName = firstName; LastName = lastName; Age = age; } public string FirstName { get; } public string LastName { get; } public int? Age { get; } } }
import { Action } from "." export enum TransactionState { READY, INITIATED, WAITING, SENDING, DONE, } /** * Waits for the specified action's transaction to be set. * * @function waitForTransaction * @param {Action} action - The action object to check for a transaction. * @param {function} [loadingFunction] - An optional function to call while waiting for completion. * @returns {Promise<Action>} - A promise that resolves with the action once its transaction is set, or rejects after a certain number of retries. */ export const waitForTransaction = ( action: Action, loadingFunction?: (index: number) => void ): Promise<Action> => { return new Promise((resolve, reject) => { const maxRetries = 150 let attempts = 0 let index = 0 const checkTransaction = () => { index++ if (loadingFunction) loadingFunction(index) if (action.tx) { // check if tx is set (i.e., it has a truthy value) resolve(action) } else if (action.error) { reject(new Error(action.error)) } else if (attempts < maxRetries) { attempts++ // wait for some time before checking again setTimeout(checkTransaction, 100) } else { reject(new Error("Max retries reached without transaction.")) } } checkTransaction() }) } /** * Waits for the specified action to be completed. * * @function waitForCompletion * @param {Action} action - The action object to check for completion. * @param {function} [loadingFunction] - An optional function to call while waiting for completion. * @returns {Promise<Action>} - A promise that resolves with the action once it's completed, or rejects after a certain number of retries. */ export const waitForCompletion = ( action: Action, loadingFunction?: (index: number) => void ): Promise<Action> => { return new Promise((resolve, reject) => { const maxRetries = 150 let attempts = 0 let index = 0 const checkCompletion = () => { index++ if (loadingFunction) loadingFunction(index) if (action.completed) { resolve(action) } else if (action.error) { reject(new Error(action.error)) } else if (attempts < maxRetries) { attempts++ // wait for some time before checking again setTimeout(checkCompletion, 100) } else { reject(new Error("Max retries reached without completion.")) } } checkCompletion() }) }
import { Form, FormInstance, FormProps } from 'antd' import { createContext, useState } from 'react' const { useForm } = Form type AntdFromContextType<T = any> = | { form: FormInstance values: T } | undefined export const AntdFromContext = createContext<AntdFromContextType>(undefined) AntdFromContext.displayName = 'AntdFromContext' export function AntdFormProvider<T>(props: FormProps<T>) { const [values, setValues] = useState<T>() const [form] = useForm() return ( <AntdFromContext.Provider value={{ form, values, }} > <Form form={form} onValuesChange={(_, v) => setValues(v)} {...props} /> </AntdFromContext.Provider> ) }
import os import random import cv2 from PIL import Image from io import BytesIO import numpy as np import torch import torchvision.transforms as transforms import torchvision.transforms.functional as F from torch.utils.data import Dataset from utils.utils import open_lmdb class RotationTransform(): def __init__(self, angles): self.angles = angles def __call__(self, x): angle = random.choice(self.angles) return F.rotate(x, angle) class CELEBAHQ(Dataset): def __init__(self, config): super().__init__() self.config = config self.data_path = self.config["data_path"] self.mask_path = self.config["mask_path"] self.image_channel = self.config["image_channel"] self.image_size = self.config["image_size"] self.train = self.config["train"] if self.train: self.transform = transforms.Compose([ transforms.Resize((self.image_size, self.image_size)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,), inplace=True) ]) else: self.transform = transforms.Compose([ transforms.Resize((self.image_size, self.image_size)), transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,), inplace=True) ]) self.mask_files = [] path = os.path.join(self.mask_path, "train_mask" if self.train else "test_mask") for _, _, files in os.walk(path): for file in files: self.mask_files.append(os.path.join(path, file)) def mask_augment(self, mask_file): mask = 255 - cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE) _, mask = cv2.threshold(mask, int(256 * 0.6), 255, cv2.THRESH_BINARY) kernel_size = torch.randint(9, 50, (1,)).item() kernel = np.ones((kernel_size, kernel_size), np.uint8) mask = cv2.dilate(mask, kernel) mask = Image.fromarray(mask) mask = transforms.Compose([ RotationTransform(angles=[-90, 0, 90, 180]), transforms.RandomAffine(degrees=0, translate=(0.12, 0.12), fill=0), transforms.Resize((self.image_size, self.image_size)), transforms.ToTensor() ])(mask) # 0-1 matrix, 1 for mask # 1 x image_size x image_size return (mask > 0.99).float() def __len__(self): return 30000 def __getitem__(self, index): if not hasattr(self, 'txn'): self.txn = open_lmdb(self.data_path) key = f'256-{str(index).zfill(5)}'.encode('utf-8') img_bytes = self.txn.get(key) buffer = BytesIO(img_bytes) image = Image.open(buffer) image = self.transform(image) gt = image.mul(0.5).add(0.5).mul(255).add(0.5).clamp(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy() # 0-1 matrix, 1 for mask # 1 x image_size x image_size if self.train: selected_mask_file = self.mask_files[torch.randint(0, len(self.mask_files), (1,)).item()] selected_mask = self.mask_augment(selected_mask_file) while selected_mask.sum() / (selected_mask.shape[1] * selected_mask.shape[2]) <= 0.05: selected_mask_path = self.mask_files[torch.randint(0, len(self.mask_files), (1,)).item()] selected_mask = self.mask_augment(selected_mask_path) else: selected_mask_file = self.mask_files[torch.randint(0, len(self.mask_files), (1,)).item()] # resize interpolation threshold: 128 selected_mask = np.array(Image.open(selected_mask_file).resize((self.image_size, self.image_size))) selected_mask = torch.from_numpy((selected_mask >= 128).astype(np.uint8)).unsqueeze(0).float() masked_gt = (image.mul(0.5).add(0.5).mul(255).add(0.5).clamp(0, 255) * ( - selected_mask + 1.)).permute(1,2,0).to('cpu', torch.uint8).numpy() return { "index": index, "gt": gt, "x_0": image, "mask": selected_mask, # 1 x image_size x image_size "condition": image * ( - selected_mask + 1.), # 3 x image_size x image_size "masked_gt": masked_gt, # image_size x image_size x image_channel } @staticmethod def collate_fn(batch): batch_size = len(batch) idx = [] x_0 = [] gt = [] mask = [] condition = [] masked_gt = [] for i in range(batch_size): idx.append(batch[i]["index"]) x_0.append(batch[i]["x_0"]) gt.append(batch[i]["gt"]) mask.append(batch[i]["mask"]) condition.append(batch[i]["condition"]) masked_gt.append(batch[i]["masked_gt"]) x_0 = torch.stack(x_0, dim=0) mask = torch.stack(mask, dim=0) condition = torch.stack(condition, dim=0) return { "idx": idx, "x_0": x_0, "gts": np.asarray(gt), "mask": mask, "condition": condition, "masked_gts": np.array(masked_gt), }
import os import requests_cache # Create the cache directory if it doesn't exist if not os.path.exists("cache"): os.makedirs("cache") # Create the cache URLS_EXPIRE_AFTER = { 'manifold.markets/api/v0/group/by-id/': 3600 * 3, 'manifold.markets/api/v0/market/': 3600 * 3, 'metaculus.com/api2/questions/': 3600 * 3, 'manifold.markets/api/v0/slug/': 3600 * 24 * 365, # One year, since the slug is only used to grab the id, and the id shouldn't change 'futuur.com': 3600 * 3, 'api.futuur.com': 3600 * 3, } session = requests_cache.CachedSession( 'cache/requests_cache', backend='sqlite', expire_after=3600 * 3, urls_expire_after=URLS_EXPIRE_AFTER, stale_if_error=True ) def get(url, invalidate_cache=False, headers=None): # If invalidate_cache is true, clear the cache for this url if invalidate_cache: print(" xx Invalidating cache for " + url) session.cache.delete_url(url) r = session.get(url, headers=headers) # Was r cached? if r.from_cache: pass else: print(" >> " + url + " was not cached") return r # This is necessary because it's callable on Windows, and just a list on linux def _get_urls_list(): # Check if session.cache.urls is a list or function if callable(session.cache.urls): # If it's a function, call it to get the list of urls return list(session.cache.urls()) else: # If it's a list, just return it return list(session.cache.urls)[:] def clear_cache(platforms = None): if not platforms: # Clear the cache print("Clearing cache for all markets") # Get count of urls matching platform as we go count = 0 for url in _get_urls_list(): # Don't clear slugs, those shouldn't change if not "/slug/" in url: count += 1 session.cache.delete_url(url) print("Cleared " + str(count) + " urls.") else: # Clear the cache for each platform for platform in platforms: print("Clearing cache for " + platform) # Get count of urls matching platform as we go count = 0 for url in _get_urls_list(): # Check for url in the domain name only. Don't clear slugs, those shouldn't change if platform in url.split("/")[2] and not "/slug/" in url: count += 1 session.cache.delete_url(url) print("Cleared " + str(count) + " urls for " + platform)
import { Box, Button, Typography } from "@mui/material"; import React from "react"; import { GameOfLife } from "../../entity/Game"; import { Tile } from "../../entity/tile/ui/Tile"; const game = new GameOfLife(); export const GameBoard = () => { const [, updateState] = React.useState(); const forceUpdate = React.useCallback(() => updateState({}), []); const [generation, setGeneration] = React.useState(0); const [intervalId, setIntervalId] = React.useState(0); const handleStart = () => { const newIntervalId = setInterval(() => handleNewGeneration(), 25); setIntervalId(newIntervalId); }; const handleStop = () => { clearInterval(intervalId); }; const handleNewGeneration = () => { game.nextTurn(); forceUpdate(); }; const handleRestart = () => { handleStop(); game.restart(); forceUpdate(); }; return ( <> <Box sx={{ display: "flex", maxWidth: "616px", flexWrap: "wrap", borderColor: "#c9c9c9", border: "2px solid", borderRadius: "10px", padding: "5px", }} > {game.grid.map((row, index) => { return row.map((el, col) => { return <Tile key={index * 120 + col} isAlive={!!el} />; }); })} </Box> <Box sx={{ width: "600px", display: "flex", gap: 1, mt: 5 }}> <Button onClick={handleStart} variant="contained" fullWidth> Start </Button> <Button onClick={handleStop} variant="contained" fullWidth> Stop </Button> <Button onClick={handleRestart} variant="contained" fullWidth> Restart </Button> </Box> <Typography variant="h5" sx={{ mt: 2 }}> Generation #{game.generation} </Typography> </> ); };
import 'package:flutter/material.dart'; import 'package:flutter_portfolio/core/global_style/global_color.dart'; import 'package:flutter_portfolio/core/presentation/pages/home.dart'; import 'package:responsive_framework/responsive_framework.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Portfolio', theme: ThemeData( primarySwatch: Colors.purple, ), builder: (context, widget) => ResponsiveWrapper.builder( BouncingScrollWrapper.builder(context, widget!), defaultScale: true, breakpoints: [ const ResponsiveBreakpoint.resize(450, name: MOBILE), const ResponsiveBreakpoint.autoScale(800, name: TABLET), const ResponsiveBreakpoint.autoScale(1000, name: TABLET), const ResponsiveBreakpoint.resize(1200, name: DESKTOP), const ResponsiveBreakpoint.autoScale(2460, name: "4K"), ], background: Container(color: kColorBackground), ), home: const HomePage(), ); } }
/* eslint-disable react/prop-types */ import React, { useState, useEffect } from 'react'; import { View } from 'react-native'; import * as Animatable from 'react-native-animatable'; import styles from '../utils/styles'; /** * BubbleOverlay Component. * Generates an animated overlay of bubbles. * * @param {Object} props - The component properties. * @param {number} [props.bubbleCount=150] - Number of bubbles to be displayed. * @param {number} [props.minRadius=5] - Minimum radius size for the bubbles. * @param {number} [props.maxRadius=100] - Maximum radius size for the bubbles. * @param {string} [props.bubbleColor='rgba(255, 255, 255, 0.1)'] - The color of the bubbles. * * @returns {JSX.Element} A View component containing animated bubbles. */ const BubbleOverlay = ({ bubbleCount = 150, minRadius = 5, maxRadius = 100, bubbleColor = 'rgba(255, 255, 255, 0.1)', }) => { const [bubbles] = useState(Array.from({ length: bubbleCount })); // Generate random values for bubbles' motion const generateRandomValue = () => { return Math.random() * 200 - 100; // Random value between -100 and 100 }; // Generate random bubble size within limits const generateRandomSize = () => { return Math.random() * (maxRadius - minRadius) + minRadius; }; useEffect(() => { // Create a timer to update the bubbles' positions periodically const bubbleTimer = setInterval(() => { // No need to set bubbles, just trigger re-render }, 100); // You can adjust the interval as needed return () => { clearInterval(bubbleTimer); // Clear the timer on component unmount }; }, []); return ( <View style={styles.overlay}> {bubbles.map((_, index) => { const bubbleSize = generateRandomSize(); // Random size for each bubble return ( <Animatable.View key={index} animation={{ from: { top: '100%', // Start from the bottom left: '50%', // Start from the horizontal center }, to: { top: `${generateRandomValue()}%`, // Move upwards left: `${generateRandomValue()}%`, // Random horizontal position }, }} iterationCount="infinite" duration={Math.random() * 10000 + 5000} easing="linear" style={[ styles.bubble, { width: bubbleSize, height: bubbleSize, backgroundColor: bubbleColor, }, ]} /> ); })} </View> ); }; export default BubbleOverlay;
package com.example.e_hotelsapplication import android.content.ContentValues import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.ActionBar import androidx.core.view.GravityCompat import androidx.recyclerview.widget.LinearLayoutManager import com.example.e_hotelsapplication.Adapters.Restaurant_list_adapter import com.example.e_hotelsapplication.Data.Menu import com.example.e_hotelsapplication.Data.Restaurant import com.example.e_hotelsapplication.Data.RestaurantListData import com.example.e_hotelsapplication.databinding.ActivityRestaurentListBinding import com.google.firebase.database.* import com.google.firebase.database.ktx.getValue class RestaurentListActivity : AppCompatActivity(), Restaurant_list_adapter.RestaurantListClickListener { private lateinit var binding: ActivityRestaurentListBinding private lateinit var database:DatabaseReference private lateinit var adapater:Restaurant_list_adapter private lateinit var restaurantlist:ArrayList<Restaurant> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRestaurentListBinding.inflate(layoutInflater) setContentView(binding.root) val actionbar:ActionBar?=supportActionBar actionbar?.setTitle( "Restaurant List") restaurantlist = ArrayList() adapater = Restaurant_list_adapter(this, restaurantlist, this) binding.recyclerview.layoutManager = LinearLayoutManager(this) binding.recyclerview.setHasFixedSize(true) binding.recyclerview.adapter = adapater binding.imageView.setOnClickListener{ val intent = Intent(this@RestaurentListActivity, LoginActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } binding.navimage.setOnClickListener{ binding.drawerlayout.openDrawer(GravityCompat.START) } binding.nav.setNavigationItemSelectedListener { item -> Log.i(ContentValues.TAG, "onNavigationItemSelected:" + item.itemId) when (item.itemId) { R.id.about -> { Toast.makeText(applicationContext, "clicked", Toast.LENGTH_SHORT).show() } R.id.settings -> { } R.id.share -> { } R.id.contact -> { } } binding.drawerlayout.closeDrawer(GravityCompat.START) Log.i(ContentValues.TAG, "onNavigationItemSelected:nothing clicked") false } getRestaurantData() } private fun getRestaurantData() { database = FirebaseDatabase.getInstance().getReference( "Restaurants") database.addValueEventListener(object: ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()){ snapshot.children.forEach { Log.d("snapshot", it.toString()) } } for (restaurantListSnapshot in snapshot.children){ val restaurant = restaurantListSnapshot.getValue(Restaurant::class.java) restaurantlist.add(restaurant!!) } binding.recyclerview.adapter =adapater } override fun onCancelled(error: DatabaseError) { Toast.makeText(this@RestaurentListActivity, error.message,Toast.LENGTH_SHORT).show() Log.e(ContentValues.TAG, "error") } }) } //passing the key "RestaurantListData" to CheckoutActivity because its parcelable override fun onItemClick(restaurantlist: Restaurant) { val intent = Intent(this@RestaurentListActivity,CheckoutActivity::class.java) intent.putExtra("RestaurantListData", restaurantlist) startActivity(intent) } }
// // String + Extensions.swift // Troshko // // Created by Faris Hurić on 17. 9. 2023.. // import Foundation extension String { var trimmed: String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } var localized: String { return NSLocalizedString(self, comment: "") } func localized(arguments: CVarArg...) -> String { return String(format: self.localized, arguments: arguments) } func toFloat() -> Float { return Float(self) ?? 0.0 } func toDouble(locale: Locale = Locale.current) -> Double { let numberFormatter = NumberFormatter() numberFormatter.locale = locale numberFormatter.numberStyle = .decimal guard let number = numberFormatter.number(from: self) else { return 0.0 } return number.doubleValue } }
import { INestApplication, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import cookieParser from 'cookie-parser'; import helmet from 'helmet'; import SwaggerOptions from './base/core/infrastructure/api/doc/swagger/swagger.options'; import DomainFilterException from './base/core/infrastructure/api/exception/domain-filter.exception'; import ValidatorOptions from './base/core/infrastructure/api/validator/config/validator.options'; import VersioningConfig from './base/core/infrastructure/api/versioning/versioning.config'; import AppModule from './base/core/infrastructure/app.module'; import JobService from '@/base/core/infrastructure/gateway/job/job.service'; import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true }); setupMiddlewares(app); await start(app); } function setupMiddlewares(app: INestApplication) { app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER)); app.use(helmet()); app.use(cookieParser()); app.enableCors({ credentials: true, origin: true, }); app.setGlobalPrefix('simple-nest-js-template'); app.enableVersioning(VersioningConfig.uri()); app.useGlobalPipes(ValidatorOptions.validatorGlobal()); app.useGlobalFilters(new DomainFilterException()); } async function start(app: INestApplication) { const configService = app.get(ConfigService); const host = configService.get('APP_HOST'); const port = configService.get('APP_PORT'); app.get(SwaggerOptions).setup(app); await app.listen(port, host, async () => { Logger.log(`App listen on ${await app.getUrl()}`, 'NestApplication'); await app.get(JobService).config(); }); } bootstrap().then();
--- title: Aspose.Tasks إدارة المشاريع والتخصيص linktitle: Aspose.Tasks إدارة المشاريع والتخصيص second_title: Aspose.Tasks .NET API description: أتقن Aspose.Tasks لـ .NET من خلال برامجنا التعليمية لإدارة المشاريع. تعلم تقنيات المعالجة والتخصيص والتحسين الفعالة لملفات MS Project. type: docs weight: 23 url: /ar/net/tasks-project-management/ --- ## مقدمة هل أنت مستعد لرفع مستوى مهاراتك في إدارة المشاريع باستخدام Aspose.Tasks لـ .NET؟ تغطي برامجنا التعليمية الشاملة مجموعة من المواضيع، بدءًا من إتقان أساليب MS Project ذات القيمة المكتسبة وحتى إدارة سمات المشروع بكفاءة وتخصيص مخططات جانت. دعونا نتعمق في عالم Aspose.Tasks ونفتح الإمكانات الكاملة لإدارة المشاريع. ## إتقان أنواع أساليب MS Project ذات القيمة المكتسبة باستخدام Aspose.Tasks استكشف تعقيدات أنواع طرق القيمة المكتسبة لـ MS Project باستخدام Aspose.Tasks لـ .NET. يوفر برنامجنا التعليمي إرشادات خطوة بخطوة لتعزيز كفاءة إدارة المشروع دون عناء.[إتقان أساليب مشروع MS ذات القيمة المكتسبة باستخدام Aspose.Tasks](./earned-value-method-types/) ## التعامل مع السمات الموسعة لـ MS Project باستخدام Aspose.Tasks أطلق العنان لقوة التعامل مع سمات MS Project الموسعة برمجياً. تعرف على خصوصيات وعموميات العمل باستخدام السمات الموسعة باستخدام Aspose.Tasks لـ .NET.[التعامل مع السمات الموسعة لـ MS Project باستخدام Aspose.Tasks](./working-with-extended-attributes/) ## إدارة مجموعة سمات مشروع MS في Aspose.Tasks إدارة مجموعة سمات MS Project بكفاءة باستخدام Aspose.Tasks لـ .NET. يمكنك التعامل مع سمات المهمة بسلاسة من خلال إرشاداتنا التفصيلية خطوة بخطوة.[إدارة مجموعة سمات مشروع MS في Aspose.Tasks](./extended-attribute-collection/) ## إتقان تعريفات السمات الموسعة لمشروع MS في Aspose.Tasks تعلم كيفية تخصيص بيانات مشروعك وتحسينها بسهولة من خلال إتقان تعريفات السمات الموسعة في Microsoft Project باستخدام Aspose.Tasks لـ .NET.[إتقان تعريفات السمات الموسعة لمشروع MS في Aspose.Tasks](./extended-attribute-definition-collection/) ## تكامل مشروع MS المساعد الميداني في Aspose.Tasks استفد من Aspose.Tasks لـ .NET للعمل مع ملفات MS Project بسلاسة. يرشدك البرنامج التعليمي الخاص بنا حول تكامل Field Helper خلال العملية دون عناء.[تكامل مشروع MS المساعد الميداني في Aspose.Tasks](./field-helper/) ## تصفية البيانات بكفاءة باستخدام Aspose.Tasks عزز قدرات الإنتاجية والتحليل من خلال تعلم كيفية تصفية البيانات في ملفات MS Project باستخدام Aspose.Tasks لـ .NET.[تصفية البيانات بكفاءة باستخدام Aspose.Tasks](./filtering-data/) ## إدارة مرشحات مشروع MS بكفاءة باستخدام Aspose.Tasks إدارة مجموعات مرشح MS Project بشكل فعال باستخدام Aspose.Tasks لـ .NET. يوفر برنامجنا التعليمي رؤى وإرشادات خطوة بخطوة.[إدارة مرشحات مشروع MS بكفاءة باستخدام Aspose.Tasks](./filter-collection/) ## إتقان معايير تصفية مشروع MS باستخدام Aspose.Tasks تعزيز كفاءة إدارة المشروع من خلال تحليل البيانات المستهدفة. تعرف على كيفية تنفيذ معايير التصفية في MS Project باستخدام Aspose.Tasks لـ .NET.[إتقان معايير تصفية مشروع MS باستخدام Aspose.Tasks](./filter-criteria/) ## معالجة الخطوط في مشروع MS لـ Aspose.Tasks اكتشف المطورين كيفية التعامل مع الخطوط في ملفات MS Project باستخدام Aspose.Tasks لـ .NET. دليلنا خطوة بخطوة يجعل الأمر سهلاً.[معالجة الخطوط في مشروع MS لـ Aspose.Tasks](./font-saving-arguments/) ## تخصيص أنماط شريط جانت باستخدام Aspose.Tasks قم بتخصيص أنماط شريط جانت في MS Project بسهولة باستخدام Aspose.Tasks لـ .NET. تعزيز تصور المشروع وإقناع أصحاب المصلحة.[تخصيص أنماط شريط جانت باستخدام Aspose.Tasks](./gantt-bar-styles/) ## تخصيص أعمدة مخطط جانت باستخدام Aspose.Tasks قم بتخصيص أعمدة مخطط جانت في Aspose.Tasks لـ .NET لعرض معلومات مهمة محددة بكفاءة. يرشدك برنامجنا التعليمي خلال عملية التخصيص.[تخصيص أعمدة مخطط جانت باستخدام Aspose.Tasks](./gantt-chart-columns/) ## إتقان طرق عرض مخطط جانت في Aspose.Tasks تبدأ الإدارة الفعالة للمشروعات من خلال عروض مخططات جانت المخصصة في ملفات Microsoft Project باستخدام Aspose.Tasks لـ .NET. اتبع دليلنا خطوة بخطوة.[إتقان طرق عرض مخطط جانت في Aspose.Tasks](./gantt-chart-views/) ## تخصيص خطوط الشبكة في مشروع MS لـ Aspose.Tasks يمكنك تحسين تصور المشروع وإدارته من خلال تعلم كيفية تخصيص خطوط الشبكة في MS Project باستخدام Aspose.Tasks لـ .NET.[تخصيص خطوط الشبكة في مشروع MS لـ Aspose.Tasks](./gridlines/) ## تخصيص خطوط شبكة المشروع باستخدام Aspose.Tasks لـ .NET اضبط إعدادات خطوط الشبكة برمجيًا في ملفات Microsoft Project باستخدام Aspose.Tasks لـ .NET لتصور المشروع وإدارته بكفاءة.[تخصيص خطوط شبكة المشروع باستخدام Aspose.Tasks لـ .NET](./gridlines-management/) ## تجميع مهام مشروع MS بكفاءة باستخدام Aspose.Tasks قم بتجميع مهام Microsoft Project بشكل فعال باستخدام Aspose.Tasks لـ .NET. يرشدك البرنامج التعليمي الخاص بنا خلال العملية دون عناء.[تجميع مهام مشروع MS بكفاءة باستخدام Aspose.Tasks](./grouping-tasks/) ## إدارة مجموعات المشروع في Aspose.Tasks تعرف على كيفية إدارة مجموعات MS Project بكفاءة باستخدام Aspose.Tasks لـ .NET. اتبع دليلنا خطوة بخطوة.[إدارة مجموعات المشروع في Aspose.Tasks](./group-collection/) ## التلاعب بمعايير مجموعة مشروع MS في Aspose.Tasks اكتشف كيفية التعامل مع ملفات MS Project برمجياً في .NET باستخدام Aspose.Tasks. استرجع معلومات مجموعة المهام والمعيار باستخدام الأمثلة خطوة بخطوة.[التلاعب بمعايير مجموعة مشروع MS في Aspose.Tasks](./group-criteria/) ## إدارة معايير مجموعة مشروع MS باستخدام Aspose.Tasks إدارة مجموعة Group Criterion MS Project بكفاءة باستخدام Aspose.Tasks لـ .NET. يوفر برنامجنا التعليمي دليلاً خطوة بخطوة للمطورين.[إدارة معايير مجموعة مشروع MS باستخدام Aspose.Tasks](./group-criterion-collection/) ## قم باستخراج معلومات الرأس والتذييل باستخدام Aspose.Tasks تعلم كيفية استخراج معلومات الرأس والتذييل من ملفات MS Project باستخدام Aspose.Tasks لـ .NET. الحل الذي نقدمه سهل وفعال وسهل للمطورين.[قم باستخراج معلومات الرأس والتذييل باستخدام Aspose.Tasks](./header-footer-information/) أطلق العنان للإمكانات الكاملة لـ Aspose.Tasks لـ .NET من خلال برامجنا التعليمية. تعمق في كل موضوع لتعزيز مهاراتك في إدارة المشروعات وتبسيط سير عملك. تعلم سعيد! --- ## Aspose.Tasks إدارة المشاريع ودروس التخصيص ### [إتقان أساليب مشروع MS ذات القيمة المكتسبة باستخدام Aspose.Tasks](./earned-value-method-types/) إتقان أنواع أساليب MS Project ذات القيمة المكتسبة باستخدام Aspose.Tasks لـ .NET. تعزيز كفاءة إدارة المشروع دون عناء. ### [التعامل مع السمات الموسعة لـ MS Project باستخدام Aspose.Tasks](./working-with-extended-attributes/) تعرف على كيفية العمل مع السمات الموسعة لـ MS Project باستخدام Aspose.Tasks لـ .NET. التعامل مع بيانات المهمة برمجيا بكل سهولة. ### [إدارة مجموعة سمات مشروع MS في Aspose.Tasks](./extended-attribute-collection/) تعرف على كيفية إدارة السمات الموسعة لـ MS Project بكفاءة باستخدام Aspose.Tasks لـ .NET. يمكنك التعامل مع سمات المهمة بسلاسة من خلال إرشادات خطوة بخطوة. ### [إتقان تعريفات السمات الموسعة لمشروع MS في Aspose.Tasks](./extended-attribute-definition-collection/) تعرف على كيفية إدارة تعريفات السمات الموسعة في Microsoft Project باستخدام Aspose.Tasks لـ .NET. قم بتخصيص وتحسين بيانات مشروعك دون عناء. ### [تكامل مشروع MS المساعد الميداني في Aspose.Tasks](./field-helper/) تعرف على كيفية الاستفادة من Aspose.Tasks لـ .NET للعمل مع ملفات MS Project بسلاسة. ### [تصفية البيانات بكفاءة باستخدام Aspose.Tasks](./filtering-data/) تعرف على كيفية تصفية البيانات في ملفات MS Project باستخدام Aspose.Tasks لـ .NET. تعزيز قدرات الإنتاجية والتحليل دون عناء. ### [إدارة مرشحات مشروع MS بكفاءة باستخدام Aspose.Tasks](./filter-collection/) تعرف على كيفية إدارة مجموعات تصفية MS Project بشكل فعال باستخدام Aspose.Tasks لـ .NET. ### [إتقان معايير تصفية مشروع MS باستخدام Aspose.Tasks](./filter-criteria/) تعرف على كيفية تنفيذ معايير التصفية في MS Project باستخدام Aspose.Tasks لـ .NET. تعزيز كفاءة إدارة المشروع من خلال تحليل البيانات المستهدفة. ### [معالجة الخطوط في مشروع MS لـ Aspose.Tasks](./font-saving-arguments/) تعرف على كيفية التعامل مع الخطوط في ملفات MS Project باستخدام Aspose.Tasks لـ .NET. دليل خطوة بخطوة للمطورين. ### [تخصيص أنماط شريط جانت باستخدام Aspose.Tasks](./gantt-bar-styles/) تعرف على كيفية تخصيص أنماط شريط جانت في MS Project باستخدام Aspose.Tasks لـ .NET. تعزيز تصور المشروع دون عناء. ### [تخصيص أعمدة مخطط جانت باستخدام Aspose.Tasks](./gantt-chart-columns/) تعرف على كيفية تخصيص أعمدة مخطط جانت في Aspose.Tasks لـ .NET لعرض معلومات مهمة محددة بكفاءة. ### [إتقان طرق عرض مخطط جانت في Aspose.Tasks](./gantt-chart-views/) تعرف على كيفية تخصيص طرق عرض مخطط جانت في ملفات Microsoft Project باستخدام Aspose.Tasks لـ .NET. دليل خطوة بخطوة لإدارة المشاريع بكفاءة. ### [تخصيص خطوط الشبكة في مشروع MS لـ Aspose.Tasks](./gridlines/) تعرف على كيفية تخصيص خطوط الشبكة في MS Project باستخدام Aspose.Tasks لـ .NET. عزز تصور مشروعك وإدارته بخطوات سهلة المتابعة. ### [ تخصيص خطوط شبكة المشروع باستخدام Aspose.Tasks لـ .NET](./gridlines-management/) تعرف على كيفية ضبط إعدادات خطوط الشبكة برمجيًا في ملفات Microsoft Project باستخدام Aspose.Tasks لـ .NET وتصور المشروع وكفاءة الإدارة. ### [تجميع مهام مشروع MS بكفاءة باستخدام Aspose.Tasks](./grouping-tasks/) تعرف على كيفية تجميع مهام Microsoft Project بشكل فعال باستخدام Aspose.Tasks لـ .NET. ### [إدارة مجموعات المشروع في Aspose.Tasks](./group-collection/) تعرف على كيفية إدارة مجموعات MS Project بكفاءة باستخدام Aspose.Tasks لـ .NET. اتبع دليلنا خطوة بخطوة. ### [التلاعب بمعايير مجموعة مشروع MS في Aspose.Tasks](./group-criteria/) اكتشف كيفية التعامل مع ملفات MS Project برمجياً في .NET باستخدام Aspose.Tasks. استرداد مجموعة المهام ومعلومات المعيار بأمثلة خطوة بخطوة. ### [إدارة معايير مجموعة مشروع MS باستخدام Aspose.Tasks](./group-criterion-collection/) تعرف على كيفية إدارة مجموعة Group Criterion MS Project باستخدام Aspose.Tasks لـ .NET. دليل خطوة بخطوة للمطورين. ### [قم باستخراج معلومات الرأس والتذييل باستخدام Aspose.Tasks](./header-footer-information/) تعلم كيفية استخراج معلومات الرأس والتذييل من ملفات MS Project باستخدام Aspose.Tasks لـ .NET. حل سهل وفعال وصديق للمطورين.
#+Title: Bootstrapping steps #+Author: Systems Team #+SETUPFILE: ./org-templates/level-0.org #+TAGS: boilerplate(b) #+EXCLUDE_TAGS: boilerplate #+OPTIONS: ^:nil * Install git #+BEGIN_EXAMPLE yum install git -y #+END_EXAMPLE * Cloning Repository #+BEGIN_EXAMPLE git clone https://github.com/vlead/cluster-automation.git cd cluster-automation #+END_EXAMPLE * Update variables in =bootstrap.sh= file After cloning repository open bootstrap.sh file and changedvariables then run make #+BEGIN_EXAMPLE #! /bin/bash # Host machine's root user password PASSWORD_HOSTMACHINE=vlead123 # Set network proxy, http_proxy and https_proxy HTTP_PROXY="http://proxy.iiit.ac.in:8080" HTTPS_PROXY="http://proxy.iiit.ac.in:8080" ## Required fields for setting up network in in host machine, Router container and config-server container. ## So that these three machines will get internet connection. ## Router and config-servers are containers. ## Following fields should be taken from LAN network which has internet HOSTMACHINE_IP=10.4.59.220 ROUTER_IP=10.4.59.221 CONFIG_SERVER_IP=10.4.59.222 DNS1=10.4.12.160 DNS2=10.4.12.220 INTERNET_GATEWAY=10.2.56.1 NET_MASK=255.255.252.0 ## Set Root password of cluster containers CONTAINER_ROOT_PASSWORD=rootpassword ## Set name of the cluster CLUSTERNAME=base8 ## Server name through which mails will be delivered to specified email address in /etc/mail/sendmail.mc. #Each cluster container will be sending mails through this server SMTP_SMART_HOST=stpi-router.vlabs.ac.in #Set the Proxy if network proxy denying ssh port CORKSCREW_PROXY=proxy.iiit.ac.in #Set network proxy port PROXY_PORT=8080 # Path for common variables for cluster automation playbooks COMMONVARS_PATH=build/code/imp/roles/common-vars/vars/main.yml HOST_PATH=build/code/imp/hosts sed -i '/proxy=.*/d' /etc/yum.conf echo "proxy=$HTTP_PROXY" >> /etc/yum.conf ## Install required packages yum install epel-release -y yum install ansible -y yum install emacs -y yum install sshpass -y echo 'Please press "n" if keys are already generated' ssh-keygen -t rsa -f /root/.ssh/id_rsa -q -P "" echo 'StrictHostKeyChecking no' >> /etc/ssh/ssh_config sudo mknod -m 666 /dev/tty c 5 0 sshpass -p $PASSWORD_HOSTMACHINE ssh-copy-id root@localhost sshpass -p $PASSWORD_HOSTMACHINE ssh-copy-id root@127.0.0.1 ## Have a copy of original file cp $COMMONVARS_PATH $COMMONVARS_PATH.bkp sed -i "s|http_proxy_name:.*|http_proxy_name: $HTTP_PROXY|g" "$COMMONVARS_PATH" sed -i "s|https_proxy_name:.*|https_proxy_name: $HTTPS_PROXY|g" "$COMMONVARS_PATH" sed -i "s|hostmachine_ip:.*|hostmachine_ip: $HOSTMACHINE_IP|g" "$COMMONVARS_PATH" sed -i "s|router_ip:.*|router_ip: $ROUTER_IP|g" "$COMMONVARS_PATH" sed -i "s|config_server_ip:.*|config_server_ip: $CONFIG_SERVER_IP|g" "$COMMONVARS_PATH" sed -i "s|dns1_server:.*|dns1_server: $DNS1|g" "$COMMONVARS_PATH" sed -i "s|dns2_server:.*|dns2_server: $DNS2|g" "$COMMONVARS_PATH" sed -i "s|clustername:.*|clustername: $CLUSTERNAME|g" "$COMMONVARS_PATH" sed -i "s|container_root_password:.*|container_root_password: $CONTAINER_ROOT_PASSWORD|g" "$COMMONVARS_PATH" sed -i "s|smtp_smart_host:.*|smtp_smart_host: $SMTP_SMART_HOST|g" "$COMMONVARS_PATH" sed -i "s|proxy_port:.*|proxy_port: $PROXY_PORT|g" "$COMMONVARS_PATH" sed -i "s|internet_gateway:.*|internet_gateway: $INTERNET_GATEWAY|g" "$COMMONVARS_PATH" sed -i "s|net_mask:.*|net_mask: $NET_MASK|g" "$COMMONVARS_PATH" sed -i "s|corkscrew_proxy:.*|corkscrew_proxy: $CORKSCREW_PROXY|g" "$COMMONVARS_PATH" sed -i "/[config-server]/{ n; s/10.2.*/$CONFIG_SERVER_IP/; }" $HOST_PATH sed -i "|^ansible-playbook .*|d" /etc/rc.local echo "cd ~/cluster-automation/build/code/imp/" >> /etc/rc.local echo "ansible-playbook -i hosts cluster.yml" >> /etc/rc.local cat ~/.ssh/id_rsa.pub echo "Please add above diplayed key in systems-model repository." read -p "Have you added host machine's public key ( ~/.ssh/id_rsa.pub) in bitbucket.org in systems-model repository " -n 1 -r echo "Please press Y or y to continue." if [[ ! $REPLY =~ ^[Yy]$ ]] then cd ~/cluster-automation/build/code/imp/ && ansible-playbook -i hosts base-machine-setup.yml fi echo "Please press Y or y to setup base machine" #+END_EXAMPLE
import { Typography } from '@mui/material' import React from 'react' function Title({variant="h6", sx={}, children, ...props}) { const _component = typeof variant !== 'object' ? variant : variant.xl || variant.lg || variant.md || variant.sm || variant.xs || "h6"; const _variantStyles = typeof variant !== 'object' ? variant : { xs: variant.xs, sm: variant.sm || variant.xs, md: variant.md || variant.sm || variant.xs, lg: variant.lg || variant.md || variant.sm || variant.xs, xl: variant.xl || variant.lg || variant.md || variant.sm || variant.xs, } return ( <Typography variant="" sx={{ ...sx, typography: typeof _variantStyles === "object" && _variantStyles, fontWeight:`${sx.fontWeight || 600}!important ` }} component={_component} {...props} > {children} </Typography> ) } export default Title
<?php namespace Drupal\Tests\Core\EventSubscriber; use Drupal\Tests\UnitTestCase; use \Drupal\Core\EventSubscriber\PsrResponseSubscriber; /** * @coversDefaultClass \Drupal\Core\EventSubscriber\PsrResponseSubscriber * @group EventSubscriber */ class PsrResponseSubscriberTest extends UnitTestCase { /** * The tested path root subscriber. * * @var \Drupal\Core\EventSubscriber\PsrResponseSubscriber */ protected $psrResponseSubscriber; /** * The tested path root subscriber. * * @var \Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $httpFoundationFactoryMock; /** * {@inheritdoc} */ protected function setUp() { $factory = $this->getMock('Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface', [], [], '', NULL); $factory ->expects($this->any()) ->method('createResponse') ->willReturn($this->getMock('Symfony\Component\HttpFoundation\Response')); $this->httpFoundationFactoryMock = $factory; $this->psrResponseSubscriber = new PsrResponseSubscriber($this->httpFoundationFactoryMock); } /** * Tests altering and finished event. * * @covers ::onKernelView */ public function testConvertsControllerResult() { $event = $this->createEventMock($this->getMock('Psr\Http\Message\ResponseInterface')); $event ->expects($this->once()) ->method('setResponse') ->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Response')); $this->psrResponseSubscriber->onKernelView($event); } /** * Tests altering and finished event. * * @covers ::onKernelView */ public function testDoesNotConvertControllerResult() { $event = $this->createEventMock([]); $event ->expects($this->never()) ->method('setResponse'); $this->psrResponseSubscriber->onKernelView($event); $event = $this->createEventMock(NULL); $event ->expects($this->never()) ->method('setResponse'); $this->psrResponseSubscriber->onKernelView($event); } /** * Sets up an alias event that return $controllerResult. * * @param mixed $controller_result * The return Object. * * @return \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent|\PHPUnit_Framework_MockObject_MockObject * A mock object to test. */ protected function createEventMock($controller_result) { $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent', [], [], '', NULL); $event ->expects($this->once()) ->method('getControllerResult') ->willReturn($controller_result); return $event; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="./lib/vue.js"></script> </head> <body> <div id="app"> 姓: <input v-model="person.firstName"/> 名: <input v-model="person.lastName" /> <hr/> 计算属性: 全名: {{ fullName }}, {{ fullName }}, {{ fullName }} <hr/> 方法调用: 全名: {{ quanming() }}, {{ quanming() }}, {{ quanming() }} <input ref="xingming" /> <button @click="setName">设置名字</button> 全名 普通属性 {{ person.fname }} </div> <script> // 关于 计算属性 new Vue({ el: '#app', data: { person: { firstName: 'zhang', lastName: 'san', fname: 'zhang san' } }, methods: { quanming() { console.log('正在计算 全名: 方法调用') return this.person.firstName + ' ' + this.person.lastName }, setName() { let name = this.$refs.xingming.value; console.log(name); this.fullName = name; } }, // watch 监控属性的变化 watch: { // 想一想 watch监控 的意义 // 当数据模型 firstName 发生变化, 那么调用此函数, // 参数 newValue 最新的值, oldValue 上一次的值 'person.firstName': function(newValue, oldValue) { console.log('新值', newValue); console.log('老值', oldValue); this.person.fname = newValue + ' ' + this.person.lastName }, 'person.lastName': function(newValue, oldValue) { this.person.fname = this.person.firstName + ' ' + newValue } }, computed: { // 计算属性定义 // 只计算一次 然后缓存, 除非 依赖的其他属性发生变化, 然后再次计算 // fullName() { // 依赖于 firstName lastName // console.log('正在计算 全名: 计算属性') // return this.person.firstName + ' ' + this.person.lastName // } fullName: { get() { console.log('正在计算 全名: 计算属性') return this.person.firstName + ' ' + this.person.lastName }, set(value) { let parts = value.split(' '); this.person.firstName = parts[0]; this.person.lastName = parts[1]; } } } }) </script> </body> </html>
#ifndef FAIR_2_TASK_ASSIGNMENT_H #define FAIR_2_TASK_ASSIGNMENT_H #include <vector> #include <string> #include <iostream> #include <algorithm> #include "Debug.h" /* Elements of programming interview, Sorting: Compute an optimum assignment of tasks We consider the problem of scheduling n = 2m tasks to be performed by m workers. Each worker must be assigned exactly two tasks. Each task has a duration. Tasks are independent, i.e., there are no constraints of the form "Task 4 cannot start before Task 3 is completed." We want to assign tasks to workers so as to minimize how long it takes before all tasks are completed. Given an array of even task durations. Divide the array into subsets where each subset has exactly 2 tasks , such that the maximum subset sum of the 2-task durations over all subsets is minimized. (Special case of PaintersPartitionFairWorkload.h) O(nlogn) time */ class Fair2TaskAssignment { public: Fair2TaskAssignment(){} ~Fair2TaskAssignment(){} std::vector<std::pair<int, int>> Partition(std::vector<int> && v) { std::string before = Debug::ToStr1D<int>()(v); std::sort(v.begin(), v.end(), std::less<int>()); int N = v.size(); std::vector<std::pair<int, int> > res; for (int i = 0, j = N - 1; i < j; ++i, --j) res.emplace_back(v[i], v[j]); std::cout << "Fair2TaskAssignment for \"" << before << "\": " << Debug::ToStr1D<int>()(res) << std::endl; return res; } }; /* Fair2TaskAssignment for "18, 3, 12, 9, 7, 17, 4, 11, 14, 20, 5, 1, 8, 15, 6, 10, 13, 16, 19, 2": [1,20], [2,19], [3,18], [4,17], [5,16], [6,15], [7,14], [8,13], [9,12], [10,11] */ #endif
package com.encore.test.test; public class ReferenceMain { /* * 기본타입과 참조타입 차이점: * 기본타입은 선언과 동시에 값을 할당할 수 있다. * 기본타입은 값을 담는 변수 * * 그러나 * 참조타입은 선언과 동시에 값을 할당할 수 없다. * 참조타입은 값을 담는 변수가 아니라, 주소값을 담는 변수이다. * 주소값을 담기 위해서는 객체생성이 선행되어야 한다. * 객체 생성시 사용하는 연산자는 new * new 뒤에는 생성자(Constructor) 호출 * * 참조타입 : 클래스, 배열, 자료구조, enum, etc... */ public static void main(String[] args) { StudentVO stuObj = new StudentVO(); System.out.println("인스턴스 소유의 메서드 호출 : "); stuObj.setName("섭섭해"); String returnValue = stuObj.getName(); System.out.println(returnValue); System.out.println(stuObj.getName()); // 접근제어자가 public 일 때 가능한 코드 // System.out.println("인스턴스 소유의 변수 호출 : " + stuObj.name); // stuObj.name = "포케"; // System.out.println("인스턴스 소유의 변수 호출 : " + stuObj.name); } }
# Multipanel Figure with Tikz This is an example of generating a multipanel figure using Tikz/Latex. See [figures](./figures/) for more formats. ## Examples ### SVG ![figure-1](./figures/figure-1.svg) ### PNG ![figure-1](./figures/figure-1.png) #### PNG Draft ![figure-1](./figures/figure-1-draft.png) ### PDF [pdf](./figures/figure-1.pdf). ## Setup To get started you'll need `texlive` and `inkscape`. Optionally, I recommend `GNUmake` for tying together see the included [`Makefile`](./Makefile). ## Why? The main benefit of this approach is visual consistency and precise alignment using entirely imperative definitions. This approach simplifies the hassle of updating a figure in the eleventh hour prior to submission. Simply update the underlying panel's file and run `make pdfs`. No more pointing and clicking (or propriety software)! ## Friction The main disadvantage of this approach is using `svg` formats which are generally preferred for simple plots. Latex can not easily ingest these as graphics, the workaround provided here is first converting all `svg`'s into `pdf`'s. Similarly if you require an `svg` or `png` output for use in other formats (docx/pptx/web) you can use `inkscape` for the final conversion. ## Docker? If you prefer to use a docker container for figure generation and don't want to need texlive and inkscape, locally open an issue Then when I have time, I'll add a `Dockerfile` and instructions for use.
package com.springboot.project.controller; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.springboot.project.model.Employee; import com.springboot.project.service.imp.EmployeeService; @RestController @RequestMapping("/api/employeee") public class EmployeeController { //DI private EmployeeService employeeService; //Constructor public EmployeeController(EmployeeService employeeService) { super(); this.employeeService = employeeService; } //Build create employee REST API @PostMapping public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee){ return new ResponseEntity<Employee>(employeeService.saveEmployee(employee), HttpStatus.CREATED); } @GetMapping public List<Employee> getAllEmployee(){ return employeeService.getAllEmployee(); } @GetMapping("{id}") public ResponseEntity<Employee> getEmployeeById(@PathVariable ("id") long employeeId){ return new ResponseEntity<Employee> (employeeService.getEmployeeById(employeeId), HttpStatus.OK); } @PutMapping("{id}") public ResponseEntity<Employee> updateEmployee(@PathVariable("id") long id, @RequestBody Employee employee ){ return new ResponseEntity<Employee> (employeeService.updateEmployee(employee,id),HttpStatus.OK); } @DeleteMapping("{id}") public ResponseEntity<String> deleteEmplpoyee(@PathVariable ("id") long id){ employeeService.deleteEmployee(id); return new ResponseEntity<String>("Employee data deleted successfully" ,HttpStatus.OK); } }
<template> <div class="pa-search"> <i class="iconfont icon-search"></i> <!--type 为search时,根据用户输入修改内容会出错--> <input ref="search" type="text" class="pa-search-input" v-model="currentValue" :placeholder="placeholder" @keypress="keypress"/> <button type="button" class="pa-search-button" v-tap="search">查询</button> </div> </template> <script> /** * pa-search * @desc 搜索框 * * @param {String} [placeholder] - 输入框提示文字 * @param {Null} [value] - 双向绑定数据 * @param {Boolean} [autoFocus] - 输入框是否自动获取焦点 */ export default { name: 'pa-search', props: { placeholder: String, value: null, autoFocus: { type: Boolean, default: false } }, mounted() { this.autoFocus && this.$refs.search.focus(); }, computed: { currentValue: { get() { return this.value; }, set(val) { this.$emit('input', val); } } }, methods: { search() { this.$emit('search', this.currentValue); }, keypress(e) { const ENTER_KEY = 13; if (Number(e.keyCode) === ENTER_KEY) { e.preventDefault(); this.search(); } } } }; </script> <style lang="less" scoped> @import "../assets/less/utils"; .pa-search { display: flex; padding: 10px 10px 0 20px; position: relative; font-size: 14px; .icon-search { font-size: 20px; color: #666; position: absolute; left: 30px; top: 13px; } } .pa-search-input { display: flex; flex: 1; background: #fff; height: 28px; border-radius: 5px; padding-left: 30px; border: 1px solid #979797; &::placeholder{ color: @textColor; } } .pa-search-button { background-color: @blue; color: #fff; width: 60px; border-radius: 4px; margin-left: 10px; height: 28px; } </style>
import { Schema, model } from "mongoose"; import Joi from "joi"; import {handleMongooseError} from "../helpers/handleMongooseError.js"; const createContactSchema = Joi.object({ name: Joi.string().min(3).required(), email: Joi.string() .email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org", "co", "uk"] }, }) .required(), phone: Joi.string() .regex(/^\(\d{3}\) \d{3}-\d{4}$/) .required(), favorite: Joi.boolean(), }); const updateContactSchema = Joi.object({ name: Joi.string().min(3), email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org", "co", "uk"] }, }), phone: Joi.string().regex(/^\(\d{3}\) \d{3}-\d{4}$/), favorite: Joi.boolean(), }); const updateFavoriteSchema = Joi.object({ favorite: Joi.boolean().required().messages({ "boolean.empty": "missing field favorite", "any.required": "missing field favorite", }), }) const contactShema = new Schema( { name: { type: String, required: [true, "Set name for contact"], }, email: { type: String, }, phone: { type: String, }, favorite: { type: Boolean, default: false, }, owner: { type: Schema.Types.ObjectId, ref: "user", }, }, { versionKey: false, timestamps: true } ); contactShema.post("save", handleMongooseError); const Contact = model("contacts", contactShema); export { createContactSchema, updateContactSchema, updateFavoriteSchema, Contact };
'use strict'; // necessary for es6 output in node import { browser, element, by, ElementFinder, ElementArrayFinder } from 'protractor'; import { promise } from 'selenium-webdriver'; const expectedH1 = 'Tour of Tasks'; const expectedTitle = `${expectedH1}`; const targetTask = { id: 11, description: 'Task1' }; const targetTaskDashboardIndex = 3; const nameSuffix = 'X'; const newTaskName = targetTask.description + nameSuffix; class Task { id: number; description: string; // Factory methods // Task from string formatted as '<id> <name>'. static fromString(s: string): Task { return { id: +s.substr(0, s.indexOf(' ')), description: s.substr(s.indexOf(' ') + 1), }; } // Task from task list <li> element. static async fromLi(li: ElementFinder): Promise<Task> { let stringsFromA = await li.all(by.css('a')).getText(); let strings = stringsFromA[0].split(' '); return { id: +strings[0], description: strings[1] }; } // Task id and name from the given detail element. static async fromDetail(detail: ElementFinder): Promise<Task> { // Get task id from the first <div> let _id = await detail.all(by.css('div')).first().getText(); // Get name from the h2 let _name = await detail.element(by.css('h2')).getText(); return { id: +_id.substr(_id.indexOf(' ') + 1), description: _name.substr(0, _name.lastIndexOf(' ')) }; } } describe('Tutorial part 6', () => { beforeAll(() => browser.get('')); function getPageElts() { let navElts = element.all(by.css('app-root nav a')); return { navElts: navElts, appDashboardHref: navElts.get(0), appDashboard: element(by.css('app-root app-dashboard')), topTasks: element.all(by.css('app-root app-dashboard > div h4')), appTasksHref: navElts.get(1), appTasks: element(by.css('app-root app-tasks')), allTasks: element.all(by.css('app-root app-tasks li')), selectedTaskSubview: element(by.css('app-root app-tasks > div:last-child')), taskDetail: element(by.css('app-root app-task-detail > div')), searchBox: element(by.css('#search-box')), searchResults: element.all(by.css('.search-result li')) }; } describe('Initial page', () => { it(`has title '${expectedTitle}'`, () => { expect(browser.getTitle()).toEqual(expectedTitle); }); it(`has h1 '${expectedH1}'`, () => { expectHeading(1, expectedH1); }); const expectedViewNames = ['Dashboard', 'Tasks']; it(`has views ${expectedViewNames}`, () => { let viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText()); expect(viewNames).toEqual(expectedViewNames); }); it('has dashboard as the active view', () => { let page = getPageElts(); expect(page.appDashboard.isPresent()).toBeTruthy(); }); }); describe('Dashboard tests', () => { beforeAll(() => browser.get('')); it('has top tasks', () => { let page = getPageElts(); expect(page.topTasks.count()).toEqual(4); }); it(`selects and routes to ${targetTask.description} details`, dashboardSelectTargetTask); it(`updates task name (${newTaskName}) in details view`, updateTaskNameInDetailView); it(`cancels and shows ${targetTask.description} in Dashboard`, () => { element(by.buttonText('go back')).click(); browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 let targetTaskElt = getPageElts().topTasks.get(targetTaskDashboardIndex); expect(targetTaskElt.getText()).toEqual(targetTask.description); }); it(`selects and routes to ${targetTask.description} details`, dashboardSelectTargetTask); it(`updates task name (${newTaskName}) in details view`, updateTaskNameInDetailView); it(`saves and shows ${newTaskName} in Dashboard`, () => { element(by.buttonText('save')).click(); browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 let targetTaskElt = getPageElts().topTasks.get(targetTaskDashboardIndex); expect(targetTaskElt.getText()).toEqual(newTaskName); }); }); describe('Tasks tests', () => { beforeAll(() => browser.get('')); it('can switch to Tasks view', () => { getPageElts().appTasksHref.click(); let page = getPageElts(); expect(page.appTasks.isPresent()).toBeTruthy(); expect(page.allTasks.count()).toEqual(10, 'number of tasks'); }); it('can route to task details', async () => { getTaskLiEltById(targetTask.id).click(); let page = getPageElts(); expect(page.taskDetail.isPresent()).toBeTruthy('shows task detail'); let task = await Task.fromDetail(page.taskDetail); expect(task.id).toEqual(targetTask.id); expect(task.description).toEqual(targetTask.description.toUpperCase()); }); it(`updates task name (${newTaskName}) in details view`, updateTaskNameInDetailView); it(`shows ${newTaskName} in Tasks list`, () => { element(by.buttonText('save')).click(); browser.waitForAngular(); let expectedText = `${targetTask.id} ${newTaskName}`; expect(getTaskAEltById(targetTask.id).getText()).toEqual(expectedText); }); it(`deletes ${newTaskName} from Tasks list`, async () => { const tasksBefore = await toTaskArray(getPageElts().allTasks); const li = getTaskLiEltById(targetTask.id); li.element(by.buttonText('x')).click(); const page = getPageElts(); expect(page.appTasks.isPresent()).toBeTruthy(); expect(page.allTasks.count()).toEqual(9, 'number of tasks'); const tasksAfter = await toTaskArray(page.allTasks); // console.log(await Task.fromLi(page.allTasks[0])); const expectedTasks = tasksBefore.filter(h => h.name !== newTaskName); expect(tasksAfter).toEqual(expectedTasks); // expect(page.selectedTaskSubview.isPresent()).toBeFalsy(); }); it(`adds back ${targetTask.description}`, async () => { const newTaskName = 'Alice'; const tasksBefore = await toTaskArray(getPageElts().allTasks); const numTasks = tasksBefore.length; element(by.css('input')).sendKeys(newTaskName); element(by.buttonText('add')).click(); let page = getPageElts(); let tasksAfter = await toTaskArray(page.allTasks); expect(tasksAfter.length).toEqual(numTasks + 1, 'number of tasks'); expect(tasksAfter.slice(0, numTasks)).toEqual(tasksBefore, 'Old tasks are still there'); const maxId = tasksBefore[tasksBefore.length - 1].id; expect(tasksAfter[numTasks]).toEqual({id: maxId + 1, description: newTaskName}); }); it('displays correctly styled buttons', async () => { element.all(by.buttonText('x')).then(buttons => { for (const button of buttons) { // Inherited styles from styles.css expect(button.getCssValue('font-family')).toBe('Arial'); expect(button.getCssValue('border')).toContain('none'); expect(button.getCssValue('padding')).toBe('5px 10px'); expect(button.getCssValue('border-radius')).toBe('4px'); // Styles defined in tasks.component.css expect(button.getCssValue('left')).toBe('194px'); expect(button.getCssValue('top')).toBe('-32px'); } }); const addButton = element(by.buttonText('add')); // Inherited styles from styles.css expect(addButton.getCssValue('font-family')).toBe('Arial'); expect(addButton.getCssValue('border')).toContain('none'); expect(addButton.getCssValue('padding')).toBe('5px 10px'); expect(addButton.getCssValue('border-radius')).toBe('4px'); }); }); describe('Progressive task search', () => { beforeAll(() => browser.get('')); it(`searches for 'Ma'`, async () => { getPageElts().searchBox.sendKeys('Ma'); browser.sleep(1000); expect(getPageElts().searchResults.count()).toBe(4); }); it(`continues search with 'g'`, async () => { getPageElts().searchBox.sendKeys('g'); browser.sleep(1000); expect(getPageElts().searchResults.count()).toBe(2); }); it(`continues search with 'e' and gets ${targetTask.description}`, async () => { getPageElts().searchBox.sendKeys('n'); browser.sleep(1000); let page = getPageElts(); expect(page.searchResults.count()).toBe(1); let task = page.searchResults.get(0); expect(task.getText()).toEqual(targetTask.description); }); it(`navigates to ${targetTask.description} details view`, async () => { let task = getPageElts().searchResults.get(0); expect(task.getText()).toEqual(targetTask.description); task.click(); let page = getPageElts(); expect(page.taskDetail.isPresent()).toBeTruthy('shows task detail'); let task2 = await Task.fromDetail(page.taskDetail); expect(task2.id).toEqual(targetTask.id); expect(task2.name).toEqual(targetTask.description.toUpperCase()); }); }); async function dashboardSelectTargetTask() { let targetTaskElt = getPageElts().topTasks.get(targetTaskDashboardIndex); expect(targetTaskElt.getText()).toEqual(targetTask.description); targetTaskElt.click(); browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6 let page = getPageElts(); expect(page.taskDetail.isPresent()).toBeTruthy('shows task detail'); let task = await Task.fromDetail(page.taskDetail); expect(task.id).toEqual(targetTask.id); expect(task.description).toEqual(targetTask.description.toUpperCase()); } async function updateTaskNameInDetailView() { // Assumes that the current view is the task details view. addToTaskName(nameSuffix); let page = getPageElts(); let task = await Task.fromDetail(page.taskDetail); expect(task.id).toEqual(targetTask.id); expect(task.description).toEqual(newTaskName.toUpperCase()); } }); function addToTaskName(text: string): promise.Promise<void> { let input = element(by.css('input')); return input.sendKeys(text); } function expectHeading(hLevel: number, expectedText: string): void { let hTag = `h${hLevel}`; let hText = element(by.css(hTag)).getText(); expect(hText).toEqual(expectedText, hTag); }; function getTaskAEltById(id: number): ElementFinder { let spanForId = element(by.cssContainingText('li span.badge', id.toString())); return spanForId.element(by.xpath('..')); } function getTaskLiEltById(id: number): ElementFinder { let spanForId = element(by.cssContainingText('li span.badge', id.toString())); return spanForId.element(by.xpath('../..')); } async function toTaskArray(allTasks: ElementArrayFinder): Promise<Task[]> { let promisedTasks = await allTasks.map(Task.fromLi); // The cast is necessary to get around issuing with the signature of Promise.all() return <Promise<any>> Promise.all(promisedTasks); }
CREATE DATABASE demoImageDB; use demoImageDB; -- SHOW TABLES; -- SELECT ROUTINE_NAME -- FROM information_schema.ROUTINES -- WHERE ROUTINE_TYPE = 'FUNCTION' AND ROUTINE_SCHEMA = 'database_name'; -- SHOW TRIGGERS; -- SHOW PROCEDURE STATUS WHERE Db = 'imageDB'; -- User Define Function CREATE FUNCTION image_sim RETURNS REAL SONAME 'sim_api.so'; CREATE FUNCTION clip RETURNS STRING SONAME 'clip_api.so'; -- Create Table CREATE TABLE image_table ( ID INT AUTO_INCREMENT PRIMARY KEY, img_path VARCHAR(255) NOT NULL, img_type1 int DEFAULT(-1), img_type2 int DEFAULT(-1), img_type3 int DEFAULT(-1), ground_truth int DEFAULT(-1) ); -- Some Procedure, Trigger, Function DELIMITER // CREATE PROCEDURE SplitString( IN input_string VARCHAR(255), OUT part1 VARCHAR(255), OUT part2 VARCHAR(255), OUT part3 VARCHAR(255) ) BEGIN -- Extract the first part SET part1 = REPLACE(SUBSTRING_INDEX(input_string, '_', 1), '$', ''); -- Extract the second part by removing the first part and extracting the next segment SET part2 = SUBSTRING_INDEX(SUBSTRING_INDEX(input_string, '_', 2), '_', -1); -- Extract the third part by removing the first two parts and extracting the next segment SET part3 = REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(input_string, '_', 3), '_', -1), '$', ''); END // DELIMITER ; DELIMITER // CREATE TRIGGER AfterImageInsert BEFORE INSERT ON image_table FOR EACH ROW BEGIN -- Calling the 'clip' function with the 'path' column of the new row and storing the result SET @result = clip(NEW.img_path); CALL SplitString(@result, @part1, @part2, @part3); SET NEW.img_type1 = CONVERT(@part1, UNSIGNED INTEGER); SET NEW.img_type2 = CONVERT(@part2, UNSIGNED INTEGER); SET NEW.img_type3 = CONVERT(@part3, UNSIGNED INTEGER); END // DELIMITER ; DELIMITER $$ CREATE PROCEDURE fastest_sim( IN input_image VARCHAR(255)) BEGIN SET @result = clip(input_image); CALL SplitString(@result, @c1, @c2, @c3); SELECT ground_truth, img_path, image_sim(img_path, input_image) AS sim FROM image_table WHERE img_type1 IN (@c1, @c2, @c3) ORDER BY sim DESC; END$$ DELIMITER ; DELIMITER $$ CREATE PROCEDURE faster_sim( IN input_image VARCHAR(255)) BEGIN SET @result = clip(input_image); CALL SplitString(@result, @c1, @c2, @c3); SELECT ground_truth, img_path, image_sim(img_path, input_image) AS sim FROM image_table WHERE (img_type1 IN (@c1, @c2, @c3) OR img_type2 IN (@c1, @c2, @c3)) ORDER BY sim DESC; END$$ DELIMITER ; DELIMITER $$ CREATE PROCEDURE fast_sim( IN input_image VARCHAR(255)) BEGIN SET @result = clip(input_image); CALL SplitString(@result, @c1, @c2, @c3); SELECT ground_truth, img_path, image_sim(img_path, input_image) AS sim FROM image_table WHERE (img_type1 IN (@c1, @c2, @c3) OR img_type2 IN (@c1, @c2, @c3) OR img_type3 IN (@c1, @c2, @c3)) ORDER BY sim DESC; END$$ DELIMITER ; -- DEMO -- insert an image and show its auto-tagging results -- /mysqludf/imgs/n02099601/n02099601_268.JPEG INSERT INTO image_table (img_path) VALUES ('/mysqludf/imgs/n02124075/n02124075_428.JPEG'); SELECT * FROM image_table; -- insert some images to show other functions INSERT INTO image_table (img_path) VALUES ('/mysqludf/imgs/n02124075/n02124075_1183.JPEG'); INSERT INTO image_table (img_path) VALUES ('/mysqludf/imgs/n01833805/n01833805_169.JPEG'); -- Similarity Search by another image SELECT img_path, image_sim(img_path, '/mysqludf/imgs/n02124075/n02124075_1183.JPEG') AS sim FROM image_table; -- Setting a real number threshold SELECT img_path FROM image_table WHERE image_sim(img_path, '/mysqludf/imgs/n02124075/n02124075_1183.JPEG') > 0.8; -- use text to search SELECT img_path, image_sim(img_path, 'A cat') AS Sim FROM image_table WHERE image_sim(img_path, 'A cat') > 0; -- More Similarity Algorithm SELECT img_path, image_sim(img_path, '/mysqludf/imgs/n02124075/n02124075_1183.JPEG', 'LPIPS') AS Sim_LPIPS FROM image_table; SELECT img_path, image_sim(img_path, '/mysqludf/imgs/n02124075/n02124075_1183.JPEG', 'PSNR') AS Sim_PSNR FROM image_table; SELECT img_path, image_sim(img_path, '/mysqludf/imgs/n02124075/n02124075_1183.JPEG', 'SSIM') AS Sim_SSIM FROM image_table; -- faster_sim SET @image_path = '/mysqludf/imgs/n02124075/n02124075_1183.JPEG'; CALL fastest_sim(@image_path); -- Large Data Experiments are shown in a python notebook named experiments.ipynb -- DROP DATABASE demoImageDB;
#pragma once // cereal #include <cereal/cereal.hpp> // cereal archive #include <cereal/archives/json.hpp> // cereal std #include <cereal/types/string.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/unordered_map.hpp> #include <cereal/types/array.hpp> #include <cereal/types/queue.hpp> #include <cereal/types/set.hpp> #include <cereal/types/bitset.hpp> #include <cereal/types/memory.hpp> #include <cereal/types/map.hpp> #include <cereal/types/base_class.hpp> #include <cereal/types/polymorphic.hpp> // glm #include <glm/glm.hpp> // sfml #include <SFML/Graphics.hpp> #include <SFML/System.hpp> // SERIALIZE FUNCTION DEFINITIONS FOR SFML, GLM, & OTHER LIBRARY TYPES // ALSO INCLUDES INCLUDE HEADERS FOR ALL OF THE NECESSARY STANDARD LIBRARY TYPES namespace glm { // glm::vec3 template<class Archive> void serialize(Archive& archive, vec3& v3) { archive(cereal::make_nvp("x", v3.x), cereal::make_nvp("y", v3.y), cereal::make_nvp("z", v3.z)); } // glm::vec2 template<class Archive> void serialize(Archive& archive, vec2& v2) { archive(cereal::make_nvp("x", v2.x), cereal::make_nvp("y", v2.y)); } } namespace sf { // sf::Vector2f template<class Archive> void serialize(Archive& archive, Vector2f v2) { archive(cereal::make_nvp("x", v2.x), cereal::make_nvp("y", v2.y)); } // sf::Vector2i template<class Archive> void serialize(Archive& archive, Vector2i v2) { archive(cereal::make_nvp("x", v2.x), cereal::make_nvp("y", v2.y)); } // sf::Color template<class Archive> void serialize(Archive& archive, Color& c) { archive(cereal::make_nvp("r", c.r), cereal::make_nvp("g", c.g), cereal::make_nvp("b", c.b), cereal::make_nvp("a", c.a)); } // sf::FloatRect template<class Archive> void serialize(Archive& archive, FloatRect& fr) { archive(cereal::make_nvp("left", fr.left), cereal::make_nvp("top", fr.top), cereal::make_nvp("width", fr.width), cereal::make_nvp("height", fr.height)); } }
import * as me from 'melonjs'; import {setLevel} from "./globals"; class TitleScreen extends me.Stage { /** * action to perform on state change */ onResetEvent() { const backgroundImage = new me.Sprite( me.game.viewport.width / 2, me.game.viewport.height / 2, { image: me.loader.getImage('title_screen'), } ); // scale to fit with the viewport size backgroundImage.scale( me.game.viewport.width / backgroundImage.width, me.game.viewport.height / backgroundImage.height ); // add to the world container me.game.world.addChild(backgroundImage, 1); // create Endlessrun text const PlayText = new me.BitmapText( me.game.viewport.width / 2, me.game.viewport.height / 1.5 - 30, { font: 'PressStart2P', text: 'PLAY', textAlign: 'center', size: 0.5, } ); PlayText.anchorPoint.set(0.5, 0.5); me.game.world.addChild(PlayText); // create Levelselect text const LevelSelectText = new me.BitmapText( me.game.viewport.width / 2, me.game.viewport.height / 1.5, { font: 'PressStart2P', text: 'LEVELSELECT', textAlign: 'center', size: 0.5, } ); LevelSelectText.anchorPoint.set(0.5, 0.5); me.game.world.addChild(LevelSelectText); // create Highscore text const HighscoreText = new me.BitmapText( me.game.viewport.width / 2, me.game.viewport.height / 1.5 + 30, { font: 'PressStart2P', text: 'HIGHSCORE', textAlign: 'center', size: 0.5, } ); HighscoreText.anchorPoint.set(0.5, 0.5); me.game.world.addChild(HighscoreText); // register mouse click event on the canvas me.input.registerPointerEvent('pointerdown', me.game.viewport, (event) => { const PlayBounds = PlayText.getBounds(); const LevelSelect = LevelSelectText.getBounds(); const highscoreBounds = HighscoreText.getBounds(); // check if the click position is within the bounds of the respective texts if ( event.gameWorldY >= PlayBounds.top && event.gameWorldY <= PlayBounds.bottom ) { setLevel('Lvl1-1'); me.state.change(me.state.PLAY); } else if ( event.gameWorldY >= LevelSelect.top && event.gameWorldY <= LevelSelect.bottom ) { me.state.change(me.state.SETTINGS); } else if ( event.gameWorldY >= highscoreBounds.top && event.gameWorldY <= highscoreBounds.bottom ) { me.state.change(me.state.SCORE); } }); } /** * action to perform when leaving this screen (state change) */ onDestroyEvent() { me.input.releasePointerEvent('pointerdown', me.game.viewport); } /** * action to perform to start the game */ } export default TitleScreen;
//{ Driver Code Starts // Initial Template for Java import java.util.*; import java.lang.*; import java.math.*; import java.io.*; class GFG { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int b[] = new int[n]; for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } Solution obj = new Solution(); List<Integer> ans = obj.maxCombinations(n, k, a, b); for (int e : ans) System.out.print(e + " "); System.out.println(); } } } // } Driver Code Ends // User function Template for Java class Pair{ int i,j; public Pair(int i,int j){ this.i=i; this.j=j; } //why? public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Pair)) { return false; } Pair obj = (Pair)o; return (i == obj.i && j == obj.j); } public int hashCode() { return Objects.hash(i, j); } } class Three implements Comparable<Three>{ int val,i,j; public Three(int val,int i,int j){ this.val=val; this.i=i; this.j=j; } //pq gives priority to the value(val) or sum. public int compareTo(Three p){ return p.val-this.val; } } class Solution { static List<Integer> maxCombinations(int N, int K, int A[], int B[]) { // code here List<Integer> list=new ArrayList<>(); PriorityQueue<Three> pq=new PriorityQueue<Three>(); HashSet<Pair> set=new HashSet<>(); Arrays.sort(A); Arrays.sort(B); int i=N-1; int j=N-1; pq.add(new Three(A[i]+B[j],i,j)); set.add(new Pair(i,j)); for(int l=0;l<K;l++){ Three p=pq.poll(); list.add(p.val); //for i-1,j values int im=p.i - 1; int jm=p.j; if(im>=0 && jm>=0 && !set.contains(new Pair(im,jm))){ set.add(new Pair(im,jm)); pq.add(new Three(A[im]+B[jm],im,jm)); } //for i,j-1 values im=p.i; jm=p.j - 1; if(im>=0 && jm>=0 && !set.contains(new Pair(im,jm))){ set.add(new Pair(im,jm)); pq.add(new Three(A[im]+B[jm],im,jm)); } } return list; } }
import { fetchWithSession, Method } from '@/lib/fetch-with-refresh'; import { ApiPaginatedResponse } from '@/models/api-paginated-response'; import { HelloEvent } from '@/models/hello-event'; export async function getOrganizerEventsPaginated( pageNumber: number = 1, pageSize: number = 100, title?: string, state?: string, orderBy?: string, orderByDesc?: boolean ): Promise<ApiPaginatedResponse<HelloEvent>> { let url = `organizer-events?PageNumber=${pageNumber}&PageSize=${pageSize}`; if (title) { url += `&title=${title}`; } if (state) { url += `&state=${state}`; } if (orderBy) { url += `&OrderBy=${orderBy}`; } if (orderByDesc) { url += `&Descending=${orderByDesc}`; } const response = await fetchWithSession(url, Method.GET); if (!response.ok) { throw new Error('Failed to fetch events'); } const responseData: ApiPaginatedResponse<HelloEvent> = await response.json(); if (responseData.error) { throw new Error('Error in response data'); } return responseData; }
import { ShoppingCart } from "@mui/icons-material"; import { AppBar, Badge, IconButton, List, ListItem, Switch, Toolbar, Typography, } from "@mui/material"; import { Box } from "@mui/system"; import { NavLink } from "react-router-dom"; import { history } from "../.."; import { useAppSelector } from "../store/configureStore"; import SignedInMenu from "./SignedInMenu"; interface Props { darkMode: boolean; handleThemeChange: () => void; } const midLinks = [ { title: "catalog", path: "/catalog", }, { title: "about", path: "/about", }, { title: "contact", path: "/contact", }, ]; const rightLinks = [ { title: "login", path: "/login", }, { title: "register", path: "/register", }, { title: "contact", path: "/contact", }, ]; const navStyles = { color: "inherit", textDecoration: "none", typography: "h6", "&:hover": { color: "gray", }, "&.active": { color: "text.secondary", }, }; export default function Header({ darkMode, handleThemeChange }: Props) { const { basket } = useAppSelector((state) => state.basket); const { user } = useAppSelector((state) => state.account); const itemCount = basket?.items.reduce((sum, item) => sum + item.quantity, 0); return ( <AppBar position="static" sx={{ mb: 4 }}> <Toolbar sx={{ display: "flex", justifyContent: "space-between", alignContent: "center", }} > <Box display="flex" alignItems="center"> <Typography variant="h6" component={NavLink} to="/" sx={navStyles}> RE-STORE </Typography> <Switch checked={darkMode} onChange={() => handleThemeChange()} /> </Box> <List sx={{ display: "flex" }}> {midLinks.map(({ title, path }) => ( <ListItem component={NavLink} to={path} key={path} sx={navStyles}> {title.toUpperCase()} </ListItem> ))} {user && user.roles?.includes("Admin") && ( <ListItem component={NavLink} to={"/inventory"} sx={navStyles}> INVENTORY </ListItem> )} </List> <Box display="flex" alignItems="center"> <IconButton onClick={() => history.push("/basket")} size="large" sx={{ color: "inherit" }} > <Badge badgeContent={itemCount} color="secondary"> <ShoppingCart /> </Badge> </IconButton> {user ? ( <SignedInMenu /> ) : ( <List sx={{ display: "flex" }}> {rightLinks.map(({ title, path }) => ( <ListItem component={NavLink} to={path} key={path} sx={navStyles} > {title.toUpperCase()} </ListItem> ))} </List> )} </Box> </Toolbar> </AppBar> ); }
extends Node2D class_name RicePot @onready var timer: Timer = $Timer @onready var progress: TextureProgressBar = $TextureProgressBar enum State {IDLE, COOKING, DONE, FINISHED} const COOKING_TIME = 6 var elapsed_time: int var state: State = State.IDLE func update_position() -> void: position += Vector2(0, -16) func timer_finished() -> void: elapsed_time += 1 progress.value = elapsed_time # label.text = "%ds" % elapsed_time if (elapsed_time >= COOKING_TIME): timer.stop() # label.text = "Done" state = State.DONE func start() -> void: if state != State.IDLE: return progress.visible = true state = State.COOKING elapsed_time = 0 timer.connect("timeout", timer_finished) timer.wait_time = 1.0 timer.start() func is_done() -> bool: return state == State.DONE func finish() -> void: if state != State.DONE: return state = State.FINISHED progress.visible = false # label.visible = false # Called when the node enters the scene tree for the first time. func _ready() -> void: set_meta("item_type", "RicePot") set_meta("merges", "SalmonSashimi") state = State.IDLE elapsed_time = 0 progress.visible = false progress.position.y -= 20 progress.min_value = 0 progress.max_value = COOKING_TIME progress.value = 0 progress.step = 1.0 / COOKING_TIME start() # Called every frame. 'delta' is the elapsed time since the previous frame. #func _process(delta: float) -> void: #pass
<template> <el-popover v-model:visible="popoverVisible" placement="right" trigger="click" :show-arrow="false" > <template #reference> <li class="px-4 cursor-pointer h-9 flex items-center gap-2 rounded-lg bg-[#242A40] transition-colors hover:text-white" > <svg-icon name="question-circle" svg-class="w-4 h-4" /> {{ $t('联系与帮助') }} </li> </template> <div class="bg-white rounded-lg flex flex-col text-[#3d3d3d] text-sm space-y-4 py-2 pl-2"> <p v-for="item in helpList" :key="item.icon" @click.stop="onHelpClick(item.link)" class="hover:text-[#909399] cursor-pointer flex items-center gap-2 whitespace-nowrap" > <svg-icon :name="item.icon" svg-class="w-4 h-4" /> {{ item.title }} </p> </div> </el-popover> </template> <script setup lang="ts"> import useSpaceRights from '@/composables/useSpaceRights' import { ESpaceRightsType } from '@/enum/space' import { ref } from 'vue' import { useI18n } from 'vue-i18n' import { useSpaceStore } from '@/stores/space' import { storeToRefs } from 'pinia' const { t } = useI18n() const spaceStore = useSpaceStore() const { followPublicVisible } = storeToRefs(spaceStore) const popoverVisible = ref(false) const helpList = [ { title: t('联系客服'), icon: 'wechat', link: 'contactUs' }, { title: t('Chato社区'), icon: 'community', link: 'https://support.qq.com/products/600388/' }, { title: t('用户手册'), icon: 'book-guide', link: 'https://baixingwang.feishu.cn/wiki/EZAPw0vwJiHBazkOCfLcMGYpnig' }, { title: t('关注公众号'), icon: 'follow', link: 'followPublic' } ] const { checkRightsTypeNeedUpgrade } = useSpaceRights() const onHelpClick = (link: string) => { popoverVisible.value = false switch (link) { case 'contactUs': checkRightsTypeNeedUpgrade(ESpaceRightsType.default) break case 'followPublic': followPublicVisible.value = true break default: window.open(link) break } } </script>
import { SimpleGrid } from "@chakra-ui/react"; import React from "react"; import { usePageLoading, useTranslations } from "../../../hooks"; import AppText from "../../common/AppText"; import QuizButton from "./QuizButton"; import QuizBox from "./QuizBox"; interface Props { handleExit: () => void; handleStart: () => void; } const EnterGameBox = (props: Props) => { const { handleExit, handleStart } = props; const t = useTranslations(); const loading = usePageLoading(); return ( <QuizBox spacing="4"> <AppText>{t.quiz.welcome.message}</AppText> <SimpleGrid columns={2} spacing="4"> <QuizButton id="exit-btn" variant="outline" onClick={handleExit} disabled={loading} > {t.quiz.welcome.exit} </QuizButton> <QuizButton id="enter-btn" onClick={handleStart} disabled={loading}> {t.quiz.welcome.enter} </QuizButton> </SimpleGrid> </QuizBox> ); }; export default EnterGameBox;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.coryneregnet7.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate Utility class with a convenient method to get Session Factory * object. * * @author mariana */ public class ConnectionFactory { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static Session getSessionFactory() { if (sessionFactory.getCurrentSession() == null) { return sessionFactory.openSession(); } else { return sessionFactory.getCurrentSession(); } } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ball Drop Physics</title> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } </style> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js"></script> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(0, 5, 15); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true; document.body.appendChild(renderer.domElement); const world = new CANNON.World(); world.gravity.set(0, -9.81, 0); world.broadphase = new CANNON.SAPBroadphase(world); const groundShape = new CANNON.Plane(); const groundBody = new CANNON.Body({ mass: 0, shape: groundShape }); groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.addBody(groundBody); const groundGeometry = new THREE.PlaneGeometry(30, 30, 32, 32); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x808080, roughness: 0.8, metalness: 0.2 }); const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground); const ambientLight = new THREE.AmbientLight(0x404040); scene.add(ambientLight); const sphereColors = [ "#FF0000", // Red "#FF7F00", // Orange "#FFFF00", // Yellow "#00FF00", // Green "#0000FF", // Blue "#FF1493", // DeepPink "#00FFFF", // Cyan "#FFD700", // Gold "#ADFF2F", // GreenYellow "#1E90FF", // DodgerBlue "#F08080", // LightCoral "#90EE90", // LightGreen "#FFB6C1", // LightPink "#FFA07A", // LightSalmon "#7CFC00", // LawnGreen "#FFDAB9", // PeachPuff "#9370DB", // MediumPurple "#20B2AA", // LightSeaGreen "#00CED1", // DarkTurquoise "#FF4500", // OrangeRed "#FF8C00", // DarkOrange "#FA8072", // Salmon "#DAA520", // Goldenrod "#4169E1", // RoyalBlue "#3CB371", // MediumSeaGreen "#7B68EE", // MediumSlateBlue "#FFC0CB", // Pink "#7FFF00", // Chartreuse "#BA55D3", // MediumOrchid "#66CDAA", // MediumAquamarine "#9932CC", // DarkOrchid "#AFEEEE", // PaleTurquoise "#8B4513", // SaddleBrown "#2E8B57", // SeaGreen "#8B008B", // DarkMagenta "#228B22", // ForestGreen "#800000", // Maroon "#008B8B", // DarkCyan "#9400D3", // DarkViolet "#000080", // Navy "#556B2F", // DarkOliveGreen "#FFA500", // Orange "#A52A2A", // Brown "#4682B4", // SteelBlue "#DC143C" // Crimson ]; const minBalls = 1; // Minimum number of balls (100) const maxBalls = 5; // Maximum number of balls (500) const numSpheres = (Math.floor(Math.random() * (maxBalls - minBalls + 1)) + minBalls) * 100; const spheres = []; for (let i = 0; i < numSpheres; i++) { const sphereGeometry = new THREE.SphereGeometry(1, 32, 32); const randomColor = sphereColors[Math.floor(Math.random() * sphereColors.length)]; const sphereMaterial = new THREE.MeshStandardMaterial({ color: randomColor, roughness: 0.5, metalness: 0.5 }); const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); const sphereBody = new CANNON.Body({ mass: Math.random() * 2 + 0.5, shape: new CANNON.Sphere(1) }); const x = Math.random() * 10 - 5; const y = Math.random() * 30 + 10; const z = Math.random() * 10 - 5; sphereBody.quaternion.setFromAxisAngle(new CANNON.Vec3(Math.random(), Math.random(), Math.random()), Math.random() * Math.PI); sphereBody.position.set(x, y, z); world.addBody(sphereBody); sphereBody.material = new CANNON.Material(); sphereBody.material.friction = 0.5; sphereBody.material.restitution = 0.3; spheres.push({ mesh: sphere, body: sphereBody }); sphere.castShadow = true; scene.add(sphere); } const light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(10, 20, 10); light.castShadow = true; light.shadow.mapSize.width = 4096; light.shadow.mapSize.height = 4096; light.shadow.radius = 2; light.shadow.camera.left = -20; light.shadow.camera.right = 20; light.shadow.camera.top = 20; light.shadow.camera.bottom = -20; scene.add(light); const dynamicLight = new THREE.PointLight(0xffffff, 1); dynamicLight.castShadow = true; scene.add(dynamicLight); const moveDirection = new THREE.Vector3(); const rotationSpeed = 0.02; const movementSpeed = 0.2; const keys = { ArrowUp: false, ArrowDown: false, ArrowLeft: false, ArrowRight: false, }; document.addEventListener('keydown', (event) => { keys[event.key] = true; }); document.addEventListener('keyup', (event) => { keys[event.key] = false; moveDirection.set(0, 0, 0); }); const update = () => { const rotationDirection = new THREE.Vector3(); moveDirection.set(0, 0, 0); if (keys.ArrowUp) { moveDirection.z = 1; } if (keys.ArrowDown) { moveDirection.z = -1; } if (keys.ArrowLeft) { rotationDirection.y = 1; } if (keys.ArrowRight) { rotationDirection.y = -1; } camera.rotateOnWorldAxis(rotationDirection, rotationSpeed); const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion); const actualMoveDirection = forward.multiplyScalar(moveDirection.z); camera.position.add(actualMoveDirection.multiplyScalar(movementSpeed)); }; const animate = () => { requestAnimationFrame(animate); world.step(1 / 60); update(); spheres.forEach(({ mesh, body }) => { mesh.position.copy(body.position); mesh.quaternion.copy(body.quaternion); }); if (spheres.length > 0) { const firstSphere = spheres[0].mesh; dynamicLight.position.copy(firstSphere.position); dynamicLight.position.y = 1; } renderer.render(scene, camera); }; animate(); </script> </body> </html>
from django import forms from .models import Regulation class RegulationForm(forms.ModelForm): class Meta: model = Regulation fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Add Bootstrap classes to form fields for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' # Add Bootstrap classes to form labels def label_tag(self, label=None, attrs=None, label_suffix=None): attrs = attrs or {} attrs['class'] = 'form-label' return super().label_tag(label, attrs, label_suffix) def clean(self): cleaned_data = super().clean() win_points = cleaned_data.get('win_points') loss_points = cleaned_data.get('loss_points') draw_points = cleaned_data.get('draw_points') if win_points and loss_points and draw_points: if win_points < draw_points or win_points < loss_points: self.add_error('win_points', "Points for a win must be greater than points for a loss and points for a draw") if draw_points < loss_points or draw_points > win_points: self.add_error('draw_points', "Points for a draw must be greater than points for a loss and lower than points for a win") if loss_points > draw_points or loss_points > win_points: self.add_error('loss_points', "Points for a loss must be lower that points for a draw and points for a win")
import {useState} from "react"; import image from "../images/login.jpg"; import Link from "next/link"; import axios from "./api/axios"; import Image from "next/image"; const Index = () => { const onSubmitHandle = async (e) => { e.preventDefault(); let inputLogin = { email, password, }; await axios .post("/users/login", JSON.stringify(inputLogin), { headers: { "Content-Type": "application/json", }, }) .then((result) => { const data = result?.data; authCtx.addToken({ user: { id: data.id, email: data.email, }, token: data.accessToken, }); if (data.response === 200) { // navigate("/"); } }) .catch((err) => { console.log(err); }); }; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isShowPassword, setIsShowPassword] = useState(""); return ( <section className='mx-auto h-screen grid place-content-center w-screen'> <div className='container w-80 lg:w-screen'> <div className='grid grid-rows-1 lg:grid-cols-2 lg:gap-1'> <div className='rounded-2xl lg:block hidden'> <Image src={image} alt='player one' className='object-cover' /> </div> <div className='lg:flex lg:justify-center'> <div className='bg-white border border-gray-200 shadow-md p-6 rounded-lg '> <div className='flex flex-col gap-1 lg:justify-center lg:items-center h-full'> <div className='text-start lg:w-96 '> <h2 className='text-start text-lg lg:text-3xl font-bold tracking-tight text-gray-900'> Sign In </h2> <p className='mt-2 text-start text-sm text-gray-600'> Or <Link href='/register' className='font-medium text-indigo-600 hover:text-indigo-500 ml-1 underline'> Create an account </Link> </p> </div> <form onSubmit={(e) => onSubmitHandle(e)} className='mt-8 space-y-6 lg:w-96' action='#' method='POST'> <div className='relative'> <input type='email' autoComplete={"off"} required={true} onChange={(e) => setEmail(e.currentTarget.value)} className='block px-2.5 pl-[1.5rem] pb-2.5 pt-4 w-full text-md text-gray-900 bg-transparent border border-gray-300 outline-none rounded-[100px] bg-white border-1 appearance-none focus:outline-none focus:ring-0 focus:border-blue-600 peer' /> <label htmlFor='email' className='absolute text-md text-slate-600 duration-300 bg-gray-50 grid place-items-center rounded-[100px] border-none h-[50px] transform -translate-y-3 scale-75 origin-[0] peer-focus:bg-white px-5 peer-focus:text-blue-600 peer-focus:px-1 peer-focus:h-auto peer-placeholder-shown:scale-100 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:top-1/2 peer-focus:top-3 peer-focus:scale-100 peer-focus:-translate-y-6 -top-3 left-1 peer-focus:left-5'> Email </label> </div> <div className='relative'> <input type={isShowPassword ? "text" : "password"} required={true} autoComplete={"off"} onChange={(e) => setPassword(e.currentTarget.value)} className='block px-2.5 pl-[1.5rem] pb-2.5 pt-4 w-full text-md text-gray-900 bg-transparent border border-gray-300 outline-none rounded-[100px] bg-white border-1 appearance-none focus:outline-none focus:ring-0 focus:border-blue-600 peer' /> <div className='absolute flex justify-end top-3 right-7 text-gray-400' onClick={() => setIsShowPassword((prev) => !prev)}> {isShowPassword ? ( <svg stroke='currentColor' fill='currentColor' strokeWidth='0' viewBox='0 0 1024 1024' height='2em' width='2em' xmlns='http://www.w3.org/2000/svg'> <path d='M396 512a112 112 0 1 0 224 0 112 112 0 1 0-224 0zm546.2-25.8C847.4 286.5 704.1 186 512 186c-192.2 0-335.4 100.5-430.2 300.3a60.3 60.3 0 0 0 0 51.5C176.6 737.5 319.9 838 512 838c192.2 0 335.4-100.5 430.2-300.3 7.7-16.2 7.7-35 0-51.5zM508 688c-97.2 0-176-78.8-176-176s78.8-176 176-176 176 78.8 176 176-78.8 176-176 176z'></path> </svg> ) : ( <svg stroke='currentColor' fill='currentColor' strokeWidth='0' viewBox='0 0 1024 1024' height='2em' width='2em' xmlns='http://www.w3.org/2000/svg'> <defs> <clipPath> <path fill='none' d='M124-288l388-672 388 672H124z' clipRule='evenodd'></path> </clipPath> </defs> <path d='M508 624a112 112 0 0 0 112-112c0-3.28-.15-6.53-.43-9.74L498.26 623.57c3.21.28 6.45.43 9.74.43zm370.72-458.44L836 122.88a8 8 0 0 0-11.31 0L715.37 232.23Q624.91 186 512 186q-288.3 0-430.2 300.3a60.3 60.3 0 0 0 0 51.5q56.7 119.43 136.55 191.45L112.56 835a8 8 0 0 0 0 11.31L155.25 889a8 8 0 0 0 11.31 0l712.16-712.12a8 8 0 0 0 0-11.32zM332 512a176 176 0 0 1 258.88-155.28l-48.62 48.62a112.08 112.08 0 0 0-140.92 140.92l-48.62 48.62A175.09 175.09 0 0 1 332 512z'></path> <path d='M942.2 486.2Q889.4 375 816.51 304.85L672.37 449A176.08 176.08 0 0 1 445 676.37L322.74 798.63Q407.82 838 512 838q288.3 0 430.2-300.3a60.29 60.29 0 0 0 0-51.5z'></path> </svg> )} </div> <label htmlFor='password' className='absolute text-md text-slate-600 duration-300 bg-gray-50 grid place-items-center rounded-[100px] border-none h-[50px] transform -translate-y-3 scale-75 origin-[0] peer-focus:bg-white px-5 peer-focus:text-blue-600 peer-focus:px-1 peer-focus:h-auto peer-placeholder-shown:scale-100 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:top-1/2 peer-focus:top-3 peer-focus:scale-100 peer-focus:-translate-y-6 -top-3 left-1 peer-focus:left-5'> Password </label> </div> <div className='flex justify-end'> <div className='text-sm'> <button> <a href='/forgot_password' className='font-medium text-indigo-600 hover:text-indigo-500'> Forgot your password? </a> </button> </div> </div> <div> <button type='submit' className='group relative flex w-full justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'> <span className='absolute inset-y-0 left-0 flex items-center pl-3'> <svg className='h-5 w-5 text-indigo-500 group-hover:text-indigo-400' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'> <path fillRule='evenodd' d='M10 1a4.5 4.5 0 00-4.5 4.5V9H5a2 2 0 00-2 2v6a2 2 0 002 2h10a2 2 0 002-2v-6a2 2 0 00-2-2h-.5V5.5A4.5 4.5 0 0010 1zm3 8V5.5a3 3 0 10-6 0V9h6z' clipRule='evenodd' /> </svg> </span> Sign in </button> </div> </form> </div> </div> </div> </div> </div> </section> ) ; }; export default Index;
<script lang="ts"> import { createForm } from "svelte-forms-lib"; import { createEventDispatcher } from "svelte"; import { Answer, Question, currentInfobyte, Infobyte, Infobit, baseUrl, isProd, } from '$lib/stores/stores'; import { Confirm } from "svelte-confirm"; import Fa from "svelte-fa"; import { faCaretLeft, faCaretRight, faLaptopCode, } from "@fortawesome/free-solid-svg-icons"; // import App from "./App.svelte"; // import Aside from "./Aside.svelte"; import AspectItem from "../Aspects/AspectItem.svelte"; export let selectedInfobyte; export let unsavedChanges; const initialQuestions = [new Question()]; const { form, errors, state, handleChange, handleSubmit, handleReset, isModified, } = createForm({ initialValues: selectedInfobyte, onSubmit: async (values) => { let infobyte = values; if (infobyte._id === "") delete infobyte._id; console.log(values); let result = await fetch( `${baseUrl}infobyte${infobyte._id ? "/" + infobyte._id : ""}`, { method: infobyte._id ? "PUT" : "POST", headers: { "Content-Type": "application/json", // 'Content-Type': 'application/x-www-form-urlencoded', }, body: JSON.stringify(infobyte), credentials: "include", } ); currentInfobyte.set(new Infobyte()); }, }); let editorTest = "<h3>Welcome to Prosemirror Svelte</h3><p>Feel free to <b>edit me</b>!</p>"; $: if (editorTest) { console.log(editorTest); } $: unsavedChanges = isModified; $: if (selectedInfobyte) { console.log(form._id, selectedInfobyte._id); if (form._id !== selectedInfobyte._id) { $form.name = selectedInfobyte.name || ""; $form.frontmatter = selectedInfobyte.frontmatter || ""; $form.questions = selectedInfobyte.questions || []; $errors.questions = selectedInfobyte.questions || []; $form._id = selectedInfobyte._id || ""; $form.infobits = selectedInfobyte.infobits || []; $errors.infobits = selectedInfobyte.infobits || []; $form.aspect = selectedInfobyte.aspect || ""; $form.factor = selectedInfobyte.factor || 0; } } const addInfobit = () => { $form.infobits = $form.infobits.concat(new Infobit()); $errors.infobits = $errors.infobits.concat(new Infobit()); }; const removeInfobit = (i) => () => { $form.infobits = $form.infobits.filter((u, j) => j !== i); $errors.infobits = $errors.infobits.filter((u, j) => j !== i); }; const addQuestion = () => { $form.questions = $form.questions.concat(new Question()); $errors.questions = $errors.questions.concat(new Question()); }; const removeQuestion = (i) => () => { $form.questions = $form.questions.filter((u, j) => j !== i); $errors.question = $errors.questions.filter((u, j) => j !== i); }; const addAnswer = (j) => () => { //console.log(j, $form.questions[j].answers, $form.questions[j].answers.concat(new Answer())) if (j) $form.questions[j].answers = $form.questions[j].answers.concat( new Answer() ); //what? $errors.questions[j].answers = $errors.questions[j].answers.concat( new Answer() ); }; const removeAnswer = (j, k) => () => { $form.questions[j].answers = $form.questions[j].answers.filter( (u, i) => k !== i ); $errors.questions[j].answers = $form.questions[j].answers.filter( (u, i) => k !== i ); }; const setFactor = (factor) => () => { $form.factor = factor; handleChange(); }; const deleteInfoByte = async () => { if (!selectedInfobyte._id) return; const response = await fetch(`/infobyte/${selectedInfobyte._id}`, { credentials: "include", method: "DELETE", }); currentInfobyte.set(new Infobyte()); return await response.json(); }; const fetchAspects = async () => { const response = await fetch( `${baseUrl}localized-aspect?${new URLSearchParams({ r: $form.region, l: $form.language, })}`, { credentials: "include", } ); return await response.json(); }; const fetchFactorsForAspect: any = (aspect, aspects) => { if (aspects != null) { if (aspect != null) { let aspects_data = aspects; const _aspects = aspects_data.find((a) => a._id === $form.aspect)?.localizedFactors ?? [] console.log(_aspects) return _aspects ; } else return []; } else return []; }; let aspects: Promise<any[]> = fetchAspects(); //$: factors = fetchFactorsForAspect($form.aspect, aspects); </script> <section> <form on:submit={handleSubmit}> <h1>Infobyte hinzufügen</h1> <label for="region">Region</label> <select id="region" name="region" type="select" on:change={handleChange} on:blur={handleChange} bind:value={$form.region} > <option>DE</option> </select> <label for="language">Sprache</label> <select id="language" name="language" type="select" on:change={handleChange} on:blur={handleChange} bind:value={$form.language} > <option>DE</option> <option>EN</option> </select> <label for="name">name</label> <input id="name" name="name" on:change={handleChange} bind:value={$form.name} /> <label for="frontmatter">Klappentext</label> <input id="frontmatter" name="frontmatter" on:change={handleChange} bind:value={$form.frontmatter} /> {#await aspects} <!-- svelte-ignore a11y-label-has-associated-control --> <label>Lade...</label> {:then data} <label for="aspect">Aspekt</label> <select id="aspect" name="aspect" type="select" on:change={handleChange} bind:value={$form.aspect} > <option value={null}> -- Aspekt -- </option> {#each data as aspect} <option value={aspect._id}>{aspect.name}</option> {/each} </select> <label for="factor">Gesichtspunkt</label> <select id="factor" name="factor" type="select" on:change={setFactor} bind:value={$form.factor} > <option value={null}> -- Gesichtspunkt -- </option> {#each fetchFactorsForAspect($form.aspect, data) as factor} <option value={factor.id}> {factor.id}. {factor.name}</option> {/each} </select> {:catch error} <p>An error occurred! {error}</p> {/await} <label for="difficulty">Schwierigkeit</label> <select id="difficulty" name="difficulty" type="select" on:change={handleChange} bind:value={$form.difficulty} > <option value={1}>Leicht</option> <option value={2}>Mittel</option> <option value={3}>Schwer</option> </select> <!--<InfoBitEditor bind:value={editorTest}/>--> <!-- <Carousel perPage={1} autoplay={false} infinite={false}> --> <!-- <span class="control" slot="left-control"> <Fa icon={faCaretLeft} /> </span> --> {#if $form.infobits.length !== 0} {#each $form.infobits as infobit, i} <InfoBitEditor bind:value={infobit} /> <div class="form-control-row"> {#if i === $form.infobits.length - 1} <button type="button" class="form-control-button" on:click={addInfobit}>+</button > {/if} {#if $form.infobits.length !== 1} <button type="button" class="form-control-button" on:click={removeInfobit(i)}>-</button > {/if} </div> {/each} {:else} <div >Klicke auf 'Infobit hinzufügen +' um ein Infobit hinzu zufügen!</div > {/if} <!-- <span class="control" slot="right-control"> <Fa icon={faCaretRight} /> </span> --> <!-- </Carousel> --> {#if $form.infobits.length === 0} <button type="button" class="form-control-button" on:click={addInfobit} >Infobit hinzufügen +</button > {/if} {#each $form.questions as question, j} <div class="form-group"> <label for={`questions[${j}]`}>Frage {j + 1}</label> <div> <label for={`questions[${j}].question`}>Frage</label> <input type="textarea" name={`questions[${j}].question`} placeholder="question" on:change={handleChange} on:blur={handleChange} bind:value={$form.questions[j].question} /> {#if $errors.questions[j].answer} <small class="error">{errors.questions[j].answer}</small> {/if} </div> <span> Für Infobit? </span> {#each $form.questions[j].answers as answer, k} <div class="form-group"> <label for={`questions[${j}].answers[${k}]`}> Antwort {k + 1}</label > <div> <label for={`questions[${j}].answers[${k}].value`}>Antwort</label> <div class="form-control-row"> <input name={`questions[${j}].answers[${k}].value`} placeholder="Antwort" on:change={handleChange} on:blur={handleChange} bind:value={$form.questions[j].answers[k].value} /> <label for={`questions[${j}].answers[${k}].correct`} style="padding: 5px;" > <span class="label-text">Richtig</span> <input class="checkbox" type="checkbox" name={`questions[${j}].answers[${k}].correct`} bind:checked={$form.questions[j].answers[k].correct} /> </label> {#if $errors.questions[j].answers[k].answer} <small class="error" >{errors.questions[j].answers[k].answer}</small > {/if} <ButtonToolbar> {#if k === $form.questions[j].answers.length - 1} <Button type="button" class="form-control-button" on:click={addAnswer(j)}>+</Button > {/if} {#if $form.questions[j].answers.length !== 1} <Button type="button" class="form-control-button" on:click={removeAnswer(j, k)}>-</Button > {/if} </ButtonToolbar> </div> </div> <div /> </div> {/each} <select type="select" name="select" id="exampleSelect" bind:value={$form.questions[j].infobit} > <option selected value={null}> -- Allgemeine Frage -- </option> {#each $form.infobits as infobit, i} <option>{i + 1}</option> {/each} </select> <div class="form-control-row"> {#if j === $form.questions.length - 1} <button type="button" class="form-control-button" on:click={addQuestion}>+</button > {/if} {#if $form.questions.length !== 1} <button type="button" class="form-control-button" on:click={removeQuestion(j)}>-</button > {/if} </div> </div> {/each} <label for={"published"} style="padding: 5px;"> <input class="checkbox" type="checkbox" name={"published"} bind:checked={$form.published} /> Veröffentlichen </label> <button type="submit">Speichern</button> <button let:confirm={confirmThis}> <button type="reset" on:click={() => confirmThis(deleteInfoByte)}> Löschen </button> </button> </form> {#if !isProd} <div> <span>Debug</span> <pre>{JSON.stringify($form, null, 2)}</pre> </div> {/if} </section> <style> input, select { font-family: inherit; font-size: inherit; max-width: 400px; width: 100%; padding: 12px; box-sizing: border-box; border: 1px solid var(--grey); border-radius: 4px; transition: all 150ms ease; background: var(--white); } input:focus, select:focus { outline: none; box-shadow: 0 0 0 4px rgb(227, 227, 245); border-color: var(--grey); } input:disabled, select:disabled { color: #ccc; } label { display: block; color: var(--grey-dark); font-weight: bold; margin-top: 20px; margin-bottom: 4px; text-transform: uppercase; font-size: 12px; letter-spacing: 1.9px; line-height: 2; } .form-group { background-color: var(--grey); padding: 8px; border-radius: 8px; display: flex; align-items: baseline; flex-direction: column; } .form-control-row { display: flex; } .form-control-button { min-width: auto; margin-right: 1em; } </style>
import { Test, TestingModule } from '@nestjs/testing'; import { getRepositoryToken } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Stock } from './entities/stock.entity'; import { StocksController } from './stocks.controller'; import { StocksService } from './stocks.service'; describe('StocksController', () => { let controller: StocksController; let stockRepository: Repository<Stock>; const STOCK_REPOSITORY_TOKEN = getRepositoryToken(Stock); beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [StocksController], providers: [ StocksService, { provide: STOCK_REPOSITORY_TOKEN, useValue: { create: jest.fn(), save: jest.fn(), }, }, ], }).compile(); controller = module.get<StocksController>(StocksController); stockRepository = module.get<Repository<Stock>>(getRepositoryToken(Stock)); }); it('should be defined', () => { expect(controller).toBeDefined(); }); it('stockRepository should be fine', () => { expect(stockRepository).toBeDefined(); }); it('should create a new Stock', async () => { jest.spyOn(stockRepository, 'create').mockReturnValueOnce({ id: 1, stock: 'PETR4', ano: 2000, mes: 'Janeiro', open_price: 1.234, highest_price: 2.345, lowest_price: 3.456, volume: 123456789, close_price: 4.567, }); await controller.createStock({ stock: 'PETR4', ano: 2000, mes: 'Janeiro', open_price: 1.234, highest_price: 2.345, lowest_price: 3.456, volume: 123456789, close_price: 4.567, }); expect(stockRepository.save).toHaveBeenCalledWith({ id: 1, stock: 'PETR4', ano: 2000, mes: 'Janeiro', open_price: 1.234, highest_price: 2.345, lowest_price: 3.456, volume: 123456789, close_price: 4.567, }); }); });
import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { getMarketChart, marketSelect } from "../marketSlice"; import { Line } from "react-chartjs-2"; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler, } from "chart.js"; import dayjs from "dayjs"; const MarketChart = ({ id, days, setDays }) => { const { marketChartResult } = useSelector(marketSelect); ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler ); return ( <div> <div> <Line data={{ labels: marketChartResult.prices && marketChartResult.prices.map((data) => { return days === "1" ? dayjs(data[0]).format("h A") : dayjs(data[0]).format("MMM D, YYYY"); }), datasets: [ { label: id, data: marketChartResult.prices && marketChartResult.prices.map((data) => { return { x: data[0], y: data[1].toFixed(2), }; }), borderColor: "rgb(255, 99, 132)", borderWidth: 1, backgroundColor: "rgb(255, 99, 132, 0.5)", fill: true, pointRadius: 0, }, ], }} options={{ maintainAspectRatio: false, lineHeightAnnotation: { always: true, hover: false, lineWeight: 1.5, }, animation: { duration: 2000, }, responsive: true, interaction: { mode: "index", intersect: false, }, }} width={400} height={600} /> </div> <div className="flex bg-gray-50"> <button onClick={() => setDays("1")} className="flex items-center justify-center w-10 h-10 text-xl bg-gray-100 hover:bg-gray-200" > 1d </button> <button onClick={() => setDays("7")} className="flex items-center justify-center w-10 h-10 text-xl bg-gray-100 hover:bg-gray-200" > 7d </button> <button onClick={() => setDays("365")} className="flex items-center justify-center w-10 h-10 text-xl bg-gray-100 hover:bg-gray-200" > 1y </button> </div> </div> ); }; export default MarketChart;
# DevJobs DevJobs (an Amalitech Technical Training Project) ## Overview DevJobs is a job search platform that allows users to view job listings, filter jobs by title, location, and full-time positions, and apply for jobs. This application is built using Angular, TypeScript, Tailwind CSS, and hosted on Vercel. ## Customer Requirements - View the optimal layout for each page depending on their device's screen size - See hover states for all interactive elements throughout the site - Be able to filter jobs on the index page by title, location, and whether a job is for a full-time position - Be able to click a job from the index page so that they can read more information and apply for the job - Have the correct color scheme chosen for them based on their computer preferences. ## Features - View job listings with details such as job title, location, and job description - Filter jobs by title, location, and full-time positions - View job details and apply for jobs - Responsive design for optimal layout on various screen sizes - Customizable color scheme based on user preferences ## Technologies Used - [Angular](https://angular.io/) - TypeScript-based open-source framework for building web applications - [TypeScript](https://www.typescriptlang.org/) - TypeScript superset - [Tailwind CSS](https://tailwindcss.com/) - Utility-first CSS framework - [Figma](https://www.figma.com/) - User interface design tool ## Design The design of DevJobs was created using Figma. ## Live Preview You can check out the live preview of App at [DevJobs](https://devjobs-bless.vercel.app/). ## Installation To install DevJobs locally, follow these steps: 1. Clone the repository to your local machine: ``` git clone https://github.com/Bless12Ahadjie/devjobs.git ``` 2. Navigate to the project directory: ``` cd devjobs ``` 3. Install dependencies: ``` npm install ``` 4. Run the development server: ``` ng serve ``` ## Usage 1. View job listings on the index page. 2. Filter jobs by title, location, and full-time positions. 3. Click on a job to view more details and apply for the job. 4. Customize the color scheme based on your preferences. ## Contributing Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request. ## License This project is licensed under the [MIT License](LICENSE). Enjoy using DevJobs! 🚀
/* Copyright (C) 2001-2012 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 7 Mt. Lassen Drive - Suite A-134, San Rafael, CA 94903, U.S.A., +1(415)492-9861, for further information. */ /* Definition of device color values */ #ifndef gxcvalue_INCLUDED # define gxcvalue_INCLUDED /* Define the type for gray or RGB values at the driver interface. */ typedef unsigned short gx_color_value; /* We might use less than the full range someday. */ /* ...bits must lie between 8 and 16. */ #define gx_color_value_bits (sizeof(gx_color_value) * 8) #define gx_max_color_value ((gx_color_value)((1L << gx_color_value_bits) - 1)) /* See the comments below on why this is no longer a simple truncation */ #define gx_color_value_to_byte(cv)\ ((gx_color_value)((((unsigned int)cv)*0xFF01 + 0x800000)>>24)) #define gx_color_value_from_byte(cb)\ (((cb) << (gx_color_value_bits - 8)) + ((cb) >> (16 - gx_color_value_bits))) /* Convert between gx_color_values and fracs. */ #define frac2cv(fr) frac2ushort(fr) #define cv2frac(cv) ushort2frac(cv) /* Convert between gx_color_values and frac31s. */ #define frac312cv(fr) frac312ushort(fr) #define cv2frac31(cv) ushort2frac31(cv) /* At various points in the code (particularly inside encode_color and * decode_color functions), we need to convert colour values between * different bitdepths. * * A typical example is where we have an 8 bit color value (0xab say) * which we need to expand to be a 16 bit color value. In order to * fill the range without biasing, we 'duplicate' the top bits down * (so giving 0xabab rather than just 0xab00). * * Traditionally, when converting to smaller numbers, we have simply * truncated (so 0xabcd => 0xab), but this doesn't actually give us the * best results possible consider for example truncating 0x0081 - this * would give 0x00, which when converted back to 16 bits later would give * 0x0000, a difference of 0x81. If instead we converted 0x0081 to 0x01, * when that got converted back it would go to be 0x0101, a difference of * 0x80. * * This disparity first came to light in bug 690538; lcms returns 16 bit * colors that we use for lineart, but returns image data in 8 bits. At the * time of the bug, gs would convert the 16 bit lineart colors to 8 bit * via simple truncation to plot them in the device, resulting in being * off by 1 to the image colors. * * We therefore adopt lcms's rounding scheme here. To convert from 16 to 8 * bit, lcms does: col8 = (col16 * 0xFF01 + 0x800000)>>24 (all unsigned ints) * * Unfortunately we do not have the luxury of only working in 16 or 8 bits * so we generalise that to convert from FROM to TO bits as follows: * * M = (((1<<TO)-1)<<(FROM-TO))+1; * S = 2*FROM-TO; * R = 1<<(S-1); * out = (M*in + R)>>S * * We express this operation in macros here so it can be reused in many * places in the code while keeping the complexity in one place. */ #define COLROUND_VARS unsigned int COLROUND_M, COLROUND_S, COLROUND_R #define COLROUND_SETUP(TO) \ do { COLROUND_M = (((1<<TO)-1)<<(gx_color_value_bits-TO))+1; \ COLROUND_S = (gx_color_value_bits*2-TO); \ COLROUND_R = 1<<(COLROUND_S-1); \ } while (0 == 1) #define COLROUND_ROUND(X) \ ((gx_color_index)(((COLROUND_M*(unsigned int)(X))+COLROUND_R)>>COLROUND_S)) #define COLDUP_VARS unsigned int COLDUP_M, COLDUP_S #define COLDUP_MULTS_STRING "\x00\x00\xFF\xFF\x55\x55\x92\x49\x11\x11\x84\x21\x10\x41\x40\x81\x01\x01\x02\x01\x04\x01\x08\x01\x10\x01\x20\x01\x40\x01\x80\x01" #define COLDUP_SETUP(FROM) \ do { COLDUP_M = (((unsigned char)COLDUP_MULTS_STRING[2*FROM])<<8)|\ (unsigned char)COLDUP_MULTS_STRING[2*FROM+1]; \ COLDUP_S = (FROM-(gx_color_value_bits % FROM)) % FROM; \ } while (0 == 1) #define COLDUP_DUP(X) \ ((gx_color_value)(((unsigned int)X) * COLDUP_M)>>COLDUP_S) #endif /* gxcvalue_INCLUDED */
import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; import ItemCard from "./ItemCard"; import '../styles/itemDetail.css'; const ItemDetail = ({addToDeck, removeFromDeck, deck, isMobile}) => { const params = useParams(); const [item, setItem] = useState([]); const [relatedProducts, setRelatedProducts] = useState([]); const [otherProducts, setOtherProducts] = useState([]); const [counter, setCounter] = useState(0); const [mainImg, setMainImg] = useState([]); const fetchData = async () => { let dataAll = await fetch('https://raw.githubusercontent.com/jackfriedman616/MTG-Mongoose-React-Deckbuilder/main/Public/Products.json') .then(res => res.json()) .catch(err => []) let item = dataAll.filter(i => {return i.id === params.id*1})[0]; setItem(item); setMainImg(item.picture[0]); let rProducts = dataAll.filter(d => {return d.colorId[0] === item.colorId[0] && d.id !== item.id}); setRelatedProducts(rProducts); let oProducts = dataAll.filter(d => d.id !== item.id); oProducts.sort(() => Math.random() > 0.5 ? 1 : -1); let oProduct = oProducts.slice(0,10); setOtherProducts(oProduct); } useEffect(() => { window.scrollTo({top: 0}) fetchData(); getCurrentCount(); }, [params.id]) useEffect(() => { getCurrentCount() }, [deck, item]) const getCurrentCount = () => { let inDeckItem = [...deck.filter(b => b.id === item.id)]; if (inDeckItem[0]?.hasOwnProperty('count') ) { setCounter(inDeckItem[0].count); } else { setCounter(0); } } const scrollLeft = (e) => { let slider = e.target.parentElement.querySelector('.slider'); let newScroll = slider.scrollLeft - 400 > 0 ? slider.scrollLeft - 400 : 0; slider.scrollTo({left: newScroll, behavior: 'smooth'}) } const scrollRight = (e) => { let slider = e.target.parentElement.querySelector('.slider'); let newScroll = slider.scrollLeft + 400 < slider.scrollWidth ? slider.scrollLeft + 400 : slider.scrollWidth; slider.scrollTo({left: newScroll, behavior: 'smooth'}) } const increment = () => { addToDeck(item); } const decrement = () => { removeFromDeck(item); setCounter( counter-1 > 0 ? counter - 1 : 0); } const setImage = (e) => { setMainImg(item.picture[e.target.id.split("-")[2]]) } return( <div className="item-detail mt-5"> <div className="item-detail-header"> <h1>{item.name}</h1> <div className={`d-flex flex-row h-auto ${isMobile ? '' : 'justify-content-center' }`}> <i className="fa-solid fa-square-minus me-3 text-red pointer" onClick={decrement}></i> <span className='me-3'>{counter}</span> <i className="fa-solid fa-square-plus me-3 text-green pointer" onClick={increment}></i> </div> </div> <div className="item-detail-description"> {item.description} </div> <div className="img-detail-container"> <div> <img src={mainImg.link} className="main-img" alt={mainImg.title} title={mainImg.title} /> </div> <div> {item?.picture?.map((im, ind) => { return <img key={`img-sm-${ind}`} id={`img-sm-${ind}`} src={im.link} alt={`Product ${ind}`} className={`small-img ${mainImg.link === im.link ? 'active-img' : ''}`} onClick={setImage}/> }) } </div> </div> <div className={`item-detail-slider-1 ${relatedProducts.length === 0 ? 'd-none': ''}`}> <h3 className="mt-5 mb-2">Related Products</h3> <div className="slider-container mb-5"> <i className="fa-solid fa-caret-left fa-3x" onClick={scrollLeft}></i> <div className="slider"> {relatedProducts.length > 0 && relatedProducts.map((r,ind) => { return ( <ItemCard data={r} key={`item-${r.id}`} addToDeck={addToDeck} deck={deck} removeFromDeck={removeFromDeck}/> ) })} </div> <i className="fa-solid fa-caret-right fa-3x" onClick={scrollRight}></i> </div> </div> <div className={`item-detail-slider-2 ${otherProducts.length === 0 ? 'd-none' : ''}`}> <h3 className="mt-5 mb-2">Users Also Viewed</h3> <div className="slider-container mb-5"> <i className="fa-solid fa-caret-left fa-3x" onClick={scrollLeft}></i> <div className="slider"> {otherProducts.length > 0 && otherProducts.map((p,ind) => { return ( <ItemCard data={p} key={`item-${p.id}`} addToDeck={addToDeck} deck={deck} removeFromDeck={removeFromDeck}/> ) })} </div> <i className="fa-solid fa-caret-right fa-3x" onClick={scrollRight}></i> </div> </div> </div> ) } export default ItemDetail;