text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="ko"> <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>칸의 병합</title> <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 10px; text-align: center; } </style> </head> <body> <h1>칸의 병합</h1> <h2>가로 방향 병합</h2> <!-- colspan 속성 - 가로방향 셀 병합을 갯수로 지정하는 속성이다. - th, td 태그의 속성이다. - <td colspan="병합할 칸의 갯수"> - <th clospan="병합할 칸의 갯수"> - 표의 칸을 맞추기 위해서는 (병합할 칸의 갯수 - 1)만큼 td, th 태그를 해당 행에서 삭제해야 한다. --> <table> <tr> <td colspan="2">1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td colspan="3">1</td> <td>2</td> <td>3</td> </tr> <tr> <td colspan="5">1</td> <!-- <td>2</td> <td>3</td> <td>4</td> <td>5</td> --> </tr> <tr> <td colspan="2">1</td> <td colspan="2">2</td> <td>3</td> <!-- <td>4</td> <td>5</td> --> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </table> <h2>세로 방향 병합</h2> <!-- rowspan 속성 - 세로방향 셀 병합을 갯수로 지정하는 속성이다. - th, td 태그의 속성이다. - <td rowspan="병합할 칸의 갯수"> - <th rowspan="병합할 칸의 갯수"> - 표의 칸을 맞추기 위해서는 (병합할 칸의 갯수 - 1)만큼 다음행의 td, th 태그를 삭제해야 한다. --> <table> <tr> <td rowspan="6">1</td> <td rowspan="3">2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <!-- <td>1</td> --> <!-- <td>2</td> --> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <!-- <td>1</td> --> <!-- <td>2</td> --> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <!-- <td>1</td> --> <td rowspan="3">2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <!-- <td>1</td> --> <!-- <td>2</td> --> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <!-- <td>1</td> --> <!-- <td>2</td> --> <td>3</td> <td>4</td> <td>5</td> </tr> </table> </body> </html>
import random from django.http import JsonResponse from django.shortcuts import render, get_object_or_404 from .models import Subject, Question, Answer, Topic from .forms import TextAnswerForm, MultipleChoiceAnswerForm def subject_list(request): subjects = Subject.objects.all() return render(request, 'quiz/subject_list.html', {'subjects': subjects}) def question_list(request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) subjects = Subject.objects.all() questions = list(Question.objects.filter(subject=subject)) random.shuffle(questions) forms = [] results = {} if request.method == 'POST' and request.headers.get('x-requested-with') == 'XMLHttpRequest': for question in questions: question_id = str(question.id) if question.question_type == Question.TEXT: form = TextAnswerForm(request.POST, prefix=question_id) if form.is_valid(): user_answer = form.cleaned_data['answer'] correct = any(answer.text.lower() == user_answer.lower() and answer.is_correct for answer in question.answers.all()) results[question_id] = { 'result': 'correct' if correct else 'incorrect', 'text': question.text } elif question.question_type == Question.MULTIPLE_CHOICE: form = MultipleChoiceAnswerForm(request.POST, question=question, prefix=question_id) if form.is_valid(): selected_answer = form.cleaned_data['answer'] results[question_id] = { 'result': 'correct' if selected_answer.is_correct else 'incorrect', 'text': question.text } elif question.question_type == Question.TEXT: results[question_id] = { 'result': 'self-check', 'text': question.text } return JsonResponse(results) for question in questions: if question.question_type == Question.TEXT: form = TextAnswerForm(prefix=str(question.id)) elif question.question_type == Question.MULTIPLE_CHOICE: form = MultipleChoiceAnswerForm(question=question, prefix=str(question.id)) else: form = None # Just in case you have another type not handled if form: # Only append if form is not None forms.append((question, form)) return render(request, 'quiz/question_list.html', {'subject': subject, 'subjects': subjects, 'forms': forms, 'results': results}) def topic_list(request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) topics = Topic.objects.filter(subject=subject) return render(request, 'quiz/topic_list.html', {'subject': subject, 'topics': topics}) def topic_detail(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) return render(request, 'quiz/topic_detail.html', {'topic': topic})
import { ArticleRangeType, PartTitleType, TOCChapterType, TOCPartType, } from "@/types/law"; import { LawArticleRange } from "./article-range"; import { LawTOCChapter } from "./toc-chapter"; import { Fragment } from "react"; import { getType } from "@/lib/law/law"; import { getTextNode } from "./text-node"; /** * 目次編のコンポーネント * @param {Object} props - プロパティオブジェクト * @param {TOCPartType[]} props.tocPartList - 表示情報 * @param {string[]} props.treeElement - 法令ツリー要素 * @returns {JSX.Element} - 目次編のコンポーネント */ export const LawTOCPart: React.FC<{ tocPartList: TOCPartType[]; treeElement: string[]; }> = (props) => { const { tocPartList, treeElement } = props; const addTreeElement = (index: number) => [ ...treeElement, `TOCPart_${index}`, ]; return ( <> {tocPartList.map((dt, index) => { const PartTitle = getType<PartTitleType>(dt.TOCPart, "PartTitle")[0]; const ArticleRange = getType<ArticleRangeType>( dt.TOCPart, "ArticleRange" ); const TOCChapter = getType<TOCChapterType>(dt.TOCPart, "TOCChapter"); return ( <Fragment key={`${addTreeElement(index).join("_")}`}> <div className="_div_TOCPart"> {getTextNode(PartTitle.PartTitle, addTreeElement(index))} {ArticleRange.length > 0 && ( <LawArticleRange articleRange={ArticleRange[0]} treeElement={addTreeElement(index)} /> )} </div> <LawTOCChapter tocChapterList={TOCChapter} treeElement={addTreeElement(index)} /> </Fragment> ); })} </> ); };
// Copyright (c) 2013-2023 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, // and you may not use this file except in compliance with the Apache License // Version 2.0. You may obtain a copy of the Apache License Version 2.0 at // http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, // software distributed under the Apache License Version 2.0 is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the Apache License Version 2.0 for the specific // language governing permissions and limitations there under. import Foundation /// Configuration of tracker properties. @objc(SPTrackerConfigurationProtocol) public protocol TrackerConfigurationProtocol: AnyObject { /// Identifer of the app. @objc var appId: String { get set } /// It sets the device platform the tracker is running on. @objc var devicePlatform: DevicePlatform { get set } /// It indicates whether the JSON data in the payload should be base64 encoded. @objc var base64Encoding: Bool { get set } /// It sets the log level of tracker logs. @objc var logLevel: LogLevel { get set } /// It sets the logger delegate that receive logs from the tracker. @objc var loggerDelegate: LoggerDelegate? { get set } /// Whether application context is sent with all the tracked events. @objc var applicationContext: Bool { get set } /// Whether mobile/platform context is sent with all the tracked events. @objc var platformContext: Bool { get set } /// Whether geo-location context is sent with all the tracked events. @objc var geoLocationContext: Bool { get set } /// Whether session context is sent with all the tracked events. @objc var sessionContext: Bool { get set } /// Whether deepLink context is sent with all the ScreenView events. @objc var deepLinkContext: Bool { get set } /// Whether screen context is sent with all the tracked events. @objc var screenContext: Bool { get set } /// Whether enable automatic tracking of ScreenView events. @objc var screenViewAutotracking: Bool { get set } /// Whether enable automatic tracking of background and foreground transitions. @objc var lifecycleAutotracking: Bool { get set } /// Whether enable automatic tracking of install event. @objc var installAutotracking: Bool { get set } /// Whether enable crash reporting. @objc var exceptionAutotracking: Bool { get set } /// Whether enable diagnostic reporting. @objc var diagnosticAutotracking: Bool { get set } /// Whether to anonymise client-side user identifiers in session (userId, previousSessionId), subject (userId, networkUserId, domainUserId, ipAddress) and platform context entities (IDFA) /// Setting this property on a running tracker instance starts a new session (if sessions are tracked). @objc var userAnonymisation: Bool { get set } /// Decorate the v_tracker field in the tracker protocol. /// @note Do not use. Internal use only. @objc var trackerVersionSuffix: String? { get set } /// Closure called to retrieve the Identifier for Advertisers (IDFA) from AdSupport module /// It is called repeatedly (on each tracked event) until a UUID is returned. @objc var advertisingIdentifierRetriever: (() -> UUID?)? { get set } } public protocol PlatformContextConfigurationProtocol { /// List of properties of the platform context to track. If not passed and `platformContext` is enabled, all available properties will be tracked. /// The required `osType`, `osVersion`, `deviceManufacturer`, and `deviceModel` properties will be tracked in the entity regardless of this setting. var platformContextProperties: [PlatformContextProperty]? { get set } } /// This class represents the configuration of the tracker and the core tracker properties. /// The TrackerConfiguration can be used to setup the tracker behaviour indicating what should be /// tracked in term of automatic tracking and contexts/entities to track with the events. @objc(SPTrackerConfiguration) public class TrackerConfiguration: SerializableConfiguration, TrackerConfigurationProtocol, PlatformContextConfigurationProtocol, ConfigurationProtocol { private var _appId: String? /// Identifer of the app. @objc public var appId: String { get { return _appId ?? sourceConfig?.appId ?? Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ?? "" } set { _appId = newValue } } private var _devicePlatform: DevicePlatform? /// It sets the device platform the tracker is running on. @objc public var devicePlatform: DevicePlatform { get { return _devicePlatform ?? sourceConfig?.devicePlatform ?? DevicePlatform.mobile } set { _devicePlatform = newValue } } private var _base64Encoding: Bool? /// It indicates whether the JSON data in the payload should be base64 encoded. @objc public var base64Encoding: Bool { get { return _base64Encoding ?? sourceConfig?.base64Encoding ?? TrackerDefaults.base64Encoded } set { _base64Encoding = newValue } } private var _logLevel: LogLevel? /// It sets the log level of tracker logs. @objc public var logLevel: LogLevel { get { return _logLevel ?? sourceConfig?.logLevel ?? LogLevel.off } set { _logLevel = newValue } } private var _loggerDelegate: LoggerDelegate? /// It sets the logger delegate that receive logs from the tracker. @objc public var loggerDelegate: LoggerDelegate? { get { return _loggerDelegate ?? sourceConfig?._loggerDelegate } set { _loggerDelegate = newValue} } private var _applicationContext: Bool? /// Whether application context is sent with all the tracked events. @objc public var applicationContext: Bool { get { return _applicationContext ?? sourceConfig?.applicationContext ?? TrackerDefaults.applicationContext } set { _applicationContext = newValue } } private var _platformContext: Bool? /// Whether mobile/platform context is sent with all the tracked events. @objc public var platformContext: Bool { get { return _platformContext ?? sourceConfig?.platformContext ?? TrackerDefaults.platformContext } set { _platformContext = newValue } } private var _geoLocationContext: Bool? /// Whether geo-location context is sent with all the tracked events. @objc public var geoLocationContext: Bool { get { return _geoLocationContext ?? sourceConfig?.geoLocationContext ?? TrackerDefaults.geoLocationContext } set { _geoLocationContext = newValue } } private var _sessionContext: Bool? /// Whether session context is sent with all the tracked events. @objc public var sessionContext: Bool { get { return _sessionContext ?? sourceConfig?.sessionContext ?? TrackerDefaults.sessionContext } set { _sessionContext = newValue } } private var _deepLinkContext: Bool? /// Whether deepLink context is sent with all the ScreenView events. @objc public var deepLinkContext: Bool { get { return _deepLinkContext ?? sourceConfig?.deepLinkContext ?? TrackerDefaults.deepLinkContext } set { _deepLinkContext = newValue } } private var _screenContext: Bool? /// Whether screen context is sent with all the tracked events. @objc public var screenContext: Bool { get { return _screenContext ?? sourceConfig?.screenContext ?? TrackerDefaults.screenContext } set { _screenContext = newValue } } private var _screenViewAutotracking: Bool? /// Whether enable automatic tracking of ScreenView events. @objc public var screenViewAutotracking: Bool { get { return _screenViewAutotracking ?? sourceConfig?.screenViewAutotracking ?? TrackerDefaults.autotrackScreenViews } set { _screenViewAutotracking = newValue } } private var _lifecycleAutotracking: Bool? /// Whether enable automatic tracking of background and foreground transitions. @objc public var lifecycleAutotracking: Bool { get { return _lifecycleAutotracking ?? sourceConfig?.lifecycleAutotracking ?? TrackerDefaults.lifecycleEvents } set { _lifecycleAutotracking = newValue } } private var _installAutotracking: Bool? /// Whether enable automatic tracking of install event. @objc public var installAutotracking: Bool { get { return _installAutotracking ?? sourceConfig?.installAutotracking ?? TrackerDefaults.installEvent } set { _installAutotracking = newValue } } private var _exceptionAutotracking: Bool? /// Whether enable crash reporting. @objc public var exceptionAutotracking: Bool { get { return _exceptionAutotracking ?? sourceConfig?.exceptionAutotracking ?? TrackerDefaults.exceptionEvents } set { _exceptionAutotracking = newValue } } private var _diagnosticAutotracking: Bool? /// Whether enable diagnostic reporting. @objc public var diagnosticAutotracking: Bool { get { return _diagnosticAutotracking ?? sourceConfig?.diagnosticAutotracking ?? TrackerDefaults.trackerDiagnostic } set { _diagnosticAutotracking = newValue } } private var _userAnonymisation: Bool? /// Whether to anonymise client-side user identifiers in session (userId, previousSessionId), subject (userId, networkUserId, domainUserId, ipAddress) and platform context entities (IDFA) /// Setting this property on a running tracker instance starts a new session (if sessions are tracked). @objc public var userAnonymisation: Bool { get { return _userAnonymisation ?? sourceConfig?.userAnonymisation ?? TrackerDefaults.userAnonymisation } set { _userAnonymisation = newValue } } private var _trackerVersionSuffix: String? /// Decorate the v_tracker field in the tracker protocol. /// @note Do not use. Internal use only. @objc public var trackerVersionSuffix: String? { get { return _trackerVersionSuffix ?? sourceConfig?.trackerVersionSuffix } set { _trackerVersionSuffix = newValue } } private var _advertisingIdentifierRetriever: (() -> UUID?)? /// Closure called to retrieve the Identifier for Advertisers (IDFA) from AdSupport module /// It is called repeatedly (on each tracked event) until a UUID is returned. @objc public var advertisingIdentifierRetriever: (() -> UUID?)? { get { return _advertisingIdentifierRetriever ?? sourceConfig?.advertisingIdentifierRetriever } set { _advertisingIdentifierRetriever = newValue } } private var _platformContextProperties: [PlatformContextProperty]? /// List of properties of the platform context to track. If not passed and `platformContext` is enabled, all available properties will be tracked. /// The required `osType`, `osVersion`, `deviceManufacturer`, and `deviceModel` properties will be tracked in the entity regardless of this setting. public var platformContextProperties: [PlatformContextProperty]? { get { return _platformContextProperties ?? sourceConfig?.platformContextProperties } set { _platformContextProperties = newValue } } // MARK: - Internal /// Fallback configuration to read from in case requested values are not present in this configuraiton. internal var sourceConfig: TrackerConfiguration? = nil private var _isPaused: Bool? internal var isPaused: Bool { get { return _isPaused ?? sourceConfig?.isPaused ?? false } set { _isPaused = newValue } } @objc public override init() { super.init() } @objc public convenience init(appId: String) { self.init() self.appId = appId } @objc public convenience init?(dictionary: [String : Any]) { self.init() if let appId = dictionary["appId"] as? String { self.appId = appId } if let devicePlatform = dictionary["devicePlatform"] as? String { self.devicePlatform = stringToDevicePlatform(devicePlatform) ?? .mobile } // TODO: Uniform "base64encoding" string on both Android and iOS trackers if let base64Encoding = dictionary["base64encoding"] as? Bool { self.base64Encoding = base64Encoding } if let logLevelValue = dictionary["logLevel"] as? String, let index = ["off", "error", "debug", "verbose"].firstIndex(of: logLevelValue), let logLevel = LogLevel(rawValue: index) { self.logLevel = logLevel } if let sessionContext = dictionary["sessionContext"] as? Bool { self.sessionContext = sessionContext } if let applicationContext = dictionary["applicationContext"] as? Bool { self.applicationContext = applicationContext } if let platformContext = dictionary["platformContext"] as? Bool { self.platformContext = platformContext } if let geoLocationContext = dictionary["geoLocationContext"] as? Bool { self.geoLocationContext = geoLocationContext } if let deepLinkContext = dictionary["deepLinkContext"] as? Bool { self.deepLinkContext = deepLinkContext } if let screenContext = dictionary["screenContext"] as? Bool { self.screenContext = screenContext } if let screenViewAutotracking = dictionary["screenViewAutotracking"] as? Bool { self.screenViewAutotracking = screenViewAutotracking } if let lifecycleAutotracking = dictionary["lifecycleAutotracking"] as? Bool { self.lifecycleAutotracking = lifecycleAutotracking } if let installAutotracking = dictionary["installAutotracking"] as? Bool { self.installAutotracking = installAutotracking } if let exceptionAutotracking = dictionary["exceptionAutotracking"] as? Bool { self.exceptionAutotracking = exceptionAutotracking } if let diagnosticAutotracking = dictionary["diagnosticAutotracking"] as? Bool { self.diagnosticAutotracking = diagnosticAutotracking } if let userAnonymisation = dictionary["userAnonymisation"] as? Bool { self.userAnonymisation = userAnonymisation } } // MARK: - Builders /// Identifer of the app. @objc public func appId(_ appId: String) -> Self { self.appId = appId return self } /// It sets the device platform the tracker is running on. @objc public func devicePlatform(_ devicePlatform: DevicePlatform) -> Self { self.devicePlatform = devicePlatform return self } /// It indicates whether the JSON data in the payload should be base64 encoded. @objc public func base64Encoding(_ base64Encoding: Bool) -> Self { self.base64Encoding = base64Encoding return self } /// It sets the log level of tracker logs. @objc public func logLevel(_ logLevel: LogLevel) -> Self { self.logLevel = logLevel return self } /// It sets the logger delegate that receive logs from the tracker. @objc public func loggerDelegate(_ loggerDelegate: LoggerDelegate?) -> Self { self.loggerDelegate = loggerDelegate return self } /// Whether application context is sent with all the tracked events. @objc public func applicationContext(_ applicationContext: Bool) -> Self { self.applicationContext = applicationContext return self } /// Whether mobile/platform context is sent with all the tracked events. @objc public func platformContext(_ platformContext: Bool) -> Self { self.platformContext = platformContext return self } /// List of properties of the platform context to track. If not passed and `platformContext` is enabled, all available properties will be tracked. /// The required `osType`, `osVersion`, `deviceManufacturer`, and `deviceModel` properties will be tracked in the entity regardless of this setting. public func platformContextProperties(_ platformContextProperties: [PlatformContextProperty]?) -> Self { self.platformContextProperties = platformContextProperties return self } /// Whether geo-location context is sent with all the tracked events. @objc public func geoLocationContext(_ geoLocationContext: Bool) -> Self { self.geoLocationContext = geoLocationContext return self } /// Whether session context is sent with all the tracked events. @objc public func sessionContext(_ sessionContext: Bool) -> Self { self.sessionContext = sessionContext return self } /// Whether deepLink context is sent with all the ScreenView events. @objc public func deepLinkContext(_ deepLinkContext: Bool) -> Self { self.deepLinkContext = deepLinkContext return self } /// Whether screen context is sent with all the tracked events. @objc public func screenContext(_ screenContext: Bool) -> Self { self.screenContext = screenContext return self } /// Whether enable automatic tracking of ScreenView events. @objc public func screenViewAutotracking(_ screenViewAutotracking: Bool) -> Self { self.screenViewAutotracking = screenViewAutotracking return self } /// Whether enable automatic tracking of background and foreground transitions. @objc public func lifecycleAutotracking(_ lifecycleAutotracking: Bool) -> Self { self.lifecycleAutotracking = lifecycleAutotracking return self } /// Whether enable automatic tracking of install event. @objc public func installAutotracking(_ installAutotracking: Bool) -> Self { self.installAutotracking = installAutotracking return self } /// Whether enable crash reporting. @objc public func exceptionAutotracking(_ exceptionAutotracking: Bool) -> Self { self.exceptionAutotracking = exceptionAutotracking return self } /// Whether enable diagnostic reporting. @objc public func diagnosticAutotracking(_ diagnosticAutotracking: Bool) -> Self { self.diagnosticAutotracking = diagnosticAutotracking return self } /// Whether to anonymise client-side user identifiers in session (userId, previousSessionId), subject (userId, networkUserId, domainUserId, ipAddress) and platform context entities (IDFA) /// Setting this property on a running tracker instance starts a new session (if sessions are tracked). @objc public func userAnonymisation(_ userAnonymisation: Bool) -> Self { self.userAnonymisation = userAnonymisation return self } /// Decorate the v_tracker field in the tracker protocol. /// @note Do not use. Internal use only. @objc public func trackerVersionSuffix(_ trackerVersionSuffix: String?) -> Self { self.trackerVersionSuffix = trackerVersionSuffix return self } /// Closure called to retrieve the Identifier for Advertisers (IDFA) from AdSupport module /// It is called repeatedly (on each tracked event) until a UUID is returned. @objc public func advertisingIdentifierRetriever(_ retriever: (() -> UUID?)?) -> Self { self.advertisingIdentifierRetriever = retriever return self } // MARK: - NSCopying @objc override public func copy(with zone: NSZone? = nil) -> Any { let copy = TrackerConfiguration() copy.appId = appId copy.devicePlatform = devicePlatform copy.base64Encoding = base64Encoding copy.logLevel = logLevel copy.loggerDelegate = loggerDelegate copy.sessionContext = sessionContext copy.applicationContext = applicationContext copy.platformContext = platformContext copy.platformContextProperties = platformContextProperties copy.geoLocationContext = geoLocationContext copy.deepLinkContext = deepLinkContext copy.screenContext = screenContext copy.screenViewAutotracking = screenViewAutotracking copy.lifecycleAutotracking = lifecycleAutotracking copy.installAutotracking = installAutotracking copy.exceptionAutotracking = exceptionAutotracking copy.diagnosticAutotracking = diagnosticAutotracking copy.trackerVersionSuffix = trackerVersionSuffix copy.userAnonymisation = userAnonymisation copy.advertisingIdentifierRetriever = advertisingIdentifierRetriever return copy } // MARK: - NSSecureCoding @objc public override class var supportsSecureCoding: Bool { return true } @objc public override func encode(with coder: NSCoder) { coder.encode(appId, forKey: "appId") coder.encode(devicePlatform.rawValue, forKey: "devicePlatform") coder.encode(base64Encoding, forKey: "base64Encoding") coder.encode(logLevel.rawValue, forKey: "logLevel") coder.encode(loggerDelegate, forKey: "loggerDelegate") coder.encode(sessionContext, forKey: "sessionContext") coder.encode(applicationContext, forKey: "applicationContext") coder.encode(platformContext, forKey: "platformContext") coder.encode(geoLocationContext, forKey: "geoLocationContext") coder.encode(deepLinkContext, forKey: "deepLinkContext") coder.encode(screenContext, forKey: "screenContext") coder.encode(screenViewAutotracking, forKey: "screenViewAutotracking") coder.encode(lifecycleAutotracking, forKey: "lifecycleAutotracking") coder.encode(installAutotracking, forKey: "installAutotracking") coder.encode(exceptionAutotracking, forKey: "exceptionAutotracking") coder.encode(diagnosticAutotracking, forKey: "diagnosticAutotracking") coder.encode(trackerVersionSuffix, forKey: "trackerVersionSuffix") coder.encode(userAnonymisation, forKey: "userAnonymisation") } required init?(coder: NSCoder) { super.init() if let appId = coder.decodeObject(forKey: "appId") as? String { self.appId = appId } if let devicePlatform = DevicePlatform(rawValue: coder.decodeInteger(forKey: "devicePlatform")) { self.devicePlatform = devicePlatform } base64Encoding = coder.decodeBool(forKey: "base64Encoding") if let logLevel = LogLevel(rawValue: coder.decodeInteger(forKey: "logLevel")) { self.logLevel = logLevel } if let loggerDelegate = coder.decodeObject(forKey: "loggerDelegate") as? LoggerDelegate { self.loggerDelegate = loggerDelegate } sessionContext = coder.decodeBool(forKey: "sessionContext") applicationContext = coder.decodeBool(forKey: "applicationContext") platformContext = coder.decodeBool(forKey: "platformContext") geoLocationContext = coder.decodeBool(forKey: "geoLocationContext") deepLinkContext = coder.decodeBool(forKey: "deepLinkContext") screenContext = coder.decodeBool(forKey: "screenContext") screenViewAutotracking = coder.decodeBool(forKey: "screenViewAutotracking") lifecycleAutotracking = coder.decodeBool(forKey: "lifecycleAutotracking") installAutotracking = coder.decodeBool(forKey: "installAutotracking") exceptionAutotracking = coder.decodeBool(forKey: "exceptionAutotracking") diagnosticAutotracking = coder.decodeBool(forKey: "diagnosticAutotracking") if let trackerVersionSuffix = coder.decodeObject(forKey: "trackerVersionSuffix") as? String { self.trackerVersionSuffix = trackerVersionSuffix } userAnonymisation = coder.decodeBool(forKey: "userAnonymisation") } }
""" Email utilities file """ import smtplib from email.message import EmailMessage def generate_email(email_text: str, email_address: str) -> EmailMessage: """ Create an email :param email_text: content of the email :param email_address: address to send and receive the notification :return: Email message """ msg: EmailMessage = EmailMessage() msg['From'] = email_address msg['To'] = email_address msg['Subject'] = 'Flight Notify' msg.set_content(email_text) return msg def send_email(email_text: str, email_address: str, email_password: str) -> None: """ Send an email via gmail smtp :param email_text: content of the email :param email_address: address to send and receive the notification :param email_password: app password to log in :return: None """ msg: EmailMessage = generate_email(email_text, email_address) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server: smtp_server.login(email_address, email_password) smtp_server.sendmail(email_address, email_address, msg.as_string()) print("Message sent!")
<script lang="ts"> import { invalidate } from "$app/navigation"; import Button from "$cmp/core/buttons/Button.svelte"; import IconButton from "$cmp/core/buttons/IconButton.svelte"; import Input from "$cmp/core/inputs/Input.svelte"; import { pushModal } from "$cmp/core/modals/modalStore"; import AppContent from "$cmp/core/scaffold/AppContent.svelte"; import AppContentSection from "$cmp/core/scaffold/AppContentSection.svelte"; import { s_headerTitle } from "$cmp/core/scaffold/appHeader/s_headerTitle"; import ModalCreateApiKey from "$cmp/modalContents/ModalCreateApiKey.svelte"; import ModalCreateChannel from "$cmp/modalContents/ModalCreateChannel.svelte"; import ModalCreateProject from "$cmp/modalContents/ModalCreateProject.svelte"; import ModalDeleteApiKey from "$cmp/modalContents/ModalDeleteApiKey.svelte"; import ModalDeleteChannel from "$cmp/modalContents/ModalDeleteChannel.svelte"; import ModalDeleteProject from "$cmp/modalContents/ModalDeleteProject.svelte"; import type { IProject } from "$lib/types/IProject"; import { copyToClipboard } from "$lib/utils/clipboard"; import { TKN_ICON } from "$lib/utils/tokens"; import type { PageServerData } from "./$types"; import IconAddSquare from "$cmp/core/icons/IconAddSquare.svelte"; import IconClipboard from "$cmp/core/icons/IconClipboard.svelte"; import IconDeleteBin2 from "$cmp/core/icons/IconDeleteBin2.svelte"; import IconSignHash from "$cmp/core/icons/IconSignHash.svelte"; import IconLoginKey from "$cmp/core/icons/IconLoginKey.svelte"; s_headerTitle.set("Projects"); // PROPS export let data: PageServerData; // STATE let filterValue = ""; $: data.projects?.sort((a, b) => a.displayName.localeCompare(b.displayName)); $: filteredProjects = data.projects.filter(e => e.displayName.toLowerCase().includes(filterValue.toLowerCase())); // HANDLERS function onNewProject() { pushModal(ModalCreateProject, { onCreated: () => invalidate("/app/settings") }); } async function onNewChannel(project: IProject) { pushModal(ModalCreateChannel, { project, onCreated: () => invalidate("/app/settings") }); } function onNewApiKey(projectKey: string) { pushModal(ModalCreateApiKey, { projectKey, onCreated: () => invalidate("/app/settings") }); } function onDeleteProject(project: IProject) { pushModal(ModalDeleteProject, { project, onDeleted: () => invalidate("/app/settings") }) } function onDeleteChannel(project: IProject, channelID: string) { pushModal(ModalDeleteChannel, { project, channelID, onDeleted: () => invalidate("/app/settings") }) } function onDeleteApiKey(apiKey: string, keyName: string) { pushModal(ModalDeleteApiKey, { apiKey, keyName, onDeleted: () => invalidate("/app/settings") }) } </script> <AppContent style="section"> {#if !data.projects || !data.apiKeys} err no project / api keys <!-- TODO: impl --> {:else} <AppContentSection> <form on:submit|preventDefault> <fieldset class="flex items-stretch gap-6"> <Button clazz="w-full shrink-0 grow flex-1 flex justify-center items-center gap-4" on:click={onNewProject}> <!--<IconPlus size={TKN_ICON.SIZE.SM} stroke={TKN_ICON.STROKE.BASE}/>--> <span>New Project</span> </Button> <Input placeholder="Search projects" bind:value={filterValue}/> </fieldset> </form> <hr class="mt-6 mb-6"> {#if !filteredProjects} no projects with filter {:else} {#each filteredProjects as project} <details class="project-item"> <!-- TODO: Fix icon --> <summary class="text-xl font-medium"><span class="icon"></span>{project.displayName}</summary> <div class="content flex flex-col items-stretch gap-6"> <div class="flex-1"> <div class="flex items-center gap-2"> <span class="uppercase text-sm font-medium text-neutral-500">Channels</span> <IconButton on:click={() => onNewChannel(project)}> <IconAddSquare size={TKN_ICON.SIZE.SM}/> </IconButton> </div> <ul> {#if project.channels.length <= 0} <li class="py-3"><span class="text-gray-500">No channels yet.</span></li> {:else} {#each project.channels as channel} <li class="flex items-center justify-between border-b-2 border-neutral-100 py-1 shrink"> <ul class="flex-1 flex items-center gap-2 shrink grow overflow-hidden"> <li class="shrink-0"> <IconSignHash size={TKN_ICON.SIZE.XS} /> </li> <li class="truncate"><span class="font-mono">{channel.id}</span></li> </ul> <ul class="flex"> <!--<li> {#if channel.notify} <IconButton ><IconBell size={TKN_ICON.SIZE.BASE} stroke={TKN_ICON.STROKE.BASE} /></IconButton> {:else} <IconButton ><IconBellOff size={TKN_ICON.SIZE.BASE} stroke={TKN_ICON.STROKE.BASE} /></IconButton> {/if} </li>--> <li> <IconButton on:click={() => { copyToClipboard(channel.id); }} ><IconClipboard size={TKN_ICON.SIZE.SM} /></IconButton> </li> <li> <IconButton on:click={() => onDeleteChannel(project, channel.id)} ><IconDeleteBin2 size={TKN_ICON.SIZE.SM} /></IconButton> </li> </ul> </li> {/each} {/if} </ul> </div> <div class="flex-1"> <div class="flex items-center gap-2"> <span class="uppercase text-sm font-medium text-neutral-500">API Keys</span> <IconButton on:click={() => onNewApiKey(project.key)}> <IconAddSquare size={TKN_ICON.SIZE.SM}/> </IconButton> </div> <ul> {#if data.apiKeys.filter(e => e.project === project.key).length <= 0} <li class="py-3"><span class="text-gray-500">No keys yet.</span></li> {:else} {#each data.apiKeys.filter(e => e.project === project.key) as apiKey} <li class="flex items-center justify-between border-b-2 border-neutral-100 py-3 shrink"> <div class="flex flex-col gap-1 shrink grow overflow-hidden"> <span class="font-mono text-sm">{apiKey.displayName}</span> <ul class="flex-1 flex items-center gap-2"> <li class="shrink-0"> <IconLoginKey size={TKN_ICON.SIZE.XS} /> </li> <li class="truncate"><span class="font-mono">{apiKey.key}</span></li> <!-- TODO: Hide by default --> </ul> </div> <ul class="flex"> <li> <IconButton on:click={() => { copyToClipboard(apiKey.key); }} ><IconClipboard size={TKN_ICON.SIZE.SM}/></IconButton> </li> <li> <IconButton on:click={() => { onDeleteApiKey(apiKey.key, apiKey.displayName); }} ><IconDeleteBin2 size={TKN_ICON.SIZE.SM}/></IconButton> </li> </ul> </li> {/each} {/if} </ul> </div> <div class="flex-1"> <div class="flex items-center gap-2"> <span class="uppercase text-sm font-medium text-neutral-500">Other</span> </div> <div class="mt-4"> <Button style="red" on:click={() => onDeleteProject(project)}>Delete Project</Button> </div> </div> </div> </details> {/each} {/if} </AppContentSection> {/if} </AppContent> <style lang="postcss"> .project-item { @apply border-2 border-neutral-200 bg-neutral-50/30 p-2 px-6 rounded-xl; } .project-item > summary { @apply cursor-pointer py-2; } .project-item > .content { @apply mt-2 mb-4; } details[open].project-item > summary { @apply border-b-2 border-neutral-200 pb-4; } .project-item + .project-item { @apply mt-6; } details > summary { list-style-type: '▶️'; } details[open] > summary { list-style-type: '▼'; } details > summary > span { @apply ml-2; } </style>
<template> <div class="container"> <form action="" method="POST" name="formulario"> <div class="form-group"> <div class="col-md-6 offset-md-3"> <select ref="textmessage" type="text" class="form-control shadow-sm mb-4 bg-body rounded" > <option>Janeiro</option> <option>Fevereiro</option> <option>Março</option> <option>Abril</option> <option>Maio</option> <option>Junho</option> <option>Julho</option> <option>Agosto</option> <option>Setembro</option> <option>Outubro</option> <option>Novembro</option> <option>Dezembro</option> </select> </div> </div> <div class="form-group"> <div class="col-md-6 offset-md-3"> <input ref="pricemessage" type="number" class="form-control shadow-sm mb-2 bg-body rounded" /> </div> </div> <br /> <div class="form-group"> <div class="col-md-6 offset-md-3"> <div class="d-grid gap-2"> <button @click="addNewMessage" type="button" class="btn btn-secondary" > Enviar </button> </div> </div> </div> </form> </div> <br /> <hr /> <div class="container col-md-6 offset-md-3"> <!-- ... --> <table class="table table-striped table-hover text-start"> <thead class="table-dark"> <tr> <th> <router-link type="button" class="btn btn-secondary" :to="`/gerenciamento/`" > Editar </router-link> </th> <th>Total</th> </tr> </thead> <tbody v-for="(value, key) in salesByMonth" :key="key"> <tr> <td> {{ key }} </td> <td>{{ value.toFixed(2) }}</td> </tr> </tbody> </table> </div> </template> <script> import { onSnapshot, collection, doc, deleteDoc, setDoc, addDoc, orderBy, query, } from "firebase/firestore"; import { db } from "../firebaseConfig"; import { ref, onUnmounted } from "vue"; export default { name: "HomeView", components: {}, data: () => { return { messages: ref([]), currentPage: 1, itemsPerPage: 5, searchTerm: "", }; }, computed: { salesByMonth() { return this.messages.reduce((acc, curr) => { if (curr.text in acc) { acc[curr.text] += curr.price; } else { acc[curr.text] = curr.price; } return acc; }, {}); }, }, methods: { addNewMessage: function () { try { addDoc(collection(db, "messages"), { text: this.$refs.textmessage.value, price: parseFloat(this.$refs.pricemessage.value), date: Date.now(), }); alert("Valor adicionada com sucesso!"); } catch (e) { console.error(e); alert("Ocorreu um erro ao tentar adicionar a mensagem. Por favor, tente novamente."); } }, updateMessage: function (message) { setDoc(doc(db, "messages", message.id), { text: message.text, price: message.price, date: message.date, }); }, deleteMessage: function (id) { deleteDoc(doc(db, "messages", id)); }, }, mounted() { const latestQuery = query(collection(db, "messages"), orderBy("date", "desc")); const livemessages = onSnapshot(latestQuery, (snapshot) => { this.messages = snapshot.docs.map((doc) => { return { id: doc.id, text: doc.data().text, price: doc.data().price, date: doc.data().date, }; }); }); onUnmounted(livemessages); }, }; </script> <style></style>
import DocLink from '@site/src/components/DocLink' Colliders are nodes which have multiple parents in a causal graph. Colliders are interesting because they can cause counterintuitive behavior in the distribution $P(A,B,C)$. Conditioning on a collider can introduce statistical association between its parents. This effect can create issues in an analysis if not accounted for (see <DocLink to="collider bias"/>). It can be exploited to infer information about the structure of a graph based on the distribution of its variables (see <DocLink to="causal discovery"/>). ## Example Suppose the following is a causal graph: ```mermaid graph TD; A-->B; C-->B; ``` In this example, $A$ and $C$ will be independent in their joint distribution $P(A,C)$, but dependent in the conditional distribution $P(A,B | C)$.
--- description: Batched orchestration for cypress-cloud --- # Batched Orchestration ### Batched Orchestration This package uses its own orchestration and reporting protocol that is independent of cypress native implementation. This approach provides several benefits, including more control, flexibility and the ability to implement new features that are not supported by the native cypress orchestration.&#x20; {% hint style="info" %} Please note: the batched orchestration is not yet available for sorry-cypress users (only for currents.dev) {% endhint %} The new approach can present a slightly different performance compared to the previous integration. To enhance its performance, the new orchestration protocol allows multiple spec files to be batched together for greater efficiency. You configure the batching in `cypress.config.js` and use different values for different testing types: ```javascript // currents.config.js module.exports = { // ... e2e: { batchSize: 3, // orchestration batch size for e2e tests (Currents only) }, component: { batchSize: 5, // orchestration batch size for component tests (Currents only) }, }; ``` Based on our benchmarks, the performance is comparable to that of the native orchestration, however, it can vary depending on your specific configuration and setup. Adjusting the batching configuration can help to achieve optimal results for e2e or component tests. #### Native Orchestration Diagram ```mermaid sequenceDiagram loop while no specs left Cypress Runner ->> Cloud Service: Get Next Spec File Cloud Service -->> Cypress Runner: Spec File activate Cypress Runner Cypress Runner ->> Cypress Runner: executing Spec File Cypress Runner ->> Cloud Service: Report Result for Spec File deactivate Cypress Runner end ``` #### Batched Orchestration Diagram ```mermaid sequenceDiagram loop while no specs are left Cypress Runner ->> Cloud Service: Get Next Spec Files Batch Cloud Service -->> Cypress Runner: SpecFileA, SpecFileB, SpecFileC activate Cypress Runner Cypress Runner ->> Cypress Runner: executing SpecFileA, SpecFileB, SpecFileC Cypress Runner ->> Cloud Service: Report Result for SpecFileA, SpecFileB, SpecFileC deactivate Cypress Runner end ```
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { Bookmark } from 'src/app/shared/models/bookmark.model'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { FlightsService } from 'src/app/flights/services/flights.service'; import { MatDialog } from '@angular/material/dialog'; import { trigger, transition, query, style, animate } from '@angular/animations'; @Component({ selector: 'app-bookmarks-list', templateUrl: './bookmarks-list.component.html', styleUrls: ['./bookmarks-list.component.css'], animations: [ trigger("listAnimation", [ transition("* => *", [ // each time the binding value changes query( ":leave", [ style({transform: 'translateX(0)', opacity: 1}), animate('1000ms', style({transform: 'translateX(100%)', opacity: 0})) ], { optional: true } ) ]) ]) ] }) export class BookmarksListComponent implements OnInit { loading = false; bookmarks = new MatTableDataSource<Bookmark>(); @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; @ViewChild(MatSort, { static: true }) matSort: MatSort; displayedColumns: string[] = [ 'idBookmark', 'title', 'addingDate', 'nbFlights', 'view']; constructor(private readonly flightsService: FlightsService, private dialog: MatDialog) { } ngOnInit(): void { this.bookmarks.paginator = this.paginator; this.bookmarks.sort = this.matSort; this.loading = true; this.flightsService.getBookmarkList().subscribe(bookmarks => { this.bookmarks.data = bookmarks; this.loading = false; }) } viewBookmark(idBookmark: number) { this.flightsService.viewBookmark(idBookmark); } openDialogWithRef(ref: TemplateRef<any>) { this.dialog.open(ref); } deleteBookmark(bookmark: Bookmark) { this.flightsService.deleteBookmark(bookmark.idBookmark).subscribe(data => { const newData = this.bookmarks.data; newData.splice(newData.indexOf(bookmark), 1); this.bookmarks.data = newData; } ); } deleteAllBookmark() { this.flightsService.deleteAllBookmark().subscribe(data => { const newData = this.bookmarks.data; newData.splice(0,this.bookmarks.data.length); this.bookmarks.data = newData; }); } }
// gcc structpoint.c -o structpoint.out // ./structpoint.out #include <stdio.h> #include <stdlib.h> #include <time.h> #include "structpoint.h" int main () { srand(time(NULL)); struct Point p1; struct Point *pt1 = &p1; pt1->x = float_rand(0,1.0); pt1->y = float_rand(0,1.0); printf("Nokta 1: (x,y) (%f,%f)\n",pt1->x,pt1->y); struct Circle cp1; struct Circle *c1 = &cp1; c1->center.x = 0.5; c1->center.y = 0.5; c1->r = 0.5; printf("Kure 1: (merkez,yaricap) ((%f,%f), %f)\n", c1->center.x,c1->center.y, c1->r); /* * **********************************************SORU1 * pt1 ve cp1 merkezi arasındaki mesafeyi ölçün. */ double dist = distance(pt1, &(cp1.center)); printf("Uzaklik : %lf\n",dist); /* * **********************************************SORU2 * pt1, c1 dairesi içinde midir?. */ int is_in = is_in_circle(pt1,c1); printf("In circle : %d\n",is_in); /* * **********************************************SORU3 * 1000 adet Point oluştur ve pt_array içinde tut */ int n_point = 1000 ; struct Point pt_array[n_point]; create_point_array(pt_array ,n_point); /* * **********************************************SORU4 * 1000 adet Point'ten kaçı daire içindedir? */ int i; int nbr_in_circle = 0 ; for(i=0;i<n_point;i++){ if(distance((pt_array+i),&(cp1.center))<=(c1->r)){ nbr_in_circle++; } } /* * **********************************************SORU5 * Pi hesapla */ printf("Cember icinde olanlar: %d\n",nbr_in_circle); double calculated_pi = calculate_pi(nbr_in_circle,n_point); printf("Hesaplanan pi sayisi: %lf\n",calculated_pi); return 0; }
--- title: "[Updated] Seamlessly Combining IPhone Videos and Images" date: 2024-05-31T07:40:56.982Z updated: 2024-06-01T07:40:56.982Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "This Article Describes [Updated] Seamlessly Combining IPhone Videos and Images" excerpt: "This Article Describes [Updated] Seamlessly Combining IPhone Videos and Images" keywords: "\"IPhone Video Sync,Video-Image Integration,Mobile Photo Fusion,Seamless iPhone Media,IPhones Combined Video,Photo+Video iOS Blend,Images with iPhone Videos\"" thumbnail: https://www.lifewire.com/thmb/j7-rZB6HuyeNRuibx63DJ8a6Fvc=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/duet-c82ee94b39e24788bcfd51d1eea24288.jpg --- ## Seamlessly Combining IPhone Videos and Images # How to Combine Videos into One on iPhone \[2024 Updated\] ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) ##### Ollie Mattison Mar 27, 2024• Proven solutions We all find ourselves delighted by watching videos for different purposes. Unsurprisingly, you have a bunch of videos on your iPhone. How about **combining your favorite genre videos into one video** on your iPhone? For example, you can merge all the funny videos and make it a single video. This way you can enjoy the videos in one go. For those people who have lots of video clips in their iPhone and want to merge those into one, we have come up with some amazing and useful apps to **combine videos on iPhone**. Let’s get off the ground to learn the methods. * [Part 1: Combine Live Photos to Videos in iOS 13 for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FPhotos) * [Part 2: Combine videos with iMovie on iPhone for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FiMovie) * [Part 3: Combine videos with Videoshop](#part3) * [Part 4: Combine videos with Filmora with more creative templates](#combine%5Fiphone%5Fvideo%5Fon%5Fcomputer) ## Part 1: Combine Live Photos to Videos with Photos app on iPhone \[iOS13\] The newly released iOS 13 added some cool features in the Photos app, and now you can combine several **Live Photos** together and save them as a new video or slideshow. Here is how to combine Live Photos to video in iOS13. * Launch the Photos app and then tap the **Select** button at the upper-right corner of the screen. * Select the taken Live Photos, tap the Share button in the lower-left corner of the screen and choose **Save As Video**. ![iPhone combine Live Photos to video](https://images.wondershare.com/filmora/article-images/select-live-photos-save-as-video.jpg) Combine Live Photos to Videos in iOS 13 ## Part 2: Combine videos with [iMovie](https://itunes.apple.com/us/app/imovie/id377298193?mt=8) iMovie is one of the apps in the list that can assist you to merge videos on iPhone. You can yourself create beautiful movies with the assistance of iMovie. Once you combine videos on iPhone, this app will let you transfer your videos between various iOS devices via AirDrop or iCloud Drive. Here is how you can add videos together on iPhone via iMovie. Check more details about [How to Edit Videos on iMovie](https://tools.techidaily.com/wondershare/filmora/download/) Step 1 – Launch iMovie app and get under the “Project” section available on the top of the screen. Step 2 – Now, tap on “Create Project” and then select the video type out of the two options available, i.e. “Movie” or “Trailer”, select “Movie” in this case. Next, tap on “Create” from the next screen. Or you can import video from File. Step 3 – Your project interface has now been successfully loaded on your screen. Now, to add the source video file, tap the “Media” icon on the left top of the timeline and your video gallery will load up on your screen. Select the desired source video and tap the “Add” icon to add it on the iMovie’s timeline. Step 4 – Once your preferred video is added on the timeline, you can scroll the timeline to left or right to let the vertical line known as "playhead’ appear on the screen. Now, place the playhead by scrolling left or right, exactly at the place where you desire to combine the video. ![imoive](https://images.wondershare.com/filmora/article-images/iMovie-app.jpg) Step 5 – This is the time where you need to add another video which you wish to combine with the source video. Follow the same process mentioned above to get your video added on the timeline. The nearest position to the playhead, be it before the existing video clip or after the clip, will let the fresh clip added to the video. Step 6 – Now, if you wish to preview the two added videos in a combined playback, simply hit on the “Play” icon available just above the timeline in middle of the screen. Step 7 – You can also use the transition effects from the presets to apply the desired effect when your first video is switched to another. Or, you can use the traditional fade in or out (default transition) as well. Step 8 – When you are satisfied with your video, simply hit the “Done” on the left top corner of your screen. And, the next interface will bring you up to a screen where you can simply save the merged video file on your local storage or can directly upload them to various cloud storage platforms. Moreover, here on this screen you can give your video a custom defined title too. ## Part 3: Combine videos with [Videoshop](https://itunes.apple.com/us/app/videoshop-video-editor/id615563599?mt=8) Videoshop is a great video editing app and is next app to combine video clips in the list. This app has got all; from trimming, cropping videos to adding sound effects, recording one’s own voice as well as resizing the video frame and many more features. Here is how you can add videos together on iPhone via Videoshop app. Step 1 – First of all, download the app from App Store. Launch it post downloading. Step 2 – Hit on the plus signed icon in order to start adding your videos. Step 3 – You can now choose the options given above the videos. You can select different settings or editing options like adding transition, typing texts, speed changes, adding audio track and many more. ![Videoshop](https://images.wondershare.com/filmora/article-images/Videoshop.jpg) Step 4 – Once done, you can move to tap on the “Next” button. Step 5 – Subsequently, move further by giving the title of video, author, place and date if you want. Also, you can customize videos with filters and themes. Step 6 – Once done with the merging videos on iPhone, tap on the Sharing button and store the file. You can also upload your file to YouTube, Vimeo or send via e-mail, save to Dropbox. ## Part 4: Combine videos with [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) on Windows or Mac You may face a little disturbance while combining videos on iPhone using iMovie. Using iMovie for merging videos may result in losing frames issue which can be unpleasant to anyone. Here, we would recommend you Filmora video editor which can be used on Windows and Mac computers. It is believed to be one of the [best video merger app](https://tools.techidaily.com/wondershare/filmora/download/) and would be a great option if you want to avoid losing frame thing. Besides [merging several videos into a longer one](https://tools.techidaily.com/wondershare/filmora/download/), Filmora also allows you to [put two videos side by side](https://tools.techidaily.com/wondershare/filmora/download/) and [make a split-screen video easily](https://tools.techidaily.com/wondershare/filmora/download/). Check the video tutorial and try the free trial version below. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) In this following part, I’ll show you how to combine iPhone videos with Filmora for Windows. 1\. Launch Wondershare Filmora on Windows and click the Import button and select “Import from a Camera or a Phone”. ![Import iPhone videos to Filmora ](https://images.wondershare.com/filmora/article-images/import-from-camera-phone-filmora9.jpg) 2\. In the pop-up Import for Device window, you will see the photos and video on your iPhone on the left side, click one to preview and then select it to import. Filmora will load it directly in the Project Media library. ![Import iPhone videos Window ](https://images.wondershare.com/filmora/article-images/import-from-device-window.jpg) Step 3 – Select all photos and videos you want to combine in the Project Media library and drag and drop them to the timeline. Once you do this, you will spot that the video files you’ve dragged will be aligned in the same timeline. ![drag iphone vidoes and photos to timeline](https://images.wondershare.com/filmora/article-images/drag-filmora.JPG) Step 4 – Filmora is packed with a great deal of powerful tools with the help of which you are allowed to modify contrast, color, [add effects, filters, elements](https://tools.techidaily.com/wondershare/filmora/download/) or background music etc. to video. So after merging, you can edit your videos if you wish. You can check our ultimate guide about [how to edit video in Filmora.](https://tools.techidaily.com/wondershare/filmora/download/) Step 5 – Once you find yourself contented with the creation, you can export it to your device. For this, choose the “EXPORT” option available in the toolbar and choose iPhone as the target device. ![export in Fimora9](https://images.wondershare.com/filmora/article-images/filmora9-export-options.jpg) [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) **Final Verdict** Here ends the discussion about **how to combine videos on iPhone** and we hope that you got a pleasant experience reading this post. Thanks for the time for browsing through the post. We offered you some refined apps like Filmora video editor to combine your videos. So, which was the best video merger app according to you? We would like to get familiar with your choice and experience. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions We all find ourselves delighted by watching videos for different purposes. Unsurprisingly, you have a bunch of videos on your iPhone. How about **combining your favorite genre videos into one video** on your iPhone? For example, you can merge all the funny videos and make it a single video. This way you can enjoy the videos in one go. For those people who have lots of video clips in their iPhone and want to merge those into one, we have come up with some amazing and useful apps to **combine videos on iPhone**. Let’s get off the ground to learn the methods. * [Part 1: Combine Live Photos to Videos in iOS 13 for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FPhotos) * [Part 2: Combine videos with iMovie on iPhone for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FiMovie) * [Part 3: Combine videos with Videoshop](#part3) * [Part 4: Combine videos with Filmora with more creative templates](#combine%5Fiphone%5Fvideo%5Fon%5Fcomputer) ## Part 1: Combine Live Photos to Videos with Photos app on iPhone \[iOS13\] The newly released iOS 13 added some cool features in the Photos app, and now you can combine several **Live Photos** together and save them as a new video or slideshow. Here is how to combine Live Photos to video in iOS13. * Launch the Photos app and then tap the **Select** button at the upper-right corner of the screen. * Select the taken Live Photos, tap the Share button in the lower-left corner of the screen and choose **Save As Video**. ![iPhone combine Live Photos to video](https://images.wondershare.com/filmora/article-images/select-live-photos-save-as-video.jpg) Combine Live Photos to Videos in iOS 13 ## Part 2: Combine videos with [iMovie](https://itunes.apple.com/us/app/imovie/id377298193?mt=8) iMovie is one of the apps in the list that can assist you to merge videos on iPhone. You can yourself create beautiful movies with the assistance of iMovie. Once you combine videos on iPhone, this app will let you transfer your videos between various iOS devices via AirDrop or iCloud Drive. Here is how you can add videos together on iPhone via iMovie. Check more details about [How to Edit Videos on iMovie](https://tools.techidaily.com/wondershare/filmora/download/) Step 1 – Launch iMovie app and get under the “Project” section available on the top of the screen. Step 2 – Now, tap on “Create Project” and then select the video type out of the two options available, i.e. “Movie” or “Trailer”, select “Movie” in this case. Next, tap on “Create” from the next screen. Or you can import video from File. Step 3 – Your project interface has now been successfully loaded on your screen. Now, to add the source video file, tap the “Media” icon on the left top of the timeline and your video gallery will load up on your screen. Select the desired source video and tap the “Add” icon to add it on the iMovie’s timeline. Step 4 – Once your preferred video is added on the timeline, you can scroll the timeline to left or right to let the vertical line known as "playhead’ appear on the screen. Now, place the playhead by scrolling left or right, exactly at the place where you desire to combine the video. ![imoive](https://images.wondershare.com/filmora/article-images/iMovie-app.jpg) Step 5 – This is the time where you need to add another video which you wish to combine with the source video. Follow the same process mentioned above to get your video added on the timeline. The nearest position to the playhead, be it before the existing video clip or after the clip, will let the fresh clip added to the video. Step 6 – Now, if you wish to preview the two added videos in a combined playback, simply hit on the “Play” icon available just above the timeline in middle of the screen. Step 7 – You can also use the transition effects from the presets to apply the desired effect when your first video is switched to another. Or, you can use the traditional fade in or out (default transition) as well. Step 8 – When you are satisfied with your video, simply hit the “Done” on the left top corner of your screen. And, the next interface will bring you up to a screen where you can simply save the merged video file on your local storage or can directly upload them to various cloud storage platforms. Moreover, here on this screen you can give your video a custom defined title too. ## Part 3: Combine videos with [Videoshop](https://itunes.apple.com/us/app/videoshop-video-editor/id615563599?mt=8) Videoshop is a great video editing app and is next app to combine video clips in the list. This app has got all; from trimming, cropping videos to adding sound effects, recording one’s own voice as well as resizing the video frame and many more features. Here is how you can add videos together on iPhone via Videoshop app. Step 1 – First of all, download the app from App Store. Launch it post downloading. Step 2 – Hit on the plus signed icon in order to start adding your videos. Step 3 – You can now choose the options given above the videos. You can select different settings or editing options like adding transition, typing texts, speed changes, adding audio track and many more. ![Videoshop](https://images.wondershare.com/filmora/article-images/Videoshop.jpg) Step 4 – Once done, you can move to tap on the “Next” button. Step 5 – Subsequently, move further by giving the title of video, author, place and date if you want. Also, you can customize videos with filters and themes. Step 6 – Once done with the merging videos on iPhone, tap on the Sharing button and store the file. You can also upload your file to YouTube, Vimeo or send via e-mail, save to Dropbox. ## Part 4: Combine videos with [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) on Windows or Mac You may face a little disturbance while combining videos on iPhone using iMovie. Using iMovie for merging videos may result in losing frames issue which can be unpleasant to anyone. Here, we would recommend you Filmora video editor which can be used on Windows and Mac computers. It is believed to be one of the [best video merger app](https://tools.techidaily.com/wondershare/filmora/download/) and would be a great option if you want to avoid losing frame thing. Besides [merging several videos into a longer one](https://tools.techidaily.com/wondershare/filmora/download/), Filmora also allows you to [put two videos side by side](https://tools.techidaily.com/wondershare/filmora/download/) and [make a split-screen video easily](https://tools.techidaily.com/wondershare/filmora/download/). Check the video tutorial and try the free trial version below. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) In this following part, I’ll show you how to combine iPhone videos with Filmora for Windows. 1\. Launch Wondershare Filmora on Windows and click the Import button and select “Import from a Camera or a Phone”. ![Import iPhone videos to Filmora ](https://images.wondershare.com/filmora/article-images/import-from-camera-phone-filmora9.jpg) 2\. In the pop-up Import for Device window, you will see the photos and video on your iPhone on the left side, click one to preview and then select it to import. Filmora will load it directly in the Project Media library. ![Import iPhone videos Window ](https://images.wondershare.com/filmora/article-images/import-from-device-window.jpg) Step 3 – Select all photos and videos you want to combine in the Project Media library and drag and drop them to the timeline. Once you do this, you will spot that the video files you’ve dragged will be aligned in the same timeline. ![drag iphone vidoes and photos to timeline](https://images.wondershare.com/filmora/article-images/drag-filmora.JPG) Step 4 – Filmora is packed with a great deal of powerful tools with the help of which you are allowed to modify contrast, color, [add effects, filters, elements](https://tools.techidaily.com/wondershare/filmora/download/) or background music etc. to video. So after merging, you can edit your videos if you wish. You can check our ultimate guide about [how to edit video in Filmora.](https://tools.techidaily.com/wondershare/filmora/download/) Step 5 – Once you find yourself contented with the creation, you can export it to your device. For this, choose the “EXPORT” option available in the toolbar and choose iPhone as the target device. ![export in Fimora9](https://images.wondershare.com/filmora/article-images/filmora9-export-options.jpg) [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) **Final Verdict** Here ends the discussion about **how to combine videos on iPhone** and we hope that you got a pleasant experience reading this post. Thanks for the time for browsing through the post. We offered you some refined apps like Filmora video editor to combine your videos. So, which was the best video merger app according to you? We would like to get familiar with your choice and experience. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions We all find ourselves delighted by watching videos for different purposes. Unsurprisingly, you have a bunch of videos on your iPhone. How about **combining your favorite genre videos into one video** on your iPhone? For example, you can merge all the funny videos and make it a single video. This way you can enjoy the videos in one go. For those people who have lots of video clips in their iPhone and want to merge those into one, we have come up with some amazing and useful apps to **combine videos on iPhone**. Let’s get off the ground to learn the methods. * [Part 1: Combine Live Photos to Videos in iOS 13 for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FPhotos) * [Part 2: Combine videos with iMovie on iPhone for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FiMovie) * [Part 3: Combine videos with Videoshop](#part3) * [Part 4: Combine videos with Filmora with more creative templates](#combine%5Fiphone%5Fvideo%5Fon%5Fcomputer) ## Part 1: Combine Live Photos to Videos with Photos app on iPhone \[iOS13\] The newly released iOS 13 added some cool features in the Photos app, and now you can combine several **Live Photos** together and save them as a new video or slideshow. Here is how to combine Live Photos to video in iOS13. * Launch the Photos app and then tap the **Select** button at the upper-right corner of the screen. * Select the taken Live Photos, tap the Share button in the lower-left corner of the screen and choose **Save As Video**. ![iPhone combine Live Photos to video](https://images.wondershare.com/filmora/article-images/select-live-photos-save-as-video.jpg) Combine Live Photos to Videos in iOS 13 ## Part 2: Combine videos with [iMovie](https://itunes.apple.com/us/app/imovie/id377298193?mt=8) iMovie is one of the apps in the list that can assist you to merge videos on iPhone. You can yourself create beautiful movies with the assistance of iMovie. Once you combine videos on iPhone, this app will let you transfer your videos between various iOS devices via AirDrop or iCloud Drive. Here is how you can add videos together on iPhone via iMovie. Check more details about [How to Edit Videos on iMovie](https://tools.techidaily.com/wondershare/filmora/download/) Step 1 – Launch iMovie app and get under the “Project” section available on the top of the screen. Step 2 – Now, tap on “Create Project” and then select the video type out of the two options available, i.e. “Movie” or “Trailer”, select “Movie” in this case. Next, tap on “Create” from the next screen. Or you can import video from File. Step 3 – Your project interface has now been successfully loaded on your screen. Now, to add the source video file, tap the “Media” icon on the left top of the timeline and your video gallery will load up on your screen. Select the desired source video and tap the “Add” icon to add it on the iMovie’s timeline. Step 4 – Once your preferred video is added on the timeline, you can scroll the timeline to left or right to let the vertical line known as "playhead’ appear on the screen. Now, place the playhead by scrolling left or right, exactly at the place where you desire to combine the video. ![imoive](https://images.wondershare.com/filmora/article-images/iMovie-app.jpg) Step 5 – This is the time where you need to add another video which you wish to combine with the source video. Follow the same process mentioned above to get your video added on the timeline. The nearest position to the playhead, be it before the existing video clip or after the clip, will let the fresh clip added to the video. Step 6 – Now, if you wish to preview the two added videos in a combined playback, simply hit on the “Play” icon available just above the timeline in middle of the screen. Step 7 – You can also use the transition effects from the presets to apply the desired effect when your first video is switched to another. Or, you can use the traditional fade in or out (default transition) as well. Step 8 – When you are satisfied with your video, simply hit the “Done” on the left top corner of your screen. And, the next interface will bring you up to a screen where you can simply save the merged video file on your local storage or can directly upload them to various cloud storage platforms. Moreover, here on this screen you can give your video a custom defined title too. ## Part 3: Combine videos with [Videoshop](https://itunes.apple.com/us/app/videoshop-video-editor/id615563599?mt=8) Videoshop is a great video editing app and is next app to combine video clips in the list. This app has got all; from trimming, cropping videos to adding sound effects, recording one’s own voice as well as resizing the video frame and many more features. Here is how you can add videos together on iPhone via Videoshop app. Step 1 – First of all, download the app from App Store. Launch it post downloading. Step 2 – Hit on the plus signed icon in order to start adding your videos. Step 3 – You can now choose the options given above the videos. You can select different settings or editing options like adding transition, typing texts, speed changes, adding audio track and many more. ![Videoshop](https://images.wondershare.com/filmora/article-images/Videoshop.jpg) Step 4 – Once done, you can move to tap on the “Next” button. Step 5 – Subsequently, move further by giving the title of video, author, place and date if you want. Also, you can customize videos with filters and themes. Step 6 – Once done with the merging videos on iPhone, tap on the Sharing button and store the file. You can also upload your file to YouTube, Vimeo or send via e-mail, save to Dropbox. ## Part 4: Combine videos with [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) on Windows or Mac You may face a little disturbance while combining videos on iPhone using iMovie. Using iMovie for merging videos may result in losing frames issue which can be unpleasant to anyone. Here, we would recommend you Filmora video editor which can be used on Windows and Mac computers. It is believed to be one of the [best video merger app](https://tools.techidaily.com/wondershare/filmora/download/) and would be a great option if you want to avoid losing frame thing. Besides [merging several videos into a longer one](https://tools.techidaily.com/wondershare/filmora/download/), Filmora also allows you to [put two videos side by side](https://tools.techidaily.com/wondershare/filmora/download/) and [make a split-screen video easily](https://tools.techidaily.com/wondershare/filmora/download/). Check the video tutorial and try the free trial version below. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) In this following part, I’ll show you how to combine iPhone videos with Filmora for Windows. 1\. Launch Wondershare Filmora on Windows and click the Import button and select “Import from a Camera or a Phone”. ![Import iPhone videos to Filmora ](https://images.wondershare.com/filmora/article-images/import-from-camera-phone-filmora9.jpg) 2\. In the pop-up Import for Device window, you will see the photos and video on your iPhone on the left side, click one to preview and then select it to import. Filmora will load it directly in the Project Media library. ![Import iPhone videos Window ](https://images.wondershare.com/filmora/article-images/import-from-device-window.jpg) Step 3 – Select all photos and videos you want to combine in the Project Media library and drag and drop them to the timeline. Once you do this, you will spot that the video files you’ve dragged will be aligned in the same timeline. ![drag iphone vidoes and photos to timeline](https://images.wondershare.com/filmora/article-images/drag-filmora.JPG) Step 4 – Filmora is packed with a great deal of powerful tools with the help of which you are allowed to modify contrast, color, [add effects, filters, elements](https://tools.techidaily.com/wondershare/filmora/download/) or background music etc. to video. So after merging, you can edit your videos if you wish. You can check our ultimate guide about [how to edit video in Filmora.](https://tools.techidaily.com/wondershare/filmora/download/) Step 5 – Once you find yourself contented with the creation, you can export it to your device. For this, choose the “EXPORT” option available in the toolbar and choose iPhone as the target device. ![export in Fimora9](https://images.wondershare.com/filmora/article-images/filmora9-export-options.jpg) [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) **Final Verdict** Here ends the discussion about **how to combine videos on iPhone** and we hope that you got a pleasant experience reading this post. Thanks for the time for browsing through the post. We offered you some refined apps like Filmora video editor to combine your videos. So, which was the best video merger app according to you? We would like to get familiar with your choice and experience. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions We all find ourselves delighted by watching videos for different purposes. Unsurprisingly, you have a bunch of videos on your iPhone. How about **combining your favorite genre videos into one video** on your iPhone? For example, you can merge all the funny videos and make it a single video. This way you can enjoy the videos in one go. For those people who have lots of video clips in their iPhone and want to merge those into one, we have come up with some amazing and useful apps to **combine videos on iPhone**. Let’s get off the ground to learn the methods. * [Part 1: Combine Live Photos to Videos in iOS 13 for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FPhotos) * [Part 2: Combine videos with iMovie on iPhone for FREE](#combine%5Fvideo%5Fon%5Fiphone%5Fwith%5FiMovie) * [Part 3: Combine videos with Videoshop](#part3) * [Part 4: Combine videos with Filmora with more creative templates](#combine%5Fiphone%5Fvideo%5Fon%5Fcomputer) ## Part 1: Combine Live Photos to Videos with Photos app on iPhone \[iOS13\] The newly released iOS 13 added some cool features in the Photos app, and now you can combine several **Live Photos** together and save them as a new video or slideshow. Here is how to combine Live Photos to video in iOS13. * Launch the Photos app and then tap the **Select** button at the upper-right corner of the screen. * Select the taken Live Photos, tap the Share button in the lower-left corner of the screen and choose **Save As Video**. ![iPhone combine Live Photos to video](https://images.wondershare.com/filmora/article-images/select-live-photos-save-as-video.jpg) Combine Live Photos to Videos in iOS 13 ## Part 2: Combine videos with [iMovie](https://itunes.apple.com/us/app/imovie/id377298193?mt=8) iMovie is one of the apps in the list that can assist you to merge videos on iPhone. You can yourself create beautiful movies with the assistance of iMovie. Once you combine videos on iPhone, this app will let you transfer your videos between various iOS devices via AirDrop or iCloud Drive. Here is how you can add videos together on iPhone via iMovie. Check more details about [How to Edit Videos on iMovie](https://tools.techidaily.com/wondershare/filmora/download/) Step 1 – Launch iMovie app and get under the “Project” section available on the top of the screen. Step 2 – Now, tap on “Create Project” and then select the video type out of the two options available, i.e. “Movie” or “Trailer”, select “Movie” in this case. Next, tap on “Create” from the next screen. Or you can import video from File. Step 3 – Your project interface has now been successfully loaded on your screen. Now, to add the source video file, tap the “Media” icon on the left top of the timeline and your video gallery will load up on your screen. Select the desired source video and tap the “Add” icon to add it on the iMovie’s timeline. Step 4 – Once your preferred video is added on the timeline, you can scroll the timeline to left or right to let the vertical line known as "playhead’ appear on the screen. Now, place the playhead by scrolling left or right, exactly at the place where you desire to combine the video. ![imoive](https://images.wondershare.com/filmora/article-images/iMovie-app.jpg) Step 5 – This is the time where you need to add another video which you wish to combine with the source video. Follow the same process mentioned above to get your video added on the timeline. The nearest position to the playhead, be it before the existing video clip or after the clip, will let the fresh clip added to the video. Step 6 – Now, if you wish to preview the two added videos in a combined playback, simply hit on the “Play” icon available just above the timeline in middle of the screen. Step 7 – You can also use the transition effects from the presets to apply the desired effect when your first video is switched to another. Or, you can use the traditional fade in or out (default transition) as well. Step 8 – When you are satisfied with your video, simply hit the “Done” on the left top corner of your screen. And, the next interface will bring you up to a screen where you can simply save the merged video file on your local storage or can directly upload them to various cloud storage platforms. Moreover, here on this screen you can give your video a custom defined title too. ## Part 3: Combine videos with [Videoshop](https://itunes.apple.com/us/app/videoshop-video-editor/id615563599?mt=8) Videoshop is a great video editing app and is next app to combine video clips in the list. This app has got all; from trimming, cropping videos to adding sound effects, recording one’s own voice as well as resizing the video frame and many more features. Here is how you can add videos together on iPhone via Videoshop app. Step 1 – First of all, download the app from App Store. Launch it post downloading. Step 2 – Hit on the plus signed icon in order to start adding your videos. Step 3 – You can now choose the options given above the videos. You can select different settings or editing options like adding transition, typing texts, speed changes, adding audio track and many more. ![Videoshop](https://images.wondershare.com/filmora/article-images/Videoshop.jpg) Step 4 – Once done, you can move to tap on the “Next” button. Step 5 – Subsequently, move further by giving the title of video, author, place and date if you want. Also, you can customize videos with filters and themes. Step 6 – Once done with the merging videos on iPhone, tap on the Sharing button and store the file. You can also upload your file to YouTube, Vimeo or send via e-mail, save to Dropbox. ## Part 4: Combine videos with [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) on Windows or Mac You may face a little disturbance while combining videos on iPhone using iMovie. Using iMovie for merging videos may result in losing frames issue which can be unpleasant to anyone. Here, we would recommend you Filmora video editor which can be used on Windows and Mac computers. It is believed to be one of the [best video merger app](https://tools.techidaily.com/wondershare/filmora/download/) and would be a great option if you want to avoid losing frame thing. Besides [merging several videos into a longer one](https://tools.techidaily.com/wondershare/filmora/download/), Filmora also allows you to [put two videos side by side](https://tools.techidaily.com/wondershare/filmora/download/) and [make a split-screen video easily](https://tools.techidaily.com/wondershare/filmora/download/). Check the video tutorial and try the free trial version below. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) In this following part, I’ll show you how to combine iPhone videos with Filmora for Windows. 1\. Launch Wondershare Filmora on Windows and click the Import button and select “Import from a Camera or a Phone”. ![Import iPhone videos to Filmora ](https://images.wondershare.com/filmora/article-images/import-from-camera-phone-filmora9.jpg) 2\. In the pop-up Import for Device window, you will see the photos and video on your iPhone on the left side, click one to preview and then select it to import. Filmora will load it directly in the Project Media library. ![Import iPhone videos Window ](https://images.wondershare.com/filmora/article-images/import-from-device-window.jpg) Step 3 – Select all photos and videos you want to combine in the Project Media library and drag and drop them to the timeline. Once you do this, you will spot that the video files you’ve dragged will be aligned in the same timeline. ![drag iphone vidoes and photos to timeline](https://images.wondershare.com/filmora/article-images/drag-filmora.JPG) Step 4 – Filmora is packed with a great deal of powerful tools with the help of which you are allowed to modify contrast, color, [add effects, filters, elements](https://tools.techidaily.com/wondershare/filmora/download/) or background music etc. to video. So after merging, you can edit your videos if you wish. You can check our ultimate guide about [how to edit video in Filmora.](https://tools.techidaily.com/wondershare/filmora/download/) Step 5 – Once you find yourself contented with the creation, you can export it to your device. For this, choose the “EXPORT” option available in the toolbar and choose iPhone as the target device. ![export in Fimora9](https://images.wondershare.com/filmora/article-images/filmora9-export-options.jpg) [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) **Final Verdict** Here ends the discussion about **how to combine videos on iPhone** and we hope that you got a pleasant experience reading this post. Thanks for the time for browsing through the post. We offered you some refined apps like Filmora video editor to combine your videos. So, which was the best video merger app according to you? We would like to get familiar with your choice and experience. [![Download Filmora Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
A/B测试+辛普森悖论,对照组实验组的选取;埋点的设置,尤其注意页面访问统计和用户浏览行为的相关指标;留存率的不同时段的分析 1.辛普森悖论 参考:http://www.woshipm.com/pmd/370128.html 辛普森悖论(Simpson’s Paradox)是英国统计学家E.H.辛普森(E.H.Simpson)于1951年提出的悖论, 即在某个条件下的两组数据,分别讨论时都会满足某种性质,可是一旦合并考虑,却可能导致相反的结论。 2.A/B测试 (1)A/B测试定义: A/B测试是一种用来比较两个样本不同的测试方法,其他的测试方法有:同期群测试,市场细分,多样本测试。 在互联网领域,A/B测试一般用来反映Web或者App界面或者流程的两个或者多个版本,在同一个时间维度,分别受相似访客群组访问,收集各个群组的用户体验数据和相关的业务数据,最后分析评估出最好的版本正式采用。 (2)A/B测试的基本步骤 A/B测试主要可以分为分析现状,提出假设;定指标;制定方案;验证假设;结果分析;版本发布几个步骤,但是需要不断迭代 分析现状:分析业务数据现状,找到关键的问题所在 提出假设:零假设和备选假设 定指标:根据实际问题定指标,如是电商网站,目标应该是点击率,注册率,留存率,页面停留时间,用户数,人均成本等。 制定方案:设置主要目标,来实现对不同优化版本的评测 验证假设: 运用假设检验,对于留存率、渗透率等漏斗类指标,采用卡方检验 对于人均时长类等均值类指标,采用t 检验 对于假设检验的结果需要进一步进行置信分析 结果分析 (3)A/B测试案例 参考:https://zhuanlan.zhihu.com/p/65825397 (4)数据分析A/B测试实战(数据蛙项目)参考:https://zhuanlan.zhihu.com/p/149059865 (5)数据分析 A/B 测试 参考:https://blog.csdn.net/beginerToBetter/article/details/117875745
import { useDispatch, useSelector } from "react-redux"; import CDN_URL from "../utils/constants"; import { addItem, decrementQuantity, incrementQuantity, updateQuantity } from "../utils/cartSlice"; const ItemList = ({ items, resInfo }) => { const dispatch = useDispatch(); const cartItems = useSelector((store) => store.cart.items); const handleAddItem = (item) => { dispatch(addItem({ item, resInfo })); }; const handleIncrement = (item) => { const existingItemIndex = cartItems.findIndex( (cartItem) => cartItem.card.info.id === item.card.info.id ); if (existingItemIndex !== -1) { // If item already exists in the cart, dispatch the incrementQuantity action dispatch(incrementQuantity(existingItemIndex)); } }; const handleDecrement = (item) => { const existingItemIndex = cartItems.findIndex( (cartItem) => cartItem.card.info.id === item.card.info.id ); if (existingItemIndex !== -1) { // If item already exists in the cart, dispatch the decrementQuantity action dispatch(decrementQuantity(existingItemIndex)); } }; // console.log(items); return ( <div className="category-item"> {items.map((item) => ( <div className="item-container" key={item.card.info.id}> <div className="item-info"> {item.card.info.itemAttribute.vegClassifier === "VEG" ? ( <i id="veg-logo" className="fa-regular fa-circle-stop"></i> ) : ( <i id="nonveg-logo" className="fa-regular fa-square-caret-up"></i> )} <h3>{item.card.info.name}</h3> <h4> ₹ {item.card.info.price ? item.card.info.price / 100 : item.card.info.defaultPrice / 100} </h4> <p>{item.card.info.description}</p> </div> <div className="item-img"> <img src={CDN_URL + item.card.info.imageId} /> {cartItems.some( (cartItem) => cartItem.card.info.id === item.card.info.id ) ? ( // If item is in the cart, show inc-dec-counter <div className="inc-dec-count menu-counter"> <div className="minus-counter" onClick={() => handleDecrement(item)}>-</div> <span> { cartItems.find( (cartItem) => cartItem.card.info.id === item.card.info.id )?.quantity } </span> <div className="plus-counter" onClick={() => handleIncrement(item)}>+</div></div> ) : ( // If item is not in the cart, show ADD button <button onClick={() => handleAddItem(item)}>ADD</button> )} </div> </div> ))} </div> ); }; export default ItemList;
package com.hao.common.domain.dto; import com.hao.common.domain.other.Code; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author Hao * @program: nengyuyue * @description: 返回结果类 * @date 2023-11-09 12:42:10 */ @Data @AllArgsConstructor @NoArgsConstructor public class Result { private Integer code; private String msg; private Object data; /** * 成功回执(带Message) * @param message 信息 * @return Result */ public static Result success(String message){ return new Result(Code.SUCCESS, message, null); } /** * 错误回执(带Message) * @param message 信息 * @return Result */ public static Result error(String message){ return new Result(Code.ERROR, message, null); } /** * 失败回执(带Message) * @param message 信息 * @return Result */ public static Result filed(String message){ return new Result(Code.FAILED, message, null); } /** * 成功回执(带Message 和 Data) * @param message 信息 * @param data 数据 * @return Result */ public static Result success(String message, Object data){ return new Result(Code.SUCCESS, message, data); } /** * token失效回执 * @return Result */ public static Result tokenInvalid(){ return new Result(Code.TOKEN_INVALID, "Token无效!!", null); } /** * 无权限操作回执 * @return Result */ public static Result noPermission(){ return new Result(Code.NO_PERMISSION, "无权限的操作", null); } /** * 系统错误回执 * @return Result */ public static Result systemError(){ return new Result(Code.SYSTEM_ERROR, "系统错误", null); } /** * 系统错误回执 * @return Result */ public static Result systemError(Object o){ return new Result(Code.SYSTEM_ERROR, "系统错误", o); } }
import {createLogic} from "redux-logic"; import PracticeActions from "./actions"; import PracticeService from "./service"; import {getId, getPermissionsInfo} from "./getters"; import actions from "../../layout/actions"; import {DialogType, fetchingTypes, PermissionsInfoFields, PracticeFields} from "./enum"; import {RussianPracticeFields} from "./constants"; import {getErroredFields} from "./validation"; import {fields} from "../WorkProgram/enum"; const service = new PracticeService(); const getPractice = createLogic({ type: PracticeActions.getPractice.type, latest: true, process({getState, action}: any, dispatch, done) { const id = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.GET_PRACTICE})); service.getPractice(id) .then((res) => { const erroredFields = getErroredFields(res.data); dispatch(PracticeActions.setPractice(res.data)); dispatch(PracticeActions.setErroredFields(erroredFields)); const practiceBaseId = res.data[PracticeFields.PRACTICE_BASE].id ?? 1; dispatch(PracticeActions.getTemplateText(practiceBaseId)); if (res.data[PracticeFields.PERMISSIONS_INFO][PermissionsInfoFields.USE_CHAT_WITH_ID_EXPERTISE]) { dispatch(PracticeActions.getComments()); } }) .catch(() => { dispatch(PracticeActions.setError(true)); }) .finally(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.GET_PRACTICE})); return done(); }); } }); const startLoading = (dispatch: any, field: string) => { if (field === PracticeFields.BIBLIOGRAPHIC_REFERENCE) { dispatch(actions.fetchingTrue({destination: field})); } else { dispatch(actions.fetchingComponentTrue({destination: field})); } } const stopLoading = (dispatch: any, field: string) => { if (field === PracticeFields.BIBLIOGRAPHIC_REFERENCE) { dispatch(actions.fetchingFalse({destination: field})); } else { dispatch(actions.fetchingComponentFalse({destination: field})); } } const saveField = createLogic({ type: PracticeActions.saveField.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const {field, value} = action.payload; startLoading(dispatch, field); service.patchPractice({[field]: value}, practiceId) .then((res: any) => { dispatch(PracticeActions.setField({field, value: res.data[field]})); }) .catch(() => { console.error(`could not save field: ${field}`); dispatch(actions.fetchingFailed([`Поле "${(RussianPracticeFields as any)[field]}" не удалось сохранить. Пожалуйста, перезагрузите страницу или попробуйте позже.`])); }) .finally(() => { stopLoading(dispatch, field) return done(); }); } }); const getTemplateText = createLogic({ type: PracticeActions.getTemplateText.type, latest: true, process({getState, action}: any, dispatch, done) { const id = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.GET_TEMPLATE_TEXT})); service.getTemplateText(id) .then((res) => { dispatch(PracticeActions.setTemplateText(res.data)); }) .finally(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.GET_TEMPLATE_TEXT})); return done(); }); } }); const createExpertise = createLogic({ type: PracticeActions.createExpertise.type, latest: true, process({getState, action}: any, dispatch, done) { const {id} = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.CREATE_EXPERTISE})); service.createExpertise(id) .then(() => { dispatch(PracticeActions.getPractice(id)); }) .catch(() => { dispatch(actions.fetchingFailed([`Не удалось отправить на экспертизу`])); }) .finally(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.CREATE_EXPERTISE})); return done(); }) } }); const approvePractice = createLogic({ type: PracticeActions.approvePractice.type, latest: true, process({getState, action}: any, dispatch, done) { const userExpertiseId = action.payload; const state = getState(); const practiceId = getId(state); dispatch(actions.fetchingTrue({destination: fetchingTypes.CHANGE_EXPERTISE_STATE})); service.approvePractice(userExpertiseId) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); }) .catch(() => { dispatch(actions.fetchingFailed([`Не удалось одобрить рабочую программу`])); }) .finally(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.CHANGE_EXPERTISE_STATE})); return done(); }) } }); const sendPracticeToRework = createLogic({ type: PracticeActions.sendPracticeToRework.type, latest: true, process({getState, action}: any, dispatch, done) { const userExpertiseId = action.payload; const state = getState(); const practiceId = getId(state); dispatch(actions.fetchingTrue({destination: fetchingTypes.CHANGE_EXPERTISE_STATE})); service.sendPracticeToWork(userExpertiseId) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); }) .catch(() => { dispatch(actions.fetchingFailed([`Не удалось вернуть рабочую программу на доработку`])); }) .finally(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.CHANGE_EXPERTISE_STATE})); return done(); }) } }); const getComments = createLogic({ type: PracticeActions.getComments.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const expertiseId = getPermissionsInfo(state)[PermissionsInfoFields.USE_CHAT_WITH_ID_EXPERTISE]; if (!expertiseId) return; service.getComments(expertiseId, 'MA') .then((res) => { dispatch(PracticeActions.setComments(res.data.results)); }) .catch(() => { }) .finally(() => { return done(); }); } }); const sendComment = createLogic({ type: PracticeActions.sendComment.type, latest: true, process({getState, action}: any, dispatch, done) { const {userExpertiseId, step, comment} = action.payload; service.sendComment(userExpertiseId, step, comment) .then(() => { dispatch(PracticeActions.getComments()); }) .catch(() => { }) .finally(() => { return done(); }); } }); const sendToIsu = createLogic({ type: PracticeActions.sendToIsu.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); dispatch(actions.fetchingTrue({destination: fetchingTypes.SEND_TO_ISU})); service.sendToIsu(practiceId) .then((res) => { dispatch(PracticeActions.getPractice(practiceId)); dispatch(actions.fetchingSuccess()); }) .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.SEND_TO_ISU})); return done(); }); } }); const addPrerequisite = createLogic({ type: PracticeActions.addPrerequisite.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const prerequisite = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.ADD_PREREQUISITES})); service.addPrerequisites(prerequisite, practiceId) .then((res) => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); dispatch(PracticeActions.closeDialog(fields.ADD_NEW_PREREQUISITES)); }) .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.ADD_PREREQUISITES})); return done(); }); } }); const changePrerequisite = createLogic({ type: PracticeActions.changePrerequisite.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const prerequisite = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.CHANGE_PREREQUISITES})); service.changePrerequisites(prerequisite, practiceId) .then((res) => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); dispatch(PracticeActions.closeDialog(fields.ADD_NEW_PREREQUISITES)); }) .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.CHANGE_PREREQUISITES})); return done(); }); } }); const deletePrerequisite = createLogic({ type: PracticeActions.deletePrerequisite.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const id = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.DELETE_PREREQUISITES})); service.deletePrerequisite(id) .then((res) => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); }) .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.DELETE_PREREQUISITES})); return done(); }); } }); const addResult = createLogic({ type: PracticeActions.addResult.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const result = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.ADD_RESULT})); service.addResult(result, practiceId) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); dispatch(PracticeActions.closeDialog({dialogType: DialogType.RESULTS})); }) // @ts-ignore .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.ADD_RESULT})); return done(); }); } }); const changeResult = createLogic({ type: PracticeActions.changeResult.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const result = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.CHANGE_RESULT})); service.changeResult(result) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); dispatch(PracticeActions.closeDialog({dialogType: DialogType.RESULTS})); }) // @ts-ignore .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.CHANGE_RESULT})); return done(); }); } }); const deleteResult = createLogic({ type: PracticeActions.deleteResult.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); const id = action.payload; dispatch(actions.fetchingTrue({destination: fetchingTypes.DELETE_RESULT})); service.deleteResult(id) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); // @ts-ignore dispatch(actions.fetchingSuccess()); }) // @ts-ignore .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.DELETE_RESULT})); return done(); }); } }); const getCompetenceDirectionsDependedOnPractice = createLogic({ type: PracticeActions.getCompetencesDependedOnPractice.type, latest: true, process({getState, action}: any, dispatch, done) { dispatch(actions.fetchingTrue({destination: fetchingTypes.GET_COMPETENCE_DIRECTIONS_DEPENDED_ON_PRACTICE})); service.getCompetenceDirectionsDependedOnPractice(action.payload) .then((res) => { dispatch(PracticeActions.setCompetencesDependedOnPractice(res.data)); dispatch(actions.fetchingSuccess()); }) .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.GET_COMPETENCE_DIRECTIONS_DEPENDED_ON_PRACTICE})); return done(); }); } }); const saveZUN = createLogic({ type: PracticeActions.saveZUN.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); dispatch(actions.fetchingTrue({destination: fetchingTypes.SAVE_ZUN})); service.saveZUN(action.payload) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); dispatch(actions.fetchingSuccess()); }) //@ts-ignore .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.SAVE_ZUN})); return done(); }); } }); const deleteZUN = createLogic({ type: PracticeActions.deleteZUN.type, latest: true, process({getState, action}: any, dispatch, done) { const state = getState(); const practiceId = getId(state); dispatch(actions.fetchingTrue({destination: fetchingTypes.DELETE_ZUN})); service.deleteZUN(action.payload) .then(() => { dispatch(PracticeActions.getPractice(practiceId)); dispatch(actions.fetchingSuccess()); }) //@ts-ignore .catch((err) => { dispatch(actions.fetchingFailed(err)); }) .then(() => { dispatch(actions.fetchingFalse({destination: fetchingTypes.DELETE_ZUN})); return done(); }); } }); export default [ getPractice, saveField, getTemplateText, createExpertise, approvePractice, sendPracticeToRework, getComments, sendComment, addPrerequisite, changePrerequisite, deletePrerequisite, addResult, deleteResult, changeResult, getCompetenceDirectionsDependedOnPractice, deleteZUN, saveZUN, sendToIsu ];
import React, { HTMLAttributes } from "react"; import { twMerge } from "tailwind-merge"; type Variants = { base: string; default: string; primary: string; danger: string; warning: string; success: string; }; const variants: Variants = { base: "inline-flex items-center rounded-md bg-gray-50 px-2 py-1 text-xs font-semibold text-gray-600 ring-1 ring-inset ring-gray-500/10", default: "bg-gray-50 text-gray-600", primary: "bg-blue-50 text-blue-600", danger: "bg-red-50 text-red-600", warning: "bg-yellow-50 text-yellow-600", success: "bg-green-100 text-green-700", }; export type BadgeProps = React.HTMLAttributes<HTMLSpanElement> & { variant?: keyof Variants; }; const Badge: React.FC<BadgeProps> = ({ children, variant }) => { return ( <span className={twMerge(variants.base, variant && variants[variant])}> {children} </span> ); }; export default Badge;
package semplest.other; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.Interval; /** * Takes a datetime in and drops all minutes, seconds, and milliseconds to make the * datetime midinite. Because we only care about the date not the time. * * @author zacharyshaw */ public class DateTimeFloored { private final DateTime flooredDate; public DateTimeFloored() { this(new DateTime()); } public DateTimeFloored(DateTime dateTimeToBeFloored) { this.flooredDate = floor(dateTimeToBeFloored); } private DateTime floor(DateTime dateTime) { return dateTime.withMillisOfDay(0); } public DateTime getDate() { return flooredDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((flooredDate == null) ? 0 : flooredDate.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DateTimeFloored other = (DateTimeFloored) obj; if (flooredDate == null) { if (other.flooredDate != null) return false; } else if (!flooredDate.equals(other.flooredDate)) return false; return true; } @Override public String toString() { return flooredDate.toString(); } public static DateTimeFloored yesterday() { return new DateTimeFloored(new DateTime().minusDays(1)); } public static DateTimeFloored today() { return new DateTimeFloored(); } public static DateTimeFloored with(int year, int month, int day) { return new DateTimeFloored(new DateTime(year, month, day, 0, 0, 0, 0)); } public boolean isFirstOfTheMonth() { return flooredDate.getDayOfMonth() == 1; } public boolean isSunday() { return flooredDate.getDayOfWeek() == DateTimeConstants.SUNDAY; } public boolean isSaturday() { return flooredDate.getDayOfWeek() == DateTimeConstants.SATURDAY; } public DateTimeFloored plusDays(int days) { return new DateTimeFloored(flooredDate.plusDays(days)); } public Interval toInterval() { return new Interval(getDate(), new DateTimeCeiling(getDate()).getDate()); } }
class BasicCalculator: def sum(self, numlist: list): _sum = 0 for num in numlist: _sum += num return _sum # need to add `self` parameter first in instance method class ComplexCalculator(BasicCalculator): def power(self, base, exponent): return base ** exponent def abs(self, number): if number>= 0: return number return -number basic = BasicCalculator() complex = ComplexCalculator() print(basic.sum([1, 2, 3])) print(complex.sum([1, 2, 3])) print(complex.power(5,2)) print(complex.abs(-5))
import React, { Suspense, lazy } from "react"; // React Router Dom import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; // Context import { DashboardProvider } from "../pages/dashboard/context/DashboardContext"; // Pages const AsyncPageNotFound = lazy(() => import("../common/router/PageNotFound")); const AsyncDashboardLayout = lazy(() => import("../common/layout/DashboardLayout")); const AsyncLogin = lazy(() => import("../pages/auth/login/index")); const AsyncRegister = lazy(() => import("../pages/auth/register/index")); const AsyncForgotPassword = lazy(() => import("../pages/auth/forgotPassword/index")); const AsyncResetPassword = lazy(() => import("../pages/auth/resetPassword/index")); const AsyncDashboard = lazy(() => import("../pages/dashboard/index")); const AsyncHome = lazy(() => import("../pages/home/index")); const AsyncPricing = lazy(() => import("../pages/pricing/index")); // Components import Loader from "../common/components/Loader"; const PageRoutes = () => { return ( <Router> <Routes> <Route element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncDashboardLayout /> </Suspense> } > <Route path="/dashboard" element={ <Suspense fallback={<Loader fullscreen={true} />}> <DashboardProvider> <AsyncDashboard /> </DashboardProvider> </Suspense> } /> <Route path="*" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncPageNotFound /> </Suspense> } /> </Route> <Route path="/" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncHome /> </Suspense> } /> <Route path="/pricing" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncPricing /> </Suspense> } /> <Route path="/login" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncLogin /> </Suspense> } /> <Route path="/register" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncRegister /> </Suspense> } /> <Route path="/forgot-password" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncForgotPassword /> </Suspense> } /> <Route path="/reset-password" element={ <Suspense fallback={<Loader fullscreen={true} />}> <AsyncResetPassword /> </Suspense> } /> </Routes> </Router> ) } export default PageRoutes
export interface WikiApiArticle { parse?: Parse; } export interface Parse { title?: Title; pageid?: number; revid?: number; // eslint-disable-next-line @typescript-eslint/no-explicit-any redirects?: any[]; text?: Text; langlinks?: Langlink[]; categories?: Category[]; links?: Link[]; templates?: Link[]; images?: string[]; externallinks?: string[]; sections?: Section[]; showtoc?: string; parsewarnings?: string[]; displaytitle?: string; iwlinks?: Iwlink[]; properties?: Property[]; } export interface Category { sortkey?: Title; hidden?: string; "*"?: string; } export type Title = string; export interface Iwlink { prefix?: string; url?: string; "*"?: string; } export interface Langlink { lang?: string; url?: string; langname?: string; autonym?: string; "*"?: string; } export interface Link { ns?: number; exists?: string; "*"?: string; } export interface Property { name?: string; "*"?: string; } export interface Section { toclevel?: number; level?: string; line?: string; number?: string; index?: string; fromtitle?: Fromtitle; byteoffset?: number; anchor?: string; linkAnchor?: string; } export type Fromtitle = string; export interface Text { "*"?: string; }
import * as sinon from 'sinon'; import * as chai from 'chai'; // @ts-ignore import chaiHttp = require('chai-http'); import { app } from '../app'; import Match from '../database/models/Match'; import { matchesMock, updatableMatchMock } from './mocks/match'; import { teamsMock } from './mocks/team'; import Messages from '../schemas/Messages'; import { StatusCodes } from 'http-status-codes'; import Team from '../database/models/Team'; chai.use(chaiHttp); const { expect } = chai; describe('Endpoint POST /matches', () => { const chaiHttpResponse = async (id: number) => ( chai.request(app).patch(`/matches/${id}/finish`) ); describe('On success', async () => { beforeEach(async () => { sinon.stub(Match, 'findByPk').resolves(updatableMatchMock); sinon.stub(Match.prototype, 'update').resolves({ ...matchesMock[2], inProgress: false } as Match); }); afterEach(() => { (Match.findByPk as sinon.SinonStub).restore(); (Match.prototype.update as sinon.SinonStub).restore(); }); it('should return a message with "Finished"', async () => { const response = await chaiHttpResponse(matchesMock[2].id); expect(response.status).to.be.equal(StatusCodes.OK); expect(response.body).to.have.property('message'); expect(response.body.message).to.be.equal(Messages.Finished); }); }); describe('On fail', () => { beforeEach(async () => { sinon.stub(Match.prototype, 'update').resolves(updatableMatchMock); }); afterEach(() => { (Match.findByPk as sinon.SinonStub).restore(); (Match.prototype.update as sinon.SinonStub).restore(); }); it('should return an error message if provided id does not exist', async () => { sinon.stub(Match, 'findByPk').resolves(null); const response = await chaiHttpResponse(123123); expect(response.status).to.be.equal(StatusCodes.NOT_FOUND); expect(response.body).to.have.property('message'); expect(response.body.message).to.be.equal(Messages.MatchNotFound); }); it('should return an error message if match is already ended', async () => { sinon.stub(Match, 'findByPk').resolves(matchesMock[0] as Match); const response = await chaiHttpResponse(123123); expect(response.status).to.be.equal(StatusCodes.CONFLICT); expect(response.body).to.have.property('message'); expect(response.body.message).to.be.equal(Messages.MatchAlreadyEnded); }); }); });
import { ChangeEvent } from 'react'; import clsx from 'clsx'; import { CheckboxTextItem } from '@/components'; type Props = { select: string | null; list: { name: string }[]; handleChange: (event: ChangeEvent<HTMLInputElement>) => void; }; export function TextButtons({ list, select, handleChange }: Props) { return ( <div className={clsx('flex w-full flex-wrap gap-4 pl-2')}> {list.map((item) => ( <CheckboxTextItem key={item.name} label={{ key: item.name, name: item.name }} checked={select === item.name} onChange={handleChange} /> ))} </div> ); } type PlusMinusProps = { n: number; handleSizeChange: (n: number) => void; }; export function PlusMinus({ n, handleSizeChange }: PlusMinusProps) { const displayNum = n > 3 ? 'x2' : n > 0 ? `+${n}` : n; return ( <button type='button' className='h-8 w-8 rounded-full bg-amber-100 shadow-list-items' onClick={() => handleSizeChange(n)} > {displayNum} </button> ); } type SelectCountProps = { name: string; n: number; min: number; selected: boolean; handleCountChange: (name: string, count: number) => void; }; export function SelectCount({ name, n, min, selected, handleCountChange }: SelectCountProps) { return ( <button type='button' className={clsx( 'h-8 w-8 rounded-full', 'shadow-list-items', selected ? 'bg-amber-300' : 'bg-amber-100', )} onClick={() => handleCountChange(name, n)} > {n > 0 ? `${n}` : `<${min}`} </button> ); }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Linq; using System.Runtime.CompilerServices; using static TucSpaceShooter.Powerup; namespace TucSpaceShooter { public enum GameStates { Menu, Play, Highscore, Quit } public class Game1 : Game { private Random random; private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; // Play private static GameStates currentState; private Player player; private Texture2D playerShip; private Texture2D playerShipAcc; private Texture2D stageOneBgr; private Vector2 playerPosition; private Texture2D healthBar; private Texture2D healthPoint; private Texture2D healthEmpty; private int bgrCounter; private Song gameMusic; private bool gameMusicIsPlaying; //enemy private EnemyTypOne enemiesOne; private EnemyTypeTwo enemiesTwo; private EnemyTypeThree enemiesThree; private EnmeyBoss bossEnemy; private Texture2D enemyShipOne; private Texture2D enemyShipTwo; private Texture2D enemyShipThree; private Texture2D BossShip; private Vector2 enemyPosition; private Vector2 enemyPositiontwo; private Vector2 enemyPositionthree; private Vector2 enemyPositionBoss; //Bullet private Texture2D bulletTexture; private List<Bullet> bullets = new List<Bullet>(); private TimeSpan lastBulletTime; private TimeSpan bulletCooldown; private bool spaceWasPressed = false; private SoundEffect shoot; // Powerups private Powerup powerup; private Texture2D jetpack; private Texture2D shield; private Texture2D repair; private Texture2D doublePoints; private Texture2D triplePoints; private Texture2D playerShield; private SoundEffect pickUp; private List<Powerup> powerups; private int powerupWidth; private int powerupHeight; //Menu private MenuScreen menu; private Texture2D startButtonTexture; private Rectangle startButtonBounds; private Texture2D highscoreButtonTexture; private Rectangle highscoreButtonBounds; private Texture2D quitButtonTexture; private Rectangle quitButtonBounds; Song menuMusic; private bool menuMusicIsPlaying; public static GameStates CurrentState { get => currentState; set => currentState = value; } public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; powerups = new List<Powerup>(); random = new Random(); } protected override void Initialize() { // TODO: Add your initialization logic here currentState = GameStates.Menu;//Ska göra så att man startar i menyn, byt ut Menu för att starta i annan state base.Initialize(); } protected override void LoadContent() { // TODO: use this.Content to load your game content here _graphics.PreferredBackBufferHeight = 720; _graphics.PreferredBackBufferWidth = 540; _graphics.ApplyChanges(); _spriteBatch = new SpriteBatch(GraphicsDevice); playerShip = Content.Load<Texture2D>("TUCShip"); playerShipAcc = Content.Load<Texture2D>("TUCShipFire"); stageOneBgr = Content.Load<Texture2D>("Background_2"); player = new Player(playerPosition, _graphics, 5); playerPosition = player.Position; powerup = new Powerup(playerPosition); jetpack = Content.Load<Texture2D>("JetpackShip"); shield = Content.Load<Texture2D>("ShieldShip"); repair = Content.Load<Texture2D>("RepairShip"); doublePoints = Content.Load<Texture2D>("2xPoints"); triplePoints = Content.Load<Texture2D>("3xPoints"); playerShield = Content.Load<Texture2D>("PlayerShield"); pickUp = Content.Load<SoundEffect>("power_up_grab-88510"); powerupWidth = 15; powerupHeight = 15; healthBar = Content.Load<Texture2D>("LeftHealthContainer"); healthPoint = Content.Load<Texture2D>("FullHeartRed"); healthEmpty = Content.Load<Texture2D>("EmptyHeartNew"); bulletTexture = Content.Load<Texture2D>("PlayerBullets"); shoot = Content.Load<SoundEffect>("laser-gun-shot-sound-future-sci-fi-lazer-wobble-chakongaudio-174883"); SoundEffect.MasterVolume = 0.5f; Bullet.LoadContent(bulletTexture); enemiesOne = new EnemyTypOne(enemyPosition, _graphics); enemiesTwo = new EnemyTypeTwo(enemyPositiontwo, _graphics); enemiesThree = new EnemyTypeThree(enemyPositionthree, _graphics); bossEnemy= new EnmeyBoss(enemyPositionBoss, _graphics); enemyPosition = enemiesOne.Position; enemyPositiontwo = enemiesTwo.Position; enemyPositionthree = enemiesThree.Position; enemyPositionBoss = bossEnemy.Position; enemyShipOne = Content.Load<Texture2D>("Enemy1"); enemyShipTwo = Content.Load<Texture2D>("Enemy2"); enemyShipThree = Content.Load<Texture2D>("Enemy3"); BossShip = Content.Load<Texture2D>("BossMonster"); //enemyPositi //Menu startButtonTexture = Content.Load<Texture2D>("StartButton"); highscoreButtonTexture = Content.Load<Texture2D>("HiscoreButton"); quitButtonTexture = Content.Load<Texture2D>("QuitButton"); startButtonBounds = new Rectangle((_graphics.PreferredBackBufferWidth-startButtonTexture.Width)/2,270, startButtonTexture.Width, startButtonTexture.Height); highscoreButtonBounds = new Rectangle((_graphics.PreferredBackBufferWidth-highscoreButtonTexture.Width)/2,300, highscoreButtonTexture.Width, highscoreButtonTexture.Height); quitButtonBounds = new Rectangle((_graphics.PreferredBackBufferWidth-quitButtonTexture.Width)/2,330,quitButtonTexture.Width, quitButtonTexture.Height); menu = new MenuScreen(startButtonTexture, startButtonBounds, highscoreButtonTexture, highscoreButtonBounds, quitButtonTexture, quitButtonBounds); menuMusic = Content.Load<Song>("electric-dreams-167873"); menuMusicIsPlaying = false; gameMusic = Content.Load<Song>("kim-lightyear-angel-eyes-vision-ii-189557"); gameMusicIsPlaying = false; MediaPlayer.Volume = 0.5f; } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here switch (currentState) { case GameStates.Menu: //Kod för meny if (!menuMusicIsPlaying) { MediaPlayer.Play(menuMusic); menuMusicIsPlaying = true; } menu.Update(gameTime); break; case GameStates.Play: //kod för Play if (!gameMusicIsPlaying) { MediaPlayer.Play(gameMusic); gameMusicIsPlaying = true; } player.PlayerMovement(player, _graphics); player.HandlePowerupCollision(powerups, pickUp); powerup.SpawnPowerup(random, _graphics, powerupWidth, jetpack, shield, repair, doublePoints, triplePoints, powerups); powerup.UpdatePowerups(gameTime, powerups, _graphics); enemiesOne.MoveToRandomPosition(_graphics); enemiesTwo.MoveToRandomPosition(_graphics); enemiesThree.MoveToRandomPosition(_graphics); bossEnemy.MoveToRandomPosition(_graphics); Bullet.UpdateAll(gameTime, player, shoot); break; case GameStates.Highscore: //kod för highscore break; } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { // TODO: Add your drawing code here switch (currentState) { case GameStates.Menu: //kod för meny _spriteBatch.Begin(); menu.Draw(_spriteBatch); _spriteBatch.End(); break; case GameStates.Play: //kod för Play _spriteBatch.Begin(); Background.DrawBackground(bgrCounter, _spriteBatch, stageOneBgr); player.DrawPlayer(_spriteBatch, playerShip, playerShipAcc, player, bgrCounter, playerShield); DrawPowerups(_spriteBatch, powerups); player.DrawPlayerHealth(player, healthBar, healthPoint, healthEmpty, _spriteBatch); //enemy _spriteBatch.Draw(enemyShipOne, enemiesOne.Position, Color.White); _spriteBatch.Draw(enemyShipTwo, enemiesTwo.Position, Color.White); _spriteBatch.Draw(enemyShipThree, enemiesThree.Position, Color.White); _spriteBatch.Draw(BossShip, bossEnemy.Position, Color.White); Bullet.DrawAll(_spriteBatch); _spriteBatch.End(); bgrCounter++; break; case GameStates.Highscore: //kod för highscore _spriteBatch.Begin(); GraphicsDevice.Clear(Color.Orange); _spriteBatch.End(); break; case GameStates.Quit: Exit(); break; } if (bgrCounter == 2160) { bgrCounter = 0; } base.Draw(gameTime); } } }
package gr.cti.eslate.scripting.logo; import java.awt.*; import java.util.*; import virtuoso.logo.*; import gr.cti.eslate.scripting.*; import gr.cti.eslate.set.*; import gr.cti.eslate.base.*; /** * This class describes the Logo primitives implemented by the set * component. * * @author Kriton Kyrimis * @version 2.0.4, 23-Jan-2008 * @see gr.cti.eslate.set.Set */ public class SetPrimitives extends PrimitiveGroup { /** * Localized resources. */ private static ResourceBundle resources = null; /** * Required for scripting. */ MyMachine myMachine; /** * Exception thrown in <code>invokeAndWait</code>. */ private Exception pendingException = null; /** * Register primitives. */ protected void setup(Machine machine, Console console) throws SetupException { try { if (resources == null) { resources = ResourceBundle.getBundle( "gr.cti.eslate.scripting.logo.SetResource", ESlateMicroworld.getCurrentLocale() ); } myRegisterPrimitive("SELECTSUBSET", "pSELECTSUBSET", 1); myRegisterPrimitive("CLEARSELECTEDSUBSET", "pCLEARSELECTEDSUBSET", 0); myRegisterPrimitive("QUERYINSET", "pQUERYINSET", 0); myRegisterPrimitive("DELETEELLIPSE", "pDELETEELLIPSE", 1); myRegisterPrimitive("SETTABLEINSET", "pSETTABLEINSET", 1); myRegisterPrimitive("TABLEINSET", "pTABLEINSET", 0); myRegisterPrimitive("TABLESINSET", "pTABLESINSET", 0); myRegisterPrimitive("SETPROJECTIONFIELD", "pSETPROJECTIONFIELD", 1); myRegisterPrimitive("PROJECTIONFIELD", "pPROJECTIONFIELD", 0); myRegisterPrimitive("PROJECTIONFIELDS", "pPROJECTIONFIELDS", 0); myRegisterPrimitive("PROJECTINGFIELDS", "pPROJECTINGFIELDS", 0); myRegisterPrimitive("SETCALCULATIONTYPE", "pSETCALCULATIONTYPE", 1); myRegisterPrimitive("CALCULATIONTYPE", "pCALCULATIONTYPE", 0); myRegisterPrimitive("CALCULATIONTYPES", "pCALCULATIONTYPES", 0); myRegisterPrimitive("SETCALCULATIONFIELD", "pSETCALCULATIONFIELD", 1); myRegisterPrimitive("CALCULATIONFIELD", "pCALCULATIONFIELD", 0); myRegisterPrimitive("CALCULATIONFIELDS", "pCALCULATIONFIELDS", 0); myRegisterPrimitive("PROJECTFIELD", "pPROJECTFIELD", 1); myRegisterPrimitive("CALCULATEINSET", "pCALCULATEINSET", 1); myRegisterPrimitive("CALCULATINGINSET", "pCALCULATINGINSET", 0); myRegisterPrimitive("NEWELLIPSE", "pNEWELLIPSE", 0); myRegisterPrimitive("ACTIVATEELLIPSE", "pACTIVATEELLIPSE", 1); myRegisterPrimitive("DEACTIVATEELLIPSE", "pDEACTIVATEELLIPSE", 0); myMachine = (MyMachine)machine; } catch (Exception e) { e.printStackTrace(); } } /** * Selects a subset. */ public final LogoObject pSELECTSUBSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); if (!(obj[0] instanceof LogoList)) { throw new LanguageException(resources.getString("badSelection")); } LogoList list = ((LogoList)obj[0]); int length = list.length(); if ((length < 2) || (length > 3)) { throw new LanguageException(resources.getString("badSelection")); } if (length == 2) { int x, y; try { x = list.pickInPlace(0).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badX")); } try { y = list.pickInPlace(1).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badY")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); selectSubset(set, x, y); } }else{ boolean a, b, c; try { a = list.pickInPlace(0).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } try { b = list.pickInPlace(1).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } try { c = list.pickInPlace(2).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); selectSubset(set, a, b, c); } } return LogoVoid.obj; } private void selectSubset(AsSet set, int x, int y) throws LanguageException { if (EventQueue.isDispatchThread()) { set.selectSubset(x, y); }else{ final AsSet s = set; final int xx = x; final int yy = y; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.selectSubset(xx, yy); } }); } catch (Exception e) { throw new LanguageException(e); } } } private void selectSubset(AsSet set, boolean a, boolean b, boolean c) throws LanguageException { if (EventQueue.isDispatchThread()) { set.selectSubset(a, b, c); }else{ final AsSet s = set; final boolean aa = a; final boolean bb = b; final boolean cc = c; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.selectSubset(aa, bb, cc); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Clears the selected subset. */ public final LogoObject pCLEARSELECTEDSUBSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); clearSelectedSubset(set); } return LogoVoid.obj; } private void clearSelectedSubset(AsSet set) throws LanguageException { if (EventQueue.isDispatchThread()) { set.clearSelectedSubset(); }else{ final AsSet s = set; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.clearSelectedSubset(); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Returns the description of the selected subset. */ public final LogoObject pQUERYINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s = set.getSelText(); return new LogoWord(s); } /** * Deletes one or more ellipses. */ public final LogoObject pDELETEELLIPSE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); if (!(obj[0] instanceof LogoList)) { throw new LanguageException(resources.getString("badSelection")); } LogoList list = ((LogoList)obj[0]); int length = list.length(); if ((length < 2) || (length > 3)) { throw new LanguageException(resources.getString("badSelection")); } if (length == 2) { int x, y; try { x = list.pickInPlace(0).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badX")); } try { y = list.pickInPlace(1).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badY")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); deleteEllipse(set, x, y); } }else{ boolean a, b, c; try { a = list.pickInPlace(0).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } try { b = list.pickInPlace(1).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } try { c = list.pickInPlace(2).toBoolean(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badBoolean")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); deleteEllipse(set, a, b, c); } } return LogoVoid.obj; } private void deleteEllipse(AsSet set, int x, int y) throws LanguageException { if (EventQueue.isDispatchThread()) { set.deleteEllipse(x, y); }else{ final AsSet s = set; final int xx = x; final int yy = y; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.deleteEllipse(xx, yy); } }); } catch (Exception e) { throw new LanguageException(e); } } } private void deleteEllipse(AsSet set, boolean a, boolean b, boolean c) throws LanguageException { if (EventQueue.isDispatchThread()) { set.deleteEllipse(a, b, c); }else{ final AsSet s = set; final boolean aa = a; final boolean bb = b; final boolean cc = c; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.deleteEllipse(aa, bb, cc); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Select the field projected onto the component. */ public final LogoObject pSETPROJECTIONFIELD(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); String s = obj[0].toString(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { try { AsSet set = (AsSet)v.elementAt(i); setProjectionField(set, s); } catch (SetException e) { throw new LanguageException(e.getMessage()); } } return LogoVoid.obj; } private void setProjectionField(AsSet set, String st) throws LanguageException, SetException { if (EventQueue.isDispatchThread()) { set.setProjectionField(st); }else{ final AsSet s = set; final String ss = st; try { EventQueue.invokeAndWait(new Runnable() { public void run() { pendingException = null; try { s.setProjectionField(ss); } catch (SetException e) { pendingException = e; } } }); if (pendingException == null) { throw new LanguageException(pendingException); } } catch (Exception e) { throw new LanguageException(e); } } } /** * Return the name of the field projected onto the component. */ public final LogoObject pPROJECTIONFIELD(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s = set.getProjectionField(); if (s == null) { throw new LanguageException(resources.getString("noProjField")); } return new LogoWord(s); } /** * Returns the names of the tables that can be displayed. */ public final LogoObject pPROJECTIONFIELDS(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s[] = set.getProjectionFields(); LogoObject[] lo = new LogoObject[s.length]; for (int i=0; i<s.length; i++) { lo[i] = new LogoWord(s[i]); } return new LogoList(lo); } /** * Select the calculation operation to perform. */ public final LogoObject pSETCALCULATIONTYPE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); String s = obj[0].toString(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { try { AsSet set = (AsSet)v.elementAt(i); setCalcOp(set, s); } catch (SetException e) { throw new LanguageException(e.getMessage()); } } return LogoVoid.obj; } private void setCalcOp(AsSet set, String st) throws LanguageException, SetException { if (EventQueue.isDispatchThread()) { set.setCalcOp(st); }else{ final AsSet s = set; final String ss = st; try { EventQueue.invokeAndWait(new Runnable() { public void run() { pendingException = null; try { s.setCalcOp(ss); } catch (SetException e) { pendingException = e; } } }); if (pendingException == null) { throw new LanguageException(pendingException); } } catch (Exception e) { throw new LanguageException(e); } } } /** * Return the name of the calculation operation that is being performed. */ public final LogoObject pCALCULATIONTYPE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s = set.getCalcOp(); if (s == null) { throw new LanguageException(resources.getString("noCalcOp")); } return new LogoWord(s); } /** * Return the names of the calculation operations that can be performed. */ public final LogoObject pCALCULATIONTYPES(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s[] = set.getCalcOps(); LogoObject[] lo = new LogoObject[s.length]; for (int i=0; i<s.length; i++) { lo[i] = new LogoWord(s[i]); } return new LogoList(lo); } /** * Select the field on which calculations will be performed. */ public final LogoObject pSETCALCULATIONFIELD(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); String s = obj[0].toString(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { try { AsSet set = (AsSet)v.elementAt(i); setCalcKey(set, s); } catch (SetException e) { throw new LanguageException(e.getMessage()); } } return LogoVoid.obj; } private void setCalcKey(AsSet set, String st) throws LanguageException, SetException { if (EventQueue.isDispatchThread()) { set.setCalcKey(st); }else{ final AsSet s = set; final String ss = st; try { EventQueue.invokeAndWait(new Runnable() { public void run() { pendingException = null; try { s.setCalcKey(ss); } catch (SetException e) { pendingException = e; } } }); if (pendingException == null) { throw new LanguageException(pendingException); } } catch (Exception e) { throw new LanguageException(e); } } } /** * Return the name of the field on which calculations are being performed. */ public final LogoObject pCALCULATIONFIELD(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s = set.getCalcKey(); if (s == null) { throw new LanguageException(resources.getString("noCalcField")); } return new LogoWord(s); } /** * Return the names of the fields on which calculations can be performed. */ public final LogoObject pCALCULATIONFIELDS(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s[] = set.getCalcKeys(); LogoObject[] lo = new LogoObject[s.length]; for (int i=0; i<s.length; i++) { lo[i] = new LogoWord(s[i]); } return new LogoList(lo); } /** * Select the table to display. */ public final LogoObject pSETTABLEINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); String s = obj[0].toString(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { try { AsSet set = (AsSet)v.elementAt(i); setSelectedTable(set, s); } catch (SetException e) { throw new LanguageException(e.getMessage()); } } return LogoVoid.obj; } private void setSelectedTable(AsSet set, String st) throws LanguageException, SetException { if (EventQueue.isDispatchThread()) { set.setSelectedTable(st); }else{ final AsSet s = set; final String ss = st; try { EventQueue.invokeAndWait(new Runnable() { public void run() { pendingException = null; try { s.setSelectedTable(ss); } catch (SetException e) { pendingException = e; } } }); if (pendingException == null) { throw new LanguageException(pendingException); } } catch (Exception e) { throw new LanguageException(e); } } } /** * Returns the name of the displayed table. */ public final LogoObject pTABLEINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s = set.getSelectedTable(); if (s == null) { throw new LanguageException(resources.getString("noTable")); } return new LogoWord(s); } /** * Returns the names of the tables that can be displayed. */ public final LogoObject pTABLESINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); String s[] = set.getTables(); LogoObject[] lo = new LogoObject[s.length]; for (int i=0; i<s.length; i++) { lo[i] = new LogoWord(s[i]); } return new LogoList(lo); } /** * Specify whether the selected projection field should be displayed. */ public final LogoObject pPROJECTFIELD(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); boolean b = obj[0].toBoolean(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); setProject(set, b); } return LogoVoid.obj; } private void setProject(AsSet set, boolean b) throws LanguageException { if (EventQueue.isDispatchThread()) { set.setProject(b); }else{ final AsSet s = set; final boolean bb = b; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.setProject(bb); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Returns whether the selected projection field is being displayed. */ public final LogoObject pPROJECTINGFIELDS(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); boolean b = set.isProjecting(); return new LogoWord(b); } /** * Specify whether individual elements or calculated data should be * displayed in the set panels. */ public final LogoObject pCALCULATEINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); boolean b = obj[0].toBoolean(); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); setCalculate(set, b); } return LogoVoid.obj; } private void setCalculate(AsSet set, boolean b) throws LanguageException { if (EventQueue.isDispatchThread()) { set.setCalculate(b); }else{ final AsSet s = set; final boolean bb = b; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.setCalculate(bb); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Returns whether calculations are displayed. */ public final LogoObject pCALCULATINGINSET(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); AsSet set = (AsSet)myMachine.componentPrimitives.getFirstComponentToTell( gr.cti.eslate.scripting.AsSet.class ); boolean b = set.isCalculating(); return new LogoWord(b); } /** * Creates and activates a new ellipse. */ public final LogoObject pNEWELLIPSE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); newEllipse(set); } return LogoVoid.obj; } private void newEllipse(AsSet set) throws LanguageException { if (EventQueue.isDispatchThread()) { set.newEllipse(); }else{ final AsSet s = set; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.newEllipse(); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Activates an ellipse. */ public final LogoObject pACTIVATEELLIPSE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 1); if ((obj[0] instanceof LogoList)) { LogoList list = ((LogoList)obj[0]); int length = list.length(); if ((length != 2)) { throw new LanguageException(resources.getString("badActivation")); } int x, y; try { x = list.pickInPlace(0).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badX")); } try { y = list.pickInPlace(1).toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badY")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); activateEllipse(set, x, y); } }else{ int n; try { n = obj[0].toInteger(); } catch (LanguageException le) { throw new LanguageException(resources.getString("badEllipse")); } if ((n < 0) || (n > 2)) { throw new LanguageException(resources.getString("badEllipse")); } Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); activateEllipse(set, n); } } return LogoVoid.obj; } private void activateEllipse(AsSet set, int x, int y) throws LanguageException { if (EventQueue.isDispatchThread()) { set.activateEllipse(x, y); }else{ final AsSet s = set; final int xx = x; final int yy = y; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.activateEllipse(xx, yy); } }); } catch (Exception e) { throw new LanguageException(e); } } } private void activateEllipse(AsSet set, int n) throws LanguageException { if (EventQueue.isDispatchThread()) { set.activateEllipse(n); }else{ final AsSet s = set; final int nn = n; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.activateEllipse(nn); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Deactivates the active ellipse. */ public final LogoObject pDEACTIVATEELLIPSE(InterpEnviron env, LogoObject obj[]) throws LanguageException { testNumParams(obj, 0); Vector<?> v = myMachine.componentPrimitives.getComponentsToTell( gr.cti.eslate.scripting.AsSet.class); for (int i=0; i<v.size(); i++) { AsSet set = (AsSet)v.elementAt(i); deactivateEllipse(set); } return LogoVoid.obj; } private void deactivateEllipse(AsSet set) throws LanguageException { if (EventQueue.isDispatchThread()) { set.deactivateEllipse(); }else{ final AsSet s = set; try { EventQueue.invokeAndWait(new Runnable() { public void run() { s.deactivateEllipse(); } }); } catch (Exception e) { throw new LanguageException(e); } } } /** * Register a LOGO primitive using both a default english name and * a localized name. * @param pName The name of the primitive. * @param method The name of the method implementing the primitive. * @param nArgs The number of arguments of the method implementing the * primitive. */ private void myRegisterPrimitive(String pName, String method, int nArgs) throws SetupException { // Register localized primitive name. registerPrimitive(resources.getString(pName), method, nArgs); // Register default english primitive name. if (!ESlateMicroworld.getCurrentLocale().getLanguage().equals("en")) { registerPrimitive(pName, method, nArgs); } } }
---> NÓS ESTAMOS RENDERIZANDO NOSSO TEMPLATE DE 'shop.pug', MAS ATÉ AGORA NÃO ESTAMOS RENDERIZANDO QUALQUER CONTEÚDO DINÂMICO COM ESSE TEMPLATE... --> ISSO, ENTRETANTO, É TODA A IDEIA POR TRÁS DESTE MÓDULO, FAZER O OUTPUT DE CONTEÚDO DINÂMICO USANDO TEMPLATING ENGINES... ---> NÓS JÁ TEMOS NOSSA 'adminData', lá em 'shop.js', _ com NOSSOS PRODUCTS, AQUELE ARRAY DE 'products', que são adicionados quando inputtamos algo e submittamos aquela form na página de 'admin/add-product'... ------> OK... PROFESSOR EXPLICA QUE VAMOS QUERER PEGAR ESSES PRODUTOS LÁ EM 'shop.js' POR MEIO DE UM CÓDIGO COMO 'const products = adminData.products;'.... ex: const adminData = require('./admin'); router.get( '/', ///////PATH FILTER. (req, res, next) => { const products = adminData.products; res.render('shop'); ////.render() --> É UM MÉTODO PROVIDENCIADO PELO EXPRESSJS, e que vai 'USE THE DEFAULT TEMPLATING ENGINE', a engine que definimos em 'app.set('view engine', 'pug')'... } ); ----------------- --> E AGORA, É CLARO, VAMOS QUERER PASSAR ESSA CONSTANTE 'products', esse array aí, PARA _ DENTRO __ DE NOSSO TEMPLATE 'shop.pug'... ------> VAMOS QUERER INJETAR ESSA CONST NESSE ARQUIVO 'TEMPLATE', para que possamos O OUTPUTTAR DE ALGUMA FORMA, NELE... -------> PARA FAZER ISSO, PODEMOS SIMPLESMENTE __ PASSAR UM SEGUNDO PARÂMETRO AO ARGUMETNO ' .render(xxx, yyy)... ----> NESSE SEGUNDO ARGUMENTO, PASSAMOS __ DATA__ QUE DEVE ___ SER ADICIONADA DENTRO DESSA VIEW ESPECÍFICA... (no caso, à view 'shop.pug'...) ----> AQUI, PORTANTO, SIMPLESMENTE PASSAMOS 'products': const products = adminData.products; res.render('shop'. products); --------------------- res.render('shop', {products: products}); ////.render() --> É UM MÉTODO PROVIDENCIADO PELO EXPRESSJS, e que vai 'USE THE DEFAULT TEMPLATING ENGINE', a engine que definimos em 'app.set('view engine', 'pug')'... ///VAI RENDERIZAR O ARQUIVO 'shop.pug' LÁ NO FOLDER 'views', tudo graças aos códigos 'app.set()' que definimos LÁ EM 'app.js'.. ////O SEGUNDO PARÂMETRO DE 'render' SERVE __ PARA INJETAR__ DATA ___ DENTRO DO ARQUIVO 'view' QUE VAMOS QUERER RENDERIZARA COM ESSE '.render()'... (nesse caso, o ARRAY DE 'PRODUCTS'...) ///essa data que queremos USAR NO NOSSO TEMPLATE___ DEVE SER, DENTRO DE UM OBJECT, MAPPEADA A UM KEYNAME... (nesse caso usamos 'products' mesmo..) --> OK... OU SEJA, vamos escrever realmente 'res.render('shop', {prods: products})' ------------------------------------- OK... ISSO TERÁ SIDO PASSADO __ AO TEMPLATE DE ' shop.pug'... ----> AGORA PODEMOS SIMPLESMENTE USAR O NOSSO TEMPALTE __ PARA ACESSAR esse 'prods' DENTRO DESSA DATA QUE foi passada por meio de 'res.render()'... --------------------------------------------------> BTW, NÓS PODERÍAMOS/PODEMOS ADICIONAR MAIS DE 1 FIELD NESSE OBJETO 'data': ---> PODEMOS ADICIONAR TAMBÉM um 'docTitle: 'Shop', POR exemplo, __ SÓ PARA VER QUE PODEMOS UTILIZAR ESSE VALOR HARDCODADO, TAMBÉM... tipo assim: 'res.render('shop', {prods: products, docTitle: 'Shop'})' ----> professor diz que DEVEMOS COMEÇAR TESTANDO SE CONSEGUIMOS USAR ESSE VALOR DE 'docTitle'.... -----> LÁ EM 'shop.pug', NAQUELA LINHA DE 'title My Shop', EM QUE TEMOS NOSSO '<title/>', em outras palavras, PROFESSOR DIZ QUE PODEMOS __USAR__ A 'CUSTOM TEMPLATING SYNTAX' QUE O PUG NOS OFERECE... -----------> OK, MAS QUAL É ESSA SINTAXE? ---> SE VOCÊ QUER APENAS OUTPUTTAR UM TEXT EM ALGUM LUGAR, UM TEXT __ DINÂMICO__, você deve recorrer a simples '#{}', HASH TAG COM CURLY BRACES.... ex: 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 #{} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main h1 My Products p List of all my products ----------------- E, DENTRO DESSAS CURLY BRACES, VOCÊ PODE COLOCAR __QUALQUER VALOR QUE ESTAMOS PASSANDO A ESSA VIEW por meio de 'res.render()'... EX: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main h1 My Products p List of all my products ------------------------------ --> NO NOSSO CASO, VAMOS USAR 'docTitle'.... SALVAMOS TUDO ISSO E RECARREGAMOS.... --------> VEREMOS A ALTERAÇÃO NA ABA DA NOSSA PÁGINA, QUE MUDARÁ DE 'My Shop' para 'SHOP', mostrando que NOSSA ALTERAÇÃO E USO DESSA DATA 'EMPRESTADA ' REALMENTE FUNCIONOU... OK... FICOU ASSIM: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main h1 My Products p List of all my products ----------------------------------- PROFESSOR EXPLICA QUE ESSE FLOW DE CÓDIGO É IMPORTANTE, DEVE SER COMPREENDIDO... OK... AGORA VAMOS QUERER USAR O ARRAY DE 'products'.... --> PARA CONSEGUIRMOS FAZER ISSO, PROFESSOR VAI ATÉ O MESMO NÍVEL DO HEADER (mesma indentation, SIBLING ELEMENTS), ------> NO MESMO NÍVEL DO HEADER ELE escreve UM ELEMENTO 'main', E AÍ NESSE ELEMENTO MAIN ELE VAI ESCREVER UMA ul com lis _dINÂMICAS (bem parecido com o que vimos no REACT...) -> mas o que o professor vai fazer é um POUCO DIFERENTE DE UMA UL comum, ELE VAI USAR UM __ GRID__, UM GRID COM VÁRIOS '<article/>', QUE SERÃO NOSSOS ITEMS.... EX: <div class="grid"> <article class="card product-item"> <header class="card__header"> <h1 class="product__title">Great Book</h1> <div class="card__image"> <img src="xxxxx"></img> </div> <div class="card__content"> <h2 class="product__price">$19.99</h2> <p class="product__description">A very interesting book about so many events</p> <div> <div class="card__actions"> <button class="btn">Add to Cart</button> </article> </div> ------------------------ OK... VAMOS REPLICAR ESSA ESTRUTURA NO .pug, MAS ___ É CLARO QUE RESPEITANDO O FATO DE QUE __ VAMOS CONVERTER OS OBJECTS 'product' em 'products', QUE SERÃO CONVERTIDOS A ESSE CÓDIGO aí.. --> o professor vai converter esse HARDCODED CODE em um formato pug, mas é claro que depois alteraremos isso... FICOU TIPO ASSIM: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main .grid article.card.product-item header.card__header h1.product__title Great Book .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart --------------------------------- OBS: SIDENOTE ---> isto: ------------------------------------------ <article class="card product-item"> (MÚLTIPLAS CLASSES APLICADAS A UM ELEMENTO) ------------------------------------------------- FICA ASSIM (concatenamos as 2 classes aplicadas a ele): ---------------------------------- article.card.product-item ------------------------------ OBS: ESSAS 'AJUDAS' QUE RECEEBMOS DO VISUAL STUDIO CODE EXISTEM POR CAUSA DE 'Emmet'... -----> Emmet abbreviation and snippet expansions are enabled by default in html, haml, pug, slim, jsx, xml, xsl, css, scss, sass, less and stylus files, as well as any language that inherits from any of the above like handlebars and php. -------------------------------------- hmm agora isso faz sentido.... -----> ele funciona mt bem com PUG... -----> ok... ISSO TERÁ CRIADO UMA IMAGE E TUDO MAIS... -----> ACHO QUE CONSEGUI... FICOU ASSIM: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main .grid article.card.product-item header.card__header h1.product__title Great Book .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart -------------------------------------- O PRICE E VÁRIAS DAS COISAS AQUI ESTÃO ESTÁTICAS, POR ENQUANTO... --> MAS MAIS TARDE VAMOS AS RENDERIZAR DE FORMA __ DINÂMICA... -------------------- ----> OK, ISSO OUTPUTTARÁ UMA GRID DE 'PRODUCT CARDS', MAS NO MOMENTO, SÓ COM 1 ÚNICO ELEMENTO, com 'STATIC CONTENT' (hardcodado)... --> e a image também está VAZANDO DO NOSSO CARD, O QUE É PÉSSIMO... OK, CONSERTEI UM POUCO... ----- PROFESSOR DIZ QUE PARA DEIXAR ESSE OUTPUT MENOS ESTÁTICO, DEVEMOS 'ITERATE THROUGH ALL THE PRODUCTS'.... -------> E, VOCÊ DEVE SE LEMBRAR QUE NÓS JÁ TEMOS O ARRAY DE 'PRODUCTS', pq eles foram passados PARA DENTRO DESSA VIEW por meio do código de ' res.render('shop', {prods: products})' -----> PODEMOS ACESSAR ESSA LIST/ARRAY _ POR MEIO ___ DA KEY 'prods' .... ------> PARA CONSEGUIR FAZER ISSO, PRECISAMOS USAR UMA SINTAXE ESPECIAL PROVIDENCIADA PELO PUG.. USAMOS A KEYWORD 'each' TIPO ASSIM: main .grid each ////////ISTO AQUI... article.card.product-item header.card__header h1.product__title A Chair .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart ------------------------------ A KEYWORD 'each' VAI __CRIAR UM LOOP__.... ---> AÍ, COM ESSE 'each', vocÊ primeiramnte ESPECIFICA UM 'VALUE' EM QUE VOCÊ VAI QUERER 'STORE THE VALUE FOR THE CURRENT ITERATION' (tipo 'for (const key in keys)'...) -----> TIPO ASSIM: each product in prods OU SEJA, É O ''''ITEM'''' DENTRO DO ''''ARRAY/LIST'''' NA QUAL VOCÊ VAI QUERER LOOOPAR... -----> no caso, esse ARRAY É prods, por isso escrevemos: main .grid each product in prods article.card.product-item header.card__header h1.product__title A Chair .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart ----------------------------------------- ok... COMO JÁ ESTAMOS 'LOOPING THROUGH THE PRODS', ___ PRECISAMOS __ INDENTAR TODO O TRECHO DO 'ARTICLE' __PARA DENTRO DESSE LOOP, para que então todos nossos objetos article que existirão __SEJAM__ RETORNADOS POR ESSE LOOP AÍ... (tipo o react, com lists e .map())... EX: main .grid each product in prods article.card.product-item header.card__header h1.product__title A Chair .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart -------------------------------- OK... esse BLOCKZAO de 'article' será repetido PARA CADA 'product' DENTRO DESSE ARRAY DE 'prods'... -----> E AGORA, PORTANTO, PODEMOS USAR A VARIÁVEL 'product' QUE ESTAMOS CRIANDO 'ON THE FLY' AQUI PARA OUTPUTTAR A DATA PERTINENTE, A DATA DE CADA PRODUCT... ex: main .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price $19.99 p.product__description A very interesting book about so many events .card__actions button.btn Add to Cart --> DE NOVO, O PROFESSOR VAI OUTPUTTAR DINAMICAMENTE O title, por meio de '#{product.title}'... ---------------------------- ok, é exatamente o que eu fazia com o react... ---> JÁ AS IMAGES, O PRICE, E O RESTO DAS COISAS, provavelmente vao ficar 'product.image', 'product.desc', e coisas assim... também 'product.price'... ------------------ FICOU TIPO ASSIM: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price #{product.price} p.product__description #{product.desc} .card__actions button.btn Add to Cart --> E PROFESSOR EXPLICA QUE QUANDO ALTERAMOS ALGO NOS TEMPLATES, NÃO TEMOS QUE REINICIAR O SERVER INTEIRO, JUSTAMENTE PQ OS TEMPLATES NÃO SÃO PARTE DO SERVERSIDE CODE, ___ E SIM ___ SÃO 'BASICALLY TEMPLATES THAT ARE PICKED UP ON THE FLY ANYWAYS', O QUE SIGNIFICA QUE SE VOCÊ OS ALTERAR, O 'NEXT REQUEST THAT IS COMING' VAI AUTOMATICAMENTE PEGAR ESSA ÚLTIMA VERSÃO DO SEU TEMPLATE... -----> COM ISSO, TIVEMOS UMA INTRODUÇÃO BÁSICA AO PUG.... -----> É UMA SINTAXE ESTRANHA, BEM MÍNIMA... --> E VIMOS COMO PODEMOS OUTPUTTAR 'single values', como TEXTS DINÂMICOS (como '#{product.title'}), E TAMBÉM LOOPS, por meio de 'each xxx in array'... ---------------> OK.. MAS É CLARO QUE PODERÍAMOS TER UM CASE EM QUE __NÃO TEMOS NENHUM PRODUCT NA PÁGINA---> E POR ISSO É BOM TER UM CASE/CONDITIONAL CHECK PARA CASOS EM QUE ____ SUA LISTA DE PRODUCTS está _vAZIA/ encontra-se vazia... ------> RENDERIZAR UM CONTÉUDO DE H1 COM 'No products found on store', ou algo assim... --> E PROFESSOR EXPLICA QUE __PODEMOS, SIM, __ FAZER UMA COISA DESSAS COM O PUG.. -----> PARA FAZER ISSO, podemos simplesmente escrever um if statement no meio dele... --> escrevemos: main if products.length > 0 .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price #{product.price} p.product__description #{product.desc} .card__actions button.btn Add to Cart --> OU SEJA,, SE O LENGTH DO ARRAY PRODUCTS FOR 0, VAMOS QUERER __ OUTPUTTAR __ ESSE CÓDIGO AÍ.... CASO CONTRÁRIO, VAMOS QUERER ESCREVER/EXECUTAR UM 'ELSE' BLOCK (no mesmo nível de 'if', para funcionar), E AÍ OUTPUTTAR UM 'H1 no products'... ex: main if prods.length > 0 .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price #{product.price} p.product__description #{product.desc} .card__actions button.btn Add to Cart else h1 No Products ------------------------- FICOU TIPO ASSIM: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main if prods.length > 0 .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price #{product.price} p.product__description #{product.desc} .card__actions button.btn Add to Cart else h1 No Products ----------------------------- AGORA QUANDO INICIAMOS NOSSO SERVER/APLICATIVO, vamos ver a página inicial com 'No Products', PQ NENHUM PRODUCT TERÁ SIDO ADICIONADO... --> se adicionarmos 1 objeto, no entanto, VEREMOS ESSE OBJETO NA STARTING PAGE... CERTO... MAS HÁ UM ERRO DE SINTAXE DO PUG: Error: A:\projeto4 - NODEJS\MODULO6-TRABALHANDOCOMCONTEÚDODINAMICO,TEMPLATINGENGINES\novonovoprojeto5-templatingengines\views\shop.pug:22:1 20| .grid 21| each product in prods > 22| article.card.product-item --------^ 23| header.card__header 24| h1.product__title #{product.title} 25| .card__image ------------------------------- CONSERTEI: 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 #{docTitle} link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a.active(href="/") Shop li.main-header__item a(href="/admin/add-product") Add Product main if prods.length > 0 .grid each product in prods article.card.product-item header.card__header h1.product__title #{product.title} .card__image img(src="https://m.media-amazon.com/images/I/41tCIsGV8UL.jpg", alt="chair") .card__content h2.product__price #{product.price} p.product__description #{product.desc} .card__actions button.btn Add to Cart else h1 No Products ------------------------------------- ---> OK... AGORA TEMOS AS 3 PARTES MAIS IMPORTANTES DO TRABALHO COM O PUG: 1) OUTPUT DE SIMPLE TEXT 2) OUTPUT DE LIST (LOOPS com 'each' e 'in'...) 3) OUTPUT DE CONTEÚDO CONDICIONAL (if statements) --> ESTE É O PUG, E É ASSIM QUE USAMOS TEMPLATING ENGINES NO EXPRESSJS, EM GERAL... ------------------------------------ DEVEMOS REPLICAR ISSO LÁ NA PÁGINA DE 'add-product'.... EU JÁ FIZ ISSO: 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 Add Product link(rel="stylesheet", href="/css/main.css") link(rel="stylesheet", href="/css/forms.css") link(rel="stylesheet", href="/css/product.css") body header.main-header nav.main-header__nav ul.main-header__item-list li.main-header__item a(href="/") Shop li.main-header__item a.active(href="/") Add Product main form.product-form(action="/admin/add-product", method="POST") .form-control label(for="title") Title input(type="text", name="title") button.btn(type="submit") Add Product --------------------------------------------------------------- --> VOCÊ PODE, COMO PRÁTICA, INJETAR UM CÓDIGO DINAMICAMENTE COM #{}, como O 'PAGE TITLE'...
import { useState, useEffect, FormEvent, ChangeEvent, InvalidEvent } from 'react' import { Comment } from './Comment'; import { Avatar } from './Avatar'; import { format, formatDistanceToNow } from 'date-fns'; import enUS from 'date-fns/locale/en-US'; import styles from './Post.module.css'; interface Author { name: string; role: string; avatarUrl: string } interface Content { type: 'paragraph' | 'link'; content: string } interface PostProps { author: Author; publishedAt: Date; content: Content[] } export function Post( // props: any { author, publishedAt, content }: PostProps ) { const [comments, setComments] = useState([ 'Awesome post buddy, congrats!!', ]) const [newCommentText, setNewCommentText] = useState('') function handleCreateNewComment(event: FormEvent) { event!.preventDefault() setComments([...comments, newCommentText]); setNewCommentText(''); } function handleNewCommentChange(event: ChangeEvent<HTMLTextAreaElement>) { event!.target.setCustomValidity(''); setNewCommentText(event!.target.value); } function deleteComment(commentToDelete: string) { const commentsWithoutDeletedOne = comments.filter(comment => { return comment !== commentToDelete; }) setComments(commentsWithoutDeletedOne) } function handleNewCommentInvalid(event: InvalidEvent<HTMLTextAreaElement>) { event!.target.setCustomValidity('This field is required'); } const isNewCommentEmpty = newCommentText.length === 0; // const publishedDateFormatted = new Intl.DateTimeFormat('en-US', { // day: '2-digit', // month: 'long', // hour: '2-digit', // minute: '2-digit' // }).format(props.publishedAt); const publishDateFormatted = format(publishedAt, "MM dd 'at' HH:mm'h'", { locale: enUS }) const publishedDateRelativeToNow = formatDistanceToNow(publishedAt, { locale: enUS, addSuffix: true }) return ( <article className={styles.post}> <header> <div className={styles.author}> <Avatar hasBorder={true} src={author.avatarUrl} alt="" /> <div className={styles.authorInfo}> <strong>{author.name}</strong> <p>{author.role} </p> </div> </div> <time title={publishDateFormatted} dateTime={publishedAt.toISOString()} > {publishedDateRelativeToNow} </time> </header> <div className={styles.content} > {content.map((line: any) => { if (line.type === 'paragraph') { return (<p key={line.content} > {line.content} </p>) } else if (line.type === 'link') { return <p key={line.content} > <a href="#" target="_blank"> {line.content} </a> </p>; } })} </div> <form onSubmit={handleCreateNewComment} className={styles.commentForm}> <strong> Leave your comment </strong> <textarea name="comment" placeholder="Leave a mesage" value={newCommentText} onChange={handleNewCommentChange} onInvalid={handleNewCommentInvalid} required ></textarea> <button type="submit" disabled={isNewCommentEmpty} > Comment </button> </form> <div className={styles.commentList}> {comments.map(comment => { return ( <Comment key={comment} content={comment} onDeleteComment={deleteComment} /> ) })} </div> </article> ) }
import React from 'react'; import {View, Text, ScrollView, TouchableOpacity, Image,FlatList} from 'react-native'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import { useNavigation } from '@react-navigation/native'; const Stories = () => { const navigation = useNavigation(); const storyInfo = [ { id: 1, name: 'Your Story', image: require('./Images/image.jpg'), }, { id: 0, name: 'Ram_Charan', image: require('./Images/istockphoto-1249287421-612x612.jpg'), }, { id: 0, name: 'Tom', image: require('./Images/istockphoto-1371823675-170667a.jpg'), }, { id: 0, name: 'The_Groot', image: require('./Images/istockphoto-1403283106-170667a.jpg'), }, , { id: 0, name: 'loverland', image: require('./Images/image.jpg'), }, , { id: 0, name: 'chillhouse', image: require('./Images/image.jpg'), }, ]; return ( <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={{paddingVertical: 20}}> {storyInfo.map((data, index) => { return ( <TouchableOpacity key={index} onPress={() => navigation.push('Status', { name: data.name, image: data.image, }) }> <View style={{ flexDirection: 'column', paddingHorizontal: 8, position: 'relative', }}> {data.id == 1 ? ( <View style={{ position: 'absolute', bottom: 15, right: 10, zIndex: 1, }}> <MaterialIcons name="add-circle-outline" style={{ fontSize: 20, color: '#405de6', backgroundColor: 'white', borderRadius: 100, }} /> </View> ) : null} <View style={{ width: 68, height: 68, backgroundColor: 'white', borderWidth: 1.8, borderRadius: 100, borderColor: '#c13584', justifyContent: 'center', alignItems: 'center', }}> <Image source={data.image} style={{ resizeMode: 'cover', width: '92%', height: '92%', borderRadius: 100, backgroundColor: 'orange', }} /> </View> <Text style={{ textAlign: 'center', fontSize: 10, opacity: data.id == 0 ? 1 : 0.5, }}> {data.name} </Text> </View> </TouchableOpacity> ); })} </ScrollView> ); }; export default Stories;
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from model_state import State, Base """ State class representing a state in the database. Attributes: id (int): An auto-generated, unique integer identifier. name (str): The name of the state, up to 128 characters. """ class State(Base): """ State class representing a state in the database. Attributes: id (int): An auto-generated, unique integer identifier. name (str): The name of the state, up to 128 characters. """ # Replace 'your_username', 'your_password', and 'your_database' with your MySQL credentials. engine = create_engine('mysql://your_username:your_password@localhost:3306/your_database') Base.metadata.create_all(engine) # Create a session Session = sessionmaker(bind=engine) session = Session() # Example: Add a new state to the database new_state = State(name='New State') session.add(new_state) session.commit() # Query and print states from the database states = session.query(State).all() for state in states: print(state.id, state.name) # Close the session session.close()
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import classname from 'classnames'; import moment from 'moment'; import 'moment/locale/id'; import { H3, TextBody, Links } from 'components/atoms'; import './styles.scss'; class CardNews extends Component { render() { const { title, date, description, url, image } = this.props; const classNames = classname('o-card-news', {}); moment.locale('id'); const formatDate = (date) => moment(date).format('dddd, DD MMMM YYYY'); const isDateValid = (date) => moment(date).isValid(); return ( <div className={classNames}> <div className="o-card-news__background"> <img src={image} alt="img-news" /> </div> <div className="o-card-news__content"> <div className="news-date"> <TextBody>{isDateValid(date) && formatDate(date)}</TextBody> </div> <div className="news-title"> <H3>{title}</H3> </div> <div className="news-desc"> <TextBody color="grey">{description}</TextBody> </div> <div className="news-link"> <Links underline color="red" to={url} tabIndex="-1" type="link"> Baca Selengkapnya </Links> </div> </div> </div> ); } } CardNews.propTypes = { title: PropTypes.string, date: PropTypes.string, description: PropTypes.string, url: PropTypes.string, image: PropTypes.string }; CardNews.defaultProps = { title: '', date: '', description: '', url: '/', image: '' }; export default withRouter(CardNews);
import { IEmailBlock } from '@novu/shared'; import { useMantineTheme, Group, Container, Card } from '@mantine/core'; import { Dropzone } from '@mantine/dropzone'; import React, { useEffect, useState } from 'react'; import { Upload } from '../../../design-system/icons'; import { colors, Text } from '../../../design-system'; import { ContentRow } from './ContentRow'; import { ControlBar } from './ControlBar'; import { ButtonRowContent } from './ButtonRowContent'; import { TextRowContent } from './TextRowContent'; import { useIsMounted } from '../../../hooks/use-is-mounted'; import { useNavigate } from 'react-router-dom'; export function EmailMessageEditor({ onChange, value, branding, readonly, }: { onChange?: (blocks: IEmailBlock[]) => void; value?: IEmailBlock[]; branding: { color: string; logo: string } | undefined; readonly: boolean; }) { const theme = useMantineTheme(); const navigate = useNavigate(); const [blocks, setBlocks] = useState<IEmailBlock[]>( value?.length ? value : [ { type: 'text', content: '', }, ] ); const isMounted = useIsMounted(); const [top, setTop] = useState<number>(0); const [controlBarVisible, setActionBarVisible] = useState<boolean>(false); useEffect(() => { if (onChange && isMounted) { onChange(blocks); } }, [blocks, isMounted]); function onBlockStyleChanged(blockIndex: number, styles: { textAlign: 'left' | 'right' | 'center' }) { blocks[blockIndex].styles = { ...styles, }; setBlocks([...blocks]); } function onBlockTextChanged(blockIndex: number, content: string) { blocks[blockIndex].content = content; setBlocks([...blocks]); } function onBlockUrlChanged(blockIndex: number, url: string) { blocks[blockIndex].url = url; setBlocks([...blocks]); } function onHoverElement(e) { setTop(e.top + e.height); } function onEnterPress(e) { const ENTER_CODE = 13; const BACKSPACE_CODE = 8; if (e.keyCode === ENTER_CODE || e.keyCode === BACKSPACE_CODE) { /* * TODO: Currently disabled, because causes to not create new line on first time * setActionBarVisible(false); */ } } function onBlockAdd(type: 'button' | 'text') { const modifiedBlocks = [...blocks]; if (type === 'button') { modifiedBlocks.push({ type: 'button', content: 'Button text', }); } if (type === 'text') { modifiedBlocks.push({ type: 'text', content: '', }); } setBlocks(modifiedBlocks); } function removeBlock(index: number) { const modified = [...blocks]; modified.splice(index, 1); setBlocks(modified); } if (!Array.isArray(blocks)) { return null; } function getBrandSettingsUrl(): string { return '/settings'; } return ( <Card withBorder sx={styledCard}> <Container pl={0} pr={0}> <div onClick={() => !branding?.logo && navigate(getBrandSettingsUrl())}> <Dropzone styles={{ root: { borderRadius: '7px', padding: '10px', border: 'none', height: '80px', backgroundColor: theme.colorScheme === 'dark' ? colors.B17 : colors.B98, }, }} disabled multiple={false} onDrop={(file) => {}} data-test-id="upload-image-button" > {(status) => ( <Group position="center" style={{ height: '100%' }}> {!branding?.logo ? ( <Group style={{ height: '100%' }} spacing={5} position="center" direction="column" data-test-id="logo-upload-button" > <Upload style={{ width: 30, height: 30, color: colors.B60 }} /> <Text color={colors.B60}>Upload Brand Logo</Text> </Group> ) : ( <img data-test-id="brand-logo" src={branding?.logo} alt="" style={{ width: 'inherit', maxHeight: '80%' }} /> )} </Group> )} </Dropzone> </div> </Container> <Container mt={30} sx={{ height: '100%', minHeight: '300px', borderRadius: '7px', padding: '30px', backgroundColor: theme.colorScheme === 'dark' ? colors.B17 : colors.B98, ...(readonly ? { backgroundColor: theme.colorScheme === 'dark' ? colors.B20 : colors.B98, color: theme.colorScheme === 'dark' ? colors.B40 : colors.B70, opacity: 0.6, } : {}), }} onMouseEnter={() => setActionBarVisible(true)} onMouseLeave={() => setActionBarVisible(false)} > <div style={{ position: 'relative' }} data-test-id="email-editor"> {blocks.map((block, index) => { return ( <ContentRow onStyleChanged={(data) => onBlockStyleChanged(index, data)} key={index} block={block} onHoverElement={onHoverElement} onRemove={() => removeBlock(index)} allowRemove={blocks?.length > 1} > {[block.type].map((type, blockIndex) => { if (type === 'text') { return ( <TextRowContent key={blockIndex} block={block} onTextChange={(text) => onBlockTextChanged(index, text)} /> ); } if (type === 'button') { return ( <ButtonRowContent key={blockIndex} block={block} brandingColor={branding?.color} onUrlChange={(url) => onBlockUrlChanged(index, url)} onTextChange={(text) => onBlockTextChanged(index, text)} /> ); } return <></>; })} </ContentRow> ); })} </div> {controlBarVisible && !readonly && ( <div> <ControlBar top={top} onBlockAdd={onBlockAdd} /> </div> )} </Container> </Card> ); } const styledCard = (theme) => ({ backgroundColor: 'transparent', borderRadius: '7px', borderColor: theme.colorScheme === 'dark' ? colors.B30 : colors.B80, padding: '30px', });
import Foundation import RxSwift class CryptoDetailRepositoryDefault: CryptoDetailRepository { private let urlString = "https://min-api.cryptocompare.com/data/pricemultifull" private let session = URLSession.shared func getCryptoInfo(with currencyType: String) -> Single<CryptoModel> { Single.create { observer -> Disposable in guard var components = URLComponents(string: self.urlString) else { return Disposables.create() } components.queryItems = [ URLQueryItem(name: "fsyms", value: currencyType), URLQueryItem(name: "tsyms", value: "USD") ] guard let url = components.url else { return Disposables.create() } var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = self.session.dataTask(with: request) { data, _, error in do { guard let data = data else { return } let cryptoModel = try JSONDecoder().decode(CryptoModel.self, from: data) observer(.success(cryptoModel)) } catch { observer(.error(error)) } } task.resume() return Disposables.create() } } }
import type { Metadata } from "next"; import "./globals.css"; import { cn } from "@/lib/utils"; import { fontGothan } from '@/lib/fonts' import { QueryClientProvider } from "@tanstack/react-query"; import { queryClient } from "@/lib/react-query"; import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import { Toaster } from "sonner"; import { ToastTitle } from "@radix-ui/react-toast"; export const metadata: Metadata = { title: "Smart Fit | Code Challenge", description: "Front-end Smart Fit", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <QueryClientProvider client={queryClient}> <html lang="en" suppressHydrationWarning={true}> <body className={cn( 'min-h-screen bg-background font-sans antialiased', fontGothan.variable, )} > {children} <Toaster richColors /> <ReactQueryDevtools initialIsOpen={false} /> </body> </html> </QueryClientProvider> ); }
import { ctx } from "@app/index.js" import { RegistryEntry } from "@app/registry.js" import { usernamePrompt } from "@app/setup.js" import fs from "fs" import path from "path" export type AppConfig = { user: RegistryEntry } function getConfigPath() { if (!process.env.IPFSHARE_HOME) throw new Error("IPFSHARE_HOME is not defined") const configPath = path.join(process.env.IPFSHARE_HOME, "config.json") return configPath } function createConfig() { const configPath = getConfigPath() if (!ctx.ipfs) throw new Error("IPFS node is not initialized") if (!ctx.orbitdb) throw new Error("OrbitDB is not initialized") const user: RegistryEntry = { username: "", orbitdbIdentity: ctx.orbitdb.id, peerId: ctx.ipfs.peer.id.toString() } const config: AppConfig = { user: user } fs.writeFileSync(configPath, JSON.stringify({ user: user })) return config } export async function getAppConfig(): Promise<undefined | AppConfig> { try { const configPath = getConfigPath() await fs.promises.access(configPath, fs.constants.R_OK,) return JSON.parse(fs.readFileSync(configPath).toString()) as AppConfig } catch (e) { return undefined } } export async function getAppConfigAndPromptIfUsernameInvalid(daemon = false) { let config = await getAppConfig() if (!config) config = await ensureAppConfig() let userInRegistry = false if (config.user.username) { userInRegistry = (await ctx.registry?.getUser(config.user.username)) === undefined } if ( config.user.username === undefined || config.user.username.length === 0 || !userInRegistry ) { console.log("Username is not set or not registered") if (!daemon) { const validateFn = async (username: string) => { const userInregistry = await ctx.registry?.getUser(username) if (userInregistry) { console.log("Username already exists") return false } console.log(`Username ${username} is not in the registry ✅`) return true } const username = await usernamePrompt(validateFn) console.log(`Setting username to ${username}`) config.user.username = username await ctx.registry?.addUser(config.user) fs.writeFileSync(getConfigPath(), JSON.stringify(config)) if (!config.user.username) throw new Error("Username is not set and should have been set") } } if (!daemon) { if (!ctx.registry) throw new Error("Registry is not initialized") const user = await ctx.registry.getUser(config.user.orbitdbIdentity) if (!user) throw new Error("User is not found in the registry") console.log(`Current user: ${JSON.stringify(user, null, 2)})`) } return config } export async function ensureAppConfig() { let config = await getAppConfig() if (!config) config = createConfig() let changes = false if (!config.user.peerId || config.user.peerId.length === 0) { if (!ctx.ipfs) throw new Error("IPFS node is not initialized") config.user.peerId = ctx.ipfs?.peer.id.toString() changes = true } if (!config.user.orbitdbIdentity || config.user.orbitdbIdentity.length === 0) { if (!ctx.orbitdb) throw new Error("OrbitDB is not initialized") config.user.orbitdbIdentity = ctx.orbitdb?.id changes = true } if (changes) { // update the config file const configPath = getConfigPath() fs.writeFileSync(configPath, JSON.stringify(config)) } return config }
package main import ( "errors" "fmt" ) func test() { //使用defer + recover 来捕获和处理异常 defer func() { err := recover() //内置函数,可以捕获到异常 if err != nil { //说明捕获到异常 fmt.Println("err=", err) //这里可以将错误信息发送给管理员 fmt.Println("发送邮件给管理员") } }() num1 := 10 num2 := 0 res := num1 / num2 fmt.Println(res) } // 函数用于读取配置文件 // 如果传入文件名错误,则返回自定义错误 func readConf(name string) (err error) { if name == "config.ini" { //读取该文件 return nil } else { //返回一个自定义的错误 return errors.New("读取文件错误") } } func test02() { err := readConf("config.in") if err != nil { //输出该错误,终止程序 panic(err) } fmt.Println("ffwefew") } func main() { // //测试 // test() // fmt.Println("错误") //测试自定义错误 test02() }
# Three Sum Given an integer array nums , return all the triplets ` [nums[i], nums[j], nums[k]] ` such that ` i != j `, ` i != k `, and ` j != k `, and ` nums[i] + nums[j] + nums[k] == 0 `. Notice that the solution set must not contain duplicate triplets. **Example 1:** ```text Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. ``` **Example 2:** ```text Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. ``` **Example 3**: ```text Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. ``` --- ## Solution ... **Run Test** `npm test three-sum.test.js` [LeetCode](https://leetcode.com/problems/3sum/)
# Тестовое задание для "500na700" ### Используемые технологии: ![NodeJS](https://img.shields.io/badge/node.js-6DA55F?style=for-the-badge&logo=node.js&logoColor=white)![NPM](https://img.shields.io/badge/NPM-%23CB3837.svg?style=for-the-badge&logo=npm&logoColor=white)![React](https://img.shields.io/badge/react-%2320232a.svg?style=for-the-badge&logo=react&logoColor=%2361DAFB)![React Router](https://img.shields.io/badge/React_Router-CA4245?style=for-the-badge&logo=react-router&logoColor=white)![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)![GitHub](https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white)![Git](https://img.shields.io/badge/git-%23F05033.svg?style=for-the-badge&logo=git&logoColor=white)![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white)![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white) ## Для установки вам необходимо: 1. скачать репозиторий. Скопировать папку с файлами можно через SSH-ключ: ``` git clone git@github.com:homo-errantium/500na700.git ``` или загрузите [ZIP-версию](git@github.com:homo-errantium/500na700.git) 2. заходим в корневую папку ``` интерфейс компакт-диска ``` 3. установить зависимости ``` установка npm ``` ## Для начала вам нужно: 1. соберите приложение для производства в папке `build`: ``` npm запустить сборку ``` 2. запустите приложение в режиме разработки: ``` запуск НПМ ``` ``` npm-тест ``` Команда запускает программу запуска тестов в режиме просмотра в реальном времени. Дополнительную информацию см. в разделе [выполнение тестов](https://facebook.github.io/create-react-app/docs/running-tests). ## Имеется план действий по улучшению сайта: - оптимизировать стили - оптимизировать логику отрисовки карточек - установать режим прокрутки слайдера infinity loop - оптимизировать загрузку изображений ### Спасибо за просмотр # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
#include "HLSL_to_PSSL.h" CONST_BUFFER_BEGIN(VShaderConstants) float4x4 u_projection; float4x4 u_view; float4x4 u_world; float4x4 u_textureMtx[1]; float4 u_fogSettings; // [Enable, Start, End, Density] float4 u_mainTextureSize; bool u_useVtxColor = false; CONST_BUFFER_END CONST_BUFFER_BEGIN(PShaderConstants) float4 u_fogColor; float4 u_overdrawColor; float4 u_debugFeatures; // x = overdraw, y = mip visualize CONST_BUFFER_END sampler2D diffuse; sampler2D mipVisualization; struct VS_INPUT { float4 Position : POSITION; float4 Color : COLOR0; float2 UV : TEXCOORD0; }; struct VS_OUTPUT { float4 Position : SV_POSITION; float4 Color : COLOR0; float2 UV : TEXCOORD0; float Fog : TEXCOORD1; }; struct VS_OUTPUT_MIPMAP_DEBUG { float4 Position : SV_POSITION; float4 Color : COLOR0; float2 UV : TEXCOORD0; float Fog : TEXCOORD1; float2 MipUV : TEXCOORD2; }; //------------------------------------------------------------------ // Helper functions float computeFog(float4 p_eye) { float fogDistance = abs(p_eye.z); // Compute linear fog float fog = (u_fogSettings.z - fogDistance) / (u_fogSettings.z - u_fogSettings.y); return saturate(fog); } float3 computeFogColor(float4 p_color, float p_fog) { // Make fog behave correctly in combination with premultiplied alpha // This is impossible with the Fixed Function pipeline // u_fogColor.a is 0 for premultiplied, 1 for straight alpha float premultiply = max(p_color.a, u_fogColor.a); float3 fogColor = u_fogColor.rgb * premultiply; return lerp(fogColor, p_color.rgb, p_fog); } //------------------------------------------------------------------ // Entry points VS_OUTPUT vs_main( VS_INPUT p_input ) { VS_OUTPUT Output; // Position in camera space float4 eye = mul(mul(p_input.Position, u_world), u_view); Output.Position = mul(eye, u_projection); Output.Color = u_useVtxColor ? p_input.Color : float4(1,1,1,1); Output.UV = mul(float4(p_input.UV,0,1), u_textureMtx[0]).xy; Output.Fog = u_fogSettings.x > 0.5 ? computeFog(eye) : 1.0; return Output; } VS_OUTPUT_MIPMAP_DEBUG vs_mipmap_debug( VS_INPUT p_input ) { VS_OUTPUT_MIPMAP_DEBUG Output; // Position in camera space float4 eye = mul(mul(p_input.Position, u_world), u_view); Output.Position = mul(eye, u_projection); Output.Color = u_useVtxColor ? p_input.Color : float4(1,1,1,1); Output.UV = mul(float4(p_input.UV,0,1), u_textureMtx[0]).xy; Output.Fog = u_fogSettings.x > 0.5 ? computeFog(eye) : 1.0; Output.MipUV = Output.UV * float2(u_mainTextureSize.x / 8.0, u_mainTextureSize.y / 8.0); return Output; } float4 ps_main( VS_OUTPUT p_input ) : SV_TARGET { float4 color = SAMPLE_TEXTURE_2D(diffuse, p_input.UV) * p_input.Color; return float4(computeFogColor(color, p_input.Fog), color.a); } float4 ps_debug( VS_OUTPUT p_input ) : SV_TARGET { if (u_debugFeatures.x > 0.0f) return u_overdrawColor; float4 color = SAMPLE_TEXTURE_2D(diffuse, p_input.UV) * p_input.Color; return float4(computeFogColor(color, p_input.Fog), color.a); } float4 ps_mipmap_debug( VS_OUTPUT_MIPMAP_DEBUG p_input ) : SV_TARGET { if (u_debugFeatures.x > 0.0f) return u_overdrawColor; float4 color = SAMPLE_TEXTURE_2D(diffuse, p_input.UV) * p_input.Color; if (u_debugFeatures.y > 0.0f) { float4 mipColor = SAMPLE_TEXTURE_2D(mipVisualization, p_input.MipUV); color.rgb = lerp(color.rgb, mipColor.rgb * color.a, mipColor.a); return color; } return float4(computeFogColor(color, p_input.Fog), color.a); } //------------------------------------------------------------------ // Shader definitions technique FixedFunction { pass P0 { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_main(); } } technique FixedFunctionDebug { pass P0 { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_debug(); } } // Unfortunately only works on Windows for now technique FixedFunctionMipMapDebug { pass P0 { VertexShader = compile vs_2_0 vs_mipmap_debug(); PixelShader = compile ps_2_0 ps_mipmap_debug(); } }
import React from 'react' import cx from 'classnames' import { graphql } from 'gatsby' import Container from '@Components/Grid/Container' import Row from '@Components/Grid/Row' import ColorPaletteSquare from '@Components/ColorPaletteSquare' import * as style from './colorPalette.module.scss' import { H4 } from '@Components/Typography' const ColorPalette = ({className, palette, title}) => { const squares = palette.map((s, i) => ( <ColorPaletteSquare className={className} rga={s.rga} opacity={s.opacity} title={s.title} hex={s.hex} key={s.hex} index={i+1} /> )); return ( <section className={cx(style.section)}> <Container className={cx(style.container)}> <Row> {squares} </Row> <Row> <H4 className={cx(style.title)} text={title} /> <p className={cx(style.desc)}>Primary color palette</p> </Row> </Container> </section> ) }; export default ColorPalette export const query = graphql` fragment ColorPaletteModule on ContentfulModuleColorPalette { palette { hex opacity rga title } title } `
import { IsString, IsEmail, IsNumber, IsPositive, IsBoolean, IsDateString, IsDate, IsNotEmpty, Min } from 'class-validator'; export class CreateUserDto { @IsString() @IsNotEmpty({ message: 'First name must not be empty' }) firstName: string; @IsString() lastName: string; @IsString() @IsNotEmpty({ message: 'Membership type must not be empty' }) membershipType: string; // e.g., 'Annual Basic', 'Monthly Premium' @IsDateString() startDate: string = new Date().toISOString(); @IsDate({ message: 'Invalid due date format. Please provide a valid due date string' }) dueDate: Date = new Date(new Date().setFullYear(new Date().getFullYear() + 1)); // For annual memberships @IsDate({ message: 'Invalid monthly due date format. Please provide a valid monthly due date string' }) monthlyDueDate: Date = new Date(new Date().setMonth(new Date().getMonth() + 1)); // For add-on services @IsNumber({}, { message: 'Total amount must be a number' }) @IsPositive({ message: 'Total amount must be a positive number' }) totalAmount: number; // For annual memberships @IsNumber({}, { message: 'Monthly amount must be a number' }) @Min(0, { message: 'Monthly amount must be a positive number'}) monthlyAmount: number = 0; // For add-on services @IsEmail({}, { message: 'Invalid email format' }) email: string; @IsBoolean() isFirstMonth: boolean = true; @IsString() invoiceLink: string; }
# Seed Data # Landlords landlord1 = Landlord.create!( username: 'landlord1', email: 'landlord1@example.com', password: 'password123', bio: 'Experienced landlord with multiple properties.', phone_number: '1234567890', image: 'url_to_landlord_image1' ) landlord2 = Landlord.create!( username: 'landlord2', email: 'landlord2@example.com', password: 'password456', bio: 'New landlord eager to provide great housing.', phone_number: '9876543210', image: 'url_to_landlord_image2' ) # No need to explicitly save landlords as create! saves and returns the record # Properties property1 = landlord1.properties.create!( name: 'Property A', images: ['url_to_property_image1', 'url_to_property_image2'], location: 'City X', environment: 'Urban', security: 'High' ) property2 = landlord2.properties.create!( name: 'Property B', images: ['url_to_property_image3', 'url_to_property_image4'], location: 'City Y', environment: 'Suburban', security: 'Medium' ) # Rooms (associated with properties) room1 = property1.rooms.create!( room_type: 'Single', price: 800, tenant_name: 'Tenant A', occupied: true, image: ['url_to_room_image1', 'url_to_room_image2'] ) room2 = property2.rooms.create!( room_type: 'Double', price: 1000, occupied: false, image: ['url_to_room_image3', 'url_to_room_image4'] ) # Users user1 = User.create!( username: 'user1', email: 'user1@example.com', password: 'password789' ) user2 = User.create!( username: 'user2', email: 'user2@example.com', password: 'passwordabc' ) # Messages (associated with landlords and properties) message1 = Message.create!( user: user1, landlord: landlord1, property: property1, content: 'Interested in renting a room.' ) message2 = Message.create!( user: user2, landlord: landlord2, property: property2, content: 'Can I schedule a property visit?' ) # Additional Seed Data as needed... puts 'Seed data has been created successfully!'
# EP2 - Doubly Linked List ## Problem Statement Design a doubly linked list that supports the following operations: - `int get(int index)` retrieves the element at position `index` in `O(n)`. - `void insert(int value, int index)` inserts the element `value` at position `index` in `O(n)`. - `void delete(int index)` removes the element at position `index` in `O(n)`. - `int size()` retrieves the number of elements in the list in `O(1)`. - `void pushBack(int value)` adds the element `value` at the end of the list in `O(1)`. - `void pushFront(int value)` adds the element `value` at the beginning of the list in `O(1)`. Please do not use any available `LinkedList` implementation on your solution, you should build your own from scratch. ## How to submit your solution Clone this repository and create a new branch for you. Then, create a folder with your name and add your solution to it. You can use any language you like. When you're ready, push your new branch and submit a PR to add your solution to the main branch and ask a colleague to review it. All solutions will be available to everyone once they are submitted. It's up to you, but highly recommended, to give it a try before looking at any other solutions. --- # EP2 - Lista duplamente ligada ## Enunciado Implemente uma lista duplamente ligada que suporte as seguintes operações: - `int get(int index)` retorna o elemento na posição `index` em `O(n)`. - `void insert(int value, int index)` insere o elemento `value` na posição `index` em `O(n)`. - `void delete(int index)` remove o elemento da posição `index` em `O(n)`. - `int size()` retorna o número de elementos da lista em `O(1)`. - `void pushBack(int value)` adiciona o elemento `value` ao final da lista em `O(1)`. - `void pushFront(int value)` adiciona o elemento `value` no começo da lista em `O(1)`. Por favor não utilize nenhuma implementação de lista ligada disponível, você deve implementar a sua própria lista do zero. ## Como submeter sua solução Clone esse repositório e crie uma branch para você. Após isso, crie uma pasta com o seu nome e adicione a sua solução nela. Você pode usar a linguagem que preferir. Quando tudo estiver pronto, faça um push da sua nova branch e envie uma PR para adicionar a sua solução ao branch main e peça a um colega para revisar. Todas as soluções estarão visíveis para todos assim que forem submetidas. É sua responsabilidade (mas altamente recomendado) se assegurar de tentar sua própria solução antes de olhar outras.
<form method="post" action="{{route('admin.admins.store')}}" id="form_add_option"> @csrf <div class="form-row mb-4"> <div class="form-group col-md-6"> <label for="name">@lang('form.label.name')</label> <input name="name" type="text" maxlength="50" class="form-control @error('name') is-invalid @enderror" id="name" placeholder="@lang('form.placeholder.admin name')" value="{{old('name')}}" required> @error('name')<span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>@enderror </div> <div class="form-group col-md-6"> <label for="email">@lang('form.label.email')</label> <input name="email" type="email" maxlength="100" class="form-control @error('email') is-invalid @enderror" id="email" placeholder="@lang('form.placeholder.admin name')" value="{{old('email')}}" required> @error('email')<span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>@enderror </div> <div class="form-group col-md-6"> <label for="phone">@lang('form.label.phone') @lang('form.label.optional')</label> <input name="phone" type="tel" maxlength="20" class="form-control @error('phone') is-invalid @enderror" id="phone" placeholder="@lang('form.placeholder.admin phone')" value="{{old('phone')}}"> @error('phone')<span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>@enderror </div> <div class="form-group col-md-6"> <label for="role_id">@lang('form.label.role')</label> <select name="role_id" class="form-control @error('role_id') is-invalid @enderror" id="role_id" required> @foreach($roles as $role) <option value="{{$role->id}}" {{old('role') == $role->id}}>{{$role->name}}</option> @endforeach </select> @error('role_id')<span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>@enderror </div> <div class="form-group col-md-12"> <label for="password" class="d-block">@lang('form.label.password')</label> <input name="password" type="text" maxlength="255" class="d-inline-block form-control @error('password') is-invalid @enderror" id="password" placeholder="@lang('form.placeholder.admin password')" value="{{old('password')}}" required> <a class="btn btn-outline-light btn-password-generator d-inline-block">@lang('form.label.password generator')</a> @error('password')<span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>@enderror </div> </div> <button type="submit" class="btn btn-primary mt-3">@lang('layout.add admin')</button> </form>
import React from 'react'; import styled from 'styled-components'; import { GridTemplate } from '@components/drawers/ticket-information/index.stories'; import { AppointmentInfoDumb } from '@components/drawers/ticket-information/components/appointment-info/index.dumb'; import { AppointmentEntity } from '@domain/types/entities/appointment'; import ClientPetInfoDumb from '@components/drawers/ticket-information/components/client-pet-info/index.dumb'; import { ClientNotes } from '@components/drawers/ticket-information/components/client-notes/index.dumb'; const randomColor = () => { return '#' + Math.floor(Math.random() * 16777215).toString(16); }; const TicketSettings = () => ( <div style={{ backgroundColor: randomColor() }}>Ticket Settings</div> ); const AppointmentNotes = () => ( <div style={{ backgroundColor: randomColor() }}>Appointment Notes</div> ); const AddOns = () => ( <div style={{ backgroundColor: randomColor() }}>AddOns</div> ); const AppointmentHistory = () => ( <div style={{ backgroundColor: randomColor() }}>Appointment History</div> ); const Grid = styled.div` display: grid; height: 100%; gap: 8px; `; export interface GridTemplateProps { gridTemplateColumns: string; gridTemplateRows: string; } const GridT = styled(Grid)<GridTemplateProps>` grid-template-columns: ${props => props.gridTemplateColumns}; grid-template-rows: ${props => props.gridTemplateRows}; `; const GridItem = styled.div``; interface GridItemProps { gridColumn: string; gridRow: string; } const GridItemC = styled(GridItem)<GridItemProps>` height: 100%; width: 100%; grid-column: ${props => props.gridColumn}; grid-row: ${props => props.gridRow}; `; export interface TicketInformationDumbProps { appointment: AppointmentEntity; } export const TicketInformationDumb: React.FC<TicketInformationDumbProps> = ({ appointment, }) => { const { customer_notes, employee_notes } = appointment; return ( <div style={{ maxHeight: '100vh', overflow: 'hidden', }} > <GridT gridTemplateColumns={'repeat(8, 1fr)'} gridTemplateRows={'repeat(8, 1fr)'} > <GridItemC gridColumn="1 / 4" gridRow="1 / 2"> <AppointmentInfoDumb appointment={appointment} /> </GridItemC> <GridItemC gridColumn="4 / 7" gridRow="1 / 2"> <ClientPetInfoDumb appointment={appointment} /> </GridItemC> <GridItemC gridColumn="7 / 9" gridRow="1 / 2"> <TicketSettings /> </GridItemC> <GridItemC gridColumn="1 / 4" gridRow="2 / 3"> <ClientNotes appointmentNotes={employee_notes} clientNotes={customer_notes} /> </GridItemC> <GridItemC gridColumn="4 / 7" gridRow="3 / 5"> <AddOns /> </GridItemC> <GridItemC gridColumn="1 / 9" gridRow="5 / 10"> <AppointmentHistory /> </GridItemC> </GridT> </div> ); };
package data; import controllers.*; public class DataInitializer { public static void inicializarData() { // ########### Inicialización de data ################# // Creacion de carrera CarreraController.getInstance().crearCarrera("Ingenieria Informatica", 350); // Creacion de materias MateriaController.getInstance().crearMateria("Calculo I", 68); MateriaController.getInstance().crearMateria("Calculo II", 72); MateriaController.getInstance().crearMateria("Historia I", 68); MateriaController.getInstance().crearMateria("Dummy Muchas Horas", 5800); // Seteo de correlativas y posteriores MateriaController.getInstance().agregarMateriaCorrelativaPosterior(1, 2); MateriaController.getInstance().agregarMateriaCorrelativaPrevia(2, 1); // Agregar materias a carrera CarreraController.getInstance().agregarMateriaACarrera(1, 1); CarreraController.getInstance().agregarMateriaACarrera(1, 2); CarreraController.getInstance().agregarMateriaACarrera(1, 4); // Creacion de Profesores ProfesorController.getInstance().crearProfesor("Ignacio", "Martinez"); ProfesorController.getInstance().crearProfesor("Laura", "Gonzalez"); // Creacion de Alumnos AlumnoController.getInstance().crearAlumno("Franco", "Pascual", 123456); AlumnoController.getInstance().crearAlumno("Sofia", "Alvarez", 987654); // Creacion de Aulas AulaController.getInstance().crearAula("I405", 60); AulaController.getInstance().crearAula("L812", 50); // Creacion de Cursos CursoController.getInstance().crearCurso("I405", 1, 50000, "monday", "noche"); CursoController.getInstance().crearCurso("I405", 1, 35000, "tuesday", "tarde"); CursoController.getInstance().crearCurso("L812", 2, 25000, "tuesday", "tarde"); CursoController.getInstance().crearCurso("L812", 3, 42000, "THURSDAY", "manana"); CursoController.getInstance().crearCurso("I405", 4, 42000, "monday", "noche"); // Seteo de fecha maxima de inscripcion InscripcionController.getInstance().setFechaMaximaDeInscripcion(2024, 6, 24); // Inscribir alumno a carrera InscripcionController.getInstance().inscribirAlumnoACarrera(123456, 1); } }
import { useNavigate } from "react-router-dom"; import { sidebarNavigationItems } from "../../constants"; import { MediaState, NavigationItem } from "../../types"; import { useMediaStore } from "../../store/mediaStore"; import { removeItemFromLocalStorage } from "../../helpers"; type SidebarProps = { isOpen: boolean; }; const Sidebar: React.FC<SidebarProps> = ({ isOpen }) => { const navigate = useNavigate(); const setGlobalLoading = useMediaStore( (state: MediaState) => state.setGlobalLoading ); const setSelectedMediaIndex = useMediaStore( (state: MediaState) => state.setSelectedMediaIndex ); const selectedMediaIndex = useMediaStore( (state: MediaState) => state.selectedMediaIndex ); const handleMediaIndex = (mediaIndex: number) => { // 1) Remove media type from local storage removeItemFromLocalStorage("savedMediaType"); setGlobalLoading(true); // 2) Navigate to root page navigate("/"); // 3) Change the menu item index setSelectedMediaIndex(mediaIndex); }; return ( isOpen && ( <div className="sidebar"> <div className="sidebar__menu"> {sidebarNavigationItems.map( (navigationItem: NavigationItem, index: number) => { return ( <li key={index} onClick={() => handleMediaIndex(index)} className={`${ selectedMediaIndex === index ? "sidebar__menu-item sidebar__menu-item--active" : "sidebar__menu-item" }`} > {navigationItem.label} <span className="sidebar__menu-icon"> {navigationItem.icon} </span> </li> ); } )} </div> </div> ) ); }; export default Sidebar;
from google.cloud import vision_v1 from google.cloud import storage import cv2 import numpy as np import math # Initialize the Google Cloud client for Vision. client_vision = vision_v1.ImageAnnotatorClient() # Replace with your GCP project ID, bucket name, and image file name. project_id = "YOUR_PROJECT_ID" bucket_name = "YOUR_BUCKET_NAME" image_file_name = "YOUR_IMAGE_FILE" # Define the GCS URI for the image gcs_uri = f"gs://{bucket_name}/{image_file_name}" # Perform landmark detection using Cloud Vision API. image = vision_v1.Image() image.source.image_uri = gcs_uri response = client_vision.landmark_detection( image=image, ) # Download the image from GCS. storage_client = storage.Client(project=project_id) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(image_file_name) image_data = blob.download_as_bytes() # Load the image using OpenCV. image_cv = cv2.imdecode(np.frombuffer(image_data, np.uint8), -1) height, width, _ = image_cv.shape FONT_SCALE = 2e-3 # Adjust for larger font size in all images. THICKNESS_SCALE = 1e-3 # Adjust for larger thickness in all images. # Define text-related parameters. font = cv2.FONT_HERSHEY_SIMPLEX font_color = (0, 255, 0) # White color in BGR format. font_scale = min(width, height) * FONT_SCALE line_thickness = math.ceil(min(width, height) * THICKNESS_SCALE) # Initialize vertical position for writing text. text_y = 200 # Write landmark names on the image if confidence is more than 0.5. for landmark in response.landmark_annotations: # Extract landmark name and confidence score. landmark_name = landmark.description confidence = landmark.score # Check if confidence is more than 0.5. if confidence > 0.5: # Define the y-coordinate position to write the text. text_x = 100 # Put the landmark name on the image. cv2.putText( image_cv, landmark_name, (text_x, text_y), font, font_scale, font_color, line_thickness, lineType=cv2.LINE_AA, ) # Increment the vertical position for the next text. text_y += 50 # You can adjust this value to control spacing. # Save the image with landmark names. cv2.imwrite("landmark_detect_output.jpg", image_cv)
require ('../config/db.js') const brcypt = require('bcryptjs') const nodemailer = require("nodemailer"); const {google} = require('googleapis') const {USER, DOCTOR} = require('../model/usermodel.js') require('dotenv').config({path : '../.env'}) exports.registerUser = async(req, res) => { const {name, email, password, contact, gender, dob, emergency_contact, primary_concern, preferred_therapist, treatment_history} = req.body if(!name || !email || !password || !contact || !gender || !dob || !emergency_contact || !primary_concern || !preferred_therapist || !treatment_history){ return res.status(400).json({msg: "Please fill all fields"}) } try{ const findUser = await USER.findOne({email: email}); if(findUser){ return res.status(422).json({msg : "User already exists"}) } //const doctorsWithFewPatients = await DOCTOR.find({ patients: { $exists: true, $ne: null }, $expr: { $lt: [{ $size: "$patients" }, 5] } }); const preferredTherapistDoctor = await DOCTOR.findOne({ _id: preferred_therapist }); //const preferredTherapistDoctor = await DOCTOR.findOne(doctor => doctor._id === preferred_therapist); if(preferredTherapistDoctor){ // if (preferredTherapistDoctor.patients.length >= 5) { // return res.status(422).json({ msg: "Preferred therapist has reached the maximum number of patients" }); // } const newUser = new USER({name: name, email: email, password: password, contact: contact, gender: gender, dob: dob, emergency_contact: emergency_contact, primary_concern: primary_concern, preferred_therapist: preferred_therapist, treatment_history: treatment_history}) console.log("Preferred Therapist", preferred_therapist) await newUser.save() preferredTherapistDoctor.patients.push(newUser._id); await preferredTherapistDoctor.save(); res.status(200).json({msg : `Patient added to preferred therapist successfully.`}); } else { // If preferred therapist is not found, add patient to any doctor with fewer than 5 patients //const otherDoctor = await DOCTOR.findOne(doctor => doctor._id != preferred_therapist); const otherDoctor = await DOCTOR.findOne({ _id: { $ne: preferred_therapist } }); if (otherDoctor && otherDoctor.patients.length < 5) { const newUser = new USER({name: name, email: email, password: password, contact: contact, gender: gender, dob: dob, emergency_contact: emergency_contact, primary_concern: primary_concern, preferred_therapist: preferred_therapist, treatment_history: treatment_history}) await newUser.save() // Add the patient to another doctor with fewer than 5 patients otherDoctor.patients.push(newUser._id); await otherDoctor.save(); res.status(200).json({msg : `Patient added to another therapist successfully.`}); } } if(!newUser){ res.json({status:500 ,msg:"Error creating User "}) } res.json({status:201, msg:"User added succesfully"}) }catch(err){ console.log("Error at user signup", err) } } exports.registerDoctor = async(req,res) => { const {name, email, password, contact, license_Number, experience} = req.body if(!name || !email || !password || !contact || !license_Number || !experience ){ return res.status(400).json({msg: "Please fill all fields"}) } try{ const findDoctor = await DOCTOR.findOne({email: email}); if(findDoctor){ return res.status(422).json({msg : "Doctor already exists"}) } const newDoctor = new DOCTOR({name: name, email: email, password: password, contact: contact, license_Number: license_Number, experience: experience }) await newDoctor.save() if(!newDoctor){ res.json({status:500 ,msg:"Error creating Doctor "}) } res.json({status:201, msg:"Doctor added succesfully"}) }catch(err){ console.log("Error at doctor registration", err) } } exports.login = async(req,res) => { const {identity, email, password} = req.body if(!identity || !email || !password){ return res.status(400).json({msg: "Please fill all fields"}) } try{ switch(identity.toLowerCase()){ case "doctor": const doctorExist = await DOCTOR.findOne( {email: email}) // console.log("donorExist:", email, " ", donorExist) if(!doctorExist){ return res.json({msg : "Account not found"}) } const matchDoctorPassword = await brcypt.compare(password, doctorExist.password) if(!matchDoctorPassword) { return res.json({ msg: "Invalid Password"}) } const doctorToken = await doctorExist.generateDoctorTokens(res) console.log("Your generated token is: ",doctorToken) // console.log("Cookies: ", req.cookies) return res.json({status:200, msg:"Logged in", token:doctorToken, doctorToken:doctorToken, identity: "doctor"}) case "user": const userExist = await USER.findOne( {email: email }) if(!userExist){ return res.json({msg : "Account not found"}) } const matchUserPassword = await brcypt.compare(password, userExist.password) if(!matchUserPassword) { return res.json({ msg: "Invalid Password"}) } const userToken = await userExist.generateUserTokens(res) console.log("Your generated token is: ",userToken) return res.json({status:200, msg:"Logged in", token:userToken, userExist:userExist, identity: "user"}) } }catch(err){ console.log("Error at login", err) } }
#ifndef MAIN_H #define MAIN_H #include <unistd.h> /* _putchar - writes the character c to stdout * @c: The character to print * * Return: On success 1. * On error, -1 is returned, and errno is set appropriately. */ int _putchar(char c); /** * _isupper - Checks if a character is uppercase * @c: The character to check * * Return: 1 if c is uppercase, 0 otherwise */ int _isupper(int c); /** * _isdigit - Checks if a character is a digit (0-9) * @c: The character to check * * Return: 1 if c is a digit, 0 otherwise */ int _isdigit(int c); #endif /* MAIN_H */
# Contributing to [Project] Thank you for your interest in contributing to Nerdcator :tada:! Nerdcator is a basic app that allows travelers to find nearby sites of special interest to scientists and nerds such as geological/botanical features, offbeat museums, graves of our scientific heroes, locations of historic/scientific events/interest, and even research labs offering tours. This documents is a set of guidelines for contributing to Nerdcator on GitHub. These are guidelines, not rules. This guide is meant to make it easy for you to get involved. * [Participation guidelines](#participation-guidelines) * [What we're working on](#what-were-working-on) * [How to submit changes](#how-to-submit-changes) * [How to report bugs](#how-to-report-bugs) * [Communication channels](#communication-channels) ## Participation guidelines This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to <aurelia@mozillafoundation.org>. ## What we're working on Take a look at the issues in our [current milestone](https://github.com/auremoser/nerdcator/issues) to get started! You're welcome to jump in wherever. ## How to submit changes Once you've identified one of the issues above that you feel you can contribute to, you're ready to make a change to the project repository! 1. **[Fork](https://help.github.com/articles/fork-a-repo/) this repository**. This makes your own version of this project you can edit and use. 2. **[Make your changes](https://guides.github.com/activities/forking/#making-changes)**! You can do this in the GitHub interface on your own local machine. Once you're happy with your changes... 3. **Submit a [pull request](https://help.github.com/articles/proposing-changes-to-a-project-with-pull-requests/)**. This opens a discussion around your project and lets the project lead know you are proposing changes. First time contributing to open source? Check out this *free* series, [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). ## How to report bugs Notice a mistake? Please file any bugs, requests, or questions in our [issue tracker](https://github.com/auremoser/nerdcator/issues)! You'll note we have translations of our repo material in German and Greek (for now!). We would love to improve our localization process and you're welcome to contribute however you can. ## Communication channels Join us on [gitter](https://gitter.im/nerdcator/Lobby) to ask any quick questions!
from nicegui import ui from nicegui import run from nicegui import events import mne import numpy as np import matplotlib.pyplot as plt from mne import Epochs, pick_types, events_from_annotations from mne.channels import make_standard_montage from mne.io import concatenate_raws, read_raw_edf from mne.datasets import eegbci import easygui import plotly.graph_objects as go from mne.datasets import eegbci import re import os from multiprocessing import Process import sklearn ###Global variables with ui.dialog().props('full-width') as dialog: with ui.card(): content = ui.markdown() ###Necessary Functions for buttons def choose_local_file() -> None: container = ui.row() with container: container.clear() try: global file file = easygui.fileopenbox() localfile_input.value = f"{file}" #ui.button('Clear', on_click=container.clear) return container except: print("ERROR WITH choose_local_file") return # # ##Bar Graph Generator Function def generate_Bar_Graph(): try: placement.clear() raw = mne.io.read_raw_edf(file) fig = go.Figure(go.Bar(x=raw.times, y=raw.get_data()[0])) fig.update_layout( title='EEG Bar Graph' ) figure = ui.plotly(fig).classes('w-full h-90') figure.move(placement) except: print("ERROR IN generate_Bar_Graph") return ##Topo Map Generator Fucnction def generate_Topo_Map(): print("File name" + file) try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) raw.compute_psd().plot_topomap() except: print("ERROR IN generate_Topo_Map") return ##Raw Plot Generator Function def raw_plot(): raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) raw.plot(block=True) ##Montage Plot Generator Function def generate_montage_plot(): raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw = apply_filter(raw) #raw.plot_sensors(ch_type="eeg") montage.plot() ##Ica Generator Function def generate_ICA(): try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) #raw.filter(7.0, 30.0, fir_design="firwin", skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components ica.plot_properties(raw, picks=ica.exclude) except: print('Failed ICA') print("Ensure you have a file selected") ##ICA components function def generate_ica_components(): try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components mne.viz.plot_ica_sources(ica, raw) ica.plot_components() except: print("ICA components failed") print("Ensure you have a filed selected") ##ICA plot overlay def generate_ica_plot_overlay(): try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) #raw.filter(7.0, 30.0, fir_design="firwin", skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components #mne.viz.plot_ica_sources(ica, raw) ica.plot_overlay(raw) except: print('Failed ICA plot overlay') print("Ensure you have a file selected") ##EEG Covariance def generate_covariance_shrunk(): try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="shrunk") fig_noise_cov = mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) except: print("EEG covariance failed") print("Ensure you have a filed selected") ##Covariarance Function def generate_covariance_diagonal_fixed(): raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="diagonal_fixed") mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) #Plot Creation Function def create_mne_plot(data): fig = go.Figure(go.Scatter(x=data.times, y=data.get_data()[0])) fig.update_layout( title='EEG data plot', xaxis=dict(title='time (s)'), yaxis=dict(title='Amplitude') ) return fig # Define the function to process the file def process_file(): global file if file: try: placement.clear() raw = mne.io.read_raw_edf(file, preload=True) # Load the EEG data raw = apply_filter(raw) fig = create_mne_plot(raw) # Create a Plotly figure figure = ui.plotly(fig).classes('w-full h-90') # Display the figure figure.move(placement) except Exception as e: print(f"Error processing the file: {str(e)}") def apply_filter(raw): if highpass.value == True & lowpass.value == True: raw.filter(lowpass_value.value, highpass_value.value, fir_design="firwin", skip_by_annotation="edge") elif highpass.value == True & lowpass.value == False: raw.filter(None, highpass_value.value, fir_design="firwin", skip_by_annotation="edge") elif highpass.value == False & lowpass.value == True: raw.filter(lowpass_value.value, None, fir_design="firwin", skip_by_annotation="edge") elif highpass.value == False & lowpass.value == False: raw.filter(None, highpass_value.value, fir_design="firwin", skip_by_annotation="edge") return raw ########### Functions For MNE Datasets def EEGBCI_raw_plot(): #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) eegbci.standardize(raw) # set channel names montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw.plot(block=True) # def EEGBCI_generate_montage_plot(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw = apply_filter(raw) #raw.plot_sensors(ch_type="eeg") montage.plot() # def EEGBCI_generate_Topo_Map(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) raw.compute_psd().plot_topomap() except: print("ERROR IN generate_Topo_Map") return # def EEGBCI_generate_ICA(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) #raw.filter(7.0, 30.0, fir_design="firwin", skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components ica.plot_properties(raw, picks=ica.exclude) print('Failed ICA') print("Ensure you have a file selected") # def EEGBCI_generate_ICA_components(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) #raw.filter(7.0, 30.0, fir_design="firwin", skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components mne.viz.plot_ica_sources(ica, raw) ica.plot_components() except: print('Failed ICA') print("Ensure you have a file selected") def EEGBCI_generate_ICA_plot_overlay(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) #raw.filter(7.0, 30.0, fir_design="firwin", skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800) ica.fit(raw) ica.exclude = [15] # ICA components #mne.viz.plot_ica_sources(ica, raw) ica.plot_overlay(raw) except: print('Failed ICA plot overlay') print("Ensure you have a file selected") def EEGBCI_generate_covariance_shrunk(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="shrunk") fig_noise_cov = mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) except: print("EEG covariance failed") print("Ensure you have a filed selected") def EEGBCI_generate_covariance_diagonal(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="diagonal_fixed") fig_noise_cov = mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) except: print("EEG covariance failed") print("Ensure you have a filed selected") def EEGBCI_generate_covariance_shrunk(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="shrunk") fig_noise_cov = mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) except: print("EEG covariance failed") print("Ensure you have a filed selected") def EEGBCI_generate_covariance_diagonal_fixed(): #boilerplate start #ensure the correct folder exists for mne home_directory = os.path.expanduser( '~' ) home_directory = home_directory + '\mne_data' print(home_directory) if not os.path.exists(home_directory): os.mkdir(home_directory) #Shows runs for testing print(subject_label.text, " Subject") print(runs_label.text, ' Runs') #regular expresions subject = re.findall(r'\d+', subject_label.text) runs = re.findall(r'\d+', runs_label.text) subject = int(subject[0]) runs = [int(i) for i in runs] print(subject, " Subject") print(runs, ' Runs') raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) #boilerplate end try: raw = mne.io.read_raw_edf(file, preload=True) eegbci.standardize(raw) montage = make_standard_montage("standard_1005") raw.set_montage(montage) raw = apply_filter(raw) noise_cov = mne.compute_raw_covariance(raw, method="diagonal_fixed") fig_noise_cov = mne.viz.plot_cov(noise_cov, raw.info, show_svd=False) except: print("EEG covariance failed") print("Ensure you have a filed selected") def test(): process = Process(target=EEGBCI_raw_plot) process.start() process.join() # ################################# #BEGINNING OF PAGE LAYOUT #Start of Header----------------------------------------------------------------------------------------------------------------------------- with ui.header(elevated=True).style('background-color: #3874c8').classes('items-center justify-between'): dark = ui.dark_mode(False) with ui.tabs() as tabs: ui.image("brainwave_compnay_logo.png").classes("w-16") ui.tab('Local Files') ui.tab('MNE Datasets') #ui.tab('Preprocessing') ui.switch('Mode').bind_value(dark) #End of Header------------------------------------------------------------------------------------------------------------------------------- #If we want something on the right side of the screen, (A right drawer, similar to the left drawer) then uncomment the 2 lines below this # with ui.right_drawer(fixed=False).style('background-color: #ebf1fa').props('bordered') as right_drawer: # ui.label('RIGHT DRAWER') #Here is the start of the Footer------------------------------------------------------------------------------------------------------------- #with ui.footer().style('background-color: #3874c8'): # with ui.row().classes('w-full justify-center'): # ui.button('Dark', on_click=dark.enable) # ui.button('Light', on_click=dark.disable) #End of the Footer--------------------------------------------------------------------------------------------------------------------------- #EVERYTHING AFTER THIS LINE WILL GO INSIDE OF THE MAIN VIEW container = ui.row() with ui.tab_panels(tabs, value='Local Files').classes('w-full'): with ui.tab_panel('Local Files'): with ui.stepper().props('vertical').classes('w-full') as stepper: with ui.step('Choose File'): container ui.button('Choose Local File', on_click= choose_local_file) localfile_input = ui.input(label="Local File Path", placeholder='Local File Path').props('clearable') with ui.stepper_navigation(): ui.button('Next', on_click=stepper.next) # with ui.step('Choose Filters'): with ui.row(): band_filter = ui.checkbox('Band Filter', value=False) other_filter = ui.checkbox('Other Filter', value = False) # ui.separator() with ui.column().bind_visibility_from(band_filter, 'value'): with ui.row(): highpass = ui.checkbox('Highpass filter', value=True) lowpass = ui.checkbox('Lowpass Filter', value=True) # with ui.row(): with ui.column().bind_visibility_from(highpass, 'value'): lowpass_value = ui.number(label='Highpass Filter', value=7, format='%.1f') # with ui.column().bind_visibility_from(lowpass, 'value'): highpass_value = ui.number(label='Lowpass Filter', value=30, format='%.1f') # # # ui.separator() with ui.column().bind_visibility_from(other_filter, 'value'): ui.label('options here') # with ui.stepper_navigation(): ui.button('Next', on_click=stepper.next) ui.button('Back', on_click=stepper.previous).props('flat') # # #place plot here with ui.row().classes('w-full justify-center m-3'): ui.button('Process File', on_click=process_file) ui.button('Raw Plot', on_click= raw_plot) ui.button('Generate Montage Plot', on_click= generate_montage_plot) #ui.button('Generate Bar Graph', on_click=generate_Bar_Graph) ui.button('Generate Topographic Map', on_click= generate_Topo_Map) #This literally did nothing, so im commenting it out #ui.button('Generate Heat Map') ui.button('Generate ICA', on_click= generate_ICA) ui.button('Generate ICA Components', on_click= generate_ica_components) ui.button('Generate ICA plot overlay', on_click= generate_ica_plot_overlay) ui.button('Generate Covariance Chart Shrunk', on_click= generate_covariance_shrunk) ui.button('Generate Covariance Chart Diagonal-Fixed', on_click= generate_covariance_diagonal_fixed) # # with ui.row(): placement = ui.row().classes('w-full justify-center') # # # # # with ui.tab_panel('Preprocessing'): ui.label('Preprocessing Options to com') # with ui.tab_panel('MNE Datasets'): with ui.row(): ui.label('Sample Data from the MNE Library') with ui.row().classes('w-full justify-center m-3'): dataset = ui.toggle(['EEGBCI', 'Eyelink'], value=1) with ui.row().classes('w-full justify-center m-3'): ui.label(' ') with ui.row().classes('w-full justify-center m-3').bind_visibility_from(dataset, 'value'): ui.input('Subjects', placeholder='4', on_change=lambda e:subject_label.set_text('Subjects selected: ' + e.value) ) subject_label = ui.label() with ui.row().classes('w-full justify-center m-3').bind_visibility_from(dataset, 'value'): ui.input('Runs', placeholder='1,2,3,4', on_change=lambda e:runs_label.set_text('Runs selected: ' + e.value)) runs_label = ui.label() with ui.row().classes('w-full justify-center m-3').bind_visibility_from(dataset, 'value'): ui.button('Raw Plot', on_click=EEGBCI_raw_plot) ui.button('Generate Montage Plot', on_click= EEGBCI_generate_montage_plot) #ui.button('Generate Bar Graph', on_click=EEGBCI_generate_Bar_Graph) ui.button('Generate Topographic Map', on_click= EEGBCI_generate_Topo_Map) #ui.button('Generate Heat Map') ui.button('Generate ICA', on_click= EEGBCI_generate_ICA) ui.button('Generate ICA Components', on_click= EEGBCI_generate_ICA_components) ui.button('Generate ICA Plot Overlay', on_click= EEGBCI_generate_ICA_plot_overlay) ui.button('Generate Covariance Chart Shrunk', on_click=EEGBCI_generate_covariance_shrunk) ui.button('Generate Covariance Chart Diagonal-Fixed', on_click=EEGBCI_generate_covariance_diagonal_fixed) # # # ###Footer that is displayed when clicking sticky button with ui.footer(value=False) as footer: ui.label('This is a Visual Interface for working with the Python MNE library') # with ui.page_sticky(position='bottom-right', x_offset=20, y_offset=20): ui.button(on_click=footer.toggle, icon='contact_support').props('fab') # ui.run()
import React from "react"; import { Link, useLocation } from "react-router-dom"; import ContactUsPage from "./Contact"; import Card from "./Card"; import Cardhome from "./Cardhome"; import NoData from "./NoData"; const Navbar = () => { return ( <div className="container my-5"> <ul className="nav nav-tabs" id="myTab" role="tablist"> <li className="nav-item" role="presentation"> <button className="nav-link active text-success" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true" > Home </button> </li> <li className="nav-item" role="presentation"> <button className="nav-link text-success" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false" > Previous </button> </li> <li className="nav-item" role="presentation"> <button className="nav-link text-success" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false" > Contact </button> </li> </ul> <div className="tab-content bg-light p-3" id="myTabContent"> <div className="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab" > {localStorage.getItem("Speed Examination 2023")?"" :<Cardhome heading="Exam 2023" title="Speed Examination 2023" description="This is speed examination for your level it will contain 250 questions and a timer of 15 minutes you have to attend the maximum number of quetions as soon as possible"/>} {localStorage.getItem("Accuracy Exam 2023 (Abacus)")?"":<Cardhome heading="Exam 2023" title="Accuracy Exam 2023 (Abacus)" description="This is a accuracy exam in which there are 50 questions that you have to attend in 15 minutes with accuracy"/>} {localStorage.getItem("Accuracy Exam 2023 (Mentally)")?"":<Cardhome heading="Exam 2023" title="Accuracy Exam 2023 (Mentally)" description="This is a accuracy exam in which there are 50 questions that you have to attend in 15 minutes with accuracy"/>} {localStorage.getItem("Speed Examination 2023") && localStorage.getItem("Accuracy Exam 2023 (Abacus)") && localStorage.getItem("Accuracy Exam 2023 (Mentally)")?<NoData/>:""} </div> <div className="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab" > {localStorage.getItem("Speed Examination 2023")?<Card heading="Exam 2023" title="Speed Examination 2023" description="This is speed examination for your level it will contain 250 questions and a timer of 15 minutes you have to attend the maximum number of quetions as soon as possible"/>:""} {localStorage.getItem("Accuracy Exam 2023 (Abacus)")?<Card heading="Exam 2023" title="Accuracy Exam 2023 (Abacus)" description="This is a accuracy exam in which there are 50 questions that you have to attend in 15 minutes with accuracy"/>:""} {localStorage.getItem("Accuracy Exam 2023 (Mentally)")?<Card heading="Exam 2023" title="Accuracy Exam 2023 (Mentally)" description="This is a accuracy exam in which there are 50 questions that you have to attend in 15 minutes with accuracy"/>:""} {!localStorage.getItem("Speed Examination 2023") && !localStorage.getItem("Accuracy Exam 2023 (Abacus)") && !localStorage.getItem("Accuracy Exam 2023 (Mentally)")?<NoData/>:""} </div> <div className="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab" > <ContactUsPage/> </div> </div> </div> ); }; export default Navbar;
# ALBEF > 文章标题:[Align before Fuse: Vision and Language Representation Learning with Momentum Distillation](https://arxiv.org/abs/2107.07651) [![citation](https://img.shields.io/badge/dynamic/json?label=citation&query=citationCount&url=https%3A%2F%2Fapi.semanticscholar.org%2Fgraph%2Fv1%2Fpaper%2Fb82c5f9efdb2ae56baa084ca41aeddd8a665c1d1%3Ffields%3DcitationCount)](https://www.semanticscholar.org/paper/Align-before-Fuse%3A-Vision-and-Language-Learning-Li-Selvaraju/b82c5f9efdb2ae56baa084ca41aeddd8a665c1d1) > > 作者:Junnan Li, Ramprasaath R. Selvaraju, Akhilesh Deepak Gotmare, Shafiq Joty, Caiming Xiong, Steven Hoi > > 发表时间:(NIPS 2021) > > [offical code](https://github.com/salesforce/ALBEF) <center> <img src = "ALBEF.assets/ALBEF.png"> <br> <div style="color:black; border-bottrm: 1px solid #d9d9d9; display: inline-block; padding: 2px;">ALBEF </div> </center> ALBEF 包含一个图像编码器 (ViT-B/16)、一个文本编码器(前 6 层 BERT)和一个多模态编码器(后 6 层 BERT,带有额外的交叉注意层)。 image input打成patch,通过patch embedding layer,在通过12层 Vision Transformer > $224\times224-$-> $(196+1)\times 768=197\times768$ BERT前六层去做文本编码,剩下的六层transformer encoder直接当成multi-model fusion的过程 **Loss** > - Image-Text Contrastive Learning (ITC)。类似于CLIP,增大同(正)样本对的similarity,减小负样本对的similarity。 > > > CLS Token当做全局特征,图像和文本各一个$768\times1$的一个向量;通过downsample和normalization变成$256\times 1$ (MoCo实现) > > - Masked Language Modeling (MLM,generative)。类似于BERT,遮盖住一些单词,然后预测出来。 > > - Image-Text Matching (ITM,contrastive)。二分类任务,判断图-文对是否匹配。 动量蒸馏 momentum distillation ## 拓展阅读 [ALBEF offical blog](https://blog.salesforceairesearch.com/align-before-fuse/) # VLMo > 文章标题:[VLMo: Unified Vision-Language Pre-Training with Mixture-of-Modality-Experts](https://arxiv.org/abs/2111.02358) [![citation](https://img.shields.io/badge/dynamic/json?label=citation&query=citationCount&url=https%3A%2F%2Fapi.semanticscholar.org%2Fgraph%2Fv1%2Fpaper%2Fcf7c2e0e4fb2af689aaf4b7a7cddf7b1f4d5e3f0%3Ffields%3DcitationCount)](https://www.semanticscholar.org/paper/VLMo%3A-Unified-Vision-Language-Pre-Training-with-Wang-Bao/cf7c2e0e4fb2af689aaf4b7a7cddf7b1f4d5e3f0) > > 作者:Hangbo Bao, Wenhui Wang, Li Dong, Qiang Liu, Owais Khan Mohammed, Kriti Aggarwal, Subhojit Som, Furu Wei > > 发表时间:(NIPS 2022) > > [offical code](https://github.com/microsoft/unilm/tree/master/vlmo) <center> <img src = "ALBEF.assets/VLMo.png"> <br> <div style="color:black; border-bottrm: 1px solid #d9d9d9; display: inline-block; padding: 2px;">VLMo </div> </center>
package com.example.demo.resources; import org.apache.logging.log4j.*; import java.util.Optional; /*import org.slf4j.Logger; import org.slf4j.LoggerFactory;*/ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; 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.example.demo.model.Train; import com.example.demo.repository.TrainRepository; @CrossOrigin(origins="http://localhost:4200", exposedHeaders="Access-Control-Allow-Origin") @RestController @RequestMapping("/trains") public class TrainController { Logger logger= LogManager.getLogger(TrainController.class); @Autowired private TrainRepository trainrepository; @PostMapping("/addTrain") public String saveTrain(@RequestBody Train trainid) { logger.info("saveTrain method accessed"); trainrepository.save(trainid); return "Added train with id : " + trainid.getTrainid(); } @GetMapping("{trainid}") public Optional<Train> getTrain(@PathVariable String trainid){ logger.info("getTrain method accessed"); return trainrepository.findById(trainid); } @DeleteMapping("/delete/{trainid}") public String deleteTrain (@PathVariable String trainid) { trainrepository.deleteById(trainid); logger.info("deleteTrain method accessed"); return "Train deleted with id : "+trainid; } @PutMapping("/update/{trainid}") public Train updateTrain(@PathVariable("trainid") String trainid,@RequestBody Train t ) { t.setTrainid(trainid); trainrepository.save(t); logger.info("updateTrain method accessed"); return t; } @PutMapping("/update") public Train updateTrain(@RequestBody Train t) { return trainrepository.save(t); } } //@CrossOrigin("http://localhost:3000") /*package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeResource { Logger logger= LoggerFactory.getLogger(HomeResource.class); @RequestMapping("/") public String home() { logger.trace("home method accessed"); return "Hello Spring boot"; } }*/
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('user', function (Blueprint $table) { $table->uuid('id')->primary()->default(random_int(1111111111,9999999999))->unique(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('photo')->nullable(); $table->tinyInteger('is_admin')->default(0); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); $table->integer('created_by')->default(0); $table->integer('updated_by')->default(0); $table->integer('deleted_by')->default(0); $table->index('name'); $table->index('email'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('user'); } };
import request from 'supertest'; import mongoose from 'mongoose'; import { app } from '../../app'; import auth, { getNewValidUser } from '../../test/helpers/auth'; import { createTicket } from '../../test/helpers/ticket'; import { createOrder } from '../../test/helpers/order'; import { OrderStatus, Subjects } from '@ramtickets/common/dist'; import { Order } from '../../models/order'; import { natsWrapper } from '../../natsWrapper'; describe('New Order', () => { it("returns an error if ticket doesn't exists", async () => { const ticketId = mongoose.Types.ObjectId(); const user = getNewValidUser(); const cookie = auth.signIn(user); await request(app) .post('/api/orders') .set('Cookie', cookie) .send({ ticketId }) .expect(404); }); it('returns an error if ticket already reserved', async () => { const ticket = await createTicket(); await createOrder({ ticket, status: OrderStatus.AwaitingPayment, }); const user = getNewValidUser(); const cookie = auth.signIn(user); await request(app) .post('/api/orders') .set('Cookie', cookie) .send({ ticketId: ticket.id }) .expect(400); }); it('creates an order', async () => { const ticket = await createTicket(); const user = getNewValidUser(); const cookie = auth.signIn(user); await request(app) .post('/api/orders') .set('Cookie', cookie) .send({ ticketId: ticket.id }) .expect(200); const orders = await Order.find({}).count(); expect(orders).toEqual(1); }); it('emits order:created event', async () => { const ticket = await createTicket(); const user = getNewValidUser(); const cookie = auth.signIn(user); const res = await request(app) .post('/api/orders') .set('Cookie', cookie) .send({ ticketId: ticket.id }); const response = JSON.parse(res.text); expect(natsWrapper.client.publish).toHaveBeenCalledWith( Subjects.OrderCreated, JSON.stringify({ id: response.id, status: response.status, userId: response.userId, ticket: { id: response.ticket.id, price: response.ticket.price, }, expiresAt: response.expiresAt, version: 0, }), expect.anything() ); }); });
from abstract_factory import Button, Checkbox, GuiFactory # factories class WindowsFactory(GuiFactory): def create_button(self): return WindowsButton() def create_checkbox(self): return WindowsCheckbox() class MacFactory(GuiFactory): def create_button(self): return MacButton() def create_checkbox(self): return MacCheckbox() ## buttons class WindowsButton(Button): def paint(self): return 'Painting a windows button' class MacButton(Button): def paint(self): return 'Painting a macos button' # Checkboxes class WindowsCheckbox(Checkbox): def paint(self): return super().paint() class MacCheckbox(Checkbox): def paint(self): return super().paint() class App: def __init__(self, factory : GuiFactory): self.factory = factory self.button : Button self.checkbox : Checkbox def create_UI(self): self.button = self.factory.create_button() def paint(self): return self.button.paint() def create_checkbox(self): self.checkbox = self.factory.create_checkbox() def create_app(**config_file): factory : GuiFactory if config_file.get('OS', '').lower() == "windows": factory = WindowsFactory() elif config_file.get('OS', '').lower() == "mac": factory = MacFactory() else: raise NotImplementedError('No factory implemented for OS ', config_file.get('OS', 'no OS passed')) return App(factory=factory)
<!DOCTYPE html> <html lang="pt-br"> <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>Matchup</title> <img id="logo" src="./img/logo.png"> <!-- Link do css --> <link rel="stylesheet" type="text/css" href="style.css"> <!-- Bootstrap 5 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- Icone da janela do computador --> <link rel="shortcut icon" href="imagens/logo2.png" type="image/x-icon"> <!-- Icone Bootstrap 5 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.8.1/font/bootstrap-icons.min.css" /> <!-- Fonte - Century --> <link rel="stylesheet" href="https://use.typekit.net/oov2wcw.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/fontawesome.min.css" integrity="sha384-zIaWifL2YFF1qaDiAo0JFgsmasocJ/rqu7LKYH8CoBEXqGbb9eO+Xi3s6fQhgFWM" crossorigin="anonymous"> <style> h2 { color: white; } .login-box { background-color: rgb(120, 149, 203); padding: 40px; border-radius: 10px; } /* Adiciona margem abaixo do h2 (Login) */ h2 { margin-bottom: 20px; } .input-field input { width: 100%; /* Define a largura como 100% */ padding: 5px; /* Adiciona um espaçamento interno */ box-sizing: border-box; /* Garante que o padding não aumenta a largura total */ } /* Adiciona espaçamento abaixo do input-field (campos de entrada) */ .input-field { margin-bottom: 5px; } .form-group button { margin-top: 5px; margin-bottom: 10px; background-color: rgb(74, 85, 162); /* Cor de fundo vermelha */ color: white; /* Cor do texto branca */ border-radius: 10px; /* Borda arredondada */ padding: 5px 10px; /* Espaçamento interno do botão */ cursor: pointer; /* Muda o cursor ao passar sobre o botão */ } .login-box a { color: white; /* Cor do texto branca */ } </style> </head> <body> <div id="container-login"> <div id="conteudo-login"> <div id="banner-login"> </div> <div class="login-box"> <!-- Conteúdo da caixa no centro --> <h2>Login</h2> <div class="input-field"> <input type="text" name="email" id="loginEmail" placeholder="Email"> </div> <div class="input-field"> <input type="password" name="senha" id="loginSenha" placeholder="Senha"> </div> <div class="form-group"> <button onclick="login()">Entrar</button> </div> <p><a href="cadastro.html">Não possui uma conta? Faça o cadastro!</a> </p> </div> </div> </div> <script> function login() { const email = document.getElementById("loginEmail").value; const password = document.getElementById("loginSenha").value; try { fetch("/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }).then(response => { if(response.status>0) { localStorage.setItem('userid',response.status); alert("Login successful!"); window.location.href = "index.html"; } else { alert("Login failed. Please try again."); } }) .catch(error => { alert("An error occurred during registration: " + error); }); } catch (error) { console.error("An error occurred:", error); } } </script> </body> </html>
import * as React from "react"; import Fill from "./Fill"; import Manager, { Component, SlotFillContext } from "./Manager"; export interface Props { /** * The name of the component. Use a symbol if you want to be 100% sue the Slot * will only be filled by a component you create */ name: string | Symbol; /** * Props to be applied to the child Element of every fill which has the same name. * * If the value is a function, it must have the following signature: * (target: Fill, fills: Fill[]) => void; * * This allows you to access props on the fill which invoked the function * by using target.props.something() */ fillChildProps?: { [key: string]: any }; children?: React.ReactNode; } export interface State { components: Component[]; } export interface Context { manager: Manager; } export default class Slot extends React.Component<Props, State> { static contextType = SlotFillContext; constructor(props: Props) { super(props); this.state = { components: [] }; this.handleComponentChange = this.handleComponentChange.bind(this); } UNSAFE_componentWillMount() { (this.context as React.ContextType<typeof SlotFillContext>).manager.onComponentsChange(this.props.name, this.handleComponentChange); } handleComponentChange(components: Component[]) { this.setState({ components }); } get fills(): Fill[] { return this.state.components.map(c => c.fill); } componentDidUpdate(prevProps: Props) { if (this.props.name !== prevProps.name) { (this.context as React.ContextType<typeof SlotFillContext>).manager .removeOnComponentsChange(this.props.name, this.handleComponentChange); const name = this.props.name; (this.context as React.ContextType<typeof SlotFillContext>).manager .onComponentsChange(name, this.handleComponentChange); } } componentWillUnmount() { const name = this.props.name; (this.context as React.ContextType<typeof SlotFillContext>).manager.removeOnComponentsChange(name, this.handleComponentChange); } render() { const aggElements: React.ReactNode[] = []; this.state.components.forEach((component, index) => { const { fill, children } = component; const { fillChildProps } = this.props; if (fillChildProps) { const transform = (acc: Record<string, any>, key: string) => { const value = fillChildProps[key]; if (typeof value === "function") { acc[key] = () => value(fill, this.fills); } else { acc[key] = value; } return acc; }; const fillChildProps2 = Object.keys(fillChildProps).reduce(transform, {}); const chilrenArray = React.Children.toArray(children); chilrenArray.forEach((child, index2) => { if (typeof child === "number" || typeof child === "string") { throw new Error("Only element children will work here"); } aggElements.push( React.cloneElement(child as React.ReactElement, { key: index.toString() + index2.toString(), ...fillChildProps2 }) ); }); } else { const chilrenArray = React.Children.toArray(children); chilrenArray.forEach((child, index2) => { if (typeof child === "number" || typeof child === "string") { throw new Error("Only element children will work here"); } aggElements.push( React.cloneElement(child as React.ReactElement, { key: index.toString() + index2.toString() }) ); }); } }); if (typeof this.props.children === "function") { const element = (this.props.children as Function)(aggElements); if (React.isValidElement(element) || element === null) { return element; } else { const untypedThis: any = this; const parentConstructor = untypedThis._reactInternalInstance._currentElement._owner._instance.constructor; const displayName = parentConstructor.displayName || parentConstructor.name; const message = "Slot rendered with function must return a valid React " + `Element. Check the ${displayName} render function.`; throw new Error(message); } } else { return aggElements; } } }
<script lang="ts"> import { defineComponent } from 'vue' import UserState from '@/components/UserState.vue' import LanguageSwitcher from '@/components/LanguageSwitcher.vue' import { i18nRoute } from '@/i18n/translation' export default defineComponent({ components: { userState: UserState, languageSwitcher: LanguageSwitcher, }, data() { return { menuItems: [ { href: '/', icon: 'mdi-home', name: 'home', }, { href: '/projects', icon: 'mdi-link', name: 'projects', }, ], drawer: false, } }, computed: { logoSrc() { const logo = import.meta.env.VITE_APP_LOGO return logo }, logoAlt() { const alt = import.meta.env.VITE_APP_NAME return alt }, }, methods: { i18nRoute, }, }) </script> <template> <v-app-bar color="secondary" flat> <v-app-bar-nav-icon class="hidden-md-and-up" @click.stop="drawer = !drawer" ></v-app-bar-nav-icon> <v-app-bar-title> <router-link to="/"> <v-img height="50" position="left center" :src="logoSrc" :alt="logoAlt" /> </router-link> </v-app-bar-title> <v-spacer /> <v-toolbar-items> <template v-for="(item, index) in menuItems" :key="index"> <v-btn :to="i18nRoute({ name: item.name })" class="hidden-sm-and-down" variant="text" large> {{ $t('appHeader.' + item.name) }} </v-btn> </template> <language-switcher /> <user-state /> </v-toolbar-items> </v-app-bar> <v-navigation-drawer v-model="drawer" temporary> <v-list v-for="(item, index) in menuItems" :key="index" density="compact" nav> <v-list-item :prepend-icon="item.icon" :title="$t('appHeader.' + item.name)" :to="i18nRoute({ name: item.name })" ></v-list-item> </v-list> </v-navigation-drawer> </template> <style scoped></style>
<script type="text/javascript"> function ajax(opts){ var xmlhttp = new XMLHttpRequest(); var dataStr = ''; for(var key in opts.data){ dataStr += key + '=' opts.data[key] + '&' } dataStr = dataStr.substr(0,dataStr.length-1); if(opts.type.toLowerCase()==='post'){ xmlhttp.open(opts.type,opts.url,true); xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded'); xmlhttp.send(dataStr); } if(opts.type.toLowerCase()==='get'){ xmlhttp.open(opts.type,opts.url+'?'+dataStr,true); xmlhttp.send(); } xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ var json = JSON.parse(xmlhttp.responseText); opts.success(json); } if(xmlhttp.readyState == 4 && xmlhttp.status ==404){ opts.error(); } }; } document.querySelector('#btn').addEventListener('click',function(){ ajax({ url: 'test.php', //接口地址 type:'get', //类型:post或者get data:{ username: document.querySelector('#username').value; }, success: function(jsonData){ dealWith(jsonData); //{status:o} }, error: function(){ console.log('出错了。。。') } }) }); function dealWith(jsonData){ var str = '<dt>性别:</dt>'; str += '<dd>'+ jsonData.sex +'</dd>'; str += '<dt>年龄:</dt>'; str += '<dd>'+ jsonData.age +'</dd>'; document.querySelector('#ct').innerHTML = str; }; </script>
import { AppBar, AppBarProps, styled } from '@mui/material'; import { drawerWidth } from '@/core/theme/constants'; import { theme } from '@/core/theme/theme'; interface StyledAppBarProps extends AppBarProps { open: boolean; } export const StyledAppBar = styled(AppBar, { shouldForwardProp: (prop) => prop !== 'open', })<StyledAppBarProps>(({ open }) => ({ backgroundColor: theme.palette.secondary.main, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { width: `calc(100% - ${drawerWidth}px)`, marginLeft: `${drawerWidth}px`, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }), }));
package com.codegym.task.task19.task1903; /* Adapting multiple interfaces */ import java.util.HashMap; import java.util.Map; public class Solution { public static Map<String, String> countries = new HashMap<>(); static { countries.put("UA", "Ukraine"); countries.put("US", "United States"); countries.put("FR", "France"); } public static void main(String[] args) { } public static class IncomeDataAdapter implements Customer, Contact { private IncomeData data; public IncomeDataAdapter(IncomeData incomeData) { this.data = incomeData; } @Override public String getCompanyName() { return data.getCompany(); } @Override public String getCountryName() { return countries.get(data.getCountryCode()); } @Override public String getName() { return data.getContactLastName() + ", " + data.getContactFirstName(); } @Override public String getPhoneNumber() { String phoneNumberTenDigits = String.format("%010d", data.getPhoneNumber()); String phoneNumberPart1 = "+" + data.getCountryPhoneCode(); String phoneNumberPart2 = phoneNumberTenDigits.substring(0,3); String phoneNumberPart3 = phoneNumberTenDigits.substring(3,6); String phoneNumberPart4 = phoneNumberTenDigits.substring(6,8); String phoneNumberPart5 = phoneNumberTenDigits.substring(8,10); String fullFormatedPhoneNumber = String.format("%s(%s)%s-%s-%s", phoneNumberPart1, phoneNumberPart2, phoneNumberPart3, phoneNumberPart4, phoneNumberPart5); return fullFormatedPhoneNumber; } } public static interface IncomeData { String getCountryCode(); // For example: US String getCompany(); // For example: CodeGym Ltd. String getContactFirstName(); // For example: John String getContactLastName(); // For example: Smith int getCountryPhoneCode(); // For example: 1 int getPhoneNumber(); // For example: 991234567 } public static interface Customer { String getCompanyName(); // For example: CodeGym Ltd. String getCountryName(); // For example: United States } public static interface Contact { String getName(); // For example: Smith, John String getPhoneNumber(); // For example: +1(099)123-45-67 } }
import {readFileSync} from "fs"; const RE = { ore: /^Each ore robot costs (\d*) ore$/g, clay: /^Each clay robot costs (\d*) ore/g, obsidian: /^Each obsidian robot costs (\d*) ore and (\d*) clay$/g, geode: /^Each geode robot costs (\d*) ore and (\d*) obsidian/g, }; const ROBOTS = ["ore", "clay", "obsidian", "geode"]; const resources = Object.fromEntries(ROBOTS.map(name => [name, 0])); const blueprints = readFileSync("real.input", {encoding: "utf-8"}) .split("\n") .slice(0, -1) .map(blueprint => blueprint.split(":")[1].slice(1).split(".").slice(0, -1).map(robot => robot.trim())) .map(([ore, clay, obsidian, geode]) => ({ ore: +[...ore.matchAll(RE.ore)][0][1], clay: +[...clay.matchAll(RE.clay)][0][1], obsidian: [...obsidian.matchAll(RE.obsidian)][0].slice(1, 3).map(Number), geode: [...geode.matchAll(RE.geode)][0].slice(1, 3).map(Number), })) .map(({ore, clay, obsidian, geode}) => ({ ore: {...resources, ore}, clay: {...resources, ore: clay}, obsidian: {...resources, ore: obsidian[0], clay: obsidian[1]}, geode: {...resources, ore: geode[0], obsidian: geode[1]}, })); const State = class { constructor({resources, blueprint, robots, minutes}) { this.resources = resources; this.blueprint = blueprint; this.robots = robots; this.minutes = minutes; } construct(robot) { const {resources, robots, blueprint, minutes} = this; return { ...this.idle(), resources: Object.fromEntries(ROBOTS.map(name => [name, resources[name] - blueprint[robot][name] + robots[name]])), robots: {...robots, [robot]: robots[robot] + 1}, }; } idle() { const {resources, robots, blueprint, minutes} = this; return { robots, blueprint, minutes: minutes - 1, resources: Object.fromEntries(ROBOTS.map(name => [name, resources[name] + robots[name]])), }; } constructible(robot) { const {resources, blueprint} = this; return ROBOTS.slice(0, 3).map(name => resources[name] - blueprint[robot][name]).every(cost => cost >= 0); }; next() { return [new State(this.idle())].concat(ROBOTS .filter(robot => this.constructible(robot)) .map(robot => new State({...this.construct(robot)}))); } assess() { const {resources, robots, minutes} = this; return (resources.geode + minutes * robots.geode) * 10 ** 3 + robots.obsidian * 10 ** 2 + robots.clay * 10 + robots.ore; } }; const start = (minutes, config) => { let states = [new State({...config, minutes})]; for (let minute = minutes; minute > 0; minute--) { const next = []; for (const state of states) { next.push(...state.next()); } states = next.sort((a, b) => b.assess() - a.assess()).slice(0, 10000); } return states .sort((a, b) => b.resources.geode - a.resources.geode)[0].resources.geode; } const part1 = (config, blueprints) => blueprints.reduce((sum, blueprint, i) => sum + start(24, {...config, blueprint}) * (i + 1), 0); const part2 = (config, blueprints) => blueprints.reduce((sum, blueprint, i) => sum * start(32, {...config, blueprint}), 1); const robots = {ore: 1, clay: 0, obsidian: 0, geode: 0}; console.log("part 1", part1({resources, robots}, blueprints)); console.log("part 2", part2({resources, robots}, blueprints.slice(0, 3)));
// import { useState } from 'react'; import './App.css'; import {Header, Footer} from './components/index.js'; import {About, Home, NotFound, ProductDetail, ProductId, Products, Profile, Reviews, Login, Register} from './routes/index.js' import AppLayout from './layouts/AppLayout.js'; // import DarkThemeContext from './context/DarkThemeContext.js'; import { DarkThemeContextProvider } from './context/DarkThemeContext.js'; import StarRatingLayer from './components/StarRating/StarRatingLayer.js'; import SidebarLayer from './components/Sidebar/SidebarLayer.js'; import { NavLink, Outlet, Route, Routes } from 'react-router-dom'; import ProductsLayout from './layouts/ProductsLayout.js'; // 3. function App_backup01() { return ( <DarkThemeContextProvider> <AppLayout> <Header /> <Routes> {/* localhost:3000/ localhost:3000/home localhost:3000/about localhost:3000/products localhost:3000/products/:id localhost:3000/products/:id/productDetail/:name localhost:3000/products/productDetail/:name localhost:3000/products/reviews localhost:3000/profile */} <Route path='/' element={<Home />}/> <Route path='/home' element={<Home />}/> {/* 중첩 라우트 */} <Route path='/products' element={<ProductsLayout />}> <Route index element={<Products />}/> <Route path=':id' element={<ProductId />}/> <Route path='product-detail' element={<ProductDetail />}/> <Route path='reviews' element={<Reviews />}/> </Route> {/* ? 뒤는 쿼리 */} {/* localhost:3000/product/reviews?name=kim&age=30 */} <Route path='/login' element={<Login />}/> <Route path='/register' element={<Register />}/> <Route path='/about' element={<About />}/> <Route path='/profile' element={<Profile />}/> <Route path='*' element={<NotFound />}/> </Routes> <Footer /> </AppLayout> </DarkThemeContextProvider> ); } // 이전작업 백업(props 방법 사용) // props.children // 저 쌍으로 이루어진 태그 사이의 내용(사과)가 children이다. // home에 보냈으면 home에서 받아서 쓴다. // function App() { // const [isDark, setIsDark] = useState(false); // return ( // <DarkThemeContext.Provider value={{isDark, setIsDark}}> // <AppLayout> // <Header isDark={isDark} setIsDark={setIsDark} /> // <Home isDark={isDark}> // <h1> 사과는 </h1> // <p> 새빨간 </p> // <div> 색입니다. </div> // </Home> // <Footer isDark={isDark} /> // </AppLayout> // </DarkThemeContext.Provider> // ); // } // 2. context 방법 사용 // function App() { // // const [isDark, setIsDark] = useState(false); // return ( // <DarkThemeContext.Provider value={{isDark, setIsDark}}> // <AppLayout> // <Header /> // <Home> // <h1> 사과는 </h1> // <p> 새빨간 </p> // <div> 색입니다. </div> // </Home> // <Footer /> // </AppLayout> // </DarkThemeContext.Provider> // ); // } export default App_backup01;
import 'package:flutter/material.dart'; import 'package:siskom_tv_dosen/cubit/manage_cubit.dart'; import 'package:siskom_tv_dosen/pages/login_page.dart'; import 'package:siskom_tv_dosen/theme.dart'; import 'package:siskom_tv_dosen/widgets/custom_form.dart'; import 'package:siskom_tv_dosen/widgets/identity_tile.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; List<String> list = <String>['ADA', 'TIDAK ADA', 'LIBUR', 'TUGAS BELAJAR']; class ProfilePage extends StatefulWidget { const ProfilePage({super.key}); @override State<ProfilePage> createState() => _ProfilePageState(); } class _ProfilePageState extends State<ProfilePage> { @override void initState() { context.read<ManageCubit>().getProfile(); super.initState(); } TextEditingController nameC = TextEditingController(); String dropdownValue = list.first; @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( body: SafeArea( child: RefreshIndicator( onRefresh: () async { context.read<ManageCubit>().getProfile(); }, child: ListView( padding: const EdgeInsets.symmetric(horizontal: 20), children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: size.width * 0.05, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Container( width: 67, height: 67, padding: EdgeInsets.all(6), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: Color(0xffEAEAF0)), ), child: Center( child: ClipRRect( borderRadius: BorderRadius.circular(60), child: BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return FadeInImage( width: double.infinity, height: double.infinity, fit: BoxFit.cover, placeholder: const AssetImage( 'assets/logo-untan.png', ), image: NetworkImage( '${state.profileModel?.data?.image}', ), ); } return Image.asset('assets/logo-untan.png'); }, ), ), ), ), const SizedBox( width: 10, ), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return Flexible( child: Container( width: size.width * 0.52, child: Text( '${state.profileModel?.data?.name ?? 'loading...'}', overflow: TextOverflow.ellipsis, style: blackTextStyle.copyWith( fontWeight: semiBold, fontSize: 16), ), ), ); } return Text( 'loading...', style: blackTextStyle.copyWith( fontWeight: semiBold, fontSize: 16), ); }, ), BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return Text( '${state.profileModel?.data?.user?.email ?? 'loading...'}', style: greyTextStyleB.copyWith(fontSize: 14), ); } return Text( 'loading...', style: greyTextStyleB.copyWith(fontSize: 14), ); }, ), ], ), ], ), IconButton( onPressed: () { showDialog( barrierDismissible: false, context: context, builder: (context) => AlertDialog( title: Center( child: Text( 'Edit Nama', style: blackTextStyle.copyWith( fontWeight: semiBold, fontSize: 15), ), ), content: CustomTextFormField( labelText: 'Nama', hintText: 'Masukkan nama kamu', keyboardType: TextInputType.emailAddress, controller: nameC, action: TextInputAction.done, ), contentPadding: EdgeInsets.fromLTRB(20, 20, 20, 0), actionsPadding: EdgeInsets.fromLTRB(20, 0, 20, 10), actions: [ Row( children: [ Flexible( flex: 1, child: SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.red, padding: EdgeInsets.symmetric( vertical: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( 7))), onPressed: () { Navigator.pop(context); }, child: Text( 'Batal', style: whiteTextStyle.copyWith( fontWeight: semiBold, fontSize: 13), ), ), ), ), SizedBox( width: 10, ), Flexible( flex: 1, child: SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.green, padding: EdgeInsets.symmetric( vertical: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( 7))), onPressed: () { context .read<ManageCubit>() .changeName(nameC.text); }, child: BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is UpdateLoading) { return Center( child: SizedBox( width: 14, height: 14, child: CircularProgressIndicator( color: whiteC, ), ), ); } else if (state is UpdateSuccess) { Navigator.pop(context); WidgetsBinding.instance .addPostFrameCallback((_) { nameC.clear(); ScaffoldMessenger.of(context) .showSnackBar( SnackBar( backgroundColor: Colors.green, content: Text( 'Nama berhasil diperbarui'), ), ); }); context .read<ManageCubit>() .getProfile(); } return Text( 'Submit', style: whiteTextStyle.copyWith( fontWeight: semiBold, fontSize: 13), ); }, ), ), ), ), ], ), ], ), ); }, icon: Icon(Icons.edit), ) ], ), SizedBox( height: 8, ), Divider( color: greyTextC, ), SizedBox( height: 10, ), Text( 'Identitas', style: blackTextStyle.copyWith( fontWeight: semiBold, fontSize: 16), ), BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return IdentityTile( name: '${state.profileModel?.data?.position ?? 'loading...'}', title: 'Jabatan', icon: Icons.account_circle_outlined, ); } return IdentityTile( name: 'loading...', title: 'Jabatan', icon: Icons.account_circle_outlined, ); }, ), BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return IdentityTile( name: '${state.profileModel?.data?.nip ?? 'loading...'}', title: 'NIP', icon: Icons.account_circle_outlined, ); } return IdentityTile( name: 'loading...', title: 'NIP', icon: Icons.account_circle_outlined, ); }, ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Icon( Icons.check_box_outlined, size: 32, ), SizedBox( width: 10, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Status', style: blackTextStyle.copyWith( fontSize: 13, ), ), BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return Text( '${state.profileModel?.data?.status ?? 'loading...'}', style: greyTextStyleB, ); } return Text( 'loading...', style: greyTextStyleB, ); }, ) ], ), ], ), Container( child: IconButton( onPressed: () { showDialog( barrierDismissible: false, context: context, builder: (context) => StatefulBuilder( builder: (context, setState) { return AlertDialog( title: Center( child: Text( 'Edit Status', style: blackTextStyle.copyWith( fontWeight: semiBold, fontSize: 15), ), ), content: DropdownButton<String>( value: dropdownValue, hint: BlocBuilder<ManageCubit, ManageState>( builder: (context, state) { if (state is ProfileSucccess) { return Text( '${state.profileModel?.data?.status ?? 'loading...'}', style: greyTextStyleB, ); } return Text( 'loading...', style: greyTextStyleB, ); }, ), icon: const Icon(Icons.arrow_downward), elevation: 16, style: const TextStyle( color: Colors.deepPurple), underline: Container( height: 2, color: Colors.deepPurpleAccent, ), onChanged: (String? value) { setState(() { dropdownValue = value!; }); }, items: list .map<DropdownMenuItem<String>>( (String value) { return DropdownMenuItem<String>( value: value, child: Text( value, style: blackTextStyle, ), ); }).toList(), ), contentPadding: const EdgeInsets.fromLTRB( 20, 20, 20, 0), actionsPadding: const EdgeInsets.fromLTRB( 20, 0, 20, 10), actions: [ Row( children: [ Flexible( flex: 1, child: SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton .styleFrom( backgroundColor: Colors.red, padding: const EdgeInsets .symmetric( vertical: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius .circular(7), ), ), onPressed: () { Navigator.pop(context); }, child: Text( 'Batal', style: whiteTextStyle .copyWith( fontWeight: semiBold, fontSize: 13), ), ), ), ), const SizedBox( width: 10, ), Flexible( flex: 1, child: SizedBox( width: double.infinity, child: ElevatedButton( style: ElevatedButton .styleFrom( backgroundColor: Colors.green, padding: const EdgeInsets .symmetric( vertical: 12), shape: RoundedRectangleBorder( borderRadius: BorderRadius .circular(7), ), ), onPressed: () { context .read<ManageCubit>() .changeStatus( dropdownValue); print(dropdownValue); }, child: BlocBuilder< ManageCubit, ManageState>( builder: (context, state) { if (state is ChangeLoading) { return Center( child: SizedBox( width: 14, height: 14, child: CircularProgressIndicator( color: whiteC, ), ), ); } else if (state is ChangeSuccess) { Navigator.pop( context); WidgetsBinding .instance .addPostFrameCallback( (_) { ScaffoldMessenger .of(context) .showSnackBar( const SnackBar( backgroundColor: Colors .green, content: Text( 'Status berhasil diperbarui'), ), ); }); context .read< ManageCubit>() .getProfile(); } return Text( 'Submit', style: whiteTextStyle .copyWith( fontWeight: semiBold, fontSize: 13), ); }, ), ), ), ), ], ), ], ); })); }, icon: Icon(Icons.edit), ), ), ], ), SizedBox( height: 20, ), Divider( color: greyTextC, ), const SizedBox( height: 20, ), BlocConsumer<ManageCubit, ManageState>( listener: (context, state) { if (state is LogoutFailed) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.red, content: Text(state.message), ), ); } else if (state is LogoutSuccess) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => LoginPage()), (route) => false); } }, builder: (context, state) { if (state is LogoutLoading) { return Center( child: CircularProgressIndicator( color: Colors.black, ), ); } return GestureDetector( onTap: () { context.read<ManageCubit>().logout(); }, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( children: [ const Icon( Icons.logout, size: 32, ), const SizedBox( width: 10, ), Text( 'Logout', style: blackTextStyle.copyWith( fontSize: 16, fontWeight: semiBold, ), ) ], ), Text( 'Version 1.0.0', style: greyTextStyleB.copyWith(fontSize: 10), ) ], ), ); }, ), ], ), ], ), ), ), ); } }
import React,{Component} from 'react'; import {Table} from 'react-bootstrap'; import {Button,ButtonToolbar} from 'react-bootstrap'; import {AddNewWorker} from './AddNewWorker.js'; import {EditWorker} from './EditWorker.js' import { TestWorker } from './TestWorker.js'; export class WorkerSetup extends Component{ constructor(props){ super(props); this.state={workers:[], addModalShow:false, editModalShow:false, testWorker:{_show:false,_ID:"",_IP:""}} } refreshList(){ fetch(process.env.REACT_APP_API +'worker/') .then(response=>response.json()) .then(data=>{ this.setState({workers:data}); }); } componentDidMount(){ this.refreshList(); } componentDidUpdate(){ this.refreshList(); } deleteWorker(worker_id){ if(window.confirm('Are you sure?')){ fetch(process.env.REACT_APP_API+'worker/',{ method:'DELETE', header:{'Accept':'application/json', 'Content-Type':'application/json'}, body:JSON.stringify({ id:worker_id })}) } } send_test_request(event, worker_id){ event.preventDefault(); fetch(process.env.REACT_APP_API +'test-worker/', { method:'POST', headers:{ 'Accept':'application/json', 'Content-Type':'application/json' }, body:JSON.stringify({ id:worker_id }) }) .then(response=>response.json()) .then( data=>this.setState({testWorker:{ _show:true, _IP:this.state.testWorker._IP, _name:this.state.testWorker._name, _response:data }}) ); } render(){ const {workers, worker_id, worker_name, worker_ip, worker_rqmpass}=this.state; let addModalClose=()=>this.setState({addModalShow:false}); let editModalClose=()=>this.setState({editModalShow:false}); let testWorkerClose=()=>this.setState({testWorker:{_show:false,_name:"",_IP:"",_response:""}}); return( <div className="container"> <Table className="mt-4" striped bordered hover size="sm"> <thead> <tr> <th>Worker ID</th> <th>Name</th> <th>IP</th> <th>Options</th> </tr> </thead> <tbody> {workers.map(worker=> <tr key={worker.WorkerID}> <td>{worker.WorkerID}</td> <td>{worker.WorkerName}</td> <td>{worker.WorkerIP}</td> <td> <ButtonToolbar> <Button className="mr-2" variant="info" onClick= { () => this.setState({ editModalShow:true, worker_id: worker.WorkerID, worker_name: worker.WorkerName, worker_ip: worker.WorkerIP, worker_rqmpass: worker.RmqPassword }) } > Edit </Button> <Button className="mr-2" variant="danger" onClick={()=>this.deleteWorker(worker.WorkerID)}> Delete </Button> <Button className="mr-2" variant="success" onClick={ (event) => { this.setState({ testWorker:{ _show:true, _IP:worker.WorkerIP, _name:worker.WorkerName, _response:"Waiting the worker for responding ..." }}); this.send_test_request(event, worker.WorkerID) } }> Test </Button> <EditWorker show={this.state.editModalShow} onHide={editModalClose} workerID={worker_id} workerName={worker_name} workerIP={worker_ip} workerRmqPass={worker_rqmpass} /> </ButtonToolbar> </td> </tr>)} </tbody> </Table> <TestWorker show={this.state.testWorker._show} onHide={testWorkerClose} workerIP={this.state.testWorker._IP} workerName={this.state.testWorker._name} response={this.state.testWorker._response} /> <ButtonToolbar> <Button variant='primary' onClick={()=>this.setState({addModalShow:true})} > Add New Worker </Button> <AddNewWorker show={this.state.addModalShow} onHide={addModalClose} /> </ButtonToolbar> </div> ); } }
import { Splide, SplideSlide, SplideTrack } from '@splidejs/react-splide'; import { BiCaretRight } from 'react-icons/bi'; import '@splidejs/react-splide/css'; import '../../../styles/Carousel.module.css'; import Link from 'next/link'; const Carousel = () => { return ( <div className="px-2 pt-4 md:px-6"> <Splide hasTrack={false} aria-label="Attribution" options={{ type: 'loop', perPage: 1, heightRatio: 0.8, mediaQuery: 'min', breakpoints: { 640: { heightRatio: 0.35, perPage: 1, gap: 20, }, }, pagination: true, }} className="container mx-auto px-8 bg-yellow-300 rounded-3xl" > <SplideTrack hasTrack={false}> <SplideSlide className="w-full"> <div className="bg-yellow-300 h-full flex md:justify-center items-center md:pl-12 gap-10"> <div className="flex flex-col md:gap-7 gap-2"> <div className="space-y-3"> <h1 className="text-2xl md:text-4xl font-semibold"> Envoyez de l’argent pour la santé de vos proches sans payer de frais </h1> {/* <p className="text-xs md:text-sm text-gray-700 w-full flex"> Gagnez une somme de 5$ pour votre première achat de passe santé WiiQare. </p> */} </div> <Link href={'https://wiiqare.com/how-it-works'} target='_blank' legacyBehavior> <a className="bg-gray-800 w-fit p-3 text-yellow-300 rounded-lg text-xs md:text-md"> Comment ça marche </a> </Link> </div> <div className="hidden justify-end md:w-full md:flex"> <img src="https://i.goopics.net/otvw2n.png" className="object-cover" alt="Wallet" /> </div> </div> </SplideSlide> <SplideSlide className="w-full"> <div className="bg-yellow-300 h-full flex md:justify-center md:pl-12"> <div className="flex flex-col justify-center md:gap-7 gap-2"> <div className="space-y-3"> <h1 className="text-2xl md:text-4xl font-semibold"> Envoyez de l’argent pour la santé de vos proches sans payer de frais </h1> {/* <p className="text-xs md:text-sm text-gray-700 w-full flex"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem </p> */} </div> <Link href={'https://wiiqare.com/how-it-works'} target='_blank' legacyBehavior> <a className="bg-gray-800 w-fit p-3 text-yellow-300 rounded-lg text-xs md:text-md"> Comment ça marche </a> </Link> </div> <div className="hidden md:w-full md:flex justify-end "> <img src="https://i.goopics.net/4kdqe7.png" className="object-cover" alt="Startup" /> </div> </div> </SplideSlide> <SplideSlide className="w-full"> <div className="bg-yellow-300 h-full flex md:justify-center md:pl-12 gap-10"> <div className="flex flex-col justify-center md:gap-7 gap-2"> <div className="space-y-3"> <h1 className="text-2xl md:text-4xl font-semibold"> Connecter vos proches aux meilleurs professionnels de santé </h1> {/* <p className="text-xs md:text-sm text-gray-700 w-full flex"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem </p> */} </div> <Link href={'https://wiiqare.com/second-opinion'} legacyBehavior> <a className="bg-gray-800 w-fit p-3 text-yellow-300 rounded-lg text-xs md:text-md"> Consulter </a> </Link> </div> <div className="hidden md:w-full md:flex justify-end relative -bottom-4 "> <img src="https://i.goopics.net/dlqbsx.png" className="object-cover" alt="Phone" /> </div> </div> </SplideSlide> <SplideSlide className="w-full"> <div className="bg-yellow-300 h-full flex md:justify-center md:pl-12 gap-10"> <div className="flex flex-col justify-center md:gap-7 gap-2"> <div className="space-y-3"> <h1 className="text-2xl md:text-4xl font-semibold"> Demander un second opinion aux professionnels de santé </h1> {/* <p className="text-xs md:text-sm text-gray-700 w-full flex"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem Adipisci, beatae nam eveniet hic nesciunt explicabo dolore quidem </p> */} </div> <Link href={'https://wiiqare.com/second-opinion'} legacyBehavior> <a className="bg-gray-800 w-fit p-3 text-yellow-300 rounded-lg text-xs md:text-md"> Consulter </a> </Link> </div> <div className="hidden md:w-full md:flex justify-end relative -bottom-4 "> <img src="https://i.goopics.net/jej08g.png" className="object-cover" alt="Phone" /> </div> </div> </SplideSlide> </SplideTrack> <div className="splide__arrows"> <button className="splide__arrow splide__arrow--prev bg-transparent relative !-left-7 top-2 bottom-0 !bg-[#F0F4FD] p-4 text-3xl focus:ring-0"> <span className="bg-white rounded-full p-1 !text-red-500"> <BiCaretRight /> </span> </button> <button className="splide__arrow splide__arrow--next bg-transparent relative !-right-7 top-2 bottom-0 !bg-[#F0F4FD] p-4 text-3xl focus:ring-0"> <span className="bg-white rounded-full p-1 !text-red-500"> <BiCaretRight /> </span> </button> </div> </Splide> </div> ); }; export default Carousel;
import re import pytest import pandas as pd from pandas import ( DataFrame, Index, Series, Timestamp, date_range, ) import pandas._testing as tm class TestDatetimeIndex: def test_get_loc_naive_dti_aware_str_deprecated(self): # GH#46903 ts = Timestamp("20130101")._value dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)]) ser = Series(range(100), index=dti) key = "2013-01-01 00:00:00.000000050+0000" msg = re.escape(repr(key)) with pytest.raises(KeyError, match=msg): ser[key] with pytest.raises(KeyError, match=msg): dti.get_loc(key) def test_indexing_with_datetime_tz(self): # GH#8260 # support datetime64 with tz idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") dr = date_range("20130110", periods=3) df = DataFrame({"A": idx, "B": dr}) df["C"] = idx df.iloc[1, 1] = pd.NaT df.iloc[1, 2] = pd.NaT expected = Series( [Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT], index=list("ABC"), dtype="object", name=1, ) # indexing result = df.iloc[1] tm.assert_series_equal(result, expected) result = df.loc[1] tm.assert_series_equal(result, expected) def test_indexing_fast_xs(self): # indexing - fast_xs df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")}) result = df.iloc[5] expected = Series( [Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], index=["a"], name=5, dtype="M8[ns, UTC]", ) tm.assert_series_equal(result, expected) result = df.loc[5] tm.assert_series_equal(result, expected) # indexing - boolean result = df[df.a > df.a[3]] expected = df.iloc[4:] tm.assert_frame_equal(result, expected) def test_consistency_with_tz_aware_scalar(self): # xef gh-12938 # various ways of indexing the same tz-aware scalar df = Series([Timestamp("2016-03-30 14:35:25", tz="Europe/Brussels")]).to_frame() df = pd.concat([df, df]).reset_index(drop=True) expected = Timestamp("2016-03-30 14:35:25+0200", tz="Europe/Brussels") result = df[0][0] assert result == expected result = df.iloc[0, 0] assert result == expected result = df.loc[0, 0] assert result == expected result = df.iat[0, 0] assert result == expected result = df.at[0, 0] assert result == expected result = df[0].loc[0] assert result == expected result = df[0].at[0] assert result == expected def test_indexing_with_datetimeindex_tz(self, indexer_sl): # GH 12050 # indexing on a series with a datetimeindex with tz index = date_range("2015-01-01", periods=2, tz="utc") ser = Series(range(2), index=index, dtype="int64") # list-like indexing for sel in (index, list(index)): # getitem result = indexer_sl(ser)[sel] expected = ser.copy() if sel is not index: expected.index = expected.index._with_freq(None) tm.assert_series_equal(result, expected) # setitem result = ser.copy() indexer_sl(result)[sel] = 1 expected = Series(1, index=index) tm.assert_series_equal(result, expected) # single element indexing # getitem assert indexer_sl(ser)[index[1]] == 1 # setitem result = ser.copy() indexer_sl(result)[index[1]] = 5 expected = Series([0, 5], index=index) tm.assert_series_equal(result, expected) def test_nanosecond_getitem_setitem_with_tz(self): # GH 11679 data = ["2016-06-28 08:30:00.123456789"] index = pd.DatetimeIndex(data, dtype="datetime64[ns, America/Chicago]") df = DataFrame({"a": [10]}, index=index) result = df.loc[df.index[0]] expected = Series(10, index=["a"], name=df.index[0]) tm.assert_series_equal(result, expected) result = df.copy() result.loc[df.index[0], "a"] = -1 expected = DataFrame(-1, index=index, columns=["a"]) tm.assert_frame_equal(result, expected) def test_getitem_str_slice_millisecond_resolution(self, frame_or_series): # GH#33589 keys = [ "2017-10-25T16:25:04.151", "2017-10-25T16:25:04.252", "2017-10-25T16:50:05.237", "2017-10-25T16:50:05.238", ] obj = frame_or_series( [1, 2, 3, 4], index=[Timestamp(x) for x in keys], ) result = obj[keys[1] : keys[2]] expected = frame_or_series( [2, 3], index=[ Timestamp(keys[1]), Timestamp(keys[2]), ], ) tm.assert_equal(result, expected) def test_getitem_pyarrow_index(self, frame_or_series): # GH 53644 pytest.importorskip("pyarrow") obj = frame_or_series( range(5), index=date_range("2020", freq="D", periods=5).astype( "timestamp[us][pyarrow]" ), ) result = obj.loc[obj.index[:-3]] expected = frame_or_series( range(2), index=date_range("2020", freq="D", periods=2).astype( "timestamp[us][pyarrow]" ), ) tm.assert_equal(result, expected)
<!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>Document</title> <style> body{ max-width: 800px; margin: 0 auto; border: 2px solid forestgreen; } h1{ font-size: 7vw; } .tiger img{ width: 100%; } .container-two{ display: flex; } .container-two .split{ width: 50%; } .split img{ width: 100%; } @media screen and ( max-width:576px) { .container-two{ /* flex-direction: column; */ flex-direction: column-reverse; } .container-two .split{ width: 100%; } } </style> </head> <body> <section> <h1> My responsive Website</h1> </section> <section class="tiger"> <h3> Tiger</h3> <img src="images/tiger-2.jpg" alt=""> </section> <section> <h2> Two parts</h2> <div class="container-two"> <div class="split"><img src="images/food.jpg" alt=""></div> <div class="split"><img src="images/tiger.jpg" alt=""></div> </div> </section> <!-- 1.viewport tag 2.CSS Relative units 3. responsive image ( fluid image) 4. Body max-width and margin auto --> </body> </html>
import React, { useState, useEffect } from "react"; import { View, Text, StyleSheet, Image, TextInput, TouchableOpacity, Alert, KeyboardAvoidingView, Platform, ScrollView, Keyboard } from "react-native"; import { useAuth } from "../context/AuthContext"; // Make sure the path is correct import { useRouter } from "expo-router"; import { useServerUrl } from "../context/ServerUrlContext"; // Make sure the path is correct import Colors from "@/constants/Colors"; // Ensure you have this path const Login = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [username, setUsername] = useState(''); const [isLogin, setIsLogin] = useState(true); // State to track login or signup const [keyboardPadding, setKeyboardPadding] = useState(0); // State for keyboard padding const { login, user } = useAuth(); const router = useRouter(); const serverUrl = useServerUrl(); // Using the server URL from the context useEffect(() => { const showSubscription = Keyboard.addListener("keyboardDidShow", () => { setKeyboardPadding(100); // Adds an extra 100 pixels of padding when the keyboard is shown }); const hideSubscription = Keyboard.addListener("keyboardDidHide", () => { setKeyboardPadding(0); // Removes the padding when the keyboard is hidden }); return () => { showSubscription.remove(); hideSubscription.remove(); }; }, []); const handleSubmit = async () => { try { if (isLogin) { await handleLogin(); } else { await handleSignup(); } } catch (error) { Alert.alert("Error", error instanceof Error ? error.message : "An unknown error occurred"); } }; const handleLogin = async () => { const response = await fetch(`${serverUrl}/backend/loginUser`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }); const result = await response.json(); if (response.ok) { console.log("Login successful, user ID:", result.user_id); await login(email, password); if (user) { router.navigate('/(tabs)'); } } else { Alert.alert("Login failed", result.error || "Invalid credentials"); } }; const handleSignup = async () => { const response = await fetch(`${serverUrl}/backend/sign_up_user`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, email, password }), }); const result = await response.json(); if (response.ok) { console.log("Signup successful, new user ID:", result.user_id); await login(email, password); if (user) { router.navigate('/(tabs)'); } } else { Alert.alert("Signup failed", result.error || "Could not create user"); } }; const toggleMode = () => { setIsLogin(prevState => !prevState); }; return ( <ScrollView contentContainerStyle={styles.scrollView}> <KeyboardAvoidingView style={[styles.container, { marginBottom: keyboardPadding }]} behavior={Platform.OS === "ios" ? "padding" : "height"} > <View style={styles.logoContainer}> <Image source={require("@/assets/images/logowhite.png")} style={styles.logoStyle} /> </View> {isLogin ? null : ( <View> <TextInput value={username} onChangeText={setUsername} autoCapitalize="none" placeholder="Username" style={styles.inputBox} /> </View> )} <TextInput value={email} onChangeText={setEmail} autoCapitalize="none" placeholder="Email Address" style={styles.inputBox} /> <TextInput value={password} onChangeText={setPassword} autoCapitalize="none" placeholder="Password" secureTextEntry style={styles.inputBox} /> <TouchableOpacity style={styles.loginButton} onPress={handleSubmit}> <Text style={styles.buttonText}>{isLogin ? 'Log in' : 'Sign up'}</Text> </TouchableOpacity> <TouchableOpacity onPress={toggleMode}> <Text style={styles.toggleText}>{isLogin ? 'Switch to Sign up' : 'Switch to Log in'}</Text> </TouchableOpacity> </KeyboardAvoidingView> </ScrollView> ); }; const styles = StyleSheet.create({ scrollView: { flexGrow: 1, justifyContent: 'center', paddingBottom: 20, backgroundColor: Colors.background, }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: Colors.background, marginTop: -50, // Shit UI up 50 }, logoContainer: { marginBottom: 10, }, logoStyle: { width: 400, height: 100, }, inputBox: { width: 300, height: 40, marginBottom: 10, padding: 10, borderWidth: 1, borderColor: '#ccc', borderRadius: 5, backgroundColor: Colors.white, }, loginButton: { backgroundColor: Colors.primary, width: 300, height: 40, justifyContent: 'center', alignItems: 'center', borderRadius: 5, marginBottom: 10, }, buttonText: { color: Colors.white, fontWeight: 'bold', fontFamily: "mon", }, toggleText: { color: Colors.primary, fontWeight: 'bold', fontFamily: "mon", }, }); export default Login;
Sub StockTicker() '-------------------------------------------------------------------------------------- ' CREATE A WORKSHEET LOOP TO WORK ON ALL WORKSHEETS ' NOTE THE STATEMENT IS "FOR EACH" 'The "ws.activate" command is needed for the script to go from sheet to sheet, 'without it, only one sheet is processed '-------------------------------------------------------------------------------------- Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets ws.activate '-------------------------------------------------------------------------------------- ' DEFINE ALL THE VARIABLES '-------------------------------------------------------------------------------------- Dim ticker As String Dim change As Double Dim percent_change As Double Dim count As Double count = 0 Dim count_adjust As Double Dim vol As Double vol = 0 Dim sum_table_row As Integer sum_table_row = 2 lastrow = Cells(Rows.count, 1).End(xlUp).Row Dim percent_range As Range Dim stock_vol As Range Dim min_dec As Double Dim max_inc As Double Dim max_vol As Double '-------------------------------------------------------------------------------------- ' CREATING THE LOOPS, BEST TO USE DIFFERENT VARIABLES ' IN ORDER TO KEEP TRACK OF WHAT LOOP IS WHAT '-------------------------------------------------------------------------------------- For a = 2 To lastrow If Cells(a + 1, 1).Value <> Cells(a, 1).Value Then vol = vol + Cells(a, 7).Value ticker = Cells(a, 1).Value count = count + 1 count_adjust = count - 1 change = Cells(a, 6).Value - Cells(a - count_adjust, 3).Value percent_change = (Cells(a, 6).Value / Cells(a - count_adjust, 3).Value) - 1 Range("i" & sum_table_row).Value = ticker Range("j" & sum_table_row).Value = change Range("k" & sum_table_row).Value = percent_change Range("l" & sum_table_row).Value = vol sum_table_row = sum_table_row + 1 vol = 0 count = 0 Else vol = vol + Cells(a, 7).Value count = count + 1 End If Next a Cells(1, 9).Value = "Ticker" Cells(1, 10).Value = "Yearly Change" Cells(1, 11).Value = "Percent Change" Cells(1, 12).Value = "Total Stock Volume" Set percent_range = Range("k2:k3001") max_inc = Application.WorksheetFunction.Max(percent_range) Cells(2, 17).Value = max_inc min_dec = Application.WorksheetFunction.Min(percent_range) Cells(3, 17).Value = min_dec Set stock_vol = Range("l2:l3001") max_vol = Application.WorksheetFunction.Max(stock_vol) Cells(4, 17).Value = max_vol For b = 2 To lastrow If Range("K" & b).Value = max_inc Then Cells(2, 16).Value = Range("i" & b).Value End If If Range("K" & b).Value = min_dec Then Cells(3, 16).Value = Range("i" & b).Value End If If Range("l" & b).Value = max_vol Then Cells(4, 16).Value = Range("i" & b).Value End If Next b For c = 2 to 3001 If Cells(c, 10).Value < 0 Then Cells(c, 10).Interior.ColorIndex = 3 Cells(c, 11).Interior.ColorIndex = 3 Else Cells(c, 10).Interior.ColorIndex = 4 Cells(c, 11).Interior.ColorIndex = 4 End If Next c Columns("k:k").NumberFormat = "0.00%" Cells(2, 15).Value = "Greatest % Increase" Cells(3, 15).Value = "Greatest % Decrease" Cells(4, 15).Value = "Greatest Total Volume" Cells(1, 16).Value = "Ticker" Cells(1, 17).Value = "Value" Cells(2, 17).NumberFormat = "0.00%" Cells(3, 17).NumberFormat = "0.00%" Columns("a:p").AutoFit Next ws End Sub
import type { FC, PropsWithChildren } from "react"; import cx from "classnames"; import styles from "./ContentContainer.module.scss"; interface Props { padding?: "normal" | "small"; widthPx?: number; heightPx?: number; onClick?: () => void; } export const ContentContainer: FC<PropsWithChildren<Props>> = ({ children, padding, heightPx, widthPx, onClick, }) => { return ( <div className={cx(styles.main, { [styles.small]: padding === "small" })} style={{ width: widthPx ? widthPx + "px" : "100%", height: heightPx + "px", }} onClick={onClick} > {children} </div> ); };
<script lang="ts"> import { createEventDispatcher, onDestroy, onMount } from 'svelte'; import Button from './Button.svelte'; import { Editor } from '@tiptap/core'; import StarterKit from '@tiptap/starter-kit'; export let content = ''; let editor: Editor | undefined; let element: HTMLElement | undefined; const dispatch = createEventDispatcher(); const postprocess = (html: string) => html .trim() .replace(/ (?<attr>style|class)=".*?"/gisu, '') .replace(/<span>(?<content>.*?)<\/span>/gisu, '$<content>') .replace(/<div>(?<content>.*?)<\/div>/gisu, '<p>$<content></p>') .replace(/<br><\/p>/gisu, '</p><p></p>') .replace(/(?<space> | |&nbsp;)<\/p>/gisu, '</p>'); // eslint-disable-line const toggleBold = () => { if (!editor) { return; } editor.chain().focus().toggleBold().run(); dispatch('change', postprocess(content)); }; const toggleItalic = () => { if (!editor) { return; } editor.chain().focus().toggleItalic().run(); dispatch('change', postprocess(content)); }; const transformText = () => { const html = content .replace(/(?<space> | |&nbsp;)<\/p>/gisu, '</p>') // eslint-disable-line // Кавычки .replace(/"(?<content>[^"]*)"/gsu, '«$<content>»') .replace(/=«(?<content>.*?)»/gsu, '="$<content>"') // eslint-disable-line // Длинное тире вместо дефиса или короткого тире .replace(/(?<space> | )(?<dash>-|–)/gu, ' —') // eslint-disable-line .replace(/(?<dash>-|–)(?<space> | )/gu, '— ') // eslint-disable-line // Многоточие .replace(/\.{3}/gu, '…') // Лишний пробел перед некоторой пунктуацией .replace(/ (?<punct>…|,|;|:|!|\?)/gu, '$<punct> ') .replace(/ (?<punct>\.(?!\.))/gu, '$<punct> ') // Лишние пробелы .replace(/ {2,}/gu, ' ') .replace(/\( /gu, '(') .replace(/ \)/gu, ')') .trim(); dispatch('change', html === '<p></p>' ? '' : postprocess(html)); }; onMount(() => { editor = new Editor({ content, element, extensions: [StarterKit], onTransaction: () => { // Force re-render so `editor.isActive` works as expected editor = editor; } }); }); onDestroy(() => { if (editor) { editor.destroy(); } }); </script> {#if editor} <div class="panel"> <button class:active={editor.isActive('bold')} type="button" aria-label="Жирный" style="--icon: url('/images/sprite.svg#bold');" disabled={!editor.can().chain().focus().toggleBold().run()} on:click={toggleBold} /> <button class:active={editor.isActive('italic')} type="button" aria-label="Курсив" style="--icon: url('/images/sprite.svg#italic');" disabled={!editor.can().chain().focus().toggleItalic().run()} on:click={toggleItalic} /> <div class="rightSide"> <Button secondary on:click={transformText}>Типограф</Button> </div> </div> <div class="editor" bind:this={element} /> {/if} <style lang="scss"> .editor { padding: 0.5rem; border: 1px solid var(--colorLightgray); border-radius: 0.125rem; outline: none; transition: border-color 0.3s ease-in-out; &:focus-visible { border-color: var(--colorGray); outline: none; } } .panel { display: flex; flex-wrap: wrap; align-items: center; } .rightSide { margin-left: auto; } button { position: relative; box-sizing: border-box; width: 2rem; height: 2rem; margin-right: 0.25rem; background-color: transparent; cursor: pointer; &.active { background-color: var(--colorLightgray); cursor: default; } &::before { content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: var(--colorBlacky); mask-image: var(--icon); } &:hover::before { background-color: var(--colorGreen); } } </style>
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CameraLensDistortionAlgo.h" #include "LensFile.h" #include "CameraLensDistortionAlgoCheckerboard.generated.h" struct FGeometry; struct FPointerEvent; class ACameraCalibrationCheckerboard; class FCameraCalibrationStepsController; class ULensDistortionTool; class SSimulcamViewport; template <typename ItemType> class SListView; class SWidget; class UMediaTexture; class UWorld; template<typename OptionType> class SComboBox; namespace CameraLensDistortionAlgoCheckerboard { class SCalibrationRowGenerator; } /** * Implements a lens distortion calibration algorithm. It requires a checkerboard pattern */ UCLASS() class UCameraLensDistortionAlgoCheckerboard : public UCameraLensDistortionAlgo { GENERATED_BODY() public: //~ Begin CameraLensDistortionAlgo virtual void Initialize(ULensDistortionTool* InTool) override; virtual void Shutdown() override; virtual void Tick(float DeltaTime) override; virtual bool OnViewportClicked(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) override; virtual TSharedRef<SWidget> BuildUI() override; virtual FName FriendlyName() const override { return TEXT("Lens Distortion Checkerboard"); }; virtual void OnDistortionSavedToLens() override; virtual bool GetLensDistortion( float& OutFocus, float& OutZoom, FDistortionInfo& OutDistortionInfo, FFocalLengthInfo& OutFocalLengthInfo, FImageCenterInfo& OutImageCenterInfo, TSubclassOf<ULensModel>& OutLensModel, double& OutError, FText& OutErrorMessage ) override; virtual TSharedRef<SWidget> BuildHelpWidget() override; //~ End CameraLensDistortionAlgo private: // SCalibrationRowGenerator will need access to the row structures below. friend class CameraLensDistortionAlgoCheckerboard::SCalibrationRowGenerator; /** Holds camera information that can be used to add the samples */ struct FCameraDataCache { // True if the rest of the contents are valid. bool bIsValid = false; // The data used to evaluate the lens data in the camera for this sample FLensFileEvalData LensFileEvalData; }; /** Holds information of the calibration row */ struct FCalibrationRowData { // Thumbnail to display in list TSharedPtr<SSimulcamViewport> Thumbnail; // Index to display in list int32 Index = -1; // Checkerboard corners in 2d image pixel coordinates. TArray<FVector2D> Points2d; // Checkerboard corners in 3d local space. TArray<FVector> Points3d; // Which calibrator was used FString CalibratorName; // Number of corner rows in pattern int32 NumCornerRows = 0; // Number of corner columns in pattern int32 NumCornerCols = 0; // Side dimension in cm float SquareSideInCm = 0; // Width of image int32 ImageWidth = 0; // Height of image int32 ImageHeight = 0; // Holds information of the camera data for this sample FCameraDataCache CameraData; }; private: /** The lens distortion tool controller */ TWeakObjectPtr<ULensDistortionTool> Tool; /** The currently selected checkerboard object. */ TWeakObjectPtr<ACameraCalibrationCheckerboard> Calibrator; /** Rows source for the CalibrationListView */ TArray<TSharedPtr<FCalibrationRowData>> CalibrationRows; /** Displays the list of calibration points that will be used to calculate the lens distortion */ TSharedPtr<SListView<TSharedPtr<FCalibrationRowData>>> CalibrationListView; /** Caches the last camera data. Will hold last value before the media is paused */ FCameraDataCache LastCameraData; /** True if a detection window should be shown after every capture */ bool bShouldShowDetectionWindow = false; private: /** Builds the UI of the calibration device picker */ TSharedRef<SWidget> BuildCalibrationDevicePickerWidget(); /** Builds the UI for the user to select if they want a corner detection window to be shown after every capture */ TSharedRef<SWidget> BuildShowDetectionWidget(); /** Builds the UI of the calibration points table */ TSharedRef<SWidget> BuildCalibrationPointsTable(); /** Builds the UI for the action buttons (RemoveLast, ClearAll) */ TSharedRef<SWidget> BuildCalibrationActionButtons(); private: /** Returns the first checkerboard object in the scene that it can find */ ACameraCalibrationCheckerboard* FindFirstCalibrator() const; /** Sets the calibrator object to be used. Updates the selection picker. */ void SetCalibrator(ACameraCalibrationCheckerboard* InCalibrator); /** Returns the currently selected calibrator object. */ ACameraCalibrationCheckerboard* GetCalibrator() const; /** Clears the list of calibration sample rows */ void ClearCalibrationRows(); /** Validates a new calibration point to determine if it should be added as a new sample row */ bool ValidateNewRow(TSharedPtr<FCalibrationRowData>& Row, FText& OutErrorMessage) const; /** Add a new calibration row from media texture and camera data */ bool AddCalibrationRow(FText& OutErrorMessage); /** Returns the steps controller */ FCameraCalibrationStepsController* GetStepsController() const; };
``` *- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2015 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * Additional contributors: * See AUTHORS file -* ``` General Information libnfc is a library which allows userspace application access to NFC devices. The official web site is: http://www.nfc-tools.org/ The official forum site is: http://www.libnfc.org/community/ The official development site is: https://github.com/nfc-tools/libnfc Important note: this file covers POSIX systems, for Windows please read README-Windows.md Requirements Some NFC drivers depend on third party software: * pn53x_usb & acr122_usb: - libusb-0.1 http://libusb.sf.net * acr122_pcsc: - pcsc-lite http://pcsclite.alioth.debian.org/ The regression test suite depends on the cutter framework: http://cutter.sf.net Installation See the file `INSTALL` for configure, build and install details. Additionnally, you may need to grant permissions to your user to drive your device. Under GNU/Linux systems, if you use udev, you could use the provided udev rules. e.g. under Debian, Ubuntu, etc. sudo cp contrib/udev/93-pn53x.rules /lib/udev/rules.d/ Under FreeBSD, if you use devd, there is also a rules file: contrib/devd/pn53x.conf. Configuration In order to change the default behavior of the library, the libnfc uses a configuration file located in sysconfdir (as provided to ./configure). A sample commented file is available in sources: libnfc.conf.sample If you have compiled using: ./configure --prefix=/usr --sysconfdir=/etc you can make configuration directory and copy the sample file: sudo mkdir /etc/nfc sudo cp libnfc.conf.sample /etc/nfc/libnfc.conf To configure multiple devices, you can either modify libnfc.conf or create a file per device in a nfc/devices.d directory: sudo mkdir -p /etc/nfc/devices.d printf 'name = "My first device"\nconnstring = "pn532_uart:/dev/ttyACM0"\n' | sudo tee /etc/nfc/devices.d/first.conf printf 'name = "My second device"\nconnstring = "pn532_uart:/dev/ttyACM1"\n' | sudo tee /etc/nfc/devices.d/second.conf How to report bugs To report a bug, visit https://github.com/nfc-tools/libnfc/issues and fill out a bug report form. If you have questions, remarks, we encourage you to post this in the developers community: http://www.libnfc.org/community Please make sure to include: * The version of libnfc * Information about your system. For instance: - What operating system and version - For Linux, what version of the C library And anything else you think is relevant. * A trace with debug activated. Reproduce the bug with debug, e.g. if it was: $ nfc-list -v run it as: $ LIBNFC_LOG_LEVEL=3 nfc-list -v * How to reproduce the bug. Please include a short test program that exhibits the behavior. As a last resort, you can also provide a pointer to a larger piece of software that can be downloaded. * If the bug was a crash, the exact text that was printed out when the crash occured. * Further information such as stack traces may be useful, but is not necessary. Patches ======= Patches can be posted to https://github.com/nfc-tools/libnfc/issues If the patch fixes a bug, it is usually a good idea to include all the information described in "How to Report Bugs". Building ======== It should be as simple as running these two commands: autoreconf -is ./configure make Troubleshooting Touchatag/ACR122: ----------------- If your Touchatag or ACR122 device fails being detected by libnfc, make sure that PCSC-lite daemon (`pcscd`) is installed and is running. If your Touchatag or ACR122 device fails being detected by PCSC-lite daemon (`pcsc_scan` doesn't see anything) then try removing the bogus firmware detection of libccid: edit libccid_Info.plist configuration file (usually `/etc/libccid_Info.plist`) and locate `<key>ifdDriverOptions</key>`, turn `<string>0x0000</string>` value into `0x0004` to allow bogus devices and restart pcscd daemon. ACR122: ------- Using an ACR122 device with libnfc and without tag (e.g. to use NFCIP modes or card emulation) needs yet another PCSC-lite tweak: You need to allow usage of CCID Exchange command. To do this, edit `libccid_Info.plist` configuration file (usually `/etc/libccid_Info.plist`) and locate `<key>ifdDriverOptions</key>`, turn `<string>0x0000</string>` value into `0x0001` to allow CCID exchange or `0x0005` to allow CCID exchange and bogus devices (cf previous remark) and restart pcscd daemon. Warning: if you use ACS CCID drivers (acsccid), configuration file is located in something like: `/usr/lib/pcsc/drivers/ifd-acsccid.bundle/Contents/Info.plist` SCL3711: -------- Libnfc cannot be used concurrently with the PCSC proprietary driver of SCL3711. Two possible solutions: * Either you don't install SCL3711 driver at all * Or you stop the PCSC daemon when you want to use libnfc-based tools PN533 USB device on Linux >= 3.1: --------------------------------- Since Linux kernel version 3.1, a few kernel-modules must not be loaded in order to use libnfc : "nfc", "pn533" and "pn533_usb". To prevent kernel from loading automatically these modules, you can blacklist them in a modprobe conf file. This file is provided within libnfc archive: sudo cp contrib/linux/blacklist-libnfc.conf /etc/modprobe.d/blacklist-libnfc.conf Proprietary Notes FeliCa is a registered trademark of the Sony Corporation. MIFARE is a trademark of NXP Semiconductors. Jewel Topaz is a trademark of Innovision Research & Technology. All other trademarks are the property of their respective owners.
import { useEffect, useState } from "react"; import { NavLink, Link } from "react-router-dom"; import { Card } from "../Card"; import { CatalogNav } from "../CatalogNav"; import { Preloader } from "../Preloader"; export function Catalog() { const [catalog, setCatalog] = useState([]); const [loading, setLoading] = useState(true); const [offset, setOffset] = useState(6); const [error, setError] = useState(null); const [categoryId, setCategoryId] = useState(null); const getData = (param, cb1, cb2) => { const URL = "http://localhost:7070/api/items"; fetch(`${URL}${param}`) .then((res) => res.json()) .then((data) => { console.log(data); cb1([...catalog, ...data]); }) .catch((error) => { console.log(error); cb1([]); cb2(error); }) .finally(() => { setLoading(false); console.log("getData test finished"); }); }; const loadMore = () => { setOffset((prev) => prev + 6); setLoading(true); getData(`?offset=${offset}&${categoryId}`, setCatalog, setError); // fetch(`http://localhost:7070/api/items?offset=${offset}`) // .then((res) => res.json()) // .then((data) => { // console.log("LoadMore: ", data); // setCatalog([...catalog, ...data]); // }).catch(error => { // console.log(error); // setCatalog([]); // setError(error); // }).finally(()=> { // setLoading(false); // }) }; useEffect(() => { fetch("http://localhost:7070/api/items") .then((res) => res.json()) .then((data) => { console.log(data); setCatalog(data); setLoading(false); }); }, []); return ( <section className="catalog"> <h2 className="text-center">Каталог</h2> <CatalogNav/> <div className="row"> {catalog.length ? catalog.map((el) => { const { title, price, images, id } = el; return <Card key={el.id} {...el} />; }) : null} {error ? <p>Ошибка при загрузке данных</p> : null} </div> {offset > 62 ? null : ( <div className="text-center"> {loading ? ( <Preloader /> ) : ( <button onClick={() => { loadMore(); }} className="btn btn-outline-primary" > Загрузить ещё </button> )} </div> )} </section> ); }
<script setup> import {useVerwaltungsStore} from '@/stores/PraktikumsverwaltungStore.js' import {onBeforeMount, ref, watch} from "vue"; import Checkbox from "@/components/Checkbox.vue"; import TabellenZeilenElement from "@/components/TabellenZeilenElement.vue"; import Dropdown from "@/components/Dropdown.vue"; import {useRoute} from "vue-router"; const store = useVerwaltungsStore() //TODO Filter werden nicht bei Kurswechsel nicht zurückgesetzt const betreuteStudentenAnzeigen = ref(!!Number(sessionStorage.getItem("betreuteAnzeigen"))) const abgebrochenStudentenAnzeigen = ref(!!Number(sessionStorage.getItem("abgebrocheneAnzeigen"))) const notenVerstecken = ref(!!Number(sessionStorage.getItem('notenVerstecken'))) const currentGroupId = ref(Number(sessionStorage.getItem('currentGroupId'))) const searchBarInput = ref("") const route = useRoute() onBeforeMount( () => { if (store.studenten.length === 0 && Number(sessionStorage.getItem("currentKursId")) !== -1) { store.fetchKursInfos(Number(sessionStorage.getItem("currentKursId"))) } }) function updateGruppe(id) { currentGroupId.value = id sessionStorage.setItem("currentGroupId", String(id)) } function updateBetreuteStudentenAnzeigen() { betreuteStudentenAnzeigen.value = !betreuteStudentenAnzeigen.value sessionStorage.setItem("betreuteAnzeigen", betreuteStudentenAnzeigen.value ? "1" : "0") } function updateAbgebrochenStudentenAnzeigen() { abgebrochenStudentenAnzeigen.value = !abgebrochenStudentenAnzeigen.value sessionStorage.setItem("abgebrocheneAnzeigen", abgebrochenStudentenAnzeigen.value ? "1" : "0") } function updateNotenVerstecken() { notenVerstecken.value = !notenVerstecken.value sessionStorage.setItem("notenVerstecken", notenVerstecken.value ? "1" : "0") } function filterStudent(student) { return student["name"].toLowerCase().includes(searchBarInput.value.toLowerCase()) && (student["gruppenId"] === currentGroupId.value || currentGroupId.value === -1) && !!student["abgebrochen"] === abgebrochenStudentenAnzeigen.value && (betreuteStudentenAnzeigen.value ? student["betreut"] === betreuteStudentenAnzeigen.value : true) } </script> <template> <div class="relative overflow shadow-md sm:rounded-lg"> <ul class="items-center flex flex-col p-4 md:p-0 mt-4 font-medium border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-8 md:mt-0 md:border-0 md:bg-white dark:bg-gray-800 md:dark:bg-gray-900 dark:border-gray-700"> <!-- TableSearchElement Anfang--> <li> <label for="table-search" class="sr-only">Student suchen</label> <div class="relative"> <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none"> <svg class="w-5 h-5 text-gray-500 dark:text-gray-400" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path> </svg> </div> <input type="text" v-model="searchBarInput" class="block p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg w-80 bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Name des Studenten"> </div> </li> <!-- TableSearchElement ende--> <Dropdown :elemente="store.alleGruppen" @onClick="args => updateGruppe(args.id)" drop-down-default-name="Alle Gruppen" :current-value="currentGroupId"></Dropdown> <li> <Checkbox :abgehackt="betreuteStudentenAnzeigen" checkbox-name="Meine Studenten" @onClick="updateBetreuteStudentenAnzeigen()"></Checkbox> </li> <li> <Checkbox :abgehackt="abgebrochenStudentenAnzeigen" checkbox-name="Praktikum abgebrochen" @onClick="updateAbgebrochenStudentenAnzeigen"></Checkbox> </li> <li> <Checkbox :abgehackt="notenVerstecken" checkbox-name="Bewertungen verstecken" @onClick="notenVerstecken = !notenVerstecken"></Checkbox> </li> </ul> <!-- Table Beginn--> <table class="overflow-y-auto overflow-x-auto w-full text-sm text-left text-gray-500 dark:text-gray-400"> <!-- Alle Aufgabennamen als Überschriften--> <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400"> <tr> <th scope="col" class="border px-6 py-3"> Name </th> <th v-for="aufgabe in store.aufgaben" scope="col" class="border px-6 py-3"> {{ aufgabe.name }} </th> </tr> </thead> <!-- Alle Zeilenelemente in der Tabellenübersicht v-show="student.gruppenId === currentGroupId || currentGroupId === -1" --> <tbody> <template v-for="student in store.studenten"> <TabellenZeilenElement v-show="filterStudent(student)" :student="student" :notenAnzeigen="notenVerstecken"></TabellenZeilenElement> </template> </tbody> </table> </div> </template>
Introduction I remember thinking about breaking into data science as if it were yesterday. I had just started my semester abroad in Shanghai and attended several talks and guest lectures about data science and machine learning. However, I had never coded before (except for some basic SQL) and did not really know where to start. Initial web searches resulted in more confusion than insight as many people recommended many different paths into data science. Some even suggested that becoming a data scientist without a Ph.D. is not possible. This article takes a different approach. I am not going to attempt to provide a one-fits-all path into data science. Instead, I am going to elaborate on my experiences while trying to break into data science, which I hope may be of use to aspiring data scientists. Part 1: Learn How To Code Before attempting to do anything else, I started to learn how to code. Because I decided that some guidance would be helpful, I decided to enroll in the 12-Week Data Science Bootcamp at the NYC Data Science Academy. The program includes an online preparation course tackling Python, R, and SQL, which has to be completed before actually attending the bootcamp itself. Code, Code, Code In hindsight, I wish I had focused more on practicing coding than on trying to study a programming language. As I later realized, programming is a skill that is mainly acquired by constant, repeated practice. Great books I later discovered and studied on my own that focus on doing exactly that include “Learn Python The Hard Way” for Python and “R for Data Science” for R. Since I had already used SQL before, I only had to review the main commands. If you would like a more start-to-finish guide for SQL, I would recommend getting started with Mode Analytics’ SQL course. While learning to code, you will run into many, many problems. Keep going. Pushing through those mistakes and examining your mistakes will be very valuable later on. When practicing Python in Jupyter Notebooks, I always documented all of my mistakes so that I would be able to review them later on. This resulted in a personalized library of code snippets and interesting discoveries that I fall back on until this day. Python or R? There are many factors that could influence one’s choice between Python and R. Do I want to have easy access to a wide variety of tools for statistical analysis of data? Then R is probably the way to go. Do I want to learn a more general-purpose language that can be applied to many things outside of data analysis? In that case, Python should probably be your first choice. However, in my experience, picking one and just starting to code is what matters most. Find out what language you prefer and do not only rely on third-party recommendations. If you want to be extremely versatile, I would recommend finding a favorite but also being able to use the other. Luckily for me, the NYC Data Science Academy teaches its entire curriculum in both, R and Python. I personally prefer using Python for machine learning but, at the same time, appreciate data analysis in R using the tidyverse, which is a collection of R packages designed for data science. Part 2: Brush Up On Statistics As a business major, I had taken an elementary statistics course in college as well as some economics and finance courses. Thus, diving deeper into statistics did not mean being confronted with something I had never seen before but it still proved to be quite a challenge. In my opinion, especially in 2019, only knowing how to use machine learning packages, such as scikit-learn, is neither enough to effectively practice data science nor will it be enough to land you a job in data science. Document Your Progress In order to organize everything I would need to know in a centralized manner, I started creating Word documents with summaries for each respective topic. There are so-called “Cheat Sheets” readily available online, however, I usually find them to be lacking in depth. Moreover, as I emphasized at the beginning of this article, there is no one-fits-all solution to anything regarding data science. Therefore, it is a good habit to build your customized data science look-up library. I took notes during the lectures at the bootcamp and refined and reviewed them at night. While this took a lot of effort, it greatly facilitated understanding more and more complex algorithms as the lectures progressed. Master the Fundamentals As a final note on this topic: do not, under any circumstances, skip the basics. While trying to jump to fancy algorithms might seem tempting at first, spending the majority of your time with the fundamentals is the better choice in my opinion. In addition to the lectures, I read several books about statistics and statistical learning. The best book on statistical learning, in my opinion, is “An Introduction to Statistical Learning: With Applications in R” by Daniela Witten, Robert Tibshirani, and Trevor Hastie. Different books take different approaches. Thus, combining books that focus on a verbal explanation of algorithms with books that dive into the technical details proved to be a good investment of my time. I, too, was intrigued by all the buzzwords circulating on the Internet but ultimately found that you first have to build very solid foundations before you can think about adding new capabilities to your data science skill set. Ask Many Questions If you should happen to attend a boot camp as I did, make use of your instructors. Ask as many questions as you can. Do not wait until you run into serious problems before starting to asking questions. Even showing more experienced people your code and asking for ways to improve its efficiency can prove to be extremely useful. In case you should not be able to get professional help, do not despair. There are plenty of online communities and resources that will help you answer your questions. Chances are, you are not the first person running into this problem. On top, figuring out the solution yourself will help you remember it more easily. Other Things to Brush Up On Depending on your background, reviewing basic linear algebra and calculus might also be a good idea. I would recommend either going through your old linear algebra or calculus notes or taking an online course, such as MIT’s freely accessible linear algebra course. This is particularly important if you should be interested in reading academic papers and more technical books. Part 3: Build a Project Portfolio Complete At Least Four Projects This third step is of utmost importance if you want to land a job in data science. In order to convince your potential employers that they should hire you and to apply what you have learned thus far, try to complete at least four major projects. If you, like myself, attend the NYC Data Science Academy bootcamp, then you will have to complete three projects covering all aspects of the data science lifecycle. These projects will cover everything from data acquisition over data visualization to machine learning. Finally, the capstone project enables you to choose any topic you would like to work on. You should use this opportunity to position yourself in the job market and target your dream employers. For instance, if your goal is to apply data science to healthcare data, then try to find a project that tackles an issue in that area, such as the prediction of diabetes onset. Do Not Stop There If you really want to break into a specific industry, you should not stop at four projects. Search for data that might be relevant to your dream employer and experiment with it. Build something interesting and write an article or blog post about your project. The more you showcase your abilities and interest in a specific field, the more likely it is that people in that industry are going to be impressed by you. Do Not Try To Be Too Fancy When choosing projects, it is tempting to go for things that sound fancy. Do not do that. At least not right away. Make sure your projects are solid from start through finish and contain as little errors as possible. Have someone check your projects and review them for you. During my time at the bootcamp, I presented all of my projects to my fellow classmates as well as my instructors. Getting different opinions on your work will help you improve future projects. Part 4: Trying to Find a Job Preparation Is Key If you want to succeed in the data science hiring process, prepare yourself as much as possible. Check out coding challenges on HackerRank, familiarize yourself with the types of questions being asked, and, perhaps most importantly, document your interviewing process. As with machine learning theory, you should create a document in which you describe and evaluate your experiences when interviewing. Then, before each interview, review that document along with your machine learning theory document(s) and make sure that you avoid repeating mistakes. Warming yourself up before starting a coding challenge by completing some tasks on HackerRank might also be helpful. Learn How To Pitch Yourself If you want a job in data science, you are going to have to compete with many other applicants. Set yourself apart by creating your personalized narrative. Why are you the perfect fit? Why did you choose these specific projects? Why data science in the first place? Since you are going to have to introduce yourself in almost every interview, make sure that you craft a strong narrative that can be adapted depending on what company you are targeting. While you are at it, prepare pitches for your projects too. Not every potential employer will want to hear you describing all of your projects. Maybe one specific project caught the attention of the people that are going to interview you. Make sure that you are able to describe each project in depth but also have a backup pitch in case you only need a short description of your projects. Practice these pitches in front of other people. Thinking of what you might say at home is not comparable to standing in front of people you do not know while trying to explain your projects. If you go to school or attend a boot camp, practice pitching yourself with your classmates and give each other constructive feedback. Doing so, you might be able to avoid several mistakes prior to your first interview. Network After completing the NYC Data Science Academy’s bootcamp, all graduates are encouraged to attend a hiring partner event in which you might be able to find your future employer. Before attending these types of events, it is absolutely crucial to have already learned how to pitch yourself and your projects. Be aggressive when attending such events. Research the hiring managers and recruiters that are going to attend the event. During the event, try to figure out whether there might be a fit between you and the company as quickly as possible. Hand over your resume and ask for business cards. Another very important piece of advice: do not talk to only one or two people. Even if there is potential for a great fit, do not limit yourself in the number of potential job offers. Move on after a certain period of getting to know each other and exchanging contact information has passed. Networking is a skill that takes practice. Luckily for myself, the bootcamp provided its students with extensive advice and tips on how to navigate networking events. Make sure to know the rules of conduct in networking (e.g. writing a good follow-up email to every hiring manager that was in attendance). However, as with the projects, do not stop there. Network with the people around you. Data science is a fascinating field with many fascinating people. Connect with your classmates if you are in school or a bootcamp. Find interesting people to follow on LinkedIn. Attend data science meetups in your city. There are many opportunities for networking and the more you do it, the better you will get at it. Do Not Give Up Finding a job can be hard. You might go to many interviews just to have people tell you they will not be able to hire you. Unless you are lucky and find a job right away, getting a job might turn out to be a very frustrating process. Do not despair. If you keep persevering and improving yourself and your resume, someone will eventually notice. Keep believing that you will get the job offer you want. Talk to people that have gone through the data science hiring process before and you will see that many of them had many extremely frustrating interviews. What separates those who make it from those who do not, ultimately, has a lot to do with the ability to keep on fighting and not giving in. Conclusion Becoming a data scientist in 2019 is not easy. There will be many hurdles you will have to jump over and many challenges you will have to overcome. Nevertheless, the rewards of making it through that process are huge. Not only will you get to do what you love doing but also engage with very bright people from all kinds of different backgrounds. Just take the first step and the rest will follow. Start following your passion. It is fine if it should take you longer than it takes others, what matters is your willpower. Making sure that you steadily improve day by day will ultimately get you where you want to go.
package fr.legrain.bdg.client.preferences; import org.eclipse.jface.preference.*; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.IWorkbench; import fr.legrain.bdg.client.Activator; /** * This class represents a preference page that * is contributed to the Preferences dialog. By * subclassing <samp>FieldEditorPreferencePage</samp>, we * can use the field support built into JFace that allows * us to create a page that is small and knows how to * save, restore and apply itself. * <p> * This page is used to modify preferences only. They * are stored in the preference store that belongs to * the main plug-in class. That way, preferences can * be accessed directly via the preference store. */ public class ServeurPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public ServeurPreferencePage() { super(GRID); setPreferenceStore(Activator.getDefault().getPreferenceStore()); setDescription("A demonstration of a preference page implementation"); } /** * Creates the field editors. Field editors are abstractions of * the common GUI blocks needed to manipulate various types * of preferences. Each field editor knows how to save and * restore itself. */ public void createFieldEditors() { addField( new StringFieldEditor(PreferenceConstants.SERVEUR, "Serveur (domaine/IP)", getFieldEditorParent())); addField( new StringFieldEditor(PreferenceConstants.SERVEUR_PORT, "Port du serveur", getFieldEditorParent())); addField( new StringFieldEditor(PreferenceConstants.SERVEUR_LOGIN, "Identifiant", getFieldEditorParent())); addField( new StringFieldEditor(PreferenceConstants.SERVEUR_PASSWORD, "Mot de passe", getFieldEditorParent())); addField( new StringFieldEditor(PreferenceConstants.SERVEUR_DOSSIER, "Dossier", getFieldEditorParent())); } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } }
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </h:head> <h:body> <ui:composition template="/WEB-INF/facelets/template.xhtml"> <ui:define name="body"> <f:view> <p:ajaxStatus onstart="PF('statusDialog').show()" onsuccess="PF('statusDialog').hide()"/> <p:dialog modal="true" widgetVar="statusDialog" header="Loading" draggable="false" closable="false"> <p:graphicImage value="#{facesContext.externalContext.request.scheme}://#{facesContext.externalContext.request.serverName}:#{facesContext.externalContext.request.serverPort}#{facesContext.externalContext.request.contextPath}/images/ajaxloadingbar.gif" /> </p:dialog> <!-- Expired session --> <p:idleMonitor onactive="PF('sessionTimeOutDialog').show();" timeout="#{session.maxInactiveInterval * 1000}" /> <p:dialog modal="true" widgetVar="sessionTimeOutDialog" header="Expired session" draggable="false" closable="false"> <h:outputText value="The session is finished" /> <input id="confirmBackToLogin" type="button" value="Sign in" onclick="window.location='#{facesContext.externalContext.requestContextPath}/index.jsp';" /> </p:dialog> <h:form id="form"> <p:panel id="msgProjectClientesTitle" header="SystemCompanyParameterData"> <p:messages id="msg" /> <p:dataTable id ="tabla" value="#{systemCompanyParameterView.data}" var="systemCompanyParameter" paginator="true" rows="5" editable="true" > <p:ajax event ="rowEdit" update=":form:msg,:form:tabla" listener="#{systemCompanyParameterView.rowEventListener}" /> <p:column filterBy="#{systemCompanyParameter.id}" sortBy="#{systemCompanyParameter.id}" headerText="id"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.id}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.id}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.code}" sortBy="#{systemCompanyParameter.code}" headerText="code"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.code}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.code}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyAddress}" sortBy="#{systemCompanyParameter.companyAddress}" headerText="companyAddress"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyAddress}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyAddress}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyEmail}" sortBy="#{systemCompanyParameter.companyEmail}" headerText="companyEmail"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyEmail}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyEmail}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyLogoUrl}" sortBy="#{systemCompanyParameter.companyLogoUrl}" headerText="companyLogoUrl"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyLogoUrl}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyLogoUrl}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyName}" sortBy="#{systemCompanyParameter.companyName}" headerText="companyName"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyName}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyName}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyNit}" sortBy="#{systemCompanyParameter.companyNit}" headerText="companyNit"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyNit}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyNit}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyPhone}" sortBy="#{systemCompanyParameter.companyPhone}" headerText="companyPhone"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyPhone}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyPhone}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.companyWeb}" sortBy="#{systemCompanyParameter.companyWeb}" headerText="companyWeb"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.companyWeb}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.companyWeb}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.createdBy}" sortBy="#{systemCompanyParameter.createdBy}" headerText="createdBy"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.createdBy}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.createdBy}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.systemLogoUrl}" sortBy="#{systemCompanyParameter.systemLogoUrl}" headerText="systemLogoUrl"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.systemLogoUrl}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.systemLogoUrl}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.systemName}" sortBy="#{systemCompanyParameter.systemName}" headerText="systemName"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.systemName}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.systemName}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.systemUrl}" sortBy="#{systemCompanyParameter.systemUrl}" headerText="systemUrl"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.systemUrl}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.systemUrl}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.systemVersion}" sortBy="#{systemCompanyParameter.systemVersion}" headerText="systemVersion"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.systemVersion}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.systemVersion}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.updatedBy}" sortBy="#{systemCompanyParameter.updatedBy}" headerText="updatedBy"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.updatedBy}"/> </f:facet> <f:facet name="input"> <p:inputText value="#{systemCompanyParameter.updatedBy}"/> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.createdAt}" sortBy="#{systemCompanyParameter.createdAt}" headerText="createdAt"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.createdAt}"> <f:convertDateTime pattern="dd/MM/yyyy"/> </h:outputText> </f:facet> <f:facet name="input"> <p:calendar value="#{systemCompanyParameter.createdAt}" showOn="button" pattern="dd/MM/yyyy" navigator="true" > <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{systemCompanyParameterView.timeZone}" /> </p:calendar> </f:facet> </p:cellEditor> </p:column> <p:column filterBy="#{systemCompanyParameter.updatedAt}" sortBy="#{systemCompanyParameter.updatedAt}" headerText="updatedAt"> <p:cellEditor> <f:facet name="output"> <h:outputText value="#{systemCompanyParameter.updatedAt}"> <f:convertDateTime pattern="dd/MM/yyyy"/> </h:outputText> </f:facet> <f:facet name="input"> <p:calendar value="#{systemCompanyParameter.updatedAt}" showOn="button" pattern="dd/MM/yyyy" navigator="true" > <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{systemCompanyParameterView.timeZone}" /> </p:calendar> </f:facet> </p:cellEditor> </p:column> <p:column headerText="Options" > <p:rowEditor id="row"/> <p:tooltip for="row" value="Edit" showEffect="fade" hideEffect="fade" /> <p:tooltip for="btnDelete" value="Delete" showEffect="fade" hideEffect="fade" /> <p:commandButton id="btnDelete" actionListener="#{systemCompanyParameterView.actionDeleteDataTableEditable}" title="Delete" onclick="if(!confirm('Do you really want to delete this Entry?')){return false;}" icon="ui-icon-trash" update=":form:msg,:form:tabla" > <f:attribute name="selectedSystemCompanyParameter" value="#{systemCompanyParameter}" /> </p:commandButton> </p:column> </p:dataTable> </p:panel> </h:form> </f:view> </ui:define> </ui:composition> </h:body> </html>
// Importing required modules import React, { Fragment, useRef, useState } from "react"; import { Link } from "react-router-dom"; // Importing MUI assets import { Stack } from "@mui/material"; // Importing react icons import { BiArrowBack, BiPaperclip, BiSolidPaperPlane } from "react-icons/bi"; // Importing custom components import AppLayout from "../components/layoutComponents/AppLayout"; import AttachFileMenu from "../components/dialogComponents/AttachFileMenu"; import { sampleMessageData } from "../components/sharedComponents/sampleData"; import MessageItem from "../components/sharedComponents/MessageItem"; // Creating the Chat Page const Chat = () => { const chatContainerRef = useRef(null); // Some states handling messages const user = { _id: "6dsgc7wgefwoic712", name: "Mafia" } const [ messages, setMessages ] = useState(sampleMessageData); // JSX to render the Chat Page return ( <Fragment> {/* Chat Header */} <div className="flex items-center justify-start mx-auto p-4 border-b border-gray-700" style={{ width: "98%", height: "9%" }}> <div className="flex items-center justify-center text-lg gap-3"> <Link to={"/"} className="flex items-center justify-center"> <BiArrowBack /> </Link> {/* User profile */} <div className="flex items-center justify-center"> <div className="avatar shrink-0"> <div className="w-10 rounded-full bg-gray-600"> <img src="" alt="DP" /> </div> </div> </div> {/* User details */} <div className="flex flex-col"> <h6 className="text-md font-light">Full name</h6> </div> </div> </div> {/* Messages Container */} <Stack ref={chatContainerRef} height={"80%"} width={"98%"} borderBottom={"1px solid #374151"} margin={"auto"} marginTop={"0.25rem"} sx={{ overflowX: "hidden", overflowY: "auto" }} > { messages?.map((msg) => ( <MessageItem key={msg._id} message={msg} user={user} /> )) } </Stack> {/* Message Input box */} <div className="flex items-center justify-between gap-1 sm:gap-2 mx-auto mt-1 sm:p-1 px-1 rounded-md" style={{ width: "98%", height: "8%" }}> <div className="shrink-0 rounded-md"> <BiPaperclip className="text-2xl text-gray-400 -rotate-45" /> </div> <form className="flex items-center justify-center gap-1 flex-1 w-full h-full rounded-md border border-gray-600 sm:border-0"> <input type="text" className="flex-1 shrink-0 px-1 h-full sm:px-3 bg-transparent border-0 border-gray-600 sm:border rounded-md outline-none" placeholder="Message here..." /> <button type="submit" className="flex items-center justify-center shrink-0 h-full p-2 text-xl rounded-md border-0 border-gray-600 sm:border"> <BiSolidPaperPlane className="text-teal-300" /> </button> </form> </div> {/* Attach file dialog box */} <AttachFileMenu /> </Fragment> ); }; // Exporting the Page export default AppLayout()(Chat);
<script setup lang="ts"> import SegmentList from '@/src/components/SegmentList.vue'; import CloseableDialog from '@/src/components/CloseableDialog.vue'; import SaveSegmentGroupDialog from '@/src/components/SaveSegmentGroupDialog.vue'; import { useCurrentImage } from '@/src/composables/useCurrentImage'; import { useDatasetStore } from '@/src/store/datasets'; import { getSelectionName, selectionEquals, DataSelection, } from '@/src/utils/dataSelection'; import { useSegmentGroupStore } from '@/src/store/segmentGroups'; import { usePaintToolStore } from '@/src/store/tools/paint'; import { Maybe } from '@/src/types'; import { reactive, ref, computed, watch, toRaw } from 'vue'; const UNNAMED_GROUP_NAME = 'Unnamed Segment Group'; const segmentGroupStore = useSegmentGroupStore(); const { currentImageID } = useCurrentImage(); const dataStore = useDatasetStore(); const currentSegmentGroups = computed(() => { if (!currentImageID.value) return []; const { orderByParent, metadataByID } = segmentGroupStore; if (!(currentImageID.value in orderByParent)) return []; return orderByParent[currentImageID.value].map((id) => { return { id, name: metadataByID[id].name, }; }); }); const paintStore = usePaintToolStore(); const currentSegmentGroupID = computed({ get: () => paintStore.activeSegmentGroupID, set: (id) => paintStore.setActiveLabelmap(id), }); // clear selection if we delete the active segment group watch(currentSegmentGroups, () => { const selection = currentSegmentGroupID.value; if (selection && !(selection in segmentGroupStore.dataIndex)) { currentSegmentGroupID.value = null; } }); function deleteGroup(id: string) { segmentGroupStore.removeGroup(id); } // --- editing state --- // const editingGroupID = ref<Maybe<string>>(null); const editState = reactive({ name: '' }); const editDialog = ref(false); const editingMetadata = computed(() => { if (!editingGroupID.value) return null; return segmentGroupStore.metadataByID[editingGroupID.value]; }); const existingNames = computed(() => { return new Set( Object.values(segmentGroupStore.metadataByID).map((meta) => meta.name) ); }); function isUniqueEditingName(name: string) { return !existingNames.value.has(name) || name === editingMetadata.value?.name; } const editingNameConflict = computed(() => { return !isUniqueEditingName(editState.name); }); function uniqueNameRule(name: string) { return isUniqueEditingName(name) || 'Name is not unique'; } function startEditing(id: string) { editDialog.value = true; editingGroupID.value = id; if (editingMetadata.value) { editState.name = editingMetadata.value.name; } } function stopEditing(commit: boolean) { if (editingNameConflict.value) return; editDialog.value = false; if (editingGroupID.value && commit) segmentGroupStore.updateMetadata(editingGroupID.value, { name: editState.name || UNNAMED_GROUP_NAME, }); editingGroupID.value = null; } // --- // function createSegmentGroup() { if (!currentImageID.value) throw new Error('Cannot create a labelmap without a base image'); const id = segmentGroupStore.newLabelmapFromImage(currentImageID.value); if (!id) throw new Error('Could not create a new labelmap'); // copy segments from current labelmap if (currentSegmentGroupID.value) { const metadata = segmentGroupStore.metadataByID[currentSegmentGroupID.value]; const copied = structuredClone(toRaw(metadata.segments)); segmentGroupStore.updateMetadata(id, { segments: copied }); } currentSegmentGroupID.value = id; startEditing(id); } // Collect images that can be converted into // a SegmentGroup for the current background image. const segmentGroupConvertibles = computed(() => { const primarySelection = dataStore.primarySelection; if (!primarySelection) return []; return dataStore.idsAsSelections .filter((selection) => !selectionEquals(selection, primarySelection)) .map((selection) => ({ selection, name: getSelectionName(selection), })); }); function createSegmentGroupFromImage(selection: DataSelection) { const primarySelection = dataStore.primarySelection; if (!primarySelection) { throw new Error('No primary selection'); } segmentGroupStore.convertImageToLabelmap(selection, primarySelection); } const saveId = ref(''); const saveDialog = ref(false); function openSaveDialog(id: string) { saveId.value = id; saveDialog.value = true; } </script> <template> <div class="my-2" v-if="currentImageID"> <div class="text-grey text-subtitle-2 d-flex align-center justify-space-evenly mb-2" > <v-btn variant="tonal" color="secondary" density="compact" @click.stop="createSegmentGroup" > <v-icon class="mr-1">mdi-plus</v-icon> New Group </v-btn> <v-menu location="bottom"> <template v-slot:activator="{ props }"> <v-btn variant="tonal" color="secondary" density="compact" v-bind="props" > <v-icon class="mr-1">mdi-chevron-down</v-icon>From Image </v-btn> </template> <v-list v-if="segmentGroupConvertibles.length !== 0"> <v-list-item v-for="(item, index) in segmentGroupConvertibles" :key="index" @click="createSegmentGroupFromImage(item.selection)" > {{ item.name }} <v-tooltip activator="parent" location="end" max-width="200px"> Convert to segment group </v-tooltip> </v-list-item> </v-list> <v-list v-else> <v-list-item class="font-italic" title="No eligible images found" /> </v-list> </v-menu> </div> <v-divider /> <v-radio-group v-model="currentSegmentGroupID" hide-details density="comfortable" class="my-1 segment-group-list" > <v-radio v-for="group in currentSegmentGroups" :key="group.id" :value="group.id" > <template #label> <div class="d-flex flex-row align-center w-100" :title="group.name"> <span class="group-name">{{ group.name }}</span> <v-spacer /> <v-btn icon="mdi-content-save" size="small" variant="flat" @click.stop="openSaveDialog(group.id)" ></v-btn> <v-btn icon="mdi-pencil" size="small" variant="flat" @click.stop="startEditing(group.id)" ></v-btn> <v-btn icon="mdi-delete" size="small" variant="flat" @click.stop="deleteGroup(group.id)" ></v-btn> </div> </template> </v-radio> </v-radio-group> <v-divider /> </div> <div v-else class="text-center text-caption">No selected image</div> <segment-list v-if="currentSegmentGroupID" :group-id="currentSegmentGroupID" /> <v-dialog v-model="editDialog" max-width="400px"> <v-card> <v-card-text> <v-text-field v-model="editState.name" :placeholder="UNNAMED_GROUP_NAME" :rules="[uniqueNameRule]" @keydown.stop.enter="stopEditing(true)" /> </v-card-text> <v-card-actions> <v-spacer /> <v-btn color="error" @click="stopEditing(false)">Cancel</v-btn> <v-btn :disabled="editingNameConflict" @click="stopEditing(true)"> Done </v-btn> </v-card-actions> </v-card> </v-dialog> <closeable-dialog v-model="saveDialog" max-width="30%"> <template v-slot="{ close }"> <save-segment-group-dialog :id="saveId" @done="close" /> </template> </closeable-dialog> </template> <style> .segment-group-list { max-height: 240px; overflow-y: auto; } .group-name { word-wrap: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style>
package api import ( "errors" "fmt" "github.com/gin-gonic/gin" "github.com/ppoonk/AirGo/global" "github.com/ppoonk/AirGo/model" "github.com/ppoonk/AirGo/service" "github.com/ppoonk/AirGo/utils/other_plugin" "github.com/ppoonk/AirGo/utils/response" "gorm.io/gorm" "strconv" "time" ) // 获取全部订单,分页获取 func GetAllOrder(ctx *gin.Context) { var params model.FieldParamsReq err := ctx.ShouldBind(&params) if err != nil { global.Logrus.Error(err.Error()) response.Fail("GetAllOrder error:"+err.Error(), nil, ctx) return } res, total, err := service.CommonSqlFindWithFieldParams(&params) if err != nil { global.Logrus.Error(err.Error()) response.Fail("GetAllOrder error:"+err.Error(), nil, ctx) return } response.OK("GetAllOrder success", model.CommonDataResp{ Total: total, Data: res, }, ctx) } // 获取订单统计 func GetMonthOrderStatistics(ctx *gin.Context) { var params model.FieldParamsReq err := ctx.ShouldBind(&params) res, err := service.GetMonthOrderStatistics(&params) if err != nil { global.Logrus.Error(err.Error()) response.Fail("GetMonthOrderStatistics error:"+err.Error(), nil, ctx) return } response.OK("GetMonthOrderStatistics success", res, ctx) } // 获取用户订单by user id func GetOrderByUserID(ctx *gin.Context) { var params model.FieldParamsReq err := ctx.ShouldBind(&params) if err != nil { global.Logrus.Error(err.Error()) response.Fail("GetAllOrder error:"+err.Error(), nil, ctx) return } uIDInt, ok := GetUserIDFromGinContext(ctx) if !ok { response.Fail("GetOrderByUserID error:user id error", nil, ctx) return } res, err := service.GetUserOrders(&params, uIDInt) if err != nil { response.Fail("GetOrderByUserID error:"+err.Error(), nil, ctx) return } response.OK("GetOrderByUserID success", res, ctx) } // 完成未支付订单 func CompletedOrder(ctx *gin.Context) { var order model.Orders err := ctx.ShouldBind(&order) if err != nil { global.Logrus.Error(err) response.Fail("CompletedOrder error:"+err.Error(), nil, ctx) return } order.TradeStatus = model.OrderCompleted //更新数据库订单状态,自定义结束状态Completed err = service.UpdateOrder(&order) //更新数据库状态 if err != nil { global.Logrus.Error(err) response.Fail("CompletedOrder error:"+err.Error(), nil, ctx) return } err = service.UpdateUserSubscribe(&order) //更新用户订阅信息 if err != nil { global.Logrus.Error(err) response.Fail("CompletedOrder error:"+err.Error(), nil, ctx) return } response.OK("CompletedOrder success", nil, ctx) } // 更新用户订单 func UpdateUserOrder(ctx *gin.Context) { var order model.Orders err := ctx.ShouldBind(&order) if err != nil { global.Logrus.Error(err) response.Fail("UpdateUserOrder error:"+err.Error(), nil, ctx) return } err = service.UpdateOrder(&order) //更新数据库状态 if err != nil { global.Logrus.Error(err) response.Fail("UpdateUserOrder error:"+err.Error(), nil, ctx) return } response.OK("UpdateUserOrder success", nil, ctx) } // 获取订单详情(计算价格等) func GetOrderInfo(ctx *gin.Context) { order, msg := PreHandleOrder(ctx) if order == nil { response.Fail("GetOrderInfo error:order is null", nil, ctx) return } if msg == "" { msg = "GetOrderInfo success" } response.OK(msg, order, ctx) } // 订单预创建,生成系统订单 func PreCreateOrder(ctx *gin.Context) { order, _ := PreHandleOrder(ctx) if order == nil { response.Fail("PreCreateOrder error:order is null", nil, ctx) return } //创建系统订单 order.TradeStatus = model.OrderCreated err := service.CommonSqlCreate[model.Orders](*order) if err != nil { global.Logrus.Error(err.Error()) response.Fail("PreCreateOrder error::"+err.Error(), nil, ctx) return } response.OK("PreCreateOrder success", order, ctx) } // 订单预处理,计算价格 func PreHandleOrder(ctx *gin.Context) (*model.Orders, string) { uIDInt, _ := GetUserIDFromGinContext(ctx) uName, _ := GetUserNameFromGinContext(ctx) var msg string user, _ := service.FindUserByID(uIDInt) var receiveOrder model.Orders err := ctx.ShouldBind(&receiveOrder) //前端传过来 goods_id,coupon_name if err != nil { global.Logrus.Error(err.Error()) response.Fail("PreHandleOrder error:"+err.Error(), nil, ctx) return nil, "" } //通过商品id查找商品 goods, err := service.FindGoodsByGoodsID(receiveOrder.GoodsID) if err != nil { global.Logrus.Error(err.Error()) if errors.Is(err, gorm.ErrRecordNotFound) { return nil, "" } } //构造系统订单参数 uIDStr := other_plugin.Sup(uIDInt, 6) //对长度不足n的后面补0 sysOrder := model.Orders{ UserID: uIDInt, UserName: uName, OutTradeNo: time.Now().Format("20060102150405") + uIDStr, //系统订单号:时间戳+6位user id GoodsID: goods.ID, GoodsType: goods.GoodsType, DeliverType: goods.DeliverType, //DeliverText: "", Subject: goods.Subject, Price: goods.TotalAmount, TotalAmount: goods.TotalAmount, //ReceiptAmount: "", //BuyerPayAmount: "", //PayID: 0, //PayType: "", //CouponID: receiveOrder.CouponID, CouponName: receiveOrder.CouponName, //CouponAmount: "", //DeductionAmount: "", //RemainAmount: "", //TradeStatus: "", //PayInfo: model.PreCreatePayToFrontend{}, //TradeNo: "", //BuyerLogonId: "", } //折扣码处理 total, _ := strconv.ParseFloat(goods.TotalAmount, 64) service.Show(sysOrder) if sysOrder.CouponName != "" { coupon, err := service.VerifyCoupon(&sysOrder) if err != nil { global.Logrus.Error(err.Error()) msg = err.Error() } if coupon.DiscountRate != 0 { sysOrder.CouponAmount = fmt.Sprintf("%.2f", total*coupon.DiscountRate) sysOrder.CouponID = coupon.ID total = total - total*coupon.DiscountRate //total-折扣码 } } //旧套餐抵扣处理 if global.Server.Subscribe.EnabledDeduction { //计算剩余率 if user.SubscribeInfo.SubStatus { rate, err := strconv.ParseFloat(fmt.Sprintf("%.2f", float64((user.SubscribeInfo.T-user.SubscribeInfo.U-user.SubscribeInfo.D))/float64(user.SubscribeInfo.T)), 64) //if math.IsNaN(rate) { if err != nil { rate = 0 // } //套餐流量剩余率大于设定的阈值才进行处理 if rate >= global.Server.Subscribe.DeductionThreshold { //查找旧套餐价格 order, _, _ := service.CommonSqlFind[model.Orders, string, model.Orders](fmt.Sprintf("user_id = %d ORDER BY id desc LIMIT 1", uIDInt)) if order.ReceiptAmount != "" { //使用 实收金额 进行判断 receiptAmount, _ := strconv.ParseFloat(order.ReceiptAmount, 64) deductionAmount := receiptAmount * rate if deductionAmount < total { sysOrder.DeductionAmount = fmt.Sprintf("%.2f", receiptAmount*rate) total = total - deductionAmount } else { sysOrder.DeductionAmount = fmt.Sprintf("%.2f", total) total = 0 } } } } } //余额抵扣,计算最终价格,TotalAmount=总价-折扣码的折扣-旧套餐的抵扣 if user.Remain > 0 { if user.Remain < total { sysOrder.RemainAmount = fmt.Sprintf("%.2f", user.Remain) total = total - user.Remain } else { sysOrder.RemainAmount = fmt.Sprintf("%.2f", total) total = 0 } } sysOrder.TotalAmount = fmt.Sprintf("%.2f", total) return &sysOrder, msg }
(function() { try { // inspired by Eli Grey's shim @ http://eligrey.com/blog/post/textcontent-in-ie8 // heavily modified to better match the spec: // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent if (Object.defineProperty && Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) { // NOTE: Neither of these "drop-in" patterns would work: // Object.defineProperty(..., ..., descriptor); // nope! // Object.defineProperty(..., ..., { get: descriptor.get, set: descriptor.set }); // nope! // So must use function-wrapped descriptor.fn.call pattern. // "Normal" Elements // NOTE: textContent is different from innerText, so its use would be incorrect: //var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText"); // nope! var getTextContent = function(x) { var c = this.firstChild; var tc=[]; // append the textContent of its children while(!!c) { if (c.nodeType !== 8 && c.nodeType !== 7) { // skip comments tc.push(c.textContent); } c = c.nextSibling; } // a <br> Element should show as a newline if (this.tagName === 'BR') { tc.push('\n'); } c = null; tc = tc.join(''); return tc; }; var setTextContent = function(x) { var c; while(!!(c=this.lastChild)) { this.removeChild(c); } if (x!==null) { c=document.createTextNode(x); this.appendChild(c); } return x; }; Object.defineProperty(Element.prototype, "textContent", { get: function() { // return innerText.get.call(this); // not good enough! return getTextContent.call(this); }, set: function(x) { // return innerText.set.call(this, x); // not good enough! return setTextContent.call(this, x); } }); // <script> Elements var scriptText = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, "text"); Object.defineProperty(HTMLScriptElement.prototype, "textContent", { get: function() { return scriptText.get.call(this); }, set: function(x) { return scriptText.set.call(this, x); } }); // <style> Elements var cssText = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, "cssText"); Object.defineProperty(HTMLStyleElement.prototype, "textContent", { get: function() { return cssText.get.call(this.styleSheet); }, set: function(x) { return cssText.set.call(this.styleSheet, x); } }); // <title> Elements var titleText = Object.getOwnPropertyDescriptor(HTMLTitleElement.prototype, "text"); Object.defineProperty(HTMLTitleElement.prototype, "textContent", { get: function() { return titleText.get.call(this); }, set: function(x) { return titleText.set.call(this, x); } }); // Text nodes var textNodeValue = Object.getOwnPropertyDescriptor(Text.prototype, "nodeValue"); Object.defineProperty(Text.prototype, "textContent", { get: function() { return textNodeValue.get.call(this); }, set: function(x) { return textNodeValue.set.call(this, x); } }); // Comments (and possibly other weird Node types that are treated as comments in IE) var elementNodeValue = Object.getOwnPropertyDescriptor(Element.prototype, "nodeValue"); Object.defineProperty(HTMLCommentElement.prototype, "textContent", { get: function() { return elementNodeValue.get.call(this); }, set: function(x) { return elementNodeValue.set.call(this, x); } }); // Document and DocumentFragment Nodes // NOTE: IE8 seems to reuse HTMLDocument for both, so have to check nodeType explicitly var documentNodeValue = Object.getOwnPropertyDescriptor(HTMLDocument.prototype, "nodeValue"); Object.defineProperty(HTMLDocument.prototype, "textContent", { get: function() { // document fragments have textContent if (this.nodeType === 11) { return getTextContent.call(this); } // a true Document's textContent is always null return null; // === documentNodeValue.get.call(this); }, set: function(x) { if (this.nodeType === 11) { return setTextContent.call(this, x); } // setting a Document's textContent has no side effects return x; // === documentNodeValue.set.call(this, x); } }); // other Node types are either deprecated or don't matter in HTML5/IE standards mode } } catch (e) { // bad Firefox } })();
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> <head> <title>Pathfinder</title> <th:block th:replace="~{fragments/head.html}"/> </head> <body> <div class="wrapper"> <!-- Navigation --> <th:block th:replace="~{fragments/header.html}"/> <input type="hidden" name="routeId" id="routeId"> <div class="details-main" th:object="${route}" name="routeName"> <section class="route-info text-center"> <h4 id="track-name" name="routeName" th:text="${route.name}"></h4> <p>Total distance: <span id="totalDistance"></span> km</p> <p>Author name: <span id="authorName" th:text="${route.getAuthor().fullName}"></span></p> <h4>Difficulty Level (1-3):</h4> <div class="level"> <th:block th:if="${route.getLevel().name() == 'BEGINNER'}"> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> </th:block> <th:block th:if="${route.getLevel().name() == 'INTERMEDIATE'}"> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> </th:block> <th:block th:if="${route.getLevel().name() == 'ADVANCED'}"> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> <p><img class="level-img" src="/images/difficulty-level.png" alt=""></p> </th:block> </div> <th:block th:if="${route.getPictures().size() > 0}"> <img style="transform: scaleX(-1);" th:src="${route.getPictures()[route.getPictures().size()-1].getUrl()}" alt="Title image"> </th:block> <th:block th:if="${route.getPictures().size() < 2}"> <form id="addPicture" th:method="post" th:action="@{/routes/picture/add}" th:object="${picture}"> <div class="form-group"> <h4>Add picture URL to the Route!</h4> <textarea th:field="*{URL}" id="picAdd" cols="30" rows="5" class="form-control" style="background-color: white;"></textarea> </div> <div class="form-group"> <input type="submit" class="btn" id="addPic" value="Add Image"/> </div> </form> </th:block> </section> <section id="weather"> <p>asdasdasdasdasdasdds</p> </section> <section class="route-description text-center"> <h4>Description:</h4> <p id="route-description" th:text="${route.getDescription()}">Description: </p> </section> <section class="gallery"> <th:block th:if="${route.getPictures().size() > 0}"> <th:block th:each="img : ${route.getPictures()}"> <img class="rounded" th:src="${img.getUrl()}" height="100%" alt=""> </th:block> </th:block> </section> <section class="comments" th:object="${user}"> <h1 class="text-center">Comments</h1> <th:block th:each="comment : ${route.getCommentsSortedByData()}"> <div class="card rounded mb-4" style="border: 1px solid gray"> <div class="card-header"> <a class="mt-2" th:href="@{/user/details/{id}(id=${comment.getAuthor().getId()})}"><h5 th:text="${comment.getAuthor().fullName}"></h5></a> <small class="text-center" th:text="${comment.getCreatedFormatted()}"></small> </div> <div class="card-body"> <p th:text="${comment.getTextContent()}" class="card-text">With supporting text below as a natural lead-in to additional content.</p> <div class="pb-3" th:if="${(comment.getAuthor().getId() == user.getId())}"> <a th:href="@{/comment/edit/{id}(id = ${comment.getId()})}"> <button class="badge-warning rounded">Edit</button> </a> <a th:href="@{/comment/delete/{id}(id = ${comment.getId()})}"> <button class="badge-danger rounded">Delete</button> </a> </div> <div class="pb-3" sec:authorize="hasRole('ADMIN')"> <th:block th:if="${(comment.getAuthor().getId() != user.getId())}"> <a th:href="@{/comment/edit/{id}(id = ${comment.getId()})}"> <button class="badge-warning rounded">Edit</button> </a> <a th:href="@{/comment/delete/{id}(id = ${comment.getId()})}"> <button class="badge-danger rounded">Delete</button> </a> </th:block> </div> <div th:if="${comment.getModifiedFormatted() != null}"> <small>Last Edited: <span th:text="${comment.getModifiedFormatted()}"></span></small> </div> </div> </div> </th:block> <div> <!-- Comments submission --> <form id="commentForm" th:method="post" th:action="@{/comment/add}"> <div class="form-group"> <h4>Leave a comment</h4> <label for="message">Message</label> <textarea name="message" id="message" cols="30" rows="5" class="form-control" style="background-color: white;"></textarea> <small id="messageError" class="invalid-feedback"> Message should be at least 10 characters. </small> </div> <div class="form-group"> <input type="submit" class="btn" id="postComment" value="Post Comment"/> </div> </form> <!-- Comments submission --> </div> <!-- All comments section --> <div> <span id="commentCtnr"><!-- Comments section, filled in by script --></span> </div> <!-- EO: All comments section --> </section> </div> <script th:src="@{/js/track.js}"></script> <script th:src="@{/js/comments.js}"></script> </div> <th:block th:replace="~{fragments/footer.html}"/> </body> </html>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE rfc SYSTEM "rfc2629.dtd" [ <!ENTITY rfc2629 PUBLIC '' 'http://xml.resource.org/public/rfc/bibxml/reference.RFC.2629.xml'> <!ENTITY RFC1035 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.1035.xml"> <!ENTITY RFC2119 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml"> <!ENTITY RFC2629 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2629.xml"> <!ENTITY RFC5280 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5280.xml"> <!ENTITY RFC3552 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3552.xml"> <!ENTITY RFC3642 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3642.xml"> <!ENTITY RFC4033 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4033.xml"> <!ENTITY RFC4055 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4055.xml"> <!ENTITY RFC4648 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4648.xml"> <!ENTITY RFC5395 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5395.xml"> <!ENTITY RFC4366 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4366.xml"> <!ENTITY HTTPINTEG SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.draft-hallambaker-httpintegrity-01.xml"> ]> <?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?> <?rfc strict="yes" ?> <?rfc toc="yes"?> <?rfc tocdepth="4"?> <?rfc symrefs="yes"?> <?rfc sortrefs="yes" ?> <?rfc compact="yes" ?> <?rfc subcompact="no" ?> <rfc category="std" docName="draft-hallambaker-httpauth-01" ipr="trust200902"> <front> <title abbrev="HTTP Authentication Considerations">HTTP Authentication Considerations</title> <author fullname="Phillip Hallam-Baker" initials="P. M." surname="Hallam-Baker"> <organization>Comodo Group Inc.</organization> <address> <email>philliph@comodo.com</email> </address> </author> <date day="22" month="October" year="2012" /> <area>General</area> <workgroup>Internet Engineering Task Force</workgroup> <abstract> <t> This draft is input to the HTTP Working Group discussion of HTTP authentication schemes. </t> <t> Since the topic is one that the intended audience is more than familiar with, the presentation style is maybe not what is usual in such papers. </t> </abstract> </front> <middle> <section title="What is Wrong in Web Authentication"> <t> What is wrong with Web Authentication is that twenty years later we still depend on passwords and what is worse, the weakest possible password infrastructure. </t> <t> Little has changed in the use of password authentication since the publication of crack in 1990. Before crack it was a point of pride for many Unix admins that the one way encryption used in UNIX "made their password system more secure than VMS". It was argued that making the one way encrypted password file public made the system more secure than the 'security-through-insecurity' approach of VMS. VMS also used one way encryption but the password file was only readable with admin privileges. Endless USENET flames explained 'why' this was a terrible, terrible idea. When crack appeared these flames were quietly forgotten and it is widely imagined that UNIX systems have always had shadow passwords. </t> <t> In the wake of crack it was discovered that most users chose terrible passwords that could be guessed through a brute force or dictionary attack in a few hours. The use of a salt made guessing passwords moderately more difficult as did minimum length password requirements and a requirement to use a non alphabetic character. </t> <t> In the two decades since the standard rules for passwords were set in scripture, computing power has increased by over a billion times and it is now possible to buy a computer that will fit in the heel of a shoe that is more powerful than the fastest mainframe on CERN campus in 1992. The ad-hoc rules developed to make brute force attacks an order of magnitude harder in 1990 have been rendered utterly irrelevant by the six orders of magnitude improvement in available computing power. We have arrived at a situation where we use passwords that are maximally hard for people to remember while being trivial for modern computers to break by brute force. </t> <t> This approach to password security: complacency followed by ad hoc patches followed by complacency has remained firmly in place since. </t> <section title="Password Promiscuity"> <t> Today the typical Internet user has to remember hundreds of passwords and account names. Since this is of couse silly, most users, myself included do no such thing. Most users have the same password for every account. Security concious users have a different password for every account they care about and an easy to remember password for the rest. My New York Times account is phil@hallmabaker.com and the password is GuessEasy. Go have a party. That information protects an asset that the New York Times wants to protect. It is not an asset that I care to spend time or effort protecting. </t> <t> Password promiscuity is a natural strategy that users have adopted to protect the asset they care about: Their time. Creating and remembering strong passwords takes time and effort. Blaming users for not taking time and effort to protect the assets of other people is futile. </t> <t> If Alice has shared her password at 100 sites then a single corrupt actor who can access just one of those sites can gain access to the other 99. </t> <t> Account names pose a harder problem since most sites require that the account name be unique for that site. So a user who finds their preferred account name is taken has to choose another. </t> <t> Expecting users to remember all this stuff is stupid, just stupid. </t> <section title="Password Recovery Schemes"> <t> Password and account name recovery schemes are necessary because users cannot remember the hundreds of passwords or account names that using the Web now involves. </t> <t> The most common password recovery mechanism is the email callback authentication mechanism first used by Mallery and Hurwitz on their Open Meeting system. A challenge (usually in the form of a link) is sent out to the user to their registered email address. The user must respond to the challenge to reset their account. </t> <t> One important consequence of the email callback scheme is that virtually every Web site that has an accounts mechanism requests an email address during registration. There is thus no loss of privacy if the email address is used as the account name. Many sites have realized this fact and avoid the need for the user to choose an account name by allowing them to give their email address instead. </t> <t> A site need not and in fact should not disclose the email address to other users when this approach is used. Shadow account names allow the user the courtesy of not having to remember the account name for that site. </t> </section> <section title="Phishing"> <t> Another circumstance that made it difficult to implement strong security mechanisms at the time was the popular misconception that the attackers were exclusively teenage miscreants engaged in the cyber equivalent of joy-riding rather than criminals motivated by money. People were warned that this was not the case but they did not want to hear. </t> <t> The core defect of the Web authentication mechanism is that passwords are presented en-clair to the verifier. Thus any party who can present a login page to the user stands a good chance of capturing their credentials. </t> <t> This problem was of course anticipated a few days after the BASIC authentication mechanism was proposed and was the original motivation for DIGEST authentication. But DIGEST authentication did not permit the re-use of legacy UNIX password files and so implementation did not take place until it was to late to deprecate BASIC. </t> <t> Even today, IE7 makes no distinction between a request for authentication using BASIC vs DIGEST. Thus an attacker can easily capture the user's credentials through a downgrade attack. DIGEST was intended to replace BASIC and for BASIC to be expunged from the spec as dangerous to use. </t> <t> In the event authentication moved into the HTML layer which likewise communicated the password enclair to the verifier. Thus enabling phishing. </t> </section> </section> <section title="Provider Lock In"> <t> Many schemes have been developed to provide the user with a portable form of credential but all those created to date present the security risk of lock-in to both users and relying parties. </t> <t> Such schemes are often described as 'identity management' a term that seems to hurt rather than help comprehension of the problems involved. </t> <t> Many users have found to their cost that when their FaceBook or Twitter account is disabled, they lose access to every other Web site linked to it. </t> <t> While end users are faced with a minor inconvenience, relying party sites are faced with the risk that the 'identity provider' will decide to change their terms of service to their great disadvantage with little or no notice. Essentially the relying parties have agreed to channel all their traffic through the portal of another without any form of contractual agreement to prevent the portal owner setting up a toll booth. </t> <t> A particular form of lock in that will doom any scheme to an inevitable and deserved death is any attempt to tie the scheme to the use of any naming registry other than the DNS. </t> <t> In one recent exercise in mindboggling futility a group of otherwise rational people spent over five years on a project where the two identifier forms to be supported were http://www.whowoulddothis.org/username and =username. It was rather obviously and abundantly clear that the only rational reason for the first choice was to corrale users to the inevitable choice of the second. Well they didn't did they? </t> <t> One of the problems with such commercial interests is that it is often considered impolite or somehow improper to point out that they exist. Even when it is rather clear that their presence is going to doom the scheme to extinction. </t> <t> While a naming ragistry can be profitable in theory, there have only been four such registries established on an international scale in the history of human civilization. Each supported a new form of communication, these being the postal system, the telephone system, the barcode product identifier system and the Internet. While commercial control of such a registry would of course bring ritches almost beyond the dreams of MBAs, the chance that such proposals might succeed is negligible to nil. </t> </section> <section title="Strong Credentials Compromised by Weak Binding"> <t> A secondary Web authentication problem is that use of strong credentials is compromised by the inadequacy of the Web protocols. For example, a One Time Password (OTP) token provides strong authentication when used in the context of a VPN or other application that can guarantee that the passcode is only presented to the intended service. When entered into a HTML page, OTP passcodes are as vulnerable to interception as passwords. </t> <t> Use of an OTP or public key token provides strong evidence that the hardware device concerned was in some way involved in a transaction but not the intention of the token holder. </t> <t> Consider the case where a wire transfer of $10,000 to be sent to Nigeria is requested, the bank asks for an OTP value to be entered as confirmation. The bank can only verify that the value entered is the next OTP value in sequence. The bank has no means to determine whether the token holder was looking at a Web page that asked them to enter the value to confrim the wire transfer or whether they were looking at a Web page asking if they would like to buy a fluffy pink bunny for their daughter's birthday. </t> <t> If an authentication system cannot tell the difference between a con trick and a pink fluffy bunny, it should not be considered strong. </t> <section title="Confirmation vs Authentication"> <t> Modern smartphones are ubiquitous and relatively cheap. They provide a computing capability, a communication capability and a display in a single package. This is a platform that can and should be leveraged as an authentication device that can provide proof not only that the user was involved but that they were committed to the transaction concerned. </t> <t> This technology provides us for the first time with a technology platform that is capable of presenting the user with the actual transaction they are being asked to confirm and to thus provide a strong binding between the device and the transaction. </t> <t> My prefered hardware device for such a use would be a wristwatch with an intelligent display. </t> </section> </section> <section title="What passwords get right"> <t> Overlooked in most security discussion of passwords is what they get right, indeed it is often assumed that they have no redeeming features. Yet if that were the case they would have been gone long ago. The real problem of passwords is that they work just well enough to be almost always better than the alternatives. </t> <t> The biggest advantage of passwords is that every Internet device has had to develop the affordances to support them. My Internet enabled weighing scale has a USB socket whose sole purpose is to enable me to plug it into a computer to set the WiFi network name and password. I can log into my personal email account from every desktop computer, laptop, tablet or mobile in the house. I can only acces my corporate email from the one machine configured for the corporate VPN and smart token. </t> <t> Passwords require no dongles, tokens or cards which in turn means that they don't require device drivers or administrator privileges. While vendors of such systems strive to present low barriers for such devices, low barriers can never compete with no barriers if the user has a choice in the matter. People take effort to secure the assets they care about which is why banks can't give authentication tokens to customers while the same customers will go and pay for a battle.net token to secure the assets that matter to them. </t> </section> </section> <section title="User Authentication is Three Separate Problems"> <t> The term 'authentication' tends to cause confusion due to the fact that there are actually three separate activities that it can refer to. When Alice establishes an account at a Web site, the site may verify her email address is correct. When Alice presents her username and password, the site verifies the data and if correct issues a HTTP cookie. When Alice re-visits the same Web site to make further requests, the cookie is verified each time. Each of these verifications is a form of authentication but they are totally different in character and only the last of these is a form of authentication that is directly related to HTTP. </t> <t> Attempts have been made to distinguish between these as 'initial authentication' and 're-authentication' but this also creates confusion as some people consider the first contact with the user as the 'initial' authentication and others consider that to be the start of a Web session. </t> <section title="Registration"> <t> Registration comprises all activities related to the establishment and maintenance of an account. These include the initial dialogu in which Alice picks out an account name for display on the site and her authentication credentials and all subsequent updates including password resets. </t> <t> In a small number of circumstances, registration involves authentication of dopcumentary evidence such as articles of incorporation, a passport, business license or professional qualifications. The term validation seems to have emerged as the term of art for this activity. </t> <t> Today registration is almost exclusively managed through HTML forms. Any new system will probably have to respect this approach. Registration establishes an account that is in almost every case to be accessible from multiple Web browsers rather than just the browser on which the registration process was completed. </t> </section> <section title="Credential Presentation"> <t> Unlike the FTP and Telnet protocols that preceded it, HTTP Web sessions typically span multiple TCP connections. In the typical case the use will 'log in' to a Web site to establish a session that then continues for several hours, days or even months. </t> <t> Like the registration phase, credential presentation has largely transitioned out of the browser to HTML. Although many users employ plugins and applets that effectively reverse this, filling in the account an password field from a password database that is stored locally or in the cloud. </t> <t> While such 'password managers' have traditionally been considered part of the problem they are in fact a necessary part of any solution. If we are going to improve matters we must first offer users a solution that meets their needs better than current solutions. </t> </section> <section title="Message Authentication"> <t> Credential presentation has a necessary impact on the user. Since it would be tedious to enter a username and password for every Web page view, a lightweight mechanism is necessary to re-authenticate the user and demonstrate that they are the user that authenticated themselves when the session was created. </t> <t> This is the only part of the process that is currently within the scope of HTTP rather than HTML and probably the only part for which it will be possible to get agreement on a better mechanism than the existing one. </t> <t> The best available mechanism is the HTTP 'cookie'. This is highly unsatisfactory as a technical mechanism as they are weakly bound to the HTTP transaction and disclosed to the verifier. These circumstances in turn lead to numerous forms of cookie-stealling and cookie-stuffing attacks. </t> <t> Using cookies for authentication also involves privacy concerns. In the context of authentication schemes, the use of cookies does not raise new privacy concerns as the purpose of the authentication scheme is to establish a session and uniquely identify the user. Unfortunately the cookie spec permits sites to establish cookies for tracking purposes without user permission or knowledge. The fact that cookies may be used for illegitimate purposes compromises legitimate uses and creates unnecessary transaction costs including customer serivce calls, congressional subpoenas and accusations on slashdot. </t> <t> My proposal for fixing this part of the problem isdescribed in <xref target="I-D.hallambaker-httpintegrity"/>. </t> <t> While there are many, many concerns that need to be considered in the registration and credential presentation operations, the problem of message authentication can be reduced to the problems of: </t> <t> <list> <t> Identifying a security context consisting of at minimum an authentication algorithm, key and account identifier. </t> <t> Applying the security context to parts of the HTTP message. </t> </list> </t> </section> </section> <section title="Deployment Approach"> <t> Proposing a better authentication mechanism for the Web is easy. In fact there is nobody involved in Web Security that could not develop a better scheme given a free hand and a group of people interested in deployment. The development of a secure scheme should be well within the capabilities of a competent first year Computer Science undergraduate. </t> <t> The much harder problem is deployment and in particular how to deploy a new scheme in the context of the legacy infrastructure. Here the ease with which a proposal can be made makes deployment harder, not easier since there are always competing proposals. </t> <section title="Password Managers as Transition Path"> <t> If the users are going to participate in any new scheme it must work at least as well as the existing password scheme. In particular it must be possible for the user to access all their accounts from their browser in a transparent fashion with minimal hassle. </t> <t> Storing passwords in the cloud is a very good way to achieve the user's interest even if the sites whose assets may be compromised as a result may see it as a bad thing. Let us agree for the sake of argument that we consider passwords to be such an intrinsically insecure form of authentication that the user choice to store them in the cloud has negligible impact on the security of the system. </t> <t> Since all the proposals to improve the Web authentication infrastructure involve some form of 'identity provider', why not give that provider the secondary purpose as a password manager? </t> <t> If the communication between the client and the password manager was a widely supported Internet standard, users could choose any provider they liked as their password manager and access their credentials from any Web browser that they might need to use. </t> <t> Such a confluence could in itself improve security as once the user is assured that every browser they need to use has access to their password manager, there is no need for the password to be memorable. It is thus possible for the password used for credential presentation to the site to be long and strong. </t> <t> Use of a standards based password management protocol permits the user to take their security into their own hands irrespective of what attempts the sites might attempt to prevent it. What is perhaps more interesting is that it also sets the scene to enabling use of strong credentials. </t> </section> <section title="Non-Transferable Credentials"> <t> While Web sites concerned with the risk that their customers store credentials in the cloud might attempt to frustrate a cloud based password infrastructure, a much better approach is to co-opt it and use it as a basis to build on. At the very least, a cloud based authentication infrastructure provides a useful pre-authentication step that could be used as a preliminary to a site specific log-in. </t> <t> But just as an identity provider can also be a cloud password manager, the converse is also true. The cloud password manager can also support one or more existing mechanisms that enable credential presentation authentication without disclosure of the credential being verified. These could be based on SAML, OpenID, OAUTH or even some new proposal. </t> </section> </section> <section title="Action Plan"> <t> My proposal to improve Web authentication has the following parts: </t> <t> <list> <t> Open Protocol for credential acquisition </t> <t> HTTP Integrity Header </t> <t> Bindings for credential presentation employing the commonly used federated authentication schemes, vis SAML, OAUTH, OpenID, etc. </t> </list> </t> <section title="Open Protocol for credential management"> <t> This protocol would be responsible for managing users legacy credentials (i.e. passwords) and to support whatever strong mechanisms for credential exchange were developed. </t> <t> The protocol itself would require registration, credential presentation and query components. Once the user had established an account they would have to be able to bind any browser or device of their choice to that account, possibly doing so for a very limited time or for limited sites. </t> <t> The query component would be of the form 'how do I access site X with identity Y'. For general applications the broker might then respond with a username and password or a secret to be used to respond to a challenge. For circumstances requiring higher security the system might support some form of key splitting or sharing or other control limiting exposure. </t> </section> <section title="HTTP Integrity Header"> <t> This is described at length in <xref target="I-D.hallambaker-httpintegrity"/> </t> <t> The biggest challenge in the design of SAML, OAUTH and OpenID was establishing a secure binding between the authentication token and the HTTP messages. Using cookies and URI fragments for this purpose is deeply unsatisfactory. </t> </section> <section title="Bindings"> <t> While we might imagine that we can get by with one single protocol that is going to solve all our authentication problems we now live in a world where there is much legacy that demands attention. Even if we decide that in future we are all going to use one single new protocol, we have to find a mechanism that allows the credential management systems to trade in their old lamps for new. </t> <t> At minimum we require a mechanism that allows Web sites to specify which forms of authentication credentials they might accept, which mechanisms for useing them for validation and of transporting the challenges and responses for such mechanisms within HTTP message headers. </t> </section> </section> <section title="Security Considerations"> <t> Since this is a discussion document and the whole thing is talking about security, I think I will just leave the headings here to remind people about the security issues I think people should consider. </t> <section title="User Lock In"> </section> <section title="Site Lock In"> </section> <section title="Impersonation"> </section> <section title="Credential Disclosure"> </section> <section title="Credential Oracle"> </section> <section title="Randomness of Secret Key"> </section> </section> <section title="IANA Considerations"> <t> </t> </section> </middle> <back> <references title="Normative References"> &HTTPINTEG; &RFC2119; </references> </back> </rfc>
import 'package:flutter/material.dart'; import 'package:imt_tp/home_page.dart'; import 'package:imt_tp/second_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), routes: { '/': (context) => const MyHomePage(title: 'Flutter Demo Home Page'), '/second': (context) => const MySecondPage(), }, ); } }
@extends('app') @section('content') <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Register</div> <div class="panel-body"> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/register') }}"> {!! csrf_field() !!} <div class="row"> <div class="col-xs-6"> <div class="form-group"> <label class="col-md-4 control-label">First</label> </div> <input type="text" class="form-control" name="firstName" value="{{ old('firstName') }}"> </div> <div class="col-xs-6"> <div class="form-group"> <label class="col-md-4 control-label">Last</label> </div> <input type="text" class="form-control" name="lastName" value="{{ old('lastName') }}"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">E-Mail Address</label> <div class="col-md-6"> <input type="email" class="form-control" name="email" value="{{ old('email') }}"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" id="passcode">Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="password"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" id="confirmpasscode">Confirm Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="password_confirmation"> </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Register </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
/****************************************************************************** * * Copyright 2019 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #pragma once #include <inttypes.h> #include <cstdlib> #ifndef LOG_TAG #define LOG_TAG "bluetooth" #endif static_assert(LOG_TAG != nullptr, "LOG_TAG should never be NULL"); #include "os/log_tags.h" #include "os/logging/log_adapter.h" #if defined(FUZZ_TARGET) #define LOG_VERBOSE_INT(...) #define LOG_DEBUG_INT(...) #define LOG_INFO_INT(...) #define LOG_WARN_INT(...) #define LOG_ERROR_INT(...) do { \ fprintf(stderr, __VA_ARGS__); \ } while (false) // for fuzz targets, we just // need to abort in this statement // to catch the bug #define LOG_ALWAYS_FATAL_INT(...) do { \ fprintf(stderr, __VA_ARGS__); \ abort(); \ } while (false) #else /* end of defined(FUZZ_TARGET) */ #if defined(__ANDROID__) #include <log/log.h> #include <log/log_event_list.h> #if __has_include("src/init_flags.rs.h") #include "common/init_flags.h" #define LOG_VERBOSE_INT(fmt, args...) \ do { \ if (bluetooth::common::InitFlags::GetLogLevelForTag(LOG_TAG) >= LOG_TAG_VERBOSE) { \ ALOGV(fmt, ##args); \ } \ } while (false) #define LOG_DEBUG_INT(fmt, args...) \ do { \ if (bluetooth::common::InitFlags::GetLogLevelForTag(LOG_TAG) >= LOG_TAG_DEBUG) { \ ALOGD(fmt, ##args); \ } \ } while (false) #endif /* __has_include("src/init_flags.rs.h") */ #define LOG_INFO_INT(fmt, args...) ALOGI(fmt, ##args) #define LOG_WARN_INT(fmt, args...) ALOGW(fmt, ##args) #define LOG_ERROR_INT(fmt, args...) ALOGE(fmt, ##args) #define LOG_ALWAYS_FATAL_INT(fmt, args...) do { \ ALOGE(fmt, ##args); \ abort(); \ } while (false) #elif defined (ANDROID_EMULATOR) /* end of defined(__ANDROID__) */ // Log using android emulator logging mechanism #include "android/utils/debug.h" #define LOGWRAPPER(fmt, args...) VERBOSE_INFO(bluetooth, "bluetooth: " fmt, \ ##args) #define LOG_VEBOSE_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_DEBUG_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_INFO_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_WARN_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_ERROR_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_ALWAYS_FATAL_INT(fmt, args...) \ do { \ fprintf(stderr, fmt "\n", ##args); \ abort(); \ } while (false) #elif defined(TARGET_FLOSS) /* end of defined (ANDROID_EMULATOR) */ #include "gd/common/init_flags.h" #include "gd/os/syslog.h" // Prefix the log with tag, file, line and function #define LOGWRAPPER(tag, fmt, args...) \ write_syslog(tag, "%s: " fmt, LOG_TAG, ##args) #define LOG_VERBOSE_INT(...) \ do { \ if (bluetooth::common::InitFlags::GetLogLevelForTag(LOG_TAG) >= LOG_TAG_VERBOSE) { \ LOGWRAPPER(LOG_TAG_VERBOSE, __VA_ARGS__); \ } \ } while (false) #define LOG_DEBUG_INT(...) \ do { \ if (bluetooth::common::InitFlags::GetLogLevelForTag(LOG_TAG) >= LOG_TAG_DEBUG) { \ LOGWRAPPER(LOG_TAG_DEBUG, __VA_ARGS__); \ } \ } while (false) #define LOG_INFO_INT(...) LOGWRAPPER(LOG_TAG_INFO, __VA_ARGS__) #define LOG_WARN_INT(...) LOGWRAPPER(LOG_TAG_WARN, __VA_ARGS__) #define LOG_ERROR_INT(...) LOGWRAPPER(LOG_TAG_ERROR, __VA_ARGS__) #define LOG_ALWAYS_FATAL_INT(...) \ do { \ LOGWRAPPER(LOG_TAG_FATAL, __VA_ARGS__); \ abort(); \ } while (false) #else /* end of defined (TARGET_FLOSS) */ /* syslog didn't work well here since we would be redefining LOG_DEBUG. */ #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <chrono> #include <cstdio> #include <ctime> #define LOGWRAPPER(fmt, args...) \ do { \ auto _now = std::chrono::system_clock::now(); \ auto _now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(_now); \ auto _now_t = std::chrono::system_clock::to_time_t(_now); \ /* YYYY-MM-DD_HH:MM:SS.sss is 23 byte long, plus 1 for null terminator */ \ char _buf[24]; \ auto l = std::strftime(_buf, sizeof(_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&_now_t)); \ snprintf( \ _buf + l, sizeof(_buf) - l, ".%03u", static_cast<unsigned int>(_now_ms.time_since_epoch().count() % 1000)); \ /* pid max is 2^22 = 4194304 in 64-bit system, and 32768 by default, hence 7 digits are needed most */ \ fprintf( \ stderr, \ "%s %7d %7ld %s:" fmt "\n", \ _buf, \ static_cast<int>(getpid()), \ syscall(SYS_gettid), \ LOG_TAG, \ ##args); \ } while (false) #define LOG_VERBOSE_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_DEBUG_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_INFO_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_WARN_INT(...) LOGWRAPPER(__VA_ARGS__) #define LOG_ERROR_INT(...) LOGWRAPPER(__VA_ARGS__) #ifndef LOG_ALWAYS_FATAL #define LOG_ALWAYS_FATAL_INT(...) \ do { \ LOGWRAPPER(__VA_ARGS__); \ abort(); \ } while (false) #endif #endif /* defined(__ANDROID__) */ #endif /* defined(FUZZ_TARGET) */ #define _LOG_SRC_FMT_STR "%s:%d - %s: " #define _PREPEND_SRC_LOC_IN_LOG(fmt, args...) \ _LOG_SRC_FMT_STR fmt, __FILE__, __LINE__, __func__, ##args // --------------------------------------------------------- // All MACROs defined above are internal and should *not* be // used directly (use LOG_XXX defined below instead). // the output of LOG_XXX_INT does not contain the source // location of the log emitting statement, so far they are only used by // LogMsg, where the source locations is passed in. #define LOG_VERBOSE(fmt, args...) \ LOG_VERBOSE_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #define LOG_DEBUG(fmt, args...) \ LOG_DEBUG_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #define LOG_INFO(fmt, args...) \ LOG_INFO_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #define LOG_WARN(fmt, args...) \ LOG_WARN_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #define LOG_ERROR(fmt, args...) \ LOG_ERROR_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #ifndef LOG_ALWAYS_FATAL #define LOG_ALWAYS_FATAL(fmt, args...) \ LOG_ALWAYS_FATAL_INT(_PREPEND_SRC_LOC_IN_LOG(fmt, ##args)) #endif #define ASSERT(condition) \ do { \ if (!(condition)) { \ LOG_ALWAYS_FATAL("assertion '" #condition "' failed"); \ } \ } while (false) #define ASSERT_LOG(condition, fmt, args...) \ do { \ if (!(condition)) { \ LOG_ALWAYS_FATAL("assertion '" #condition "' failed - " fmt, ##args); \ } \ } while (false)
import EyeIcon from "./icons/eye.svg?component"; import HomeIcon from "./icons/home.svg?component"; import BillIcon from "./icons/bill.svg?component"; import CardIcon from "./icons/card.svg?component"; import MailIcon from "./icons/mail.svg?component"; import BellIcon from "./icons/bell.svg?component"; import SendIcon from "./icons/send.svg?component"; import PlusIcon from "./icons/plus.svg?component"; import FundIcon from "./icons/fund.svg?component"; import InboxIcon from "./icons/inbox.svg?component"; import SearchIcon from "./icons/search.svg?component"; import InvoiceIcon from "./icons/invoice.svg?component"; import RevenueIcon from "./icons/revenue.svg?component"; import ExpenseIcon from "./icons/expense.svg?component"; import ReceiveIcon from "./icons/receive.svg?component"; import BuildingIcon from "./icons/building.svg?component"; import SettingsIcon from "./icons/settings.svg?component"; import CalendarIcon from "./icons/calendar.svg?component"; import DashboardIcon from "./icons/dashboard.svg?component"; import DoughnutChart from "./charts/doughnut.svg?component"; import StatisticChart from "./charts/statistic.svg?component"; import InvestmentIcon from "./icons/investment.svg?component"; import CreditCardIcon from "./icons/credit-card.svg?component"; import DotsCircleIcon from "./icons/dots-circle.svg?component"; import ChevronDownIcon from "./icons/chevron-down.svg?component"; import { useState } from "react"; const menu = [ { name: "Home", icon: HomeIcon }, { name: "USA Payors", icon: BillIcon }, { name: "Invoices", icon: InvoiceIcon }, { name: "My Banks", icon: BuildingIcon }, { name: "Withdraw", icon: CardIcon }, { name: "Settings", icon: SettingsIcon }, ]; const recentTransactions = [ { icon: SendIcon, color: "bg-indigo-700", type: "Send transaction", date: "Dec 24, 2021", amount: "$ 123.00", balance: "$ 334.00", }, { icon: ReceiveIcon, color: "bg-green-400", type: "Receive fund", date: "Jul 20. 2021", amount: "$ 322.00", balance: "$ 658.00", }, ]; const invoices = [ { no: "#BCS101", date: "Jun 21, 2020", avatar: "/img/avatar-2.jpeg", name: "Alexandar Parkinson", amount: "$ 13435.50", status: "Successful", }, { no: "#BSD133", date: "Jun 21, 2020", avatar: "/img/avatar-3.jpeg", name: "Natasha Analington", amount: "$ 1654.50", status: "Pending", }, ]; function App() { const [showCvc, setShowCvc] = useState(false); return ( <div className="flex min-h-screen w-full bg-gray-700 font-sans"> <aside className="flex w-64 flex-col px-4 pt-10 pb-6"> <a href="#" className="flex items-center gap-x-4 px-8 text-2xl font-medium text-white" > <DashboardIcon className="h-6 w-6 stroke-current" /> <span>Transfer</span> </a> <ul className="flex flex-1 flex-col gap-y-10 px-8 pt-14"> {menu.map((item, index) => { const Icon = item.icon; return ( <li key={item.name}> <a href="#" className="flex items-center gap-x-4 text-gray-400 hover:font-medium hover:text-white" > <Icon className="h-6 w-6 stroke-current" /> <span>{item.name}</span> </a> </li> ); })} </ul> <div className="rounded-10 sticky bottom-4 bg-gray-900 bg-[url(/img/line-pattern.svg?component)] bg-top p-6"> <div className="text-white"> Refer a friend and get <span className="font-bold">$5</span> </div> <div className="mt-3 text-sm text-gray-400"> The reward of transfer. </div> <button className="mt-4 w-full rounded-lg bg-gray-700 py-2 text-sm font-normal text-white"> Invite </button> </div> </aside> <main className="flex min-h-screen flex-1 flex-col rounded-l-[48px] bg-gray-800 p-8"> <nav className="flex items-center gap-x-6"> <div className="flex w-3/5 items-center justify-between"> <h1 className="text-[30px] font-bold text-white">Overview</h1> <div className="flex items-center gap-x-2"> <div className="relative"> <span className="pointer-events-none absolute inset-y-0 flex items-center px-3"> <SearchIcon className="h-6 w-6 stroke-current text-gray-400" /> </span> <input type="text" placeholder="Search" className="rounded-10 bg-gray-900 py-3 pr-4 pl-10 text-sm font-light text-gray-400" /> </div> <button className="rounded-10 bg-gray-900 py-3 px-4 text-sm font-light text-gray-400"> Add Account </button> </div> </div> <div className="flex w-2/5 items-center justify-between"> <div className="flex items-center gap-x-2.5"> <button className="flex h-11 w-11 items-center justify-center rounded-full bg-gray-900"> <MailIcon className="h-7 w-7 stroke-current text-gray-400" /> </button> <button className="relative flex h-11 w-11 items-center justify-center rounded-full bg-gray-900"> <BellIcon className="h-7 w-7 stroke-current text-gray-400" /> <div className="absolute top-3 right-3 flex h-2 w-2"> <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-indigo-400 opacity-75" /> <span className="relative inline-flex h-2 w-2 rounded-full bg-indigo-400" /> </div> </button> <button className="flex h-11 w-11 items-center justify-center rounded-full bg-gray-900"> <InboxIcon className="h-7 w-7 stroke-current text-gray-400" /> </button> </div> <button className="flex h-11 items-center justify-center rounded-full bg-gray-900 px-2"> <img src="/img/avatar-1.jpeg" alt="" className="h-8 w-8 rounded-full object-cover" /> <span className="pl-2 text-sm font-light text-white"> Alexander </span> <ChevronDownIcon className="h-6 w-6 stroke-current text-gray-400" /> </button> </div> </nav> <div className="flex gap-x-6 py-8"> <div className="flex w-3/5 flex-col gap-y-8"> <div className="rounded-10 flex items-center justify-between bg-gray-900 bg-[url(/img/line-pattern.svg?component)] p-7"> <div className="flex items-center gap-x-4"> <div className="rounded-full bg-gray-700 p-3"> <CreditCardIcon className="h-5 w-5 fill-current text-indigo-400" /> </div> <div> <div className="text-sm text-gray-400">CARD NUMBER</div> <div className="pt-1 text-white">5540 2280 8647 5687</div> </div> </div> <div className="h-full w-px bg-gray-700" /> <div className=""> <div className="text-sm text-gray-400">EXPIRE DATE</div> <div className="pt-1 text-white">08/28</div> </div> <div className="h-full w-px bg-gray-700" /> <div className=""> <div className="text-sm text-gray-400">CVC</div> <div className="flex items-center gap-x-2"> {showCvc ? ( <div className="pt-1 text-white tabular-nums">433</div> ) : ( <div className="pt-1 text-white tabular-nums">***</div> )} <button onClick={() => setShowCvc(!showCvc)}> <EyeIcon className="h-6 w-6 stroke-current text-white" /> </button> </div> </div> <div className="h-full w-px bg-gray-700" /> <div className=""> <div className="text-sm text-gray-400">STATUS</div> <div className="pt-1 text-white">Active</div> </div> </div> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white"> Statistics of costs </h2> <button className="rounded-10 inline-flex items-center gap-x-1 bg-gray-700 py-2 px-4 text-sm font-light text-gray-400"> <span>Jan - Aug</span> <ChevronDownIcon className="h-6 w-6 stroke-current" /> </button> </div> <div className="flex pt-8"> <StatisticChart className="w-full" /> <div className="flex flex-col gap-4"> <div className="rounded-10 flex items-center gap-x-3 bg-indigo-400 p-4"> <div className="rounded-full bg-gray-900 p-2 text-indigo-700"> <RevenueIcon className="h-6 w-6 fill-current" /> </div> <div> <div className="text-sm text-indigo-700">Revenue</div> <div className="font-normal">$10.567</div> </div> </div> <div className="rounded-10 flex items-center gap-x-3 bg-green-400 p-4"> <div className="rounded-full bg-gray-900 p-2 text-green-700"> <ExpenseIcon className="h-6 w-6 fill-current" /> </div> <div> <div className="text-sm text-green-700">Expenses</div> <div className="font-normal">$8,567</div> </div> </div> </div> </div> </div> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white"> Recent transactions </h2> <button className="rounded-10 inline-flex items-center gap-x-1 bg-gray-700 py-2.5 px-4 text-sm font-light text-gray-400"> View All </button> </div> <table> <tbody> {recentTransactions.map((transaction) => { const TransactionIcon = transaction.icon; return ( <tr v-for="transaction in recentTransactions" className="border-b border-gray-700 last:border-none" > <td className="py-4"> <div className="flex items-center gap-x-4"> <div className={`flex items-center justify-center rounded-full p-2 ${transaction.color}`} > <TransactionIcon className="h-5 w-5 fill-current text-gray-900" /> </div> <span className="text-sm text-white"> {transaction.type} </span> </div> </td> <td className="py-4"> <div className="flex items-center gap-x-2"> <div className="flex items-center justify-center rounded-full bg-gray-700 p-2"> <CalendarIcon className="h-6 w-6 stroke-current text-gray-400" /> </div> <span className="text-sm text-gray-400"> {transaction.date} </span> </div> </td> <td className="py-4"> <span className="text-sm text-white"> {transaction.amount} </span> </td> <td className="py-4"> <span className="text-sm text-white"> {transaction.balance} </span> </td> </tr> ); })} </tbody> </table> </div> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white">Invoices</h2> <button className="rounded-10 inline-flex items-center gap-x-1 bg-gray-700 py-2.5 px-4 text-sm font-light text-gray-400"> <PlusIcon className="h-6 w-6 stroke-current" /> <span>New Invoices</span> </button> </div> <table className="mt-4"> <thead> <tr> <td className="py-1 text-sm text-gray-400">No</td> <td className="py-1 text-sm text-gray-400">Date</td> <td className="py-1 text-sm text-gray-400">Client</td> <td className="py-1 text-sm text-gray-400">Amount</td> <td className="py-1 text-sm text-gray-400">Status</td> </tr> </thead> <tbody> {invoices.map((invoice, index) => ( <tr className="border-b border-gray-700 last:border-none"> <td className="py-4"> <span className="text-sm font-medium text-white"> {invoice.no} </span> </td> <td className="py-4"> <span className="text-sm text-gray-400"> {invoice.date} </span> </td> <td className="py-4"> <div className="flex items-center gap-x-2"> <img src={invoice.avatar} alt="" className="h-6 w-6 rounded-full object-cover" /> <span className="text-sm text-white"> {invoice.name} </span> </div> </td> <td className="py-4"> <span className="text-sm text-white"> {invoice.amount} </span> </td> <td className="py-4"> <div className={`rounded-10 flex items-center justify-center gap-x-2 border py-2 px-1 ${ invoice.status === "Successful" ? "bg-green-700/20 border-green-400/10" : "bg-indigo-700/20 border-indigo-400/10" }`} > <span className={`h-2 w-2 rounded-full ${ invoice.status === "Successful" ? "bg-green-400" : "bg-indigo-400" }`} /> <span className={`text-xs ${ invoice.status === "Successful" ? "text-green-400" : "text-indigo-400" }`} > {invoice.status} </span> </div> </td> </tr> ))} </tbody> </table> </div> </div> <div className="flex w-2/5 flex-col gap-y-8"> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white"> Scheduled transfer </h2> <button className="rounded-10 inline-flex items-center gap-x-1 bg-gray-700 py-2.5 px-4 text-sm font-light text-gray-400"> <PlusIcon className="h-6 w-6 stroke-current" /> <span>Add new</span> </button> </div> <div className="grid grid-cols-3 gap-x-4 pt-4"> <div className="rounded-10 bg-gray-700 p-2"> <img src="/img/Youtube-logo.png" alt="" className="w-16" /> <div className="pt-6 text-sm font-normal text-white"> $39.9/m </div> </div> <div className="rounded-10 bg-gray-700 p-2"> <img src="/img/Netflix-logo.png" alt="" className="w-16" /> <div className="pt-6 text-sm font-normal text-white"> $45.2/m </div> </div> <div className="rounded-10 bg-gray-700 p-2"> <img src="/img/Spotify-logo.png" alt="" className="w-16" /> <div className="pt-6 text-sm font-normal text-white"> $59.5/m </div> </div> </div> <button className="rounded-10 mt-4 w-full bg-gray-700 py-3 text-white"> Get Started </button> </div> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white"> My savings </h2> <button className="rounded-10 inline-flex items-center gap-x-1 bg-gray-700 py-2.5 px-4 text-sm font-light text-gray-400"> <span>Weekly</span> <ChevronDownIcon className="h-6 w-6 stroke-current" /> </button> </div> <div className="flex flex-col gap-y-4 pt-4"> <div className="rounded-10 flex w-full items-center gap-x-4 bg-gray-700 p-4"> <div className="flex items-center justify-center rounded-full bg-indigo-400 p-2"> <InvestmentIcon className="h-5 w-5 fill-current" /> </div> <div className="flex-1"> <div className="flex items-center justify-between"> <span className="text-white">Investment</span> <span className="font-medium text-white">$2.350.02</span> </div> <span className="text-sm text-gray-400"> 2 months income 80% </span> <div className="mt-2 h-2 w-full rounded-full bg-gray-900"> <div className="h-2 rounded-full bg-indigo-400" style={{ width: "80%" }} /> </div> </div> </div> <div className="rounded-10 flex w-full items-center gap-x-4 bg-gray-700 p-4"> <div className="flex items-center justify-center rounded-full bg-green-400 p-2"> <FundIcon className="h-5 w-5 fill-current" /> </div> <div className="flex-1"> <div className="flex items-center justify-between"> <span className="text-white">Mutual fund</span> <span className="font-medium text-white">$1,450.02</span> </div> <span className="text-sm text-gray-400"> 3 months income 50% </span> <div className="mt-2 h-2 w-full rounded-full bg-gray-900"> <div className="h-2 rounded-full bg-green-400" style={{ width: "50%" }} /> </div> </div> </div> </div> </div> <div className="rounded-10 flex flex-col justify-between bg-gray-900 p-7"> <div className="flex items-center justify-between"> <h2 className="text-[20px] font-medium text-white"> Revenue statistics </h2> <button className="p-2 text-gray-400"> <DotsCircleIcon className="h-6 w-6 fill-current" /> </button> </div> <div className="flex items-center gap-4 pt-4"> <div className="rounded-10 bg-gray-700 p-4"> <DoughnutChart /> </div> <div className="flex flex-col gap-4"> <div className="rounded-10 flex items-center gap-x-3 bg-indigo-400 p-4"> <div className="rounded-full bg-gray-900 p-2 text-indigo-700"> <RevenueIcon className="h-6 w-6 fill-current" /> </div> <div> <div className="text-sm text-indigo-700"> Mutual Funds </div> <div className="font-normal">$10.567</div> </div> </div> <div className="rounded-10 flex items-center gap-x-3 bg-green-400 p-4"> <div className="rounded-full bg-gray-900 p-2 text-green-700"> <ExpenseIcon className="h-6 w-6 fill-current" /> </div> <div> <div className="text-sm text-green-700">Investment</div> <div className="font-normal">$8,567</div> </div> </div> </div> </div> </div> </div> </div> </main> </div> ); } export default App;
package com.gojodev.spring_mvc.controller; import com.gojodev.spring_mvc.model.User; import com.gojodev.spring_mvc.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/users") public class UsersController { private final UserService userService; @Autowired public UsersController(UserService userService) { this.userService = userService; } @GetMapping("/") public String showAllUsers(Model model) { model.addAttribute("users", userService.getAllUsers()); return "users"; } @GetMapping("/{id}") public String getUserById(@PathVariable("id") int id, Model model) { model.addAttribute("user", userService.getUserById(id)); return "user_by_id"; } @GetMapping("/create") public String createUserForm(Model model) { model.addAttribute("user", new User()); return "create"; } @PostMapping("/create") public String createUser(@ModelAttribute("user") User user) { userService.saveUser(user); return "redirect:/users/"; } @GetMapping("/delete/{id}") public String deleteUserForm(Model model, @PathVariable("id") long id) { User user = userService.getUserById(id); model.addAttribute("allowDelete", true); model.addAttribute("user", user); return "user_by_id"; } @PostMapping("/delete/{id}") public String deleteUser(@PathVariable("id") long id) { userService.removeUserById(id); return "redirect:/users/"; } @GetMapping("/edit/{id}") public String editUserForm(Model model, @PathVariable("id") Long id) { User user = userService.getUserById(id); model.addAttribute("user", user); return "edit"; } @PostMapping("/edit/{id}") public String editUser(@ModelAttribute("user") User user, @PathVariable("id") long id) { userService.updateUser(user); return "redirect:/users/"; } }
<script lang="ts" setup> import type { User } from '~/models/user'; interface SuggestedListProps { label: string; labelEmpty?: string; items: User[]; } const props = defineProps<SuggestedListProps>(); const isEmpty = computed(() => { return !props.items || props.items.length === 0; }); </script> <template> <div :class="$style.wrapper"> <p :class="$style.label">{{ label }}</p> <div v-if="!isEmpty"> <AccountItem v-for="acc in items" :key="acc.nickname" :item="acc" /> <RouterLink to="#" :class="$style['more-link']">See all</RouterLink> </div> <p v-else :class="$style['label-empty']">{{ labelEmpty }}</p> </div> </template> <style lang="scss" module> .wrapper { border-top: 1px solid #e3e3e4; padding-bottom: 1rem; padding-top: 1rem; } .label { padding: pxToRem(8px); font-size: 1.4rem; font-weight: 600; } .more-link { font-size: 1.4rem; font-weight: 600; color: $danger; } .label-empty { color: rgba($text, 0.5); font-weight: 400; font-size: 1.4rem; padding: 0 0.8rem; } </style>
package org.alg.advanced.graph.undirected.util; import org.alg.advanced.graph.undirected.represent.Graph; /** * Util class for graph to computer operation like degree, maxDegree, * averageDegree, etc */ public final class GraphUtil { private GraphUtil() { throw new IllegalAccessError(); } /** * computer the degree of (v), number of vertices connected to (v) */ public final static int degree(Graph graph, int v) { int degree = 0; for (int w : graph.adj(v)) { degree++; } return degree; } /** * computer maximum degree, which vertex has max number of connected vertices to * it */ public final static int maxDegree(Graph graph) { int max = 0, deg; for (int v = 0; v < graph.getVertices(); v++) { deg = degree(graph, v); if (deg > max) { max = deg; } } return max; } /** * computer average degree */ public final static double averageDegree(Graph graph) { return 2.0 * graph.getEdges() / graph.getVertices(); } /** * count self-loops */ public final static int numberOfSelfLoops(Graph graph) { int count = 0; for (int v = 0; v < graph.getVertices(); v++) { for (int w : graph.adj(v)) { if (v == w) count++; } } return count / 2; // each edge counted twice } }
#pragma once #include "PCH.h" #include "Math.h" #include "Elements.h" inline float MinutesToAngle(float minutes) { return (fmod(minutes, 60.0f) / 60.0f) * 360; } inline float MinutesToAngleRads(float minutes) { return (fmod(minutes, 60.0f) / 60.0f) * PI2; } inline float HoursToAngle(float hours) { return (fmod(hours, 12.0f) / 12.0f) * 360; } inline float HoursToAngleRads(float hours) { return (fmod(hours, 12.0f) / 12.0f) * PI2; } inline float RoundAngleToMinute(float anglerads) { const float normalizedangle = anglerads / PI2; return round(normalizedangle * 60.0f); } inline float MinuteToAngle(float minutes) { return (minutes / 60.0f) * PI2; } class Timer { public: Timer(); void StartTimer(); void StopTimer(); void ResumeTimer(); void SuspendTimer(); void ResetTimer(); void update(); float getAlarmMinutes(); float getAlarmHours(); float getAlarmRemainingMinutes(); float getAlarmRemainingHours(); float getGameMinutes(); float getGameSeconds(); float getGameHours(); float getGameDays(); void AddMinutes(float minutes); float AngleToMinutes(float angle); void AdjustTime(float MouseAnglerads, GrabbedElement& grabbed); void AdjustAlarmTime(float MouseAnglerads, GrabbedElement& grabbed); void ResetAlarm() { m_AlarmMilliSeconds = 0; } BOOL isTiming() { return Timing; } BOOL isSuspended() { return Suspended; } private: INT64 MinutesToMilliseconds(float minutes); std::chrono::time_point<std::chrono::steady_clock> start; INT64 m_CurrentMilliSecondsDuration = 0; INT64 m_AccumulatedMilliSecondsDuration = 0; INT64 m_AlarmMilliSeconds = 0; BOOL Timing = FALSE; BOOL Suspended = FALSE; };
package storage import ( "context" "time" "github.com/jackc/pgx/v5/pgtype" ) type Point struct { ID int `json:"id"` Coordinates Coordinates `json:"coordinates"` Address string `json:"address"` Description string `json:"description"` OpenTime time.Duration `json:"open"` CloseTime time.Duration `json:"close"` Creator User `json:"creator"` Tags []Tag `json:"tags"` } type Coordinates [2]float64 func (s *Storage) CreatePoint(ctx context.Context, point *Point) error { ctx, timeout := context.WithTimeout(ctx, s.config.Timeout) defer timeout() query := `INSERT INTO points (coordinates, address, description, open_time, close_time, created_by) VALUES (POINT($1, $2), $3, $4, $5, $6, $7) RETURNING id` row := s.pool.QueryRow( ctx, query, point.Coordinates[0], point.Coordinates[1], point.Address, point.Description, pgtype.Time{ Microseconds: point.OpenTime.Microseconds(), Valid: true, }, pgtype.Time{ Microseconds: point.CloseTime.Microseconds(), Valid: true, }, point.Creator.ID, ) if err := row.Scan(&point.ID); err != nil { return err } return nil } func (s *Storage) GetPointByID(ctx context.Context, point *Point) error { ctx, timeout := context.WithTimeout(ctx, s.config.Timeout) defer timeout() query := `SELECT coordinates, address, description, open_time, close_time, created_by FROM points WHERE id = $1` var ( coords = pgtype.Point{} openTime = pgtype.Time{} closeTime = pgtype.Time{} ) if err := s.pool.QueryRow(ctx, query, point.ID).Scan(&coords, &point.Address, &point.Description, &openTime, &closeTime, &point.Creator.ID); err != nil { return err } point.Coordinates = [2]float64{coords.P.X, coords.P.Y} point.OpenTime = time.Duration(openTime.Microseconds) point.CloseTime = time.Duration(closeTime.Microseconds) return nil } func (s *Storage) GetPoints(ctx context.Context, points *[]Point) error { ctx, timeout := context.WithTimeout(ctx, s.config.Timeout) defer timeout() query := `SELECT id, coordinates, address, description, open_time, close_time, created_by FROM points` rows, err := s.pool.Query(ctx, query) if err != nil { return err } newPoints := make([]Point, 0) for rows.Next() { point := Point{} coords := pgtype.Point{} openTime := pgtype.Time{} closeTime := pgtype.Time{} if err = rows.Scan(&point.ID, &coords, &point.Address, &point.Description, &openTime, &closeTime, &point.Creator.ID); err != nil { return err } point.Coordinates = [2]float64{coords.P.X, coords.P.Y} point.OpenTime = time.Duration(openTime.Microseconds) point.CloseTime = time.Duration(closeTime.Microseconds) newPoints = append(newPoints, point) } *points = newPoints return nil } func (s *Storage) UpdatePoint(ctx context.Context, point *Point) error { ctx, timeout := context.WithTimeout(ctx, s.config.Timeout) defer timeout() query := `UPDATE points SET coordinates = POINT($2, $3), address = $4, description = $5, open_time = $6, close_time = $7 WHERE id = $1` var ( openTime = pgtype.Time{ Microseconds: point.OpenTime.Microseconds(), Valid: true, } closeTime = pgtype.Time{ Microseconds: point.CloseTime.Microseconds(), Valid: true, } ) if _, err := s.pool.Query(ctx, query, point.ID, point.Coordinates[0], point.Coordinates[1], point.Address, point.Description, openTime, closeTime); err != nil { return err } return nil }
package carshare.service; import carshare.controller.dto.UserDetailsDTO; import carshare.database.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * Service for loading users from database */ @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; @Autowired public CustomUserDetailsService(final UserRepository userRepository) { this.userRepository = userRepository; } /** * Method return userdata by login * * @param login Login from authentication request * @return User data * @throws UsernameNotFoundException if user not found */ @Override public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException { return UserDetailsDTO.build(userRepository .getByLogin(login) .orElseThrow(() -> new UsernameNotFoundException("User not found: " + login))); } }
Feature: PurgoMalum Functional Tests A short summary of the feature @profanity @SmokeTests Scenario: Verify PurgoMalum containsprofanity api status Given I send the get request to the 'containsprofanity' api Then the status code should be success @xml @SmokeTests Scenario: Verify PurgoMalum xml api status Given I send the get request to the 'xml' api Then the status code should be success @json @SmokeTests Scenario: Verify PurgoMalum json api status Given I send the get request to the 'json' api Then the status code should be success @plain @SmokeTests Scenario: Verify PurgoMalum plain api status Given I send the get request to the 'plain' api Then the status code should be success @profanity Scenario Outline: Verify the profanity api results based on the input text Given the Profanity api is up and running When I call the profanity api Then the response should be <result> against the <input> Examples: | input | result | | this is some test input bollox | true | | this is some test input shit | true | | this is some test input arse | true | | wop | true | | wiseasses | true | | skank | true | | panooch | true | | bitch | true | | dear | false | | sir | false | | madam | false | | mr | false | | mrs | false | @xml Scenario: Verify PurgoMalum xml api response When I send the request to the xml api Then the response should be processed input text 'sample text test' as XML @json Scenario: Verify PurgoMalum json api response When I send the request to the json api Then the response should be processed input text 'sample text test' as json @plain Scenario: Verify PurgoMalum plain api response When I send the request to the plain api Then the response should be processed input text 'sample text test' as plain @profanity Scenario Outline: Verify the api filters words which contain from the profanity list When I send the request to the json api Then the response should filter the profanity <words> from the input text as <result> Examples: | words | result | | sample text test bollox | sample text test ****** | | sample text shit test | sample text **** test | | wop | *** | | wiseasses text shit test | ********* text **** test| | sample bitch text | sample ***** text | | panooch | ******* | | skank | ***** | @json @optional_parameters @potential_bug Scenario: Verify user can add/replace words to the profanity list using optional parameters Given the PurgoMalum api service is up and running When I send the request to the json api with the optional parameters add and fill_text Then the new word 'new_word' should be added and replaced by 'fill_text' value '|replace_word|' in the input text 'new_word is some test input' @json @optional_parameters Scenario: Verify user can add and replace profanity words with a single character using optional parameter Given the PurgoMalum api service is up and running When I send the request to the json api with the optional parameters add and fill_char Then the new word 'newword' should be added and replaced by 'fill_char' value '~' in the input text 'newword is some test input'
# Test accessing glTexCoordIn without redeclaration but with constant indices. # # From the ARB_geometry_shader4 spec (section ): # "Indices used to subscript gl_TexCoord must either be an integral constant # expressions, or this array must be re-declared by the shader with a size." [require] GL >= 2.0 GLSL >= 1.10 GL_ARB_geometry_shader4 [vertex shader] #version 110 attribute vec4 vertex; attribute float offset; varying float gs_offset; void main() { gl_TexCoord[0] = vec4(offset + float(0)); gl_TexCoord[1] = vec4(offset + float(1)); gl_TexCoord[2] = vec4(offset + float(2)); gs_offset = offset; gl_Position = vertex; } [geometry shader] #version 110 #extension GL_ARB_geometry_shader4: enable varying in float gs_offset[]; varying out float fs_ok; void main() { bool ok = true; if (gl_TexCoordIn[0][0] != vec4(gs_offset[0] + float(0))) ok = false; if (gl_TexCoordIn[0][1] != vec4(gs_offset[0] + float(1))) ok = false; if (gl_TexCoordIn[1][0] != vec4(gs_offset[1] + float(0))) ok = false; if (gl_TexCoordIn[1][1] != vec4(gs_offset[1] + float(1))) ok = false; if (gl_TexCoordIn[2][0] != vec4(gs_offset[2] + float(0))) ok = false; if (gl_TexCoordIn[2][1] != vec4(gs_offset[2] + float(1))) ok = false; for (int i = 0; i < 3; ++i) { fs_ok = float(ok); gl_Position = gl_PositionIn[i]; EmitVertex(); } } [geometry layout] input type GL_TRIANGLES output type GL_TRIANGLE_STRIP vertices out 3 [fragment shader] #version 110 varying float fs_ok; void main() { if (distance(fs_ok, 1.0) < 1e-6) gl_FragColor = vec4(0, 1, 0, 1); else gl_FragColor = vec4(1, 0, 0, 1); } [vertex data] vertex/float/2 offset/float/1 -1.0 -1.0 1.0 1.0 -1.0 2.0 1.0 1.0 3.0 -1.0 1.0 4.0 [test] draw arrays GL_TRIANGLE_FAN 0 4 probe all rgb 0 1 0
import { render, fireEvent } from '@testing-library/react' import { it, vi } from 'vitest' import { ProgressBar } from '.' describe('Component: ProgressBar', () => { beforeEach(() => { vi.resetAllMocks() }) it('renders with right timer', () => { const timer = { time: 0, start: () => null, reset: () => null } const { getByRole } = render(<ProgressBar timer={timer} quizStatus="0 / 193" />) expect(getByRole('timer')).toHaveTextContent('00:00') }) it('should reset when the reset button is clicked', () => { const timer = { time: 0, start: () => vi.fn(), reset: vi.fn() } const { getByRole } = render(<ProgressBar timer={timer} quizStatus="0 / 193" />) fireEvent.click(getByRole('button')) expect(getByRole('timer')).toHaveTextContent('00:00') expect(timer.reset).toHaveBeenCalledTimes(1) }) })